org.el 792 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919
  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-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4-dev
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-attach-dir "org-attach"
  111. (&optional create-if-not-exists-p no-fs-check))
  112. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  113. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  114. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  115. (declare-function org-clock-auto-clockout "org-clock" ())
  116. (declare-function org-clock-cancel "org-clock" ())
  117. (declare-function org-clock-display "org-clock" (&optional arg))
  118. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  119. (declare-function org-clock-goto "org-clock" (&optional select))
  120. (declare-function org-clock-in "org-clock" (&optional select start-time))
  121. (declare-function org-clock-in-last "org-clock" (&optional arg))
  122. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  123. (declare-function org-clock-out-if-current "org-clock" ())
  124. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  125. (declare-function org-clock-report "org-clock" (&optional arg))
  126. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  127. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  128. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  129. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  130. (declare-function org-clock-update-time-maybe "org-clock" ())
  131. (declare-function org-clocking-buffer "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-element-at-point "org-element" ())
  137. (declare-function org-element-cache-refresh "org-element" (pos))
  138. (declare-function org-element-cache-reset "org-element" (&optional all))
  139. (declare-function org-element-contents "org-element" (element))
  140. (declare-function org-element-context "org-element" (&optional element))
  141. (declare-function org-element-copy "org-element" (datum))
  142. (declare-function org-element-create "org-element" (type &optional props &rest children))
  143. (declare-function org-element-interpret-data "org-element" (data))
  144. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  145. (declare-function org-element-link-parser "org-element" ())
  146. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  147. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  148. (declare-function org-element-property "org-element" (property element))
  149. (declare-function org-element-put-property "org-element" (element property value))
  150. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  151. (declare-function org-element-timestamp-parser "org-element" ())
  152. (declare-function org-element-type "org-element" (element))
  153. (declare-function org-export-dispatch "ox" (&optional arg))
  154. (declare-function org-export-get-backend "ox" (name))
  155. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  156. (declare-function org-feed-goto-inbox "org-feed" (feed))
  157. (declare-function org-feed-update-all "org-feed" ())
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-num-mode "org-num" (&optional arg))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  168. (declare-function org-timer "org-timer" (&optional restart no-insert))
  169. (declare-function org-timer-item "org-timer" (&optional arg))
  170. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  171. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  172. (declare-function org-timer-start "org-timer" (&optional offset))
  173. (declare-function org-timer-stop "org-timer" ())
  174. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  175. (declare-function org-update-radio-target-regexp "ol" ())
  176. (defvar ffap-url-regexp)
  177. (defvar org-element-paragraph-separate)
  178. (defvar org-indent-indentation-per-level)
  179. (defvar org-radio-target-regexp)
  180. (defvar org-target-link-regexp)
  181. (defvar org-target-regexp)
  182. (defvar org-id-overriding-file-name)
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With
  202. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  203. byte-compiled before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  206. ;; Tangle only if the Org file is newer than the Elisp file.
  207. (unless (org-file-newer-than-p
  208. tangled-file
  209. (file-attribute-modification-time
  210. (file-attributes (file-truename file))))
  211. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  212. (if compile
  213. (progn
  214. (byte-compile-file tangled-file 'load)
  215. (message "Compiled and loaded %s" tangled-file))
  216. (load-file tangled-file)
  217. (message "Loaded %s" tangled-file))))
  218. (defcustom org-babel-load-languages '((emacs-lisp . t))
  219. "Languages which can be evaluated in Org buffers.
  220. \\<org-mode-map>
  221. This list can be used to load support for any of the languages
  222. below. Each language will depend on a different set of system
  223. executables and/or Emacs modes.
  224. When a language is \"loaded\", code blocks in that language can
  225. be evaluated with `org-babel-execute-src-block', which is bound
  226. by default to \\[org-ctrl-c-ctrl-c].
  227. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  228. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  229. default, only Emacs Lisp is loaded, since it has no specific
  230. requirement."
  231. :group 'org-babel
  232. :set 'org-babel-do-load-languages
  233. :version "24.1"
  234. :type '(alist :tag "Babel Languages"
  235. :key-type
  236. (choice
  237. (const :tag "Awk" awk)
  238. (const :tag "C" C)
  239. (const :tag "R" R)
  240. (const :tag "Asymptote" asymptote)
  241. (const :tag "Calc" calc)
  242. (const :tag "Clojure" clojure)
  243. (const :tag "CSS" css)
  244. (const :tag "Ditaa" ditaa)
  245. (const :tag "Dot" dot)
  246. (const :tag "Ebnf2ps" ebnf2ps)
  247. (const :tag "Emacs Lisp" emacs-lisp)
  248. (const :tag "Forth" forth)
  249. (const :tag "Fortran" fortran)
  250. (const :tag "Gnuplot" gnuplot)
  251. (const :tag "Haskell" haskell)
  252. (const :tag "hledger" hledger)
  253. (const :tag "IO" io)
  254. (const :tag "J" J)
  255. (const :tag "Java" java)
  256. (const :tag "Javascript" js)
  257. (const :tag "LaTeX" latex)
  258. (const :tag "Ledger" ledger)
  259. (const :tag "Lilypond" lilypond)
  260. (const :tag "Lisp" lisp)
  261. (const :tag "Makefile" makefile)
  262. (const :tag "Maxima" maxima)
  263. (const :tag "Matlab" matlab)
  264. (const :tag "Mscgen" mscgen)
  265. (const :tag "Ocaml" ocaml)
  266. (const :tag "Octave" octave)
  267. (const :tag "Org" org)
  268. (const :tag "Perl" perl)
  269. (const :tag "Pico Lisp" picolisp)
  270. (const :tag "PlantUML" plantuml)
  271. (const :tag "Python" python)
  272. (const :tag "Ruby" ruby)
  273. (const :tag "Sass" sass)
  274. (const :tag "Scala" scala)
  275. (const :tag "Scheme" scheme)
  276. (const :tag "Screen" screen)
  277. (const :tag "Shell Script" shell)
  278. (const :tag "Shen" shen)
  279. (const :tag "Sql" sql)
  280. (const :tag "Sqlite" sqlite)
  281. (const :tag "Stan" stan)
  282. (const :tag "Vala" vala))
  283. :value-type (boolean :tag "Activate" :value t)))
  284. ;;;; Customization variables
  285. (defcustom org-clone-delete-id nil
  286. "Remove ID property of clones of a subtree.
  287. When non-nil, clones of a subtree don't inherit the ID property.
  288. Otherwise they inherit the ID property with a new unique
  289. identifier."
  290. :type 'boolean
  291. :version "24.1"
  292. :group 'org-id)
  293. ;;; Version
  294. (org-check-version)
  295. ;;;###autoload
  296. (defun org-version (&optional here full message)
  297. "Show the Org version.
  298. Interactively, or when MESSAGE is non-nil, show it in echo area.
  299. With prefix argument, or when HERE is non-nil, insert it at point.
  300. In non-interactive uses, a reduced version string is output unless
  301. FULL is given."
  302. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  303. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  304. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  305. (load-suffixes (list ".el"))
  306. (org-install-dir
  307. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  308. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  309. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  310. (let* ((load-suffixes save-load-suffixes)
  311. (release (org-release))
  312. (git-version (org-git-version))
  313. (version (format "Org mode version %s (%s @ %s)"
  314. release
  315. git-version
  316. (if org-install-dir
  317. (if (string= org-dir org-install-dir)
  318. org-install-dir
  319. (concat "mixed installation! "
  320. org-install-dir
  321. " and "
  322. org-dir))
  323. "org-loaddefs.el can not be found!")))
  324. (version1 (if full version release)))
  325. (when here (insert version1))
  326. (when message (message "%s" version1))
  327. version1)))
  328. (defconst org-version (org-version))
  329. ;;; Syntax Constants
  330. ;;;; Comments
  331. (defconst org-comment-regexp
  332. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  333. "Regular expression for comment lines.")
  334. ;;;; Keyword
  335. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  336. "Regular expression for keyword-lines")
  337. ;;;; Block
  338. (defconst org-block-regexp
  339. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  340. "Regular expression for hiding blocks.")
  341. (defconst org-dblock-start-re
  342. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  343. "Matches the start line of a dynamic block, with parameters.")
  344. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  345. "Matches the end of a dynamic block.")
  346. ;;;; Timestamp
  347. (defconst org-ts--internal-regexp
  348. (rx (seq
  349. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  350. (optional " " (*? nonl))))
  351. "Regular expression matching the innards of a time stamp.")
  352. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  353. "Regular expression for fast time stamp matching.")
  354. (defconst org-ts-regexp-inactive
  355. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  356. "Regular expression for fast inactive time stamp matching.")
  357. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  358. "Regular expression for fast time stamp matching.")
  359. (defconst org-ts-regexp0
  360. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  361. "Regular expression matching time strings for analysis.
  362. This one does not require the space after the date, so it can be used
  363. on a string that terminates immediately after the date.")
  364. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  365. "Regular expression matching time strings for analysis.")
  366. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  367. "Regular expression matching time stamps, with groups.")
  368. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  369. "Regular expression matching time stamps (also [..]), with groups.")
  370. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  371. "Regular expression matching a time stamp range.")
  372. (defconst org-tr-regexp-both
  373. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  374. "Regular expression matching a time stamp range.")
  375. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  376. org-ts-regexp "\\)?")
  377. "Regular expression matching a time stamp or time stamp range.")
  378. (defconst org-tsr-regexp-both
  379. (concat org-ts-regexp-both "\\(--?-?"
  380. org-ts-regexp-both "\\)?")
  381. "Regular expression matching a time stamp or time stamp range.
  382. The time stamps may be either active or inactive.")
  383. (defconst org-repeat-re
  384. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  385. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  386. "Regular expression for specifying repeated events.
  387. After a match, group 1 contains the repeat expression.")
  388. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  389. "Formats for `format-time-string' which are used for time stamps.")
  390. ;;;; Clock and Planning
  391. (defconst org-clock-string "CLOCK:"
  392. "String used as prefix for timestamps clocking work hours on an item.")
  393. (defvar org-closed-string "CLOSED:"
  394. "String used as the prefix for timestamps logging closing a TODO entry.")
  395. (defvar org-deadline-string "DEADLINE:"
  396. "String to mark deadline entries.
  397. \\<org-mode-map>
  398. A deadline is this string, followed by a time stamp. It must be
  399. a word, terminated by a colon. You can insert a schedule keyword
  400. and a timestamp with `\\[org-deadline]'.")
  401. (defvar org-scheduled-string "SCHEDULED:"
  402. "String to mark scheduled TODO entries.
  403. \\<org-mode-map>
  404. A schedule is this string, followed by a time stamp. It must be
  405. a word, terminated by a colon. You can insert a schedule keyword
  406. and a timestamp with `\\[org-schedule]'.")
  407. (defconst org-ds-keyword-length
  408. (+ 2
  409. (apply #'max
  410. (mapcar #'length
  411. (list org-deadline-string org-scheduled-string
  412. org-clock-string org-closed-string))))
  413. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  414. (defconst org-planning-line-re
  415. (concat "^[ \t]*"
  416. (regexp-opt
  417. (list org-closed-string org-deadline-string org-scheduled-string)
  418. t))
  419. "Matches a line with planning info.
  420. Matched keyword is in group 1.")
  421. (defconst org-clock-line-re
  422. (concat "^[ \t]*" org-clock-string)
  423. "Matches a line with clock info.")
  424. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  425. "Matches the DEADLINE keyword.")
  426. (defconst org-deadline-time-regexp
  427. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  428. "Matches the DEADLINE keyword together with a time stamp.")
  429. (defconst org-deadline-time-hour-regexp
  430. (concat "\\<" org-deadline-string
  431. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  432. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  433. (defconst org-deadline-line-regexp
  434. (concat "\\<\\(" org-deadline-string "\\).*")
  435. "Matches the DEADLINE keyword and the rest of the line.")
  436. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  437. "Matches the SCHEDULED keyword.")
  438. (defconst org-scheduled-time-regexp
  439. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  440. "Matches the SCHEDULED keyword together with a time stamp.")
  441. (defconst org-scheduled-time-hour-regexp
  442. (concat "\\<" org-scheduled-string
  443. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  444. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  445. (defconst org-closed-time-regexp
  446. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  447. "Matches the CLOSED keyword together with a time stamp.")
  448. (defconst org-keyword-time-regexp
  449. (concat "\\<"
  450. (regexp-opt
  451. (list org-scheduled-string org-deadline-string org-closed-string
  452. org-clock-string)
  453. t)
  454. " *[[<]\\([^]>]+\\)[]>]")
  455. "Matches any of the 4 keywords, together with the time stamp.")
  456. (defconst org-keyword-time-not-clock-regexp
  457. (concat
  458. "\\<"
  459. (regexp-opt
  460. (list org-scheduled-string org-deadline-string org-closed-string) t)
  461. " *[[<]\\([^]>]+\\)[]>]")
  462. "Matches any of the 3 keywords, together with the time stamp.")
  463. (defconst org-all-time-keywords
  464. (mapcar (lambda (w) (substring w 0 -1))
  465. (list org-scheduled-string org-deadline-string
  466. org-clock-string org-closed-string))
  467. "List of time keywords.")
  468. ;;;; Drawer
  469. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  470. "Matches first or last line of a hidden block.
  471. Group 1 contains drawer's name or \"END\".")
  472. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  473. "Regular expression matching the first line of a property drawer.")
  474. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  475. "Regular expression matching the last line of a property drawer.")
  476. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  477. "Regular expression matching the first line of a clock drawer.")
  478. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  479. "Regular expression matching the last line of a clock drawer.")
  480. (defconst org-logbook-drawer-re
  481. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  482. (*? (0+ nonl) "\n")
  483. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  484. "Matches an entire LOGBOOK drawer.")
  485. (defconst org-property-drawer-re
  486. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  487. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  488. "[ \t]*:END:[ \t]*$")
  489. "Matches an entire property drawer.")
  490. (defconst org-clock-drawer-re
  491. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  492. org-clock-drawer-end-re "\\)\n?")
  493. "Matches an entire clock drawer.")
  494. ;;;; Headline
  495. (defconst org-heading-keyword-regexp-format
  496. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  497. "Printf format for a regexp matching a headline with some keyword.
  498. This regexp will match the headline of any node which has the
  499. exact keyword that is put into the format. The keyword isn't in
  500. any group by default, but the stars and the body are.")
  501. (defconst org-heading-keyword-maybe-regexp-format
  502. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  503. "Printf format for a regexp matching a headline, possibly with some keyword.
  504. This regexp can match any headline with the specified keyword, or
  505. without a keyword. The keyword isn't in any group by default,
  506. but the stars and the body are.")
  507. (defconst org-archive-tag "ARCHIVE"
  508. "The tag that marks a subtree as archived.
  509. An archived subtree does not open during visibility cycling, and does
  510. not contribute to the agenda listings.")
  511. (defconst org-tag-re "[[:alnum:]_@#%]+"
  512. "Regexp matching a single tag.")
  513. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  514. "Regexp matching the tag group at the end of a line, with leading spaces.
  515. Tags are stored in match group 1. Match group 2 stores the tags
  516. without the enclosing colons.")
  517. (defconst org-tag-line-re
  518. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  519. "Regexp matching tags in a headline.
  520. Tags are stored in match group 1. Match group 2 stores the tags
  521. without the enclosing colons.")
  522. (eval-and-compile
  523. (defconst org-comment-string "COMMENT"
  524. "Entries starting with this keyword will never be exported.
  525. \\<org-mode-map>
  526. An entry can be toggled between COMMENT and normal with
  527. `\\[org-toggle-comment]'."))
  528. ;;;; LaTeX Environments and Fragments
  529. (defconst org-latex-regexps
  530. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  531. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  532. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  533. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  534. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  535. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  536. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  537. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  538. "Regular expressions for matching embedded LaTeX.")
  539. ;;;; Node Property
  540. (defconst org-effort-property "Effort"
  541. "The property that is being used to keep track of effort estimates.
  542. Effort estimates given in this property need to be in the format
  543. defined in org-duration.el.")
  544. ;;; The custom variables
  545. (defgroup org nil
  546. "Outline-based notes management and organizer."
  547. :tag "Org"
  548. :group 'outlines
  549. :group 'calendar)
  550. (defcustom org-mode-hook nil
  551. "Mode hook for Org mode, run after the mode was turned on."
  552. :group 'org
  553. :type 'hook)
  554. (defcustom org-load-hook nil
  555. "Hook that is run after org.el has been loaded."
  556. :group 'org
  557. :type 'hook)
  558. (defcustom org-log-buffer-setup-hook nil
  559. "Hook that is run after an Org log buffer is created."
  560. :group 'org
  561. :version "24.1"
  562. :type 'hook)
  563. (defvar org-modules) ; defined below
  564. (defvar org-modules-loaded nil
  565. "Have the modules been loaded already?")
  566. (defun org-load-modules-maybe (&optional force)
  567. "Load all extensions listed in `org-modules'."
  568. (when (or force (not org-modules-loaded))
  569. (dolist (ext org-modules)
  570. (condition-case nil (require ext)
  571. (error (message "Problems while trying to load feature `%s'" ext))))
  572. (setq org-modules-loaded t)))
  573. (defun org-set-modules (var value)
  574. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  575. (set var value)
  576. (when (featurep 'org)
  577. (org-load-modules-maybe 'force)
  578. (org-element-cache-reset 'all)))
  579. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  580. "Modules that should always be loaded together with org.el.
  581. If a description starts with <C>, the file is not part of Emacs
  582. and loading it will require that you have downloaded and properly
  583. installed the Org mode distribution.
  584. You can also use this system to load external packages (i.e. neither Org
  585. core modules, nor modules from the CONTRIB directory). Just add symbols
  586. to the end of the list. If the package is called org-xyz.el, then you need
  587. to add the symbol `xyz', and the package must have a call to:
  588. (provide \\='org-xyz)
  589. For export specific modules, see also `org-export-backends'."
  590. :group 'org
  591. :set 'org-set-modules
  592. :version "26.1"
  593. :package-version '(Org . "9.2")
  594. :type
  595. '(set :greedy t
  596. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  597. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  598. (const :tag " crypt: Encryption of subtrees" org-crypt)
  599. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  600. (const :tag " docview: Links to Docview buffers" ol-docview)
  601. (const :tag " eww: Store link to URL of Eww" ol-eww)
  602. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  603. (const :tag " habit: Track your consistency with habits" org-habit)
  604. (const :tag " id: Global IDs for identifying entries" org-id)
  605. (const :tag " info: Links to Info nodes" ol-info)
  606. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  607. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  608. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  609. (const :tag " mouse: Additional mouse support" org-mouse)
  610. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  611. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  612. (const :tag " tempo: Fast completion for structures" org-tempo)
  613. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  614. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  615. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  616. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  617. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  618. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  619. (const :tag "C collector: Collect properties into tables" org-collector)
  620. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  621. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  622. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  623. (const :tag "C eval: Include command output as text" org-eval)
  624. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  625. (const :tag "C git-link: Links to specific file version" ol-git-link)
  626. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  627. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  628. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  629. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  630. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  631. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  632. (const :tag "C man: Links to man pages in Org mode" ol-man)
  633. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  634. (const :tag "C notify: Notifications for Org mode" org-notify)
  635. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  636. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  637. (const :tag "C registry: A registry for Org links" org-registry)
  638. (const :tag "C screen: Visit screen sessions through links" org-screen)
  639. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  640. (const :tag "C secretary: Team management with Org" org-secretary)
  641. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  642. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  643. (const :tag "C track: Keep up with Org mode development" org-track)
  644. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  645. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  646. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  647. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  648. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  649. (defvar org-export-registered-backends) ; From ox.el.
  650. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  651. (declare-function org-export-backend-name "ox" (backend) t)
  652. (defcustom org-export-backends '(ascii html icalendar latex odt)
  653. "List of export back-ends that should be always available.
  654. If a description starts with <C>, the file is not part of Emacs
  655. and loading it will require that you have downloaded and properly
  656. installed the Org mode distribution.
  657. Unlike to `org-modules', libraries in this list will not be
  658. loaded along with Org, but only once the export framework is
  659. needed.
  660. This variable needs to be set before org.el is loaded. If you
  661. need to make a change while Emacs is running, use the customize
  662. interface or run the following code, where VAL stands for the new
  663. value of the variable, after updating it:
  664. (progn
  665. (setq org-export-registered-backends
  666. (cl-remove-if-not
  667. (lambda (backend)
  668. (let ((name (org-export-backend-name backend)))
  669. (or (memq name val)
  670. (catch \\='parentp
  671. (dolist (b val)
  672. (and (org-export-derived-backend-p b name)
  673. (throw \\='parentp t)))))))
  674. org-export-registered-backends))
  675. (let ((new-list (mapcar #\\='org-export-backend-name
  676. org-export-registered-backends)))
  677. (dolist (backend val)
  678. (cond
  679. ((not (load (format \"ox-%s\" backend) t t))
  680. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  681. backend))
  682. ((not (memq backend new-list)) (push backend new-list))))
  683. (set-default \\='org-export-backends new-list)))
  684. Adding a back-end to this list will also pull the back-end it
  685. depends on, if any."
  686. :group 'org
  687. :group 'org-export
  688. :version "26.1"
  689. :package-version '(Org . "9.0")
  690. :initialize 'custom-initialize-set
  691. :set (lambda (var val)
  692. (if (not (featurep 'ox)) (set-default var val)
  693. ;; Any back-end not required anymore (not present in VAL and not
  694. ;; a parent of any back-end in the new value) is removed from the
  695. ;; list of registered back-ends.
  696. (setq org-export-registered-backends
  697. (cl-remove-if-not
  698. (lambda (backend)
  699. (let ((name (org-export-backend-name backend)))
  700. (or (memq name val)
  701. (catch 'parentp
  702. (dolist (b val)
  703. (and (org-export-derived-backend-p b name)
  704. (throw 'parentp t)))))))
  705. org-export-registered-backends))
  706. ;; Now build NEW-LIST of both new back-ends and required
  707. ;; parents.
  708. (let ((new-list (mapcar #'org-export-backend-name
  709. org-export-registered-backends)))
  710. (dolist (backend val)
  711. (cond
  712. ((not (load (format "ox-%s" backend) t t))
  713. (message "Problems while trying to load export back-end `%s'"
  714. backend))
  715. ((not (memq backend new-list)) (push backend new-list))))
  716. ;; Set VAR to that list with fixed dependencies.
  717. (set-default var new-list))))
  718. :type '(set :greedy t
  719. (const :tag " ascii Export buffer to ASCII format" ascii)
  720. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  721. (const :tag " html Export buffer to HTML format" html)
  722. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  723. (const :tag " latex Export buffer to LaTeX format" latex)
  724. (const :tag " man Export buffer to MAN format" man)
  725. (const :tag " md Export buffer to Markdown format" md)
  726. (const :tag " odt Export buffer to ODT format" odt)
  727. (const :tag " org Export buffer to Org format" org)
  728. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  729. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  730. (const :tag "C deck Export buffer to deck.js presentations" deck)
  731. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  732. (const :tag "C groff Export buffer to Groff format" groff)
  733. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  734. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  735. (const :tag "C s5 Export buffer to s5 presentations" s5)
  736. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  737. (eval-after-load 'ox
  738. '(dolist (backend org-export-backends)
  739. (condition-case nil (require (intern (format "ox-%s" backend)))
  740. (error (message "Problems while trying to load export back-end `%s'"
  741. backend)))))
  742. (defcustom org-support-shift-select nil
  743. "Non-nil means make shift-cursor commands select text when possible.
  744. \\<org-mode-map>
  745. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  746. start selecting a region, or enlarge regions started in this way.
  747. In Org mode, in special contexts, these same keys are used for
  748. other purposes, important enough to compete with shift selection.
  749. Org tries to balance these needs by supporting `shift-select-mode'
  750. outside these special contexts, under control of this variable.
  751. The default of this variable is nil, to avoid confusing behavior. Shifted
  752. cursor keys will then execute Org commands in the following contexts:
  753. - on a headline, changing TODO state (left/right) and priority (up/down)
  754. - on a time stamp, changing the time
  755. - in a plain list item, changing the bullet type
  756. - in a property definition line, switching between allowed values
  757. - in the BEGIN line of a clock table (changing the time block).
  758. - in a table, moving the cell in the specified direction.
  759. Outside these contexts, the commands will throw an error.
  760. When this variable is t and the cursor is not in a special
  761. context, Org mode will support shift-selection for making and
  762. enlarging regions. To make this more effective, the bullet
  763. cycling will no longer happen anywhere in an item line, but only
  764. if the cursor is exactly on the bullet.
  765. If you set this variable to the symbol `always', then the keys
  766. will not be special in headlines, property lines, item lines, and
  767. table cells, to make shift selection work there as well. If this is
  768. what you want, you can use the following alternative commands:
  769. `\\[org-todo]' and `\\[org-priority]' \
  770. to change TODO state and priority,
  771. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  772. can be used to switch TODO sets,
  773. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  774. and properties can be edited by hand or in column view.
  775. However, when the cursor is on a timestamp, shift-cursor commands
  776. will still edit the time stamp - this is just too good to give up."
  777. :group 'org
  778. :type '(choice
  779. (const :tag "Never" nil)
  780. (const :tag "When outside special context" t)
  781. (const :tag "Everywhere except timestamps" always)))
  782. (defcustom org-loop-over-headlines-in-active-region t
  783. "Shall some commands act upon headlines in the active region?
  784. When set to t, some commands will be performed in all headlines
  785. within the active region.
  786. When set to `start-level', some commands will be performed in all
  787. headlines within the active region, provided that these headlines
  788. are of the same level than the first one.
  789. When set to a string, those commands will be performed on the
  790. matching headlines within the active region. Such string must be
  791. a tags/property/todo match as it is used in the agenda tags view.
  792. The list of commands is: `org-schedule', `org-deadline',
  793. `org-todo', `org-set-tags-command', `org-archive-subtree',
  794. `org-archive-set-tag', `org-toggle-archive-tag' and
  795. `org-archive-to-archive-sibling'. The archiving commands skip
  796. already archived entries.
  797. See `org-agenda-loop-over-headlines-in-active-region' for the
  798. equivalent option for agenda views."
  799. :type '(choice (const :tag "Don't loop" nil)
  800. (const :tag "All headlines in active region" t)
  801. (const :tag "In active region, headlines at the same level than the first one" start-level)
  802. (string :tag "Tags/Property/Todo matcher"))
  803. :package-version '(Org . "9.4")
  804. :group 'org-todo
  805. :group 'org-archive)
  806. (defcustom org-startup-folded t
  807. "Non-nil means entering Org mode will switch to OVERVIEW.
  808. This can also be configured on a per-file basis by adding one of
  809. the following lines anywhere in the buffer:
  810. #+STARTUP: fold (or `overview', this is equivalent)
  811. #+STARTUP: nofold (or `showall', this is equivalent)
  812. #+STARTUP: content
  813. #+STARTUP: showeverything
  814. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  815. to ignore this option when Org opens agenda files for the first
  816. time."
  817. :group 'org-startup
  818. :type '(choice
  819. (const :tag "nofold: show all" nil)
  820. (const :tag "fold: overview" t)
  821. (const :tag "content: all headlines" content)
  822. (const :tag "show everything, even drawers" showeverything)))
  823. (defcustom org-startup-truncated t
  824. "Non-nil means entering Org mode will set `truncate-lines'.
  825. This is useful since some lines containing links can be very long and
  826. uninteresting. Also tables look terrible when wrapped.
  827. The variable `org-startup-truncated' allows to configure
  828. truncation for Org mode different to the other modes that use the
  829. variable `truncate-lines' and as a shortcut instead of putting
  830. the variable `truncate-lines' into the `org-mode-hook'. If one
  831. wants to configure truncation for Org mode not statically but
  832. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  833. the variable `truncate-lines' has to be used because in such a
  834. case it is too late to set the variable `org-startup-truncated'."
  835. :group 'org-startup
  836. :type 'boolean)
  837. (defcustom org-startup-indented nil
  838. "Non-nil means turn on `org-indent-mode' on startup.
  839. This can also be configured on a per-file basis by adding one of
  840. the following lines anywhere in the buffer:
  841. #+STARTUP: indent
  842. #+STARTUP: noindent"
  843. :group 'org-structure
  844. :type '(choice
  845. (const :tag "Not" nil)
  846. (const :tag "Globally (slow on startup in large files)" t)))
  847. (defcustom org-startup-numeroted nil
  848. "Non-nil means turn on `org-num-mode' on startup.
  849. This can also be configured on a per-file basis by adding one of
  850. the following lines anywhere in the buffer:
  851. #+STARTUP: num
  852. #+STARTUP: nonum"
  853. :group 'org-structure
  854. :package-version '(Org . "9.4")
  855. :type '(choice
  856. (const :tag "Not" nil)
  857. (const :tag "Globally" t)))
  858. (defcustom org-use-sub-superscripts t
  859. "Non-nil means interpret \"_\" and \"^\" for display.
  860. If you want to control how Org exports those characters, see
  861. `org-export-with-sub-superscripts'.
  862. When this option is turned on, you can use TeX-like syntax for
  863. sub- and superscripts within the buffer. Several characters after
  864. \"_\" or \"^\" will be considered as a single item - so grouping
  865. with {} is normally not needed. For example, the following things
  866. will be parsed as single sub- or superscripts:
  867. 10^24 or 10^tau several digits will be considered 1 item.
  868. 10^-12 or 10^-tau a leading sign with digits or a word
  869. x^2-y^3 will be read as x^2 - y^3, because items are
  870. terminated by almost any nonword/nondigit char.
  871. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  872. Still, ambiguity is possible. So when in doubt, use {} to enclose
  873. the sub/superscript. If you set this variable to the symbol `{}',
  874. the braces are *required* in order to trigger interpretations as
  875. sub/superscript. This can be helpful in documents that need \"_\"
  876. frequently in plain text."
  877. :group 'org-startup
  878. :version "24.4"
  879. :package-version '(Org . "8.0")
  880. :type '(choice
  881. (const :tag "Always interpret" t)
  882. (const :tag "Only with braces" {})
  883. (const :tag "Never interpret" nil)))
  884. (defcustom org-startup-with-beamer-mode nil
  885. "Non-nil means turn on `org-beamer-mode' on startup.
  886. This can also be configured on a per-file basis by adding one of
  887. the following lines anywhere in the buffer:
  888. #+STARTUP: beamer"
  889. :group 'org-startup
  890. :version "24.1"
  891. :type 'boolean)
  892. (defcustom org-startup-align-all-tables nil
  893. "Non-nil means align all tables when visiting a file.
  894. This can also be configured on a per-file basis by adding one of
  895. the following lines anywhere in the buffer:
  896. #+STARTUP: align
  897. #+STARTUP: noalign"
  898. :group 'org-startup
  899. :type 'boolean)
  900. (defcustom org-startup-shrink-all-tables nil
  901. "Non-nil means shrink all table columns with a width cookie.
  902. This can also be configured on a per-file basis by adding one of
  903. the following lines anywhere in the buffer:
  904. #+STARTUP: shrink"
  905. :group 'org-startup
  906. :type 'boolean
  907. :version "27.1"
  908. :package-version '(Org . "9.2")
  909. :safe #'booleanp)
  910. (defcustom org-startup-with-inline-images nil
  911. "Non-nil means show inline images when loading a new Org file.
  912. This can also be configured on a per-file basis by adding one of
  913. the following lines anywhere in the buffer:
  914. #+STARTUP: inlineimages
  915. #+STARTUP: noinlineimages"
  916. :group 'org-startup
  917. :version "24.1"
  918. :type 'boolean)
  919. (defcustom org-startup-with-latex-preview nil
  920. "Non-nil means preview LaTeX fragments when loading a new Org file.
  921. This can also be configured on a per-file basis by adding one of
  922. the following lines anywhere in the buffer:
  923. #+STARTUP: latexpreview
  924. #+STARTUP: nolatexpreview"
  925. :group 'org-startup
  926. :version "24.4"
  927. :package-version '(Org . "8.0")
  928. :type 'boolean)
  929. (defcustom org-insert-mode-line-in-empty-file nil
  930. "Non-nil means insert the first line setting Org mode in empty files.
  931. When the function `org-mode' is called interactively in an empty file, this
  932. normally means that the file name does not automatically trigger Org mode.
  933. To ensure that the file will always be in Org mode in the future, a
  934. line enforcing Org mode will be inserted into the buffer, if this option
  935. has been set."
  936. :group 'org-startup
  937. :type 'boolean)
  938. (defcustom org-ellipsis nil
  939. "The ellipsis to use in the Org mode outline.
  940. When nil, just use the standard three dots. When a non-empty string,
  941. use that string instead.
  942. The change affects only Org mode (which will then use its own display table).
  943. Changing this requires executing `\\[org-mode]' in a buffer to become
  944. effective. It cannot be set as a local variable."
  945. :group 'org-startup
  946. :type '(choice (const :tag "Default" nil)
  947. (string :tag "String" :value "...#")))
  948. (defvar org-display-table nil
  949. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  950. (defcustom org-directory "~/org"
  951. "Directory with Org files.
  952. This is just a default location to look for Org files. There is no need
  953. at all to put your files into this directory. It is used in the
  954. following situations:
  955. 1. When a capture template specifies a target file that is not an
  956. absolute path. The path will then be interpreted relative to
  957. `org-directory'
  958. 2. When the value of variable `org-agenda-files' is a single file, any
  959. relative paths in this file will be taken as relative to
  960. `org-directory'."
  961. :group 'org-refile
  962. :group 'org-capture
  963. :type 'directory)
  964. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  965. "Default target for storing notes.
  966. Used as a fall back file for org-capture.el, for templates that
  967. do not specify a target file."
  968. :group 'org-refile
  969. :group 'org-capture
  970. :type 'file)
  971. (defcustom org-reverse-note-order nil
  972. "Non-nil means store new notes at the beginning of a file or entry.
  973. When nil, new notes will be filed to the end of a file or entry.
  974. This can also be a list with cons cells of regular expressions that
  975. are matched against file names, and values."
  976. :group 'org-capture
  977. :group 'org-refile
  978. :type '(choice
  979. (const :tag "Reverse always" t)
  980. (const :tag "Reverse never" nil)
  981. (repeat :tag "By file name regexp"
  982. (cons regexp boolean))))
  983. (defgroup org-keywords nil
  984. "Keywords in Org mode."
  985. :tag "Org Keywords"
  986. :group 'org)
  987. (defcustom org-closed-keep-when-no-todo nil
  988. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  989. :group 'org-todo
  990. :group 'org-keywords
  991. :version "24.4"
  992. :package-version '(Org . "8.0")
  993. :type 'boolean)
  994. (defgroup org-structure nil
  995. "Options concerning the general structure of Org files."
  996. :tag "Org Structure"
  997. :group 'org)
  998. (defgroup org-reveal-location nil
  999. "Options about how to make context of a location visible."
  1000. :tag "Org Reveal Location"
  1001. :group 'org-structure)
  1002. (defcustom org-show-context-detail '((agenda . local)
  1003. (bookmark-jump . lineage)
  1004. (isearch . lineage)
  1005. (default . ancestors))
  1006. "Alist between context and visibility span when revealing a location.
  1007. \\<org-mode-map>Some actions may move point into invisible
  1008. locations. As a consequence, Org always expose a neighborhood
  1009. around point. How much is shown depends on the initial action,
  1010. or context. Valid contexts are
  1011. agenda when exposing an entry from the agenda
  1012. org-goto when using the command `org-goto' (`\\[org-goto]')
  1013. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1014. tags-tree when constructing a sparse tree based on tags matches
  1015. link-search when exposing search matches associated with a link
  1016. mark-goto when exposing the jump goal of a mark
  1017. bookmark-jump when exposing a bookmark location
  1018. isearch when exiting from an incremental search
  1019. default default for all contexts not set explicitly
  1020. Allowed visibility spans are
  1021. minimal show current headline; if point is not on headline,
  1022. also show entry
  1023. local show current headline, entry and next headline
  1024. ancestors show current headline and its direct ancestors; if
  1025. point is not on headline, also show entry
  1026. lineage show current headline, its direct ancestors and all
  1027. their children; if point is not on headline, also show
  1028. entry and first child
  1029. tree show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and all children
  1032. canonical show current headline, its direct ancestors along with
  1033. their entries and children; if point is not located on
  1034. the headline, also show current entry and all children
  1035. As special cases, a nil or t value means show all contexts in
  1036. `minimal' or `canonical' view, respectively.
  1037. Some views can make displayed information very compact, but also
  1038. make it harder to edit the location of the match. In such
  1039. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1040. more context."
  1041. :group 'org-reveal-location
  1042. :version "26.1"
  1043. :package-version '(Org . "9.0")
  1044. :type '(choice
  1045. (const :tag "Canonical" t)
  1046. (const :tag "Minimal" nil)
  1047. (repeat :greedy t :tag "Individual contexts"
  1048. (cons
  1049. (choice :tag "Context"
  1050. (const agenda)
  1051. (const org-goto)
  1052. (const occur-tree)
  1053. (const tags-tree)
  1054. (const link-search)
  1055. (const mark-goto)
  1056. (const bookmark-jump)
  1057. (const isearch)
  1058. (const default))
  1059. (choice :tag "Detail level"
  1060. (const minimal)
  1061. (const local)
  1062. (const ancestors)
  1063. (const lineage)
  1064. (const tree)
  1065. (const canonical))))))
  1066. (defcustom org-indirect-buffer-display 'other-window
  1067. "How should indirect tree buffers be displayed?
  1068. This applies to indirect buffers created with the commands
  1069. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1070. Valid values are:
  1071. current-window Display in the current window
  1072. other-window Just display in another window.
  1073. dedicated-frame Create one new frame, and re-use it each time.
  1074. new-frame Make a new frame each time. Note that in this case
  1075. previously-made indirect buffers are kept, and you need to
  1076. kill these buffers yourself."
  1077. :group 'org-structure
  1078. :group 'org-agenda-windows
  1079. :type '(choice
  1080. (const :tag "In current window" current-window)
  1081. (const :tag "In current frame, other window" other-window)
  1082. (const :tag "Each time a new frame" new-frame)
  1083. (const :tag "One dedicated frame" dedicated-frame)))
  1084. (defconst org-file-apps-gnu
  1085. '((remote . emacs)
  1086. (system . mailcap)
  1087. (t . mailcap))
  1088. "Default file applications on a UNIX or GNU/Linux system.
  1089. See `org-file-apps'.")
  1090. (defconst org-file-apps-macos
  1091. '((remote . emacs)
  1092. (system . "open %s")
  1093. ("ps.gz" . "gv %s")
  1094. ("eps.gz" . "gv %s")
  1095. ("dvi" . "xdvi %s")
  1096. ("fig" . "xfig %s")
  1097. (t . "open %s"))
  1098. "Default file applications on a macOS system.
  1099. The system \"open\" is known as a default, but we use X11 applications
  1100. for some files for which the OS does not have a good default.
  1101. See `org-file-apps'.")
  1102. (defconst org-file-apps-windowsnt
  1103. (list '(remote . emacs)
  1104. (cons 'system (lambda (file _path)
  1105. (with-no-warnings (w32-shell-execute "open" file))))
  1106. (cons t (lambda (file _path)
  1107. (with-no-warnings (w32-shell-execute "open" file)))))
  1108. "Default file applications on a Windows NT system.
  1109. The system \"open\" is used for most files.
  1110. See `org-file-apps'.")
  1111. (defcustom org-file-apps
  1112. '((auto-mode . emacs)
  1113. (directory . emacs)
  1114. ("\\.mm\\'" . default)
  1115. ("\\.x?html?\\'" . default)
  1116. ("\\.pdf\\'" . default))
  1117. "Applications for opening `file:path' items in a document.
  1118. \\<org-mode-map>
  1119. Org mode uses system defaults for different file types, but you
  1120. can use this variable to set the application for a given file
  1121. extension. The entries in this list are cons cells where the car
  1122. identifies files and the cdr the corresponding command.
  1123. Possible values for the file identifier are:
  1124. \"string\" A string as a file identifier can be interpreted in different
  1125. ways, depending on its contents:
  1126. - Alphanumeric characters only:
  1127. Match links with this file extension.
  1128. Example: (\"pdf\" . \"evince %s\")
  1129. to open PDFs with evince.
  1130. - Regular expression: Match links where the
  1131. filename matches the regexp. If you want to
  1132. use groups here, use shy groups.
  1133. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1134. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1135. to open *.html and *.xhtml with firefox.
  1136. - Regular expression which contains (non-shy) groups:
  1137. Match links where the whole link, including \"::\", and
  1138. anything after that, matches the regexp.
  1139. In a custom command string, %1, %2, etc. are replaced with
  1140. the parts of the link that were matched by the groups.
  1141. For backwards compatibility, if a command string is given
  1142. that does not use any of the group matches, this case is
  1143. handled identically to the second one (i.e. match against
  1144. file name only).
  1145. In a custom function, you can access the group matches with
  1146. (match-string n link).
  1147. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1148. \"evince -p %1 %s\")
  1149. to open [[file:document.pdf::5]] with evince at page 5.
  1150. `directory' Matches a directory
  1151. `remote' Matches a remote file, accessible through tramp or efs.
  1152. Remote files most likely should be visited through Emacs
  1153. because external applications cannot handle such paths.
  1154. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1155. so all files Emacs knows how to handle. Using this with
  1156. command `emacs' will open most files in Emacs. Beware that this
  1157. will also open html files inside Emacs, unless you add
  1158. (\"html\" . default) to the list as well.
  1159. `system' The system command to open files, like `open' on Windows
  1160. and macOS, and mailcap under GNU/Linux. This is the command
  1161. that will be selected if you call `org-open-at-point' with a
  1162. double prefix argument (`\\[universal-argument] \
  1163. \\[universal-argument] \\[org-open-at-point]').
  1164. t Default for files not matched by any of the other options.
  1165. Possible values for the command are:
  1166. `emacs' The file will be visited by the current Emacs process.
  1167. `default' Use the default application for this file type, which is the
  1168. association for t in the list, most likely in the system-specific
  1169. part. This can be used to overrule an unwanted setting in the
  1170. system-specific variable.
  1171. `system' Use the system command for opening files, like \"open\".
  1172. This command is specified by the entry whose car is `system'.
  1173. Most likely, the system-specific version of this variable
  1174. does define this command, but you can overrule/replace it
  1175. here.
  1176. `mailcap' Use command specified in the mailcaps.
  1177. string A command to be executed by a shell; %s will be replaced
  1178. by the path to the file.
  1179. function A Lisp function, which will be called with two arguments:
  1180. the file path and the original link string, without the
  1181. \"file:\" prefix.
  1182. For more examples, see the system specific constants
  1183. `org-file-apps-macos'
  1184. `org-file-apps-windowsnt'
  1185. `org-file-apps-gnu'."
  1186. :group 'org
  1187. :package-version '(Org . "9.4")
  1188. :type '(repeat
  1189. (cons (choice :value ""
  1190. (string :tag "Extension")
  1191. (const :tag "System command to open files" system)
  1192. (const :tag "Default for unrecognized files" t)
  1193. (const :tag "Remote file" remote)
  1194. (const :tag "Links to a directory" directory)
  1195. (const :tag "Any files that have Emacs modes"
  1196. auto-mode))
  1197. (choice :value ""
  1198. (const :tag "Visit with Emacs" emacs)
  1199. (const :tag "Use default" default)
  1200. (const :tag "Use the system command" system)
  1201. (string :tag "Command")
  1202. (function :tag "Function")))))
  1203. (defcustom org-open-non-existing-files nil
  1204. "Non-nil means `org-open-file' opens non-existing files.
  1205. When nil, an error is thrown.
  1206. This variable applies only to external applications because they
  1207. might choke on non-existing files. If the link is to a file that
  1208. will be opened in Emacs, the variable is ignored."
  1209. :group 'org
  1210. :type 'boolean
  1211. :safe #'booleanp)
  1212. (defcustom org-open-directory-means-index-dot-org nil
  1213. "When non-nil a link to a directory really means to \"index.org\".
  1214. When nil, following a directory link runs Dired or opens
  1215. a finder/explorer window on that directory."
  1216. :group 'org
  1217. :type 'boolean
  1218. :safe #'booleanp)
  1219. (defcustom org-bookmark-names-plist
  1220. '(:last-capture "org-capture-last-stored"
  1221. :last-refile "org-refile-last-stored"
  1222. :last-capture-marker "org-capture-last-stored-marker")
  1223. "Names for bookmarks automatically set by some Org commands.
  1224. This can provide strings as names for a number of bookmarks Org sets
  1225. automatically. The following keys are currently implemented:
  1226. :last-capture
  1227. :last-capture-marker
  1228. :last-refile
  1229. When a key does not show up in the property list, the corresponding bookmark
  1230. is not set."
  1231. :group 'org-structure
  1232. :type 'plist)
  1233. (defgroup org-cycle nil
  1234. "Options concerning visibility cycling in Org mode."
  1235. :tag "Org Cycle"
  1236. :group 'org-structure)
  1237. (defcustom org-cycle-skip-children-state-if-no-children t
  1238. "Non-nil means skip CHILDREN state in entries that don't have any."
  1239. :group 'org-cycle
  1240. :type 'boolean)
  1241. (defcustom org-cycle-max-level nil
  1242. "Maximum level which should still be subject to visibility cycling.
  1243. Levels higher than this will, for cycling, be treated as text, not a headline.
  1244. When `org-odd-levels-only' is set, a value of N in this variable actually
  1245. means 2N-1 stars as the limiting headline.
  1246. When nil, cycle all levels.
  1247. Note that the limiting level of cycling is also influenced by
  1248. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1249. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1250. than its value."
  1251. :group 'org-cycle
  1252. :type '(choice
  1253. (const :tag "No limit" nil)
  1254. (integer :tag "Maximum level")))
  1255. (defcustom org-hide-block-startup nil
  1256. "Non-nil means entering Org mode will fold all blocks.
  1257. This can also be set in on a per-file basis with
  1258. #+STARTUP: hideblocks
  1259. #+STARTUP: showblocks"
  1260. :group 'org-startup
  1261. :group 'org-cycle
  1262. :type 'boolean)
  1263. (defcustom org-cycle-global-at-bob nil
  1264. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1265. This makes it possible to do global cycling without having to use `S-TAB'
  1266. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1267. line of the buffer
  1268. must not be a headline -- it may be empty or some other text.
  1269. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1270. sure the cursor stays at the beginning of the buffer.
  1271. When this option is nil, don't do anything special at the beginning of
  1272. the buffer."
  1273. :group 'org-cycle
  1274. :type 'boolean)
  1275. (defcustom org-cycle-level-after-item/entry-creation t
  1276. "Non-nil means cycle entry level or item indentation in new empty entries.
  1277. When the cursor is at the end of an empty headline, i.e., with only stars
  1278. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1279. and then all possible ancestor states, before returning to the original state.
  1280. This makes data entry extremely fast: M-RET to create a new headline,
  1281. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1282. When the cursor is at the end of an empty plain list item, one TAB will
  1283. make it a subitem, two or more tabs will back up to make this an item
  1284. higher up in the item hierarchy."
  1285. :group 'org-cycle
  1286. :type 'boolean)
  1287. (defcustom org-cycle-emulate-tab t
  1288. "Where should `org-cycle' emulate TAB.
  1289. nil Never
  1290. white Only in completely white lines
  1291. whitestart Only at the beginning of lines, before the first non-white char
  1292. t Everywhere except in headlines
  1293. exc-hl-bol Everywhere except at the start of a headline
  1294. If TAB is used in a place where it does not emulate TAB, the current subtree
  1295. visibility is cycled."
  1296. :group 'org-cycle
  1297. :type '(choice (const :tag "Never" nil)
  1298. (const :tag "Only in completely white lines" white)
  1299. (const :tag "Before first char in a line" whitestart)
  1300. (const :tag "Everywhere except in headlines" t)
  1301. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1302. (defcustom org-cycle-separator-lines 2
  1303. "Number of empty lines needed to keep an empty line between collapsed trees.
  1304. If you leave an empty line between the end of a subtree and the following
  1305. headline, this empty line is hidden when the subtree is folded.
  1306. Org mode will leave (exactly) one empty line visible if the number of
  1307. empty lines is equal or larger to the number given in this variable.
  1308. So the default 2 means at least 2 empty lines after the end of a subtree
  1309. are needed to produce free space between a collapsed subtree and the
  1310. following headline.
  1311. If the number is negative, and the number of empty lines is at least -N,
  1312. all empty lines are shown.
  1313. Special case: when 0, never leave empty lines in collapsed view."
  1314. :group 'org-cycle
  1315. :type 'integer)
  1316. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1317. (defcustom org-pre-cycle-hook nil
  1318. "Hook that is run before visibility cycling is happening.
  1319. The function(s) in this hook must accept a single argument which indicates
  1320. the new state that will be set right after running this hook. The
  1321. argument is a symbol. Before a global state change, it can have the values
  1322. `overview', `content', or `all'. Before a local state change, it can have
  1323. the values `folded', `children', or `subtree'."
  1324. :group 'org-cycle
  1325. :type 'hook)
  1326. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1327. org-cycle-show-empty-lines
  1328. org-optimize-window-after-visibility-change)
  1329. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1330. The function(s) in this hook must accept a single argument which indicates
  1331. the new state that was set by the most recent `org-cycle' command. The
  1332. argument is a symbol. After a global state change, it can have the values
  1333. `overview', `contents', or `all'. After a local state change, it can have
  1334. the values `folded', `children', or `subtree'."
  1335. :group 'org-cycle
  1336. :type 'hook
  1337. :version "26.1"
  1338. :package-version '(Org . "8.3"))
  1339. (defgroup org-edit-structure nil
  1340. "Options concerning structure editing in Org mode."
  1341. :tag "Org Edit Structure"
  1342. :group 'org-structure)
  1343. (defcustom org-odd-levels-only nil
  1344. "Non-nil means skip even levels and only use odd levels for the outline.
  1345. This has the effect that two stars are being added/taken away in
  1346. promotion/demotion commands. It also influences how levels are
  1347. handled by the exporters.
  1348. Changing it requires restart of `font-lock-mode' to become effective
  1349. for fontification also in regions already fontified.
  1350. You may also set this on a per-file basis by adding one of the following
  1351. lines to the buffer:
  1352. #+STARTUP: odd
  1353. #+STARTUP: oddeven"
  1354. :group 'org-edit-structure
  1355. :group 'org-appearance
  1356. :type 'boolean)
  1357. (defcustom org-adapt-indentation t
  1358. "Non-nil means adapt indentation to outline node level.
  1359. When this variable is set to t, Org assumes that you write
  1360. outlines by indenting text in each node to align with the
  1361. headline (after the stars).
  1362. When this variable is set to 'headline-data, only adapt the
  1363. indentation of the data lines right below the headline, such as
  1364. planning/clock lines and property/logbook drawers.
  1365. The following issues are influenced by this variable:
  1366. - The indentation is increased by one space in a demotion
  1367. command, and decreased by one in a promotion command. However,
  1368. in the latter case, if shifting some line in the entry body
  1369. would alter document structure (e.g., insert a new headline),
  1370. indentation is not changed at all.
  1371. - Property drawers and planning information is inserted indented
  1372. when this variable is set. When nil, they will not be indented.
  1373. - TAB indents a line relative to current level. The lines below
  1374. a headline will be indented when this variable is set to t.
  1375. Note that this is all about true indentation, by adding and
  1376. removing space characters. See also \"org-indent.el\" which does
  1377. level-dependent indentation in a virtual way, i.e. at display
  1378. time in Emacs."
  1379. :group 'org-edit-structure
  1380. :type '(choice
  1381. (const :tag "Adapt indentation for all lines" t)
  1382. (const :tag "Adapt indentation for headline data lines"
  1383. 'headline-data)
  1384. (const :tag "Do not adapt indentation at all" nil))
  1385. :safe #'booleanp)
  1386. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1387. (defcustom org-special-ctrl-a/e nil
  1388. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1389. When t, `C-a' will bring back the cursor to the beginning of the
  1390. headline text, i.e. after the stars and after a possible TODO
  1391. keyword. In an item, this will be the position after bullet and
  1392. check-box, if any. When the cursor is already at that position,
  1393. another `C-a' will bring it to the beginning of the line.
  1394. `C-e' will jump to the end of the headline, ignoring the presence
  1395. of tags in the headline. A second `C-e' will then jump to the
  1396. true end of the line, after any tags. This also means that, when
  1397. this variable is non-nil, `C-e' also will never jump beyond the
  1398. end of the heading of a folded section, i.e. not after the
  1399. ellipses.
  1400. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1401. normally, going to the true line boundary first. Only a directly
  1402. following, identical keypress will bring the cursor to the
  1403. special positions.
  1404. This may also be a cons cell where the behavior for `C-a' and
  1405. `C-e' is set separately."
  1406. :group 'org-edit-structure
  1407. :type '(choice
  1408. (const :tag "off" nil)
  1409. (const :tag "on: after stars/bullet and before tags first" t)
  1410. (const :tag "reversed: true line boundary first" reversed)
  1411. (cons :tag "Set C-a and C-e separately"
  1412. (choice :tag "Special C-a"
  1413. (const :tag "off" nil)
  1414. (const :tag "on: after stars/bullet first" t)
  1415. (const :tag "reversed: before stars/bullet first" reversed))
  1416. (choice :tag "Special C-e"
  1417. (const :tag "off" nil)
  1418. (const :tag "on: before tags first" t)
  1419. (const :tag "reversed: after tags first" reversed)))))
  1420. (defcustom org-special-ctrl-k nil
  1421. "Non-nil means `C-k' will behave specially in headlines.
  1422. When nil, `C-k' will call the default `kill-line' command.
  1423. When t, the following will happen while the cursor is in the headline:
  1424. - When at the beginning of a headline, kill the entire subtree.
  1425. - When in the middle of the headline text, kill the text up to the tags.
  1426. - When after the headline text and before the tags, kill all the tags."
  1427. :group 'org-edit-structure
  1428. :type 'boolean)
  1429. (defcustom org-ctrl-k-protect-subtree nil
  1430. "Non-nil means, do not delete a hidden subtree with C-k.
  1431. When set to the symbol `error', simply throw an error when C-k is
  1432. used to kill (part-of) a headline that has hidden text behind it.
  1433. Any other non-nil value will result in a query to the user, if it is
  1434. OK to kill that hidden subtree. When nil, kill without remorse."
  1435. :group 'org-edit-structure
  1436. :version "24.1"
  1437. :type '(choice
  1438. (const :tag "Do not protect hidden subtrees" nil)
  1439. (const :tag "Protect hidden subtrees with a security query" t)
  1440. (const :tag "Never kill a hidden subtree with C-k" error)))
  1441. (defcustom org-special-ctrl-o t
  1442. "Non-nil means, make `C-o' insert a row in tables."
  1443. :group 'org-edit-structure
  1444. :type 'boolean)
  1445. (defcustom org-catch-invisible-edits nil
  1446. "Check if in invisible region before inserting or deleting a character.
  1447. Valid values are:
  1448. nil Do not check, so just do invisible edits.
  1449. error Throw an error and do nothing.
  1450. show Make point visible, and do the requested edit.
  1451. show-and-error Make point visible, then throw an error and abort the edit.
  1452. smart Make point visible, and do insertion/deletion if it is
  1453. adjacent to visible text and the change feels predictable.
  1454. Never delete a previously invisible character or add in the
  1455. middle or right after an invisible region. Basically, this
  1456. allows insertion and backward-delete right before ellipses.
  1457. FIXME: maybe in this case we should not even show?"
  1458. :group 'org-edit-structure
  1459. :version "24.1"
  1460. :type '(choice
  1461. (const :tag "Do not check" nil)
  1462. (const :tag "Throw error when trying to edit" error)
  1463. (const :tag "Unhide, but do not do the edit" show-and-error)
  1464. (const :tag "Show invisible part and do the edit" show)
  1465. (const :tag "Be smart and do the right thing" smart)))
  1466. (defcustom org-yank-folded-subtrees t
  1467. "Non-nil means when yanking subtrees, fold them.
  1468. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1469. it starts with a heading and all other headings in it are either children
  1470. or siblings, then fold all the subtrees. However, do this only if no
  1471. text after the yank would be swallowed into a folded tree by this action."
  1472. :group 'org-edit-structure
  1473. :type 'boolean)
  1474. (defcustom org-yank-adjusted-subtrees nil
  1475. "Non-nil means when yanking subtrees, adjust the level.
  1476. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1477. this function for details."
  1478. :group 'org-edit-structure
  1479. :type 'boolean)
  1480. (defcustom org-M-RET-may-split-line '((default . t))
  1481. "Non-nil means M-RET will split the line at the cursor position.
  1482. When nil, it will go to the end of the line before making a
  1483. new line.
  1484. You may also set this option in a different way for different
  1485. contexts. Valid contexts are:
  1486. headline when creating a new headline
  1487. item when creating a new item
  1488. table in a table field
  1489. default the value to be used for all contexts not explicitly
  1490. customized"
  1491. :group 'org-structure
  1492. :group 'org-table
  1493. :type '(choice
  1494. (const :tag "Always" t)
  1495. (const :tag "Never" nil)
  1496. (repeat :greedy t :tag "Individual contexts"
  1497. (cons
  1498. (choice :tag "Context"
  1499. (const headline)
  1500. (const item)
  1501. (const table)
  1502. (const default))
  1503. (boolean)))))
  1504. (defcustom org-insert-heading-respect-content nil
  1505. "Non-nil means insert new headings after the current subtree.
  1506. \\<org-mode-map>
  1507. When nil, the new heading is created directly after the current line.
  1508. The commands `\\[org-insert-heading-respect-content]' and \
  1509. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1510. for the duration of the command."
  1511. :group 'org-structure
  1512. :type 'boolean)
  1513. (defcustom org-blank-before-new-entry '((heading . auto)
  1514. (plain-list-item . auto))
  1515. "Should `org-insert-heading' leave a blank line before new heading/item?
  1516. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1517. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1518. which case Org will look at the surrounding headings/items and try to
  1519. make an intelligent decision whether to insert a blank line or not."
  1520. :group 'org-edit-structure
  1521. :type '(list
  1522. (cons (const heading)
  1523. (choice (const :tag "Never" nil)
  1524. (const :tag "Always" t)
  1525. (const :tag "Auto" auto)))
  1526. (cons (const plain-list-item)
  1527. (choice (const :tag "Never" nil)
  1528. (const :tag "Always" t)
  1529. (const :tag "Auto" auto)))))
  1530. (defcustom org-insert-heading-hook nil
  1531. "Hook being run after inserting a new heading."
  1532. :group 'org-edit-structure
  1533. :type 'hook)
  1534. (defgroup org-sparse-trees nil
  1535. "Options concerning sparse trees in Org mode."
  1536. :tag "Org Sparse Trees"
  1537. :group 'org-structure)
  1538. (defcustom org-highlight-sparse-tree-matches t
  1539. "Non-nil means highlight all matches that define a sparse tree.
  1540. The highlights will automatically disappear the next time the buffer is
  1541. changed by an edit command."
  1542. :group 'org-sparse-trees
  1543. :type 'boolean)
  1544. (defcustom org-remove-highlights-with-change t
  1545. "Non-nil means any change to the buffer will remove temporary highlights.
  1546. \\<org-mode-map>\
  1547. Such highlights are created by `org-occur' and `org-clock-display'.
  1548. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1549. to get rid of the highlights.
  1550. The highlights created by `org-latex-preview' always need
  1551. `\\[org-latex-preview]' to be removed."
  1552. :group 'org-sparse-trees
  1553. :group 'org-time
  1554. :type 'boolean)
  1555. (defcustom org-occur-case-fold-search t
  1556. "Non-nil means `org-occur' should be case-insensitive.
  1557. If set to `smart' the search will be case-insensitive only if it
  1558. doesn't specify any upper case character."
  1559. :group 'org-sparse-trees
  1560. :version "26.1"
  1561. :type '(choice
  1562. (const :tag "Case-sensitive" nil)
  1563. (const :tag "Case-insensitive" t)
  1564. (const :tag "Case-insensitive for lower case searches only" smart)))
  1565. (defcustom org-occur-hook '(org-first-headline-recenter)
  1566. "Hook that is run after `org-occur' has constructed a sparse tree.
  1567. This can be used to recenter the window to show as much of the structure
  1568. as possible."
  1569. :group 'org-sparse-trees
  1570. :type 'hook)
  1571. (defcustom org-self-insert-cluster-for-undo nil
  1572. "Non-nil means cluster self-insert commands for undo when possible.
  1573. If this is set, then, like in the Emacs command loop, 20 consecutive
  1574. characters will be undone together.
  1575. This is configurable, because there is some impact on typing performance."
  1576. :group 'org-table
  1577. :type 'boolean)
  1578. (defvaralias 'org-activate-links 'org-highlight-links)
  1579. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1580. "Types of links that should be highlighted in Org files.
  1581. This is a list of symbols, each one of them leading to the
  1582. highlighting of a certain link type.
  1583. You can still open links that are not highlighted.
  1584. In principle, it does not hurt to turn on highlighting for all
  1585. link types. There may be a small gain when turning off unused
  1586. link types. The types are:
  1587. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1588. angle Links in angular brackets that may contain whitespace like
  1589. <bbdb:Carsten Dominik>.
  1590. plain Plain links in normal text, no whitespace, like http://google.com.
  1591. radio Text that is matched by a radio target, see manual for details.
  1592. tag Tag settings in a headline (link to tag search).
  1593. date Time stamps (link to calendar).
  1594. footnote Footnote labels.
  1595. If you set this variable during an Emacs session, use `org-mode-restart'
  1596. in the Org buffer so that the change takes effect."
  1597. :group 'org-appearance
  1598. :type '(set :greedy t
  1599. (const :tag "Double bracket links" bracket)
  1600. (const :tag "Angular bracket links" angle)
  1601. (const :tag "Plain text links" plain)
  1602. (const :tag "Radio target matches" radio)
  1603. (const :tag "Tags" tag)
  1604. (const :tag "Timestamps" date)
  1605. (const :tag "Footnotes" footnote)))
  1606. (defcustom org-mark-ring-length 4
  1607. "Number of different positions to be recorded in the ring.
  1608. Changing this requires a restart of Emacs to work correctly."
  1609. :group 'org-link-follow
  1610. :type 'integer)
  1611. (defgroup org-todo nil
  1612. "Options concerning TODO items in Org mode."
  1613. :tag "Org TODO"
  1614. :group 'org)
  1615. (defgroup org-progress nil
  1616. "Options concerning Progress logging in Org mode."
  1617. :tag "Org Progress"
  1618. :group 'org-time)
  1619. (defvar org-todo-interpretation-widgets
  1620. '((:tag "Sequence (cycling hits every state)" sequence)
  1621. (:tag "Type (cycling directly to DONE)" type))
  1622. "The available interpretation symbols for customizing `org-todo-keywords'.
  1623. Interested libraries should add to this list.")
  1624. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1625. "List of TODO entry keyword sequences and their interpretation.
  1626. \\<org-mode-map>This is a list of sequences.
  1627. Each sequence starts with a symbol, either `sequence' or `type',
  1628. indicating if the keywords should be interpreted as a sequence of
  1629. action steps, or as different types of TODO items. The first
  1630. keywords are states requiring action - these states will select a headline
  1631. for inclusion into the global TODO list Org produces. If one of the
  1632. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1633. signify that no further action is necessary. If \"|\" is not found,
  1634. the last keyword is treated as the only DONE state of the sequence.
  1635. The command `\\[org-todo]' cycles an entry through these states, and one
  1636. additional state where no keyword is present. For details about this
  1637. cycling, see the manual.
  1638. TODO keywords and interpretation can also be set on a per-file basis with
  1639. the special #+SEQ_TODO and #+TYP_TODO lines.
  1640. Each keyword can optionally specify a character for fast state selection
  1641. \(in combination with the variable `org-use-fast-todo-selection')
  1642. and specifiers for state change logging, using the same syntax that
  1643. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1644. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1645. indicates to record a time stamp each time this state is selected.
  1646. Each keyword may also specify if a timestamp or a note should be
  1647. recorded when entering or leaving the state, by adding additional
  1648. characters in the parenthesis after the keyword. This looks like this:
  1649. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1650. record only the time of the state change. With X and Y being either
  1651. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1652. Y when leaving the state if and only if the *target* state does not
  1653. define X. You may omit any of the fast-selection key or X or /Y,
  1654. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1655. For backward compatibility, this variable may also be just a list
  1656. of keywords. In this case the interpretation (sequence or type) will be
  1657. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1658. :group 'org-todo
  1659. :group 'org-keywords
  1660. :type '(choice
  1661. (repeat :tag "Old syntax, just keywords"
  1662. (string :tag "Keyword"))
  1663. (repeat :tag "New syntax"
  1664. (cons
  1665. (choice
  1666. :tag "Interpretation"
  1667. ;;Quick and dirty way to see
  1668. ;;`org-todo-interpretations'. This takes the
  1669. ;;place of item arguments
  1670. :convert-widget
  1671. (lambda (widget)
  1672. (widget-put widget
  1673. :args (mapcar
  1674. (lambda (x)
  1675. (widget-convert
  1676. (cons 'const x)))
  1677. org-todo-interpretation-widgets))
  1678. widget))
  1679. (repeat
  1680. (string :tag "Keyword"))))))
  1681. (defvar-local org-todo-keywords-1 nil
  1682. "All TODO and DONE keywords active in a buffer.")
  1683. (defvar org-todo-keywords-for-agenda nil)
  1684. (defvar org-done-keywords-for-agenda nil)
  1685. (defvar org-todo-keyword-alist-for-agenda nil)
  1686. (defvar org-tag-alist-for-agenda nil
  1687. "Alist of all tags from all agenda files.")
  1688. (defvar org-tag-groups-alist-for-agenda nil
  1689. "Alist of all groups tags from all current agenda files.")
  1690. (defvar-local org-tag-groups-alist nil)
  1691. (defvar org-agenda-contributing-files nil)
  1692. (defvar-local org-current-tag-alist nil
  1693. "Alist of all tag groups in current buffer.
  1694. This variable takes into consideration `org-tag-alist',
  1695. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1696. (defvar-local org-not-done-keywords nil)
  1697. (defvar-local org-done-keywords nil)
  1698. (defvar-local org-todo-heads nil)
  1699. (defvar-local org-todo-sets nil)
  1700. (defvar-local org-todo-log-states nil)
  1701. (defvar-local org-todo-kwd-alist nil)
  1702. (defvar-local org-todo-key-alist nil)
  1703. (defvar-local org-todo-key-trigger nil)
  1704. (defcustom org-todo-interpretation 'sequence
  1705. "Controls how TODO keywords are interpreted.
  1706. This variable is in principle obsolete and is only used for
  1707. backward compatibility, if the interpretation of todo keywords is
  1708. not given already in `org-todo-keywords'. See that variable for
  1709. more information."
  1710. :group 'org-todo
  1711. :group 'org-keywords
  1712. :type '(choice (const sequence)
  1713. (const type)))
  1714. (defcustom org-use-fast-todo-selection 'auto
  1715. "\\<org-mode-map>\
  1716. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1717. This variable describes if and under what circumstances the cycling
  1718. mechanism for TODO keywords will be replaced by a single-key, direct
  1719. selection scheme, where the choices are displayed in a little window.
  1720. When nil, fast selection is never used. This means that the command
  1721. will always switch to the next state.
  1722. When it is the symbol `auto', fast selection is whenever selection
  1723. keys have been defined.
  1724. `expert' is like `auto', but no special window with the keyword
  1725. will be shown, choices will only be listed in the prompt.
  1726. In all cases, the special interface is only used if access keys have
  1727. actually been assigned by the user, i.e. if keywords in the configuration
  1728. are followed by a letter in parenthesis, like TODO(t)."
  1729. :group 'org-todo
  1730. :set (lambda (var val)
  1731. (cond
  1732. ((eq var t) (set var 'auto))
  1733. ((eq var 'prefix) (set var nil))
  1734. (t (set var val))))
  1735. :type '(choice
  1736. (const :tag "Never" nil)
  1737. (const :tag "Automatically, when key letter have been defined" auto)
  1738. (const :tag "Automatically, but don't show the selection window" expert)))
  1739. (defcustom org-provide-todo-statistics t
  1740. "Non-nil means update todo statistics after insert and toggle.
  1741. ALL-HEADLINES means update todo statistics by including headlines
  1742. with no TODO keyword as well, counting them as not done.
  1743. A list of TODO keywords means the same, but skip keywords that are
  1744. not in this list.
  1745. When set to a list of two lists, the first list contains keywords
  1746. to consider as TODO keywords, the second list contains keywords
  1747. to consider as DONE keywords.
  1748. When this is set, todo statistics is updated in the parent of the
  1749. current entry each time a todo state is changed."
  1750. :group 'org-todo
  1751. :type '(choice
  1752. (const :tag "Yes, only for TODO entries" t)
  1753. (const :tag "Yes, including all entries" all-headlines)
  1754. (repeat :tag "Yes, for TODOs in this list"
  1755. (string :tag "TODO keyword"))
  1756. (list :tag "Yes, for TODOs and DONEs in these lists"
  1757. (repeat (string :tag "TODO keyword"))
  1758. (repeat (string :tag "DONE keyword")))
  1759. (other :tag "No TODO statistics" nil)))
  1760. (defcustom org-hierarchical-todo-statistics t
  1761. "Non-nil means TODO statistics covers just direct children.
  1762. When nil, all entries in the subtree are considered.
  1763. This has only an effect if `org-provide-todo-statistics' is set.
  1764. To set this to nil for only a single subtree, use a COOKIE_DATA
  1765. property and include the word \"recursive\" into the value."
  1766. :group 'org-todo
  1767. :type 'boolean)
  1768. (defcustom org-after-todo-state-change-hook nil
  1769. "Hook which is run after the state of a TODO item was changed.
  1770. The new state (a string with a TODO keyword, or nil) is available in the
  1771. Lisp variable `org-state'."
  1772. :group 'org-todo
  1773. :type 'hook)
  1774. (defvar org-blocker-hook nil
  1775. "Hook for functions that are allowed to block a state change.
  1776. Functions in this hook should not modify the buffer.
  1777. Each function gets as its single argument a property list,
  1778. see `org-trigger-hook' for more information about this list.
  1779. If any of the functions in this hook returns nil, the state change
  1780. is blocked.")
  1781. (defvar org-trigger-hook nil
  1782. "Hook for functions that are triggered by a state change.
  1783. Each function gets as its single argument a property list with at
  1784. least the following elements:
  1785. (:type type-of-change :position pos-at-entry-start
  1786. :from old-state :to new-state)
  1787. Depending on the type, more properties may be present.
  1788. This mechanism is currently implemented for:
  1789. TODO state changes
  1790. ------------------
  1791. :type todo-state-change
  1792. :from previous state (keyword as a string), or nil, or a symbol
  1793. `todo' or `done', to indicate the general type of state.
  1794. :to new state, like in :from")
  1795. (defcustom org-enforce-todo-dependencies nil
  1796. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1797. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1798. be blocked if any prior sibling is not yet done.
  1799. Finally, if the parent is blocked because of ordered siblings of its own,
  1800. the child will also be blocked."
  1801. :set (lambda (var val)
  1802. (set var val)
  1803. (if val
  1804. (add-hook 'org-blocker-hook
  1805. 'org-block-todo-from-children-or-siblings-or-parent)
  1806. (remove-hook 'org-blocker-hook
  1807. 'org-block-todo-from-children-or-siblings-or-parent)))
  1808. :group 'org-todo
  1809. :type 'boolean)
  1810. (defcustom org-enforce-todo-checkbox-dependencies nil
  1811. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1812. When this is nil, checkboxes have no influence on switching TODO states.
  1813. When non-nil, you first need to check off all check boxes before the TODO
  1814. entry can be switched to DONE.
  1815. This variable needs to be set before org.el is loaded, and you need to
  1816. restart Emacs after a change to make the change effective. The only way
  1817. to change it while Emacs is running is through the customize interface."
  1818. :set (lambda (var val)
  1819. (set var val)
  1820. (if val
  1821. (add-hook 'org-blocker-hook
  1822. 'org-block-todo-from-checkboxes)
  1823. (remove-hook 'org-blocker-hook
  1824. 'org-block-todo-from-checkboxes)))
  1825. :group 'org-todo
  1826. :type 'boolean)
  1827. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1828. "Non-nil means inserting a TODO heading is treated as state change.
  1829. So when the command `\\[org-insert-todo-heading]' is used, state change
  1830. logging will apply if appropriate. When nil, the new TODO item will
  1831. be inserted directly, and no logging will take place."
  1832. :group 'org-todo
  1833. :type 'boolean)
  1834. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1835. "Non-nil means switching TODO states with S-cursor counts as state change.
  1836. This is the default behavior. However, setting this to nil allows a
  1837. convenient way to select a TODO state and bypass any logging associated
  1838. with that."
  1839. :group 'org-todo
  1840. :type 'boolean)
  1841. (defcustom org-todo-state-tags-triggers nil
  1842. "Tag changes that should be triggered by TODO state changes.
  1843. This is a list. Each entry is
  1844. (state-change (tag . flag) .......)
  1845. State-change can be a string with a state, and empty string to indicate the
  1846. state that has no TODO keyword, or it can be one of the symbols `todo'
  1847. or `done', meaning any not-done or done state, respectively."
  1848. :group 'org-todo
  1849. :group 'org-tags
  1850. :type '(repeat
  1851. (cons (choice :tag "When changing to"
  1852. (const :tag "Not-done state" todo)
  1853. (const :tag "Done state" done)
  1854. (string :tag "State"))
  1855. (repeat
  1856. (cons :tag "Tag action"
  1857. (string :tag "Tag")
  1858. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1859. (defcustom org-log-done nil
  1860. "Information to record when a task moves to the DONE state.
  1861. Possible values are:
  1862. nil Don't add anything, just change the keyword
  1863. time Add a time stamp to the task
  1864. note Prompt for a note and add it with template `org-log-note-headings'
  1865. This option can also be set with on a per-file-basis with
  1866. #+STARTUP: nologdone
  1867. #+STARTUP: logdone
  1868. #+STARTUP: lognotedone
  1869. You can have local logging settings for a subtree by setting the LOGGING
  1870. property to one or more of these keywords."
  1871. :group 'org-todo
  1872. :group 'org-progress
  1873. :type '(choice
  1874. (const :tag "No logging" nil)
  1875. (const :tag "Record CLOSED timestamp" time)
  1876. (const :tag "Record CLOSED timestamp with note." note)))
  1877. ;; Normalize old uses of org-log-done.
  1878. (cond
  1879. ((eq org-log-done t) (setq org-log-done 'time))
  1880. ((and (listp org-log-done) (memq 'done org-log-done))
  1881. (setq org-log-done 'note)))
  1882. (defcustom org-log-reschedule nil
  1883. "Information to record when the scheduling date of a task is modified.
  1884. Possible values are:
  1885. nil Don't add anything, just change the date
  1886. time Add a time stamp to the task
  1887. note Prompt for a note and add it with template `org-log-note-headings'
  1888. This option can also be set with on a per-file-basis with
  1889. #+STARTUP: nologreschedule
  1890. #+STARTUP: logreschedule
  1891. #+STARTUP: lognotereschedule
  1892. You can have local logging settings for a subtree by setting the LOGGING
  1893. property to one or more of these keywords.
  1894. This variable has an effect when calling `org-schedule' or
  1895. `org-agenda-schedule' only."
  1896. :group 'org-todo
  1897. :group 'org-progress
  1898. :type '(choice
  1899. (const :tag "No logging" nil)
  1900. (const :tag "Record timestamp" time)
  1901. (const :tag "Record timestamp with note" note)))
  1902. (defcustom org-log-redeadline nil
  1903. "Information to record when the deadline date of a task is modified.
  1904. Possible values are:
  1905. nil Don't add anything, just change the date
  1906. time Add a time stamp to the task
  1907. note Prompt for a note and add it with template `org-log-note-headings'
  1908. This option can also be set with on a per-file-basis with
  1909. #+STARTUP: nologredeadline
  1910. #+STARTUP: logredeadline
  1911. #+STARTUP: lognoteredeadline
  1912. You can have local logging settings for a subtree by setting the LOGGING
  1913. property to one or more of these keywords.
  1914. This variable has an effect when calling `org-deadline' or
  1915. `org-agenda-deadline' only."
  1916. :group 'org-todo
  1917. :group 'org-progress
  1918. :type '(choice
  1919. (const :tag "No logging" nil)
  1920. (const :tag "Record timestamp" time)
  1921. (const :tag "Record timestamp with note." note)))
  1922. (defcustom org-log-note-clock-out nil
  1923. "Non-nil means record a note when clocking out of an item.
  1924. This can also be configured on a per-file basis by adding one of
  1925. the following lines anywhere in the buffer:
  1926. #+STARTUP: lognoteclock-out
  1927. #+STARTUP: nolognoteclock-out"
  1928. :group 'org-todo
  1929. :group 'org-progress
  1930. :type 'boolean)
  1931. (defcustom org-log-done-with-time t
  1932. "Non-nil means the CLOSED time stamp will contain date and time.
  1933. When nil, only the date will be recorded."
  1934. :group 'org-progress
  1935. :type 'boolean)
  1936. (defcustom org-log-note-headings
  1937. '((done . "CLOSING NOTE %t")
  1938. (state . "State %-12s from %-12S %t")
  1939. (note . "Note taken on %t")
  1940. (reschedule . "Rescheduled from %S on %t")
  1941. (delschedule . "Not scheduled, was %S on %t")
  1942. (redeadline . "New deadline from %S on %t")
  1943. (deldeadline . "Removed deadline, was %S on %t")
  1944. (refile . "Refiled on %t")
  1945. (clock-out . ""))
  1946. "Headings for notes added to entries.
  1947. The value is an alist, with the car being a symbol indicating the
  1948. note context, and the cdr is the heading to be used. The heading
  1949. may also be the empty string. The following placeholders can be
  1950. used:
  1951. %t a time stamp.
  1952. %T an active time stamp instead the default inactive one
  1953. %d a short-format time stamp.
  1954. %D an active short-format time stamp.
  1955. %s the new TODO state or time stamp (inactive), in double quotes.
  1956. %S the old TODO state or time stamp (inactive), in double quotes.
  1957. %u the user name.
  1958. %U full user name.
  1959. In fact, it is not a good idea to change the `state' entry,
  1960. because Agenda Log mode depends on the format of these entries."
  1961. :group 'org-todo
  1962. :group 'org-progress
  1963. :type '(list :greedy t
  1964. (cons (const :tag "Heading when closing an item" done) string)
  1965. (cons (const :tag
  1966. "Heading when changing todo state (todo sequence only)"
  1967. state) string)
  1968. (cons (const :tag "Heading when just taking a note" note) string)
  1969. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1970. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1971. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1972. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1973. (cons (const :tag "Heading when refiling" refile) string)
  1974. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1975. (unless (assq 'note org-log-note-headings)
  1976. (push '(note . "%t") org-log-note-headings))
  1977. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1978. (defcustom org-log-into-drawer nil
  1979. "Non-nil means insert state change notes and time stamps into a drawer.
  1980. When nil, state changes notes will be inserted after the headline and
  1981. any scheduling and clock lines, but not inside a drawer.
  1982. The value of this variable should be the name of the drawer to use.
  1983. LOGBOOK is proposed as the default drawer for this purpose, you can
  1984. also set this to a string to define the drawer of your choice.
  1985. A value of t is also allowed, representing \"LOGBOOK\".
  1986. A value of t or nil can also be set with on a per-file-basis with
  1987. #+STARTUP: logdrawer
  1988. #+STARTUP: nologdrawer
  1989. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1990. will be ignored.
  1991. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1992. a subtree.
  1993. Do not check directly this variable in a Lisp program. Call
  1994. function `org-log-into-drawer' instead."
  1995. :group 'org-todo
  1996. :group 'org-progress
  1997. :type '(choice
  1998. (const :tag "Not into a drawer" nil)
  1999. (const :tag "LOGBOOK" t)
  2000. (string :tag "Other")))
  2001. (defun org-log-into-drawer ()
  2002. "Name of the log drawer, as a string, or nil.
  2003. This is the value of `org-log-into-drawer'. However, if the
  2004. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2005. be used instead of the default value."
  2006. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2007. (cond ((equal p "nil") nil)
  2008. ((equal p "t") "LOGBOOK")
  2009. ((stringp p) p)
  2010. (p "LOGBOOK")
  2011. ((stringp org-log-into-drawer) org-log-into-drawer)
  2012. (org-log-into-drawer "LOGBOOK"))))
  2013. (defcustom org-log-state-notes-insert-after-drawers nil
  2014. "Non-nil means insert state change notes after any drawers in entry.
  2015. Only the drawers that *immediately* follow the headline and the
  2016. deadline/scheduled line are skipped.
  2017. When nil, insert notes right after the heading and perhaps the line
  2018. with deadline/scheduling if present.
  2019. This variable will have no effect if `org-log-into-drawer' is
  2020. set."
  2021. :group 'org-todo
  2022. :group 'org-progress
  2023. :type 'boolean)
  2024. (defcustom org-log-states-order-reversed t
  2025. "Non-nil means the latest state note will be directly after heading.
  2026. When nil, the state change notes will be ordered according to time.
  2027. This option can also be set with on a per-file-basis with
  2028. #+STARTUP: logstatesreversed
  2029. #+STARTUP: nologstatesreversed"
  2030. :group 'org-todo
  2031. :group 'org-progress
  2032. :type 'boolean)
  2033. (defcustom org-todo-repeat-to-state nil
  2034. "The TODO state to which a repeater should return the repeating task.
  2035. By default this is the first task of a TODO sequence or the
  2036. previous state of a TYPE_TODO set. But you can specify to use
  2037. the previous state in a TODO sequence or a string.
  2038. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2039. entry, which has precedence over this option."
  2040. :group 'org-todo
  2041. :version "24.1"
  2042. :type '(choice (const :tag "Use the previous TODO state" t)
  2043. (const :tag "Use the head of the TODO sequence" nil)
  2044. (string :tag "Use a specific TODO state")))
  2045. (defcustom org-log-repeat 'time
  2046. "Non-nil means record moving through the DONE state when triggering repeat.
  2047. An auto-repeating task is immediately switched back to TODO when
  2048. marked DONE. If you are not logging state changes (by adding \"@\"
  2049. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2050. record a closing note, there will be no record of the task moving
  2051. through DONE. This variable forces taking a note anyway.
  2052. nil Don't force a record
  2053. time Record a time stamp
  2054. note Prompt for a note and add it with template `org-log-note-headings'
  2055. This option can also be set with on a per-file-basis with
  2056. #+STARTUP: nologrepeat
  2057. #+STARTUP: logrepeat
  2058. #+STARTUP: lognoterepeat
  2059. You can have local logging settings for a subtree by setting the LOGGING
  2060. property to one or more of these keywords."
  2061. :group 'org-todo
  2062. :group 'org-progress
  2063. :type '(choice
  2064. (const :tag "Don't force a record" nil)
  2065. (const :tag "Force recording the DONE state" time)
  2066. (const :tag "Force recording a note with the DONE state" note)))
  2067. (defcustom org-todo-repeat-hook nil
  2068. "Hook that is run after a task has been repeated."
  2069. :package-version '(Org . "9.2")
  2070. :group 'org-todo
  2071. :type 'hook)
  2072. (defgroup org-priorities nil
  2073. "Priorities in Org mode."
  2074. :tag "Org Priorities"
  2075. :group 'org-todo)
  2076. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2077. (defcustom org-priority-enable-commands t
  2078. "Non-nil means priority commands are active.
  2079. When nil, these commands will be disabled, so that you never accidentally
  2080. set a priority."
  2081. :group 'org-priorities
  2082. :type 'boolean)
  2083. (defvaralias 'org-highest-priority 'org-priority-highest)
  2084. (defcustom org-priority-highest ?A
  2085. "The highest priority of TODO items.
  2086. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2087. Must be smaller than `org-priority-lowest'."
  2088. :group 'org-priorities
  2089. :type '(choice
  2090. (character :tag "Character")
  2091. (integer :tag "Integer (< 65)")))
  2092. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2093. (defcustom org-priority-lowest ?C
  2094. "The lowest priority of TODO items.
  2095. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2096. Must be higher than `org-priority-highest'."
  2097. :group 'org-priorities
  2098. :type '(choice
  2099. (character :tag "Character")
  2100. (integer :tag "Integer (< 65)")))
  2101. (defvaralias 'org-default-priority 'org-priority-default)
  2102. (defcustom org-priority-default ?B
  2103. "The default priority of TODO items.
  2104. This is the priority an item gets if no explicit priority is given.
  2105. When starting to cycle on an empty priority the first step in the cycle
  2106. depends on `org-priority-start-cycle-with-default'. The resulting first
  2107. step priority must not exceed the range from `org-priority-highest' to
  2108. `org-priority-lowest' which means that `org-priority-default' has to be
  2109. in this range exclusive or inclusive to the range boundaries. Else the
  2110. first step refuses to set the default and the second will fall back on
  2111. (depending on the command used) the highest or lowest priority."
  2112. :group 'org-priorities
  2113. :type '(choice
  2114. (character :tag "Character")
  2115. (integer :tag "Integer (< 65)")))
  2116. (defcustom org-priority-start-cycle-with-default t
  2117. "Non-nil means start with default priority when starting to cycle.
  2118. When this is nil, the first step in the cycle will be (depending on the
  2119. command used) one higher or lower than the default priority.
  2120. See also `org-priority-default'."
  2121. :group 'org-priorities
  2122. :type 'boolean)
  2123. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2124. (defcustom org-priority-get-priority-function nil
  2125. "Function to extract the priority from a string.
  2126. The string is normally the headline. If this is nil, Org
  2127. computes the priority from the priority cookie like [#A] in the
  2128. headline. It returns an integer, increasing by 1000 for each
  2129. priority level.
  2130. The user can set a different function here, which should take a
  2131. string as an argument and return the numeric priority."
  2132. :group 'org-priorities
  2133. :version "24.1"
  2134. :type '(choice
  2135. (const nil)
  2136. (function)))
  2137. (defgroup org-time nil
  2138. "Options concerning time stamps and deadlines in Org mode."
  2139. :tag "Org Time"
  2140. :group 'org)
  2141. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2142. "Number of minutes to round time stamps to.
  2143. \\<org-mode-map>\
  2144. These are two values, the first applies when first creating a time stamp.
  2145. The second applies when changing it with the commands `S-up' and `S-down'.
  2146. When changing the time stamp, this means that it will change in steps
  2147. of N minutes, as given by the second value.
  2148. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2149. numbers should be factors of 60, so for example 5, 10, 15.
  2150. When this is larger than 1, you can still force an exact time stamp by using
  2151. a double prefix argument to a time stamp command like \
  2152. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2153. and by using a prefix arg to `S-up/down' to specify the exact number
  2154. of minutes to shift."
  2155. :group 'org-time
  2156. :get (lambda (var) ; Make sure both elements are there
  2157. (if (integerp (default-value var))
  2158. (list (default-value var) 5)
  2159. (default-value var)))
  2160. :type '(list
  2161. (integer :tag "when inserting times")
  2162. (integer :tag "when modifying times")))
  2163. ;; Normalize old customizations of this variable.
  2164. (when (integerp org-time-stamp-rounding-minutes)
  2165. (setq org-time-stamp-rounding-minutes
  2166. (list org-time-stamp-rounding-minutes
  2167. org-time-stamp-rounding-minutes)))
  2168. (defcustom org-display-custom-times nil
  2169. "Non-nil means overlay custom formats over all time stamps.
  2170. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2171. To turn this on on a per-file basis, insert anywhere in the file:
  2172. #+STARTUP: customtime"
  2173. :group 'org-time
  2174. :set 'set-default
  2175. :type 'sexp)
  2176. (make-variable-buffer-local 'org-display-custom-times)
  2177. (defcustom org-time-stamp-custom-formats
  2178. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2179. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2180. These are overlaid over the default ISO format if the variable
  2181. `org-display-custom-times' is set. Time like %H:%M should be at the
  2182. end of the second format. The custom formats are also honored by export
  2183. commands, if custom time display is turned on at the time of export."
  2184. :group 'org-time
  2185. :type 'sexp)
  2186. (defun org-time-stamp-format (&optional long inactive)
  2187. "Get the right format for a time string."
  2188. (let ((f (if long (cdr org-time-stamp-formats)
  2189. (car org-time-stamp-formats))))
  2190. (if inactive
  2191. (concat "[" (substring f 1 -1) "]")
  2192. f)))
  2193. (defcustom org-deadline-warning-days 14
  2194. "Number of days before expiration during which a deadline becomes active.
  2195. This variable governs the display in sparse trees and in the agenda.
  2196. When 0 or negative, it means use this number (the absolute value of it)
  2197. even if a deadline has a different individual lead time specified.
  2198. Custom commands can set this variable in the options section."
  2199. :group 'org-time
  2200. :group 'org-agenda-daily/weekly
  2201. :type 'integer)
  2202. (defcustom org-scheduled-delay-days 0
  2203. "Number of days before a scheduled item becomes active.
  2204. This variable governs the display in sparse trees and in the agenda.
  2205. The default value (i.e. 0) means: don't delay scheduled item.
  2206. When negative, it means use this number (the absolute value of it)
  2207. even if a scheduled item has a different individual delay time
  2208. specified.
  2209. Custom commands can set this variable in the options section."
  2210. :group 'org-time
  2211. :group 'org-agenda-daily/weekly
  2212. :version "24.4"
  2213. :package-version '(Org . "8.0")
  2214. :type 'integer)
  2215. (defcustom org-read-date-prefer-future t
  2216. "Non-nil means assume future for incomplete date input from user.
  2217. This affects the following situations:
  2218. 1. The user gives a month but not a year.
  2219. For example, if it is April and you enter \"feb 2\", this will be read
  2220. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2221. 2. The user gives a day, but no month.
  2222. For example, if today is the 15th, and you enter \"3\", Org will read
  2223. this as the third of *next* month. However, if you enter \"17\",
  2224. it will be considered as *this* month.
  2225. If you set this variable to the symbol `time', then also the following
  2226. will work:
  2227. 3. If the user gives a time.
  2228. If the time is before now, it will be interpreted as tomorrow.
  2229. Currently none of this works for ISO week specifications.
  2230. When this option is nil, the current day, month and year will always be
  2231. used as defaults.
  2232. See also `org-agenda-jump-prefer-future'."
  2233. :group 'org-time
  2234. :type '(choice
  2235. (const :tag "Never" nil)
  2236. (const :tag "Check month and day" t)
  2237. (const :tag "Check month, day, and time" time)))
  2238. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2239. "Should the agenda jump command prefer the future for incomplete dates?
  2240. The default is to do the same as configured in `org-read-date-prefer-future'.
  2241. But you can also set a deviating value here.
  2242. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2243. :group 'org-agenda
  2244. :group 'org-time
  2245. :version "24.1"
  2246. :type '(choice
  2247. (const :tag "Use org-read-date-prefer-future"
  2248. org-read-date-prefer-future)
  2249. (const :tag "Never" nil)
  2250. (const :tag "Always" t)))
  2251. (defcustom org-read-date-force-compatible-dates t
  2252. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2253. Depending on the system Emacs is running on, certain dates cannot
  2254. be represented with the type used internally to represent time.
  2255. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2256. correctly. Some systems allow for earlier dates, some for later,
  2257. some for both. One way to find out is to insert any date into an
  2258. Org buffer, putting the cursor on the year and hitting S-up and
  2259. S-down to test the range.
  2260. When this variable is set to t, the date/time prompt will not let
  2261. you specify dates outside the 1970-2037 range, so it is certain that
  2262. these dates will work in whatever version of Emacs you are
  2263. running, and also that you can move a file from one Emacs implementation
  2264. to another. Whenever Org is forcing the year for you, it will display
  2265. a message and beep.
  2266. When this variable is nil, Org will check if the date is
  2267. representable in the specific Emacs implementation you are using.
  2268. If not, it will force a year, usually the current year, and beep
  2269. to remind you. Currently this setting is not recommended because
  2270. the likelihood that you will open your Org files in an Emacs that
  2271. has limited date range is not negligible.
  2272. A workaround for this problem is to use diary sexp dates for time
  2273. stamps outside of this range."
  2274. :group 'org-time
  2275. :version "24.1"
  2276. :type 'boolean)
  2277. (defcustom org-read-date-display-live t
  2278. "Non-nil means display current interpretation of date prompt live.
  2279. This display will be in an overlay, in the minibuffer."
  2280. :group 'org-time
  2281. :type 'boolean)
  2282. (defvaralias 'org-popup-calendar-for-date-prompt
  2283. 'org-read-date-popup-calendar)
  2284. (defcustom org-read-date-popup-calendar t
  2285. "Non-nil means pop up a calendar when prompting for a date.
  2286. In the calendar, the date can be selected with mouse-1. However, the
  2287. minibuffer will also be active, and you can simply enter the date as well.
  2288. When nil, only the minibuffer will be available."
  2289. :group 'org-time
  2290. :type 'boolean)
  2291. (defcustom org-extend-today-until 0
  2292. "The hour when your day really ends. Must be an integer.
  2293. This has influence for the following applications:
  2294. - When switching the agenda to \"today\". If it is still earlier than
  2295. the time given here, the day recognized as TODAY is actually yesterday.
  2296. - When a date is read from the user and it is still before the time given
  2297. here, the current date and time will be assumed to be yesterday, 23:59.
  2298. Also, timestamps inserted in capture templates follow this rule.
  2299. IMPORTANT: This is a feature whose implementation is and likely will
  2300. remain incomplete. Really, it is only here because past midnight seems to
  2301. be the favorite working time of John Wiegley :-)"
  2302. :group 'org-time
  2303. :type 'integer)
  2304. (defcustom org-use-effective-time nil
  2305. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2306. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2307. \"effective time\" of any timestamps between midnight and 8am will be
  2308. 23:59 of the previous day."
  2309. :group 'org-time
  2310. :version "24.1"
  2311. :type 'boolean)
  2312. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2313. "When non-nil, use the last clock out time for `org-todo'.
  2314. Note that this option has precedence over the combined use of
  2315. `org-use-effective-time' and `org-extend-today-until'."
  2316. :group 'org-time
  2317. :version "24.4"
  2318. :package-version '(Org . "8.0")
  2319. :type 'boolean)
  2320. (defcustom org-edit-timestamp-down-means-later nil
  2321. "Non-nil means S-down will increase the time in a time stamp.
  2322. When nil, S-up will increase."
  2323. :group 'org-time
  2324. :type 'boolean)
  2325. (defcustom org-calendar-follow-timestamp-change t
  2326. "Non-nil means make the calendar window follow timestamp changes.
  2327. When a timestamp is modified and the calendar window is visible, it will be
  2328. moved to the new date."
  2329. :group 'org-time
  2330. :type 'boolean)
  2331. (defgroup org-tags nil
  2332. "Options concerning tags in Org mode."
  2333. :tag "Org Tags"
  2334. :group 'org)
  2335. (defcustom org-tag-alist nil
  2336. "Default tags available in Org files.
  2337. The value of this variable is an alist. Associations either:
  2338. (TAG)
  2339. (TAG . SELECT)
  2340. (SPECIAL)
  2341. where TAG is a tag as a string, SELECT is character, used to
  2342. select that tag through the fast tag selection interface, and
  2343. SPECIAL is one of the following keywords: `:startgroup',
  2344. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2345. `:newline'. These keywords are used to define a hierarchy of
  2346. tags. See manual for details.
  2347. When this variable is nil, Org mode bases tag input on what is
  2348. already in the buffer. The value can be overridden locally by
  2349. using a TAGS keyword, e.g.,
  2350. #+TAGS: tag1 tag2
  2351. See also `org-tag-persistent-alist' to sidestep this behavior."
  2352. :group 'org-tags
  2353. :type '(repeat
  2354. (choice
  2355. (cons :tag "Tag with key"
  2356. (string :tag "Tag name")
  2357. (character :tag "Access char"))
  2358. (list :tag "Tag" (string :tag "Tag name"))
  2359. (const :tag "Start radio group" (:startgroup))
  2360. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2361. (const :tag "Group tags delimiter" (:grouptags))
  2362. (const :tag "End radio group" (:endgroup))
  2363. (const :tag "End tag group, non distinct" (:endgrouptag))
  2364. (const :tag "New line" (:newline)))))
  2365. (defcustom org-tag-persistent-alist nil
  2366. "Tags always available in Org files.
  2367. The value of this variable is an alist. Associations either:
  2368. (TAG)
  2369. (TAG . SELECT)
  2370. (SPECIAL)
  2371. where TAG is a tag as a string, SELECT is a character, used to
  2372. select that tag through the fast tag selection interface, and
  2373. SPECIAL is one of the following keywords: `:startgroup',
  2374. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2375. `:newline'. These keywords are used to define a hierarchy of
  2376. tags. See manual for details.
  2377. Unlike to `org-tag-alist', tags defined in this variable do not
  2378. depend on a local TAGS keyword. Instead, to disable these tags
  2379. on a per-file basis, insert anywhere in the file:
  2380. #+STARTUP: noptag"
  2381. :group 'org-tags
  2382. :type '(repeat
  2383. (choice
  2384. (cons :tag "Tag with key"
  2385. (string :tag "Tag name")
  2386. (character :tag "Access char"))
  2387. (list :tag "Tag" (string :tag "Tag name"))
  2388. (const :tag "Start radio group" (:startgroup))
  2389. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2390. (const :tag "Group tags delimiter" (:grouptags))
  2391. (const :tag "End radio group" (:endgroup))
  2392. (const :tag "End tag group, non distinct" (:endgrouptag))
  2393. (const :tag "New line" (:newline)))))
  2394. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2395. "If non-nil, always offer completion for all tags of all agenda files.
  2396. Setting this variable locally allows for dynamic generation of tag
  2397. completions in capture buffers.
  2398. (add-hook \\='org-capture-mode-hook
  2399. (lambda ()
  2400. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2401. :group 'org-tags
  2402. :version "24.1"
  2403. :type 'boolean)
  2404. (defvar org-file-tags nil
  2405. "List of tags that can be inherited by all entries in the file.
  2406. The tags will be inherited if the variable `org-use-tag-inheritance'
  2407. says they should be.
  2408. This variable is populated from #+FILETAGS lines.")
  2409. (defcustom org-use-fast-tag-selection 'auto
  2410. "Non-nil means use fast tag selection scheme.
  2411. This is a special interface to select and deselect tags with single keys.
  2412. When nil, fast selection is never used.
  2413. When the symbol `auto', fast selection is used if and only if selection
  2414. characters for tags have been configured, either through the variable
  2415. `org-tag-alist' or through a #+TAGS line in the buffer.
  2416. When t, fast selection is always used and selection keys are assigned
  2417. automatically if necessary."
  2418. :group 'org-tags
  2419. :type '(choice
  2420. (const :tag "Always" t)
  2421. (const :tag "Never" nil)
  2422. (const :tag "When selection characters are configured" auto)))
  2423. (defcustom org-fast-tag-selection-single-key nil
  2424. "Non-nil means fast tag selection exits after first change.
  2425. When nil, you have to press RET to exit it.
  2426. During fast tag selection, you can toggle this flag with `C-c'.
  2427. This variable can also have the value `expert'. In this case, the window
  2428. displaying the tags menu is not even shown, until you press C-c again."
  2429. :group 'org-tags
  2430. :type '(choice
  2431. (const :tag "No" nil)
  2432. (const :tag "Yes" t)
  2433. (const :tag "Expert" expert)))
  2434. (defvar org-fast-tag-selection-include-todo nil
  2435. "Non-nil means fast tags selection interface will also offer TODO states.
  2436. This is an undocumented feature, you should not rely on it.")
  2437. (defcustom org-tags-column -77
  2438. "The column to which tags should be indented in a headline.
  2439. If this number is positive, it specifies the column. If it is negative,
  2440. it means that the tags should be flushright to that column. For example,
  2441. -80 works well for a normal 80 character screen.
  2442. When 0, place tags directly after headline text, with only one space in
  2443. between."
  2444. :group 'org-tags
  2445. :type 'integer)
  2446. (defcustom org-auto-align-tags t
  2447. "Non-nil keeps tags aligned when modifying headlines.
  2448. Some operations (i.e. demoting) change the length of a headline and
  2449. therefore shift the tags around. With this option turned on, after
  2450. each such operation the tags are again aligned to `org-tags-column'."
  2451. :group 'org-tags
  2452. :type 'boolean)
  2453. (defcustom org-use-tag-inheritance t
  2454. "Non-nil means tags in levels apply also for sublevels.
  2455. When nil, only the tags directly given in a specific line apply there.
  2456. This may also be a list of tags that should be inherited, or a regexp that
  2457. matches tags that should be inherited. Additional control is possible
  2458. with the variable `org-tags-exclude-from-inheritance' which gives an
  2459. explicit list of tags to be excluded from inheritance, even if the value of
  2460. `org-use-tag-inheritance' would select it for inheritance.
  2461. If this option is t, a match early-on in a tree can lead to a large
  2462. number of matches in the subtree when constructing the agenda or creating
  2463. a sparse tree. If you only want to see the first match in a tree during
  2464. a search, check out the variable `org-tags-match-list-sublevels'."
  2465. :group 'org-tags
  2466. :type '(choice
  2467. (const :tag "Not" nil)
  2468. (const :tag "Always" t)
  2469. (repeat :tag "Specific tags" (string :tag "Tag"))
  2470. (regexp :tag "Tags matched by regexp")))
  2471. (defcustom org-tags-exclude-from-inheritance nil
  2472. "List of tags that should never be inherited.
  2473. This is a way to exclude a few tags from inheritance. For way to do
  2474. the opposite, to actively allow inheritance for selected tags,
  2475. see the variable `org-use-tag-inheritance'."
  2476. :group 'org-tags
  2477. :type '(repeat (string :tag "Tag")))
  2478. (defun org-tag-inherit-p (tag)
  2479. "Check if TAG is one that should be inherited."
  2480. (cond
  2481. ((member tag org-tags-exclude-from-inheritance) nil)
  2482. ((eq org-use-tag-inheritance t) t)
  2483. ((not org-use-tag-inheritance) nil)
  2484. ((stringp org-use-tag-inheritance)
  2485. (string-match org-use-tag-inheritance tag))
  2486. ((listp org-use-tag-inheritance)
  2487. (member tag org-use-tag-inheritance))
  2488. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2489. (defcustom org-tags-match-list-sublevels t
  2490. "Non-nil means list also sublevels of headlines matching a search.
  2491. This variable applies to tags/property searches, and also to stuck
  2492. projects because this search is based on a tags match as well.
  2493. When set to the symbol `indented', sublevels are indented with
  2494. leading dots.
  2495. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2496. the sublevels of a headline matching a tag search often also match
  2497. the same search. Listing all of them can create very long lists.
  2498. Setting this variable to nil causes subtrees of a match to be skipped.
  2499. This variable is semi-obsolete and probably should always be true. It
  2500. is better to limit inheritance to certain tags using the variables
  2501. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2502. :group 'org-tags
  2503. :type '(choice
  2504. (const :tag "No, don't list them" nil)
  2505. (const :tag "Yes, do list them" t)
  2506. (const :tag "List them, indented with leading dots" indented)))
  2507. (defcustom org-tags-sort-function nil
  2508. "When set, tags are sorted using this function as a comparator."
  2509. :group 'org-tags
  2510. :type '(choice
  2511. (const :tag "No sorting" nil)
  2512. (const :tag "Alphabetical" org-string-collate-lessp)
  2513. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2514. (function :tag "Custom function" nil)))
  2515. (defvar org-tags-history nil
  2516. "History of minibuffer reads for tags.")
  2517. (defvar org-last-tags-completion-table nil
  2518. "The last used completion table for tags.")
  2519. (defvar org-after-tags-change-hook nil
  2520. "Hook that is run after the tags in a line have changed.")
  2521. (defgroup org-properties nil
  2522. "Options concerning properties in Org mode."
  2523. :tag "Org Properties"
  2524. :group 'org)
  2525. (defcustom org-property-format "%-10s %s"
  2526. "How property key/value pairs should be formatted by `indent-line'.
  2527. When `indent-line' hits a property definition, it will format the line
  2528. according to this format, mainly to make sure that the values are
  2529. lined-up with respect to each other."
  2530. :group 'org-properties
  2531. :type 'string)
  2532. (defcustom org-properties-postprocess-alist nil
  2533. "Alist of properties and functions to adjust inserted values.
  2534. Elements of this alist must be of the form
  2535. ([string] [function])
  2536. where [string] must be a property name and [function] must be a
  2537. lambda expression: this lambda expression must take one argument,
  2538. the value to adjust, and return the new value as a string.
  2539. For example, this element will allow the property \"Remaining\"
  2540. to be updated wrt the relation between the \"Effort\" property
  2541. and the clock summary:
  2542. ((\"Remaining\" (lambda(value)
  2543. (let ((clocksum (org-clock-sum-current-item))
  2544. (effort (org-duration-to-minutes
  2545. (org-entry-get (point) \"Effort\"))))
  2546. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2547. :group 'org-properties
  2548. :version "24.1"
  2549. :type '(alist :key-type (string :tag "Property")
  2550. :value-type (function :tag "Function")))
  2551. (defcustom org-use-property-inheritance nil
  2552. "Non-nil means properties apply also for sublevels.
  2553. This setting is chiefly used during property searches. Turning it on can
  2554. cause significant overhead when doing a search, which is why it is not
  2555. on by default.
  2556. When nil, only the properties directly given in the current entry count.
  2557. When t, every property is inherited. The value may also be a list of
  2558. properties that should have inheritance, or a regular expression matching
  2559. properties that should be inherited.
  2560. However, note that some special properties use inheritance under special
  2561. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2562. and the properties ending in \"_ALL\" when they are used as descriptor
  2563. for valid values of a property.
  2564. Note for programmers:
  2565. When querying an entry with `org-entry-get', you can control if inheritance
  2566. should be used. By default, `org-entry-get' looks only at the local
  2567. properties. You can request inheritance by setting the inherit argument
  2568. to t (to force inheritance) or to `selective' (to respect the setting
  2569. in this variable)."
  2570. :group 'org-properties
  2571. :type '(choice
  2572. (const :tag "Not" nil)
  2573. (const :tag "Always" t)
  2574. (repeat :tag "Specific properties" (string :tag "Property"))
  2575. (regexp :tag "Properties matched by regexp")))
  2576. (defun org-property-inherit-p (property)
  2577. "Return a non-nil value if PROPERTY should be inherited."
  2578. (cond
  2579. ((eq org-use-property-inheritance t) t)
  2580. ((not org-use-property-inheritance) nil)
  2581. ((stringp org-use-property-inheritance)
  2582. (string-match org-use-property-inheritance property))
  2583. ((listp org-use-property-inheritance)
  2584. (member-ignore-case property org-use-property-inheritance))
  2585. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2586. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2587. "The default column format, if no other format has been defined.
  2588. This variable can be set on the per-file basis by inserting a line
  2589. #+COLUMNS: %25ITEM ....."
  2590. :group 'org-properties
  2591. :type 'string)
  2592. (defcustom org-columns-default-format-for-agenda nil
  2593. "The default column format in an agenda buffer.
  2594. This will be used for column view in the agenda unless a format has
  2595. been set by adding `org-overriding-columns-format' to the local
  2596. settings list of a custom agenda view. When nil, the columns format
  2597. for the first item in the agenda list will be used, or as a fall-back,
  2598. `org-columns-default-format'."
  2599. :group 'org-properties
  2600. :type '(choice
  2601. (const :tag "No default" nil)
  2602. (string :tag "Format string")))
  2603. (defcustom org-columns-ellipses ".."
  2604. "The ellipses to be used when a field in column view is truncated.
  2605. When this is the empty string, as many characters as possible are shown,
  2606. but then there will be no visual indication that the field has been truncated.
  2607. When this is a string of length N, the last N characters of a truncated
  2608. field are replaced by this string. If the column is narrower than the
  2609. ellipses string, only part of the ellipses string will be shown."
  2610. :group 'org-properties
  2611. :type 'string)
  2612. (defconst org-global-properties-fixed
  2613. '(("VISIBILITY_ALL" . "folded children content all")
  2614. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2615. "List of property/value pairs that can be inherited by any entry.
  2616. These are fixed values, for the preset properties. The user variable
  2617. that can be used to add to this list is `org-global-properties'.
  2618. The entries in this list are cons cells where the car is a property
  2619. name and cdr is a string with the value. If the value represents
  2620. multiple items like an \"_ALL\" property, separate the items by
  2621. spaces.")
  2622. (defcustom org-global-properties nil
  2623. "List of property/value pairs that can be inherited by any entry.
  2624. This list will be combined with the constant `org-global-properties-fixed'.
  2625. The entries in this list are cons cells where the car is a property
  2626. name and cdr is a string with the value.
  2627. Buffer local properties are added either by a document property drawer
  2628. :PROPERTIES:
  2629. :NAME: VALUE
  2630. :END:
  2631. or by adding lines like
  2632. #+PROPERTY: NAME VALUE"
  2633. :group 'org-properties
  2634. :type '(repeat
  2635. (cons (string :tag "Property")
  2636. (string :tag "Value"))))
  2637. (defvar-local org-keyword-properties nil
  2638. "List of property/value pairs inherited by any entry.
  2639. Valid for the current buffer. This variable is populated from
  2640. PROPERTY keywords.
  2641. Note that properties are defined also in property drawers.
  2642. Properties defined there take precedence over properties defined
  2643. as keywords.")
  2644. (defgroup org-agenda nil
  2645. "Options concerning agenda views in Org mode."
  2646. :tag "Org Agenda"
  2647. :group 'org)
  2648. (defvar-local org-category nil
  2649. "Variable used by Org files to set a category for agenda display.
  2650. There are multiple ways to set the category. One way is to set
  2651. it in the document property drawer. For example:
  2652. :PROPERTIES:
  2653. :CATEGORY: ELisp
  2654. :END:
  2655. Other ways to define it is as an emacs file variable, for example
  2656. # -*- mode: org; org-category: \"ELisp\"
  2657. or for the file to contain a special line:
  2658. #+CATEGORY: ELisp
  2659. If the file does not specify a category, then file's base name
  2660. is used instead.")
  2661. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2662. (defcustom org-agenda-files nil
  2663. "The files to be used for agenda display.
  2664. If an entry is a directory, all files in that directory that are matched
  2665. by `org-agenda-file-regexp' will be part of the file list.
  2666. If the value of the variable is not a list but a single file name, then
  2667. the list of agenda files is actually stored and maintained in that file,
  2668. one agenda file per line. In this file paths can be given relative to
  2669. `org-directory'. Tilde expansion and environment variable substitution
  2670. are also made.
  2671. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2672. and removed with `\\[org-remove-file]'."
  2673. :group 'org-agenda
  2674. :type '(choice
  2675. (repeat :tag "List of files and directories" file)
  2676. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2677. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2678. "Regular expression to match files for `org-agenda-files'.
  2679. If any element in the list in that variable contains a directory instead
  2680. of a normal file, all files in that directory that are matched by this
  2681. regular expression will be included."
  2682. :group 'org-agenda
  2683. :type 'regexp)
  2684. (defvaralias 'org-agenda-multi-occur-extra-files
  2685. 'org-agenda-text-search-extra-files)
  2686. (defcustom org-agenda-text-search-extra-files nil
  2687. "List of extra files to be searched by text search commands.
  2688. These files will be searched in addition to the agenda files by the
  2689. commands `org-search-view' (`\\[org-agenda] s') \
  2690. and `org-occur-in-agenda-files'.
  2691. Note that these files will only be searched for text search commands,
  2692. not for the other agenda views like todo lists, tag searches or the weekly
  2693. agenda. This variable is intended to list notes and possibly archive files
  2694. that should also be searched by these two commands.
  2695. In fact, if the first element in the list is the symbol `agenda-archives',
  2696. then all archive files of all agenda files will be added to the search
  2697. scope."
  2698. :group 'org-agenda
  2699. :type '(set :greedy t
  2700. (const :tag "Agenda Archives" agenda-archives)
  2701. (repeat :inline t (file))))
  2702. (defcustom org-agenda-skip-unavailable-files nil
  2703. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2704. A nil value means to remove them, after a query, from the list."
  2705. :group 'org-agenda
  2706. :type 'boolean)
  2707. (defgroup org-latex nil
  2708. "Options for embedding LaTeX code into Org mode."
  2709. :tag "Org LaTeX"
  2710. :group 'org)
  2711. (defcustom org-format-latex-options
  2712. '(:foreground default :background default :scale 1.0
  2713. :html-foreground "Black" :html-background "Transparent"
  2714. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2715. "Options for creating images from LaTeX fragments.
  2716. This is a property list with the following properties:
  2717. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2718. `default' means use the foreground of the default face.
  2719. `auto' means use the foreground from the text face.
  2720. :background the background color, or \"Transparent\".
  2721. `default' means use the background of the default face.
  2722. `auto' means use the background from the text face.
  2723. :scale a scaling factor for the size of the images, to get more pixels
  2724. :html-foreground, :html-background, :html-scale
  2725. the same numbers for HTML export.
  2726. :matchers a list indicating which matchers should be used to
  2727. find LaTeX fragments. Valid members of this list are:
  2728. \"begin\" find environments
  2729. \"$1\" find single characters surrounded by $.$
  2730. \"$\" find math expressions surrounded by $...$
  2731. \"$$\" find math expressions surrounded by $$....$$
  2732. \"\\(\" find math expressions surrounded by \\(...\\)
  2733. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2734. :group 'org-latex
  2735. :type 'plist)
  2736. (defcustom org-format-latex-signal-error t
  2737. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2738. When nil, just push out a message."
  2739. :group 'org-latex
  2740. :version "24.1"
  2741. :type 'boolean)
  2742. (defcustom org-latex-to-mathml-jar-file nil
  2743. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2744. Use this to specify additional executable file say a jar file.
  2745. When using MathToWeb as the converter, specify the full-path to
  2746. your mathtoweb.jar file."
  2747. :group 'org-latex
  2748. :version "24.1"
  2749. :type '(choice
  2750. (const :tag "None" nil)
  2751. (file :tag "JAR file" :must-match t)))
  2752. (defcustom org-latex-to-mathml-convert-command nil
  2753. "Command to convert LaTeX fragments to MathML.
  2754. Replace format-specifiers in the command as noted below and use
  2755. `shell-command' to convert LaTeX to MathML.
  2756. %j: Executable file in fully expanded form as specified by
  2757. `org-latex-to-mathml-jar-file'.
  2758. %I: Input LaTeX file in fully expanded form.
  2759. %i: The latex fragment to be converted.
  2760. %o: Output MathML file.
  2761. This command is used by `org-create-math-formula'.
  2762. When using MathToWeb as the converter, set this option to
  2763. \"java -jar %j -unicode -force -df %o %I\".
  2764. When using LaTeXML set this option to
  2765. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2766. :group 'org-latex
  2767. :version "24.1"
  2768. :type '(choice
  2769. (const :tag "None" nil)
  2770. (string :tag "\nShell command")))
  2771. (defcustom org-latex-to-html-convert-command nil
  2772. "Command to convert LaTeX fragments to HTML.
  2773. This command is very open-ended: the output of the command will
  2774. directly replace the LaTeX fragment in the resulting HTML.
  2775. Replace format-specifiers in the command as noted below and use
  2776. `shell-command' to convert LaTeX to HTML.
  2777. %i: The LaTeX fragment to be converted.
  2778. For example, this could be used with LaTeXML as
  2779. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2780. :group 'org-latex
  2781. :package-version '(Org . "9.4")
  2782. :type '(choice
  2783. (const :tag "None" nil)
  2784. (string :tag "Shell command")))
  2785. (defcustom org-preview-latex-default-process 'dvipng
  2786. "The default process to convert LaTeX fragments to image files.
  2787. All available processes and theirs documents can be found in
  2788. `org-preview-latex-process-alist', which see."
  2789. :group 'org-latex
  2790. :version "26.1"
  2791. :package-version '(Org . "9.0")
  2792. :type 'symbol)
  2793. (defcustom org-preview-latex-process-alist
  2794. '((dvipng
  2795. :programs ("latex" "dvipng")
  2796. :description "dvi > png"
  2797. :message "you need to install the programs: latex and dvipng."
  2798. :image-input-type "dvi"
  2799. :image-output-type "png"
  2800. :image-size-adjust (1.0 . 1.0)
  2801. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2802. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2803. (dvisvgm
  2804. :programs ("latex" "dvisvgm")
  2805. :description "dvi > svg"
  2806. :message "you need to install the programs: latex and dvisvgm."
  2807. :image-input-type "dvi"
  2808. :image-output-type "svg"
  2809. :image-size-adjust (1.7 . 1.5)
  2810. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2811. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2812. (imagemagick
  2813. :programs ("latex" "convert")
  2814. :description "pdf > png"
  2815. :message "you need to install the programs: latex and imagemagick."
  2816. :image-input-type "pdf"
  2817. :image-output-type "png"
  2818. :image-size-adjust (1.0 . 1.0)
  2819. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2820. :image-converter
  2821. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2822. "Definitions of external processes for LaTeX previewing.
  2823. Org mode can use some external commands to generate TeX snippet's images for
  2824. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2825. `org-create-formula-image' how to call them.
  2826. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2827. PROPERTIES accepts the following attributes:
  2828. :programs list of strings, required programs.
  2829. :description string, describe the process.
  2830. :message string, message it when required programs cannot be found.
  2831. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2832. :image-output-type string, output file type of image converter (e.g., \"png\").
  2833. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2834. image size showed in buffer and the cdr element is for
  2835. HTML file. This option is only useful for process
  2836. developers, users should use variable
  2837. `org-format-latex-options' instead.
  2838. :post-clean list of strings, files matched are to be cleaned up once
  2839. the image is generated. When nil, the files with \".dvi\",
  2840. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2841. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2842. be cleaned up.
  2843. :latex-header list of strings, the LaTeX header of the snippet file.
  2844. When nil, the fallback value is used instead, which is
  2845. controlled by `org-format-latex-header',
  2846. `org-latex-default-packages-alist' and
  2847. `org-latex-packages-alist', which see.
  2848. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2849. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2850. replaced with values defined below.
  2851. :image-converter list of image converter commands strings. Each of them is
  2852. given to the shell and supports any of the following
  2853. place-holders defined below.
  2854. Place-holders used by `:image-converter' and `:latex-compiler':
  2855. %f input file name
  2856. %b base name of input file
  2857. %o base directory of input file
  2858. %O absolute output file name
  2859. Place-holders only used by `:image-converter':
  2860. %D dpi, which is used to adjust image size by some processing commands.
  2861. %S the image size scale ratio, which is used to adjust image size by some
  2862. processing commands."
  2863. :group 'org-latex
  2864. :version "26.1"
  2865. :package-version '(Org . "9.0")
  2866. :type '(alist :tag "LaTeX to image backends"
  2867. :value-type (plist)))
  2868. (defcustom org-preview-latex-image-directory "ltximg/"
  2869. "Path to store latex preview images.
  2870. A relative path here creates many directories relative to the
  2871. processed Org files paths. An absolute path puts all preview
  2872. images at the same place."
  2873. :group 'org-latex
  2874. :version "26.1"
  2875. :package-version '(Org . "9.0")
  2876. :type 'string)
  2877. (defun org-format-latex-mathml-available-p ()
  2878. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2879. (save-match-data
  2880. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2881. org-latex-to-mathml-convert-command)
  2882. (let ((executable (car (split-string
  2883. org-latex-to-mathml-convert-command))))
  2884. (when (executable-find executable)
  2885. (if (string-match
  2886. "%j" org-latex-to-mathml-convert-command)
  2887. (file-readable-p org-latex-to-mathml-jar-file)
  2888. t))))))
  2889. (defcustom org-format-latex-header "\\documentclass{article}
  2890. \\usepackage[usenames]{color}
  2891. \[PACKAGES]
  2892. \[DEFAULT-PACKAGES]
  2893. \\pagestyle{empty} % do not remove
  2894. % The settings below are copied from fullpage.sty
  2895. \\setlength{\\textwidth}{\\paperwidth}
  2896. \\addtolength{\\textwidth}{-3cm}
  2897. \\setlength{\\oddsidemargin}{1.5cm}
  2898. \\addtolength{\\oddsidemargin}{-2.54cm}
  2899. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2900. \\setlength{\\textheight}{\\paperheight}
  2901. \\addtolength{\\textheight}{-\\headheight}
  2902. \\addtolength{\\textheight}{-\\headsep}
  2903. \\addtolength{\\textheight}{-\\footskip}
  2904. \\addtolength{\\textheight}{-3cm}
  2905. \\setlength{\\topmargin}{1.5cm}
  2906. \\addtolength{\\topmargin}{-2.54cm}"
  2907. "The document header used for processing LaTeX fragments.
  2908. It is imperative that this header make sure that no page number
  2909. appears on the page. The package defined in the variables
  2910. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2911. will either replace the placeholder \"[PACKAGES]\" in this
  2912. header, or they will be appended."
  2913. :group 'org-latex
  2914. :type 'string)
  2915. (defun org-set-packages-alist (var val)
  2916. "Set the packages alist and make sure it has 3 elements per entry."
  2917. (set var (mapcar (lambda (x)
  2918. (if (and (consp x) (= (length x) 2))
  2919. (list (car x) (nth 1 x) t)
  2920. x))
  2921. val)))
  2922. (defun org-get-packages-alist (var)
  2923. "Get the packages alist and make sure it has 3 elements per entry."
  2924. (mapcar (lambda (x)
  2925. (if (and (consp x) (= (length x) 2))
  2926. (list (car x) (nth 1 x) t)
  2927. x))
  2928. (default-value var)))
  2929. (defcustom org-latex-default-packages-alist
  2930. '(("AUTO" "inputenc" t ("pdflatex"))
  2931. ("T1" "fontenc" t ("pdflatex"))
  2932. ("" "graphicx" t)
  2933. ("" "grffile" t)
  2934. ("" "longtable" nil)
  2935. ("" "wrapfig" nil)
  2936. ("" "rotating" nil)
  2937. ("normalem" "ulem" t)
  2938. ("" "amsmath" t)
  2939. ("" "textcomp" t)
  2940. ("" "amssymb" t)
  2941. ("" "capt-of" nil)
  2942. ("" "hyperref" nil))
  2943. "Alist of default packages to be inserted in the header.
  2944. Change this only if one of the packages here causes an
  2945. incompatibility with another package you are using.
  2946. The packages in this list are needed by one part or another of
  2947. Org mode to function properly:
  2948. - inputenc, fontenc: for basic font and character selection
  2949. - graphicx: for including images
  2950. - grffile: allow periods and spaces in graphics file names
  2951. - longtable: For multipage tables
  2952. - wrapfig: for figure placement
  2953. - rotating: for sideways figures and tables
  2954. - ulem: for underline and strike-through
  2955. - amsmath: for subscript and superscript and math environments
  2956. - textcomp, amssymb: for various symbols used
  2957. for interpreting the entities in `org-entities'. You can skip
  2958. some of these packages if you don't use any of their symbols.
  2959. - capt-of: for captions outside of floats
  2960. - hyperref: for cross references
  2961. Therefore you should not modify this variable unless you know
  2962. what you are doing. The one reason to change it anyway is that
  2963. you might be loading some other package that conflicts with one
  2964. of the default packages. Each element is either a cell or
  2965. a string.
  2966. A cell is of the format
  2967. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2968. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2969. when compiling LaTeX snippets into images for inclusion into
  2970. non-LaTeX output.
  2971. COMPILERS is a list of compilers that should include the package,
  2972. see `org-latex-compiler'. If the document compiler is not in the
  2973. list, and the list is non-nil, the package will not be inserted
  2974. in the final document.
  2975. A string will be inserted as-is in the header of the document."
  2976. :group 'org-latex
  2977. :group 'org-export-latex
  2978. :set 'org-set-packages-alist
  2979. :get 'org-get-packages-alist
  2980. :version "26.1"
  2981. :package-version '(Org . "8.3")
  2982. :type '(repeat
  2983. (choice
  2984. (list :tag "options/package pair"
  2985. (string :tag "options")
  2986. (string :tag "package")
  2987. (boolean :tag "Snippet")
  2988. (choice
  2989. (const :tag "For all compilers" nil)
  2990. (repeat :tag "Allowed compiler" string)))
  2991. (string :tag "A line of LaTeX"))))
  2992. (defcustom org-latex-packages-alist nil
  2993. "Alist of packages to be inserted in every LaTeX header.
  2994. These will be inserted after `org-latex-default-packages-alist'.
  2995. Each element is either a cell or a string.
  2996. A cell is of the format:
  2997. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2998. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2999. needed when turning LaTeX snippets into images for inclusion into
  3000. non-LaTeX output.
  3001. COMPILERS is a list of compilers that should include the package,
  3002. see `org-latex-compiler'. If the document compiler is not in the
  3003. list, and the list is non-nil, the package will not be inserted
  3004. in the final document.
  3005. A string will be inserted as-is in the header of the document.
  3006. Make sure that you only list packages here which:
  3007. - you want in every file;
  3008. - do not conflict with the setup in `org-format-latex-header';
  3009. - do not conflict with the default packages in
  3010. `org-latex-default-packages-alist'."
  3011. :group 'org-latex
  3012. :group 'org-export-latex
  3013. :set 'org-set-packages-alist
  3014. :get 'org-get-packages-alist
  3015. :type '(repeat
  3016. (choice
  3017. (list :tag "options/package pair"
  3018. (string :tag "options")
  3019. (string :tag "package")
  3020. (boolean :tag "Snippet"))
  3021. (string :tag "A line of LaTeX"))))
  3022. (defgroup org-appearance nil
  3023. "Settings for Org mode appearance."
  3024. :tag "Org Appearance"
  3025. :group 'org)
  3026. (defcustom org-level-color-stars-only nil
  3027. "Non-nil means fontify only the stars in each headline.
  3028. When nil, the entire headline is fontified.
  3029. Changing it requires restart of `font-lock-mode' to become effective
  3030. also in regions already fontified."
  3031. :group 'org-appearance
  3032. :type 'boolean)
  3033. (defcustom org-hide-leading-stars nil
  3034. "Non-nil means hide the first N-1 stars in a headline.
  3035. This works by using the face `org-hide' for these stars. This
  3036. face is white for a light background, and black for a dark
  3037. background. You may have to customize the face `org-hide' to
  3038. make this work.
  3039. Changing it requires restart of `font-lock-mode' to become effective
  3040. also in regions already fontified.
  3041. You may also set this on a per-file basis by adding one of the following
  3042. lines to the buffer:
  3043. #+STARTUP: hidestars
  3044. #+STARTUP: showstars"
  3045. :group 'org-appearance
  3046. :type 'boolean)
  3047. (defcustom org-hidden-keywords nil
  3048. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3049. For example, a value \\='(title) for this list makes the document's title
  3050. appear in the buffer without the initial \"#+TITLE:\" part."
  3051. :group 'org-appearance
  3052. :version "24.1"
  3053. :type '(set (const :tag "#+AUTHOR" author)
  3054. (const :tag "#+DATE" date)
  3055. (const :tag "#+EMAIL" email)
  3056. (const :tag "#+TITLE" title)))
  3057. (defcustom org-custom-properties nil
  3058. "List of properties (as strings) with a special meaning.
  3059. The default use of these custom properties is to let the user
  3060. hide them with `org-toggle-custom-properties-visibility'."
  3061. :group 'org-properties
  3062. :group 'org-appearance
  3063. :version "24.3"
  3064. :type '(repeat (string :tag "Property Name")))
  3065. (defcustom org-fontify-todo-headline nil
  3066. "Non-nil means change the face of a headline if it is marked as TODO.
  3067. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3068. When this is non-nil, the headline after the keyword is set to the
  3069. `org-headline-todo' as an additional indication."
  3070. :group 'org-appearance
  3071. :package-version '(Org . "9.4")
  3072. :type 'boolean
  3073. :safe t)
  3074. (defcustom org-fontify-done-headline t
  3075. "Non-nil means change the face of a headline if it is marked DONE.
  3076. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3077. When this is non-nil, the headline after the keyword is set to the
  3078. `org-headline-done' as an additional indication."
  3079. :group 'org-appearance
  3080. :package-version '(Org . "9.4")
  3081. :type 'boolean)
  3082. (defcustom org-fontify-emphasized-text t
  3083. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3084. Changing this variable requires a restart of Emacs to take effect."
  3085. :group 'org-appearance
  3086. :type 'boolean)
  3087. (defcustom org-fontify-whole-heading-line nil
  3088. "Non-nil means fontify the whole line for headings.
  3089. This is useful when setting a background color for the
  3090. org-level-* faces."
  3091. :group 'org-appearance
  3092. :type 'boolean)
  3093. (defcustom org-fontify-whole-block-delimiter-line t
  3094. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3095. This is useful when setting a background color for the
  3096. org-block-begin-line and org-block-end-line faces."
  3097. :group 'org-appearance
  3098. :type 'boolean)
  3099. (defcustom org-highlight-latex-and-related nil
  3100. "Non-nil means highlight LaTeX related syntax in the buffer.
  3101. When non-nil, the value should be a list containing any of the
  3102. following symbols:
  3103. `native' Highlight LaTeX snippets and environments natively.
  3104. `latex' Highlight LaTeX snippets and environments.
  3105. `script' Highlight subscript and superscript.
  3106. `entities' Highlight entities."
  3107. :group 'org-appearance
  3108. :version "24.4"
  3109. :package-version '(Org . "8.0")
  3110. :type '(choice
  3111. (const :tag "No highlighting" nil)
  3112. (set :greedy t :tag "Highlight"
  3113. (const :tag "LaTeX snippets and environments (native)" native)
  3114. (const :tag "LaTeX snippets and environments" latex)
  3115. (const :tag "Subscript and superscript" script)
  3116. (const :tag "Entities" entities))))
  3117. (defcustom org-hide-emphasis-markers nil
  3118. "Non-nil mean font-lock should hide the emphasis marker characters."
  3119. :group 'org-appearance
  3120. :type 'boolean
  3121. :safe #'booleanp)
  3122. (defcustom org-hide-macro-markers nil
  3123. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3124. :group 'org-appearance
  3125. :type 'boolean)
  3126. (defcustom org-pretty-entities nil
  3127. "Non-nil means show entities as UTF8 characters.
  3128. When nil, the \\name form remains in the buffer."
  3129. :group 'org-appearance
  3130. :version "24.1"
  3131. :type 'boolean)
  3132. (defcustom org-pretty-entities-include-sub-superscripts t
  3133. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3134. :group 'org-appearance
  3135. :version "24.1"
  3136. :type 'boolean)
  3137. (defvar org-emph-re nil
  3138. "Regular expression for matching emphasis.
  3139. After a match, the match groups contain these elements:
  3140. 0 The match of the full regular expression, including the characters
  3141. before and after the proper match
  3142. 1 The character before the proper match, or empty at beginning of line
  3143. 2 The proper match, including the leading and trailing markers
  3144. 3 The leading marker like * or /, indicating the type of highlighting
  3145. 4 The text between the emphasis markers, not including the markers
  3146. 5 The character after the match, empty at the end of a line")
  3147. (defvar org-verbatim-re nil
  3148. "Regular expression for matching verbatim text.")
  3149. (defvar org-emphasis-regexp-components) ; defined just below
  3150. (defvar org-emphasis-alist) ; defined just below
  3151. (defun org-set-emph-re (var val)
  3152. "Set variable and compute the emphasis regular expression."
  3153. (set var val)
  3154. (when (and (boundp 'org-emphasis-alist)
  3155. (boundp 'org-emphasis-regexp-components)
  3156. org-emphasis-alist org-emphasis-regexp-components)
  3157. (pcase-let*
  3158. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3159. (body (if (<= nl 0) body
  3160. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3161. (template
  3162. (format (concat "\\([%s]\\|^\\)" ;before markers
  3163. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3164. "\\([%s]\\|$\\)") ;after markers
  3165. pre border border body border post)))
  3166. (setq org-emph-re (format template "*/_+"))
  3167. (setq org-verbatim-re (format template "=~")))))
  3168. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3169. ;; set this option proved cumbersome. See this message/thread:
  3170. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3171. (defvar org-emphasis-regexp-components
  3172. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3173. "Components used to build the regular expression for emphasis.
  3174. This is a list with five entries. Terminology: In an emphasis string
  3175. like \" *strong word* \", we call the initial space PREMATCH, the final
  3176. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3177. and \"trong wor\" is the body. The different components in this variable
  3178. specify what is allowed/forbidden in each part:
  3179. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3180. post Chars allowed as postmatch. End of line will be allowed too.
  3181. border The chars *forbidden* as border characters.
  3182. body-regexp A regexp like \".\" to match a body character. Don't use
  3183. non-shy groups here, and don't allow newline here.
  3184. newline The maximum number of newlines allowed in an emphasis exp.
  3185. You need to reload Org or to restart Emacs after setting this.")
  3186. (defcustom org-emphasis-alist
  3187. '(("*" bold)
  3188. ("/" italic)
  3189. ("_" underline)
  3190. ("=" org-verbatim verbatim)
  3191. ("~" org-code verbatim)
  3192. ("+" (:strike-through t)))
  3193. "Alist of characters and faces to emphasize text.
  3194. Text starting and ending with a special character will be emphasized,
  3195. for example *bold*, _underlined_ and /italic/. This variable sets the
  3196. marker characters and the face to be used by font-lock for highlighting
  3197. in Org buffers.
  3198. You need to reload Org or to restart Emacs after customizing this."
  3199. :group 'org-appearance
  3200. :set 'org-set-emph-re
  3201. :version "24.4"
  3202. :package-version '(Org . "8.0")
  3203. :type '(repeat
  3204. (list
  3205. (string :tag "Marker character")
  3206. (choice
  3207. (face :tag "Font-lock-face")
  3208. (plist :tag "Face property list"))
  3209. (option (const verbatim)))))
  3210. (defvar org-protecting-blocks '("src" "example" "export")
  3211. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3212. This is needed for font-lock setup.")
  3213. ;;; Functions and variables from their packages
  3214. ;; Declared here to avoid compiler warnings
  3215. (defvar mark-active)
  3216. ;; Various packages
  3217. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3218. (declare-function calendar-forward-day "cal-move" (arg))
  3219. (declare-function calendar-goto-date "cal-move" (date))
  3220. (declare-function calendar-goto-today "cal-move" ())
  3221. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3222. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3223. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3224. (declare-function cdlatex-tab "ext:cdlatex" ())
  3225. (declare-function dired-get-filename
  3226. "dired"
  3227. (&optional localp no-error-if-not-filep))
  3228. (declare-function iswitchb-read-buffer
  3229. "iswitchb"
  3230. (prompt &optional
  3231. default require-match _predicate start matches-set))
  3232. (declare-function org-agenda-change-all-lines
  3233. "org-agenda"
  3234. (newhead hdmarker &optional fixface just-this))
  3235. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3236. "org-agenda"
  3237. (&optional end))
  3238. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3239. (declare-function org-agenda-format-item
  3240. "org-agenda"
  3241. (extra txt &optional level category tags dotime
  3242. remove-re habitp))
  3243. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3244. (declare-function org-agenda-save-markers-for-cut-and-paste
  3245. "org-agenda"
  3246. (beg end))
  3247. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3248. (declare-function org-agenda-skip "org-agenda" ())
  3249. (declare-function org-attach-expand "org-attach" (file))
  3250. (declare-function org-attach-reveal "org-attach" ())
  3251. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3252. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3253. (declare-function org-indent-mode "org-indent" (&optional arg))
  3254. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3255. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3256. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3257. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3258. (declare-function parse-time-string "parse-time" (string))
  3259. (defvar align-mode-rules-list)
  3260. (defvar calc-embedded-close-formula)
  3261. (defvar calc-embedded-open-formula)
  3262. (defvar calc-embedded-open-mode)
  3263. (defvar font-lock-unfontify-region-function)
  3264. (defvar iswitchb-temp-buflist)
  3265. (defvar org-agenda-tags-todo-honor-ignore-options)
  3266. (defvar remember-data-file)
  3267. (defvar texmathp-why)
  3268. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3269. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3270. (declare-function org-resolve-clocks "org-clock"
  3271. (&optional also-non-dangling-p prompt last-valid))
  3272. (defvar org-clock-start-time)
  3273. (defvar org-clock-marker (make-marker)
  3274. "Marker recording the last clock-in.")
  3275. (defvar org-clock-hd-marker (make-marker)
  3276. "Marker recording the last clock-in, but the headline position.")
  3277. (defvar org-clock-heading ""
  3278. "The heading of the current clock entry.")
  3279. (defun org-clock-is-active ()
  3280. "Return the buffer where the clock is currently running.
  3281. Return nil if no clock is running."
  3282. (marker-buffer org-clock-marker))
  3283. (defun org-check-running-clock ()
  3284. "Check if the current buffer contains the running clock.
  3285. If yes, offer to stop it and to save the buffer with the changes."
  3286. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3287. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3288. (buffer-name))))
  3289. (org-clock-out)
  3290. (when (y-or-n-p "Save changed buffer?")
  3291. (save-buffer))))
  3292. (defun org-clocktable-try-shift (dir n)
  3293. "Check if this line starts a clock table, if yes, shift the time block."
  3294. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3295. (org-clocktable-shift dir n)))
  3296. ;;;###autoload
  3297. (defun org-clock-persistence-insinuate ()
  3298. "Set up hooks for clock persistence."
  3299. (require 'org-clock)
  3300. (add-hook 'org-mode-hook 'org-clock-load)
  3301. (add-hook 'kill-emacs-hook 'org-clock-save))
  3302. (defun org-clock-auto-clockout-insinuate ()
  3303. "Set up hook for auto clocking out when Emacs is idle.
  3304. See `org-clock-auto-clockout-timer'.
  3305. This function is meant to be added to the user configuration."
  3306. (require 'org-clock)
  3307. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3308. (defgroup org-archive nil
  3309. "Options concerning archiving in Org mode."
  3310. :tag "Org Archive"
  3311. :group 'org-structure)
  3312. (defcustom org-archive-location "%s_archive::"
  3313. "The location where subtrees should be archived.
  3314. The value of this variable is a string, consisting of two parts,
  3315. separated by a double-colon. The first part is a filename and
  3316. the second part is a headline.
  3317. When the filename is omitted, archiving happens in the same file.
  3318. %s in the filename will be replaced by the current file
  3319. name (without the directory part). Archiving to a different file
  3320. is useful to keep archived entries from contributing to the
  3321. Org Agenda.
  3322. The archived entries will be filed as subtrees of the specified
  3323. headline. When the headline is omitted, the subtrees are simply
  3324. filed away at the end of the file, as top-level entries. Also in
  3325. the heading you can use %s to represent the file name, this can be
  3326. useful when using the same archive for a number of different files.
  3327. Here are a few examples:
  3328. \"%s_archive::\"
  3329. If the current file is Projects.org, archive in file
  3330. Projects.org_archive, as top-level trees. This is the default.
  3331. \"::* Archived Tasks\"
  3332. Archive in the current file, under the top-level headline
  3333. \"* Archived Tasks\".
  3334. \"~/org/archive.org::\"
  3335. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3336. \"~/org/archive.org::* From %s\"
  3337. Archive in file ~/org/archive.org (absolute path), under headlines
  3338. \"From FILENAME\" where file name is the current file name.
  3339. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3340. The \"datetree/\" string is special, signifying to archive
  3341. items to the datetree. Items are placed in either the CLOSED
  3342. date of the item, or the current date if there is no CLOSED date.
  3343. The heading will be a subentry to the current date. There doesn't
  3344. need to be a heading, but there always needs to be a slash after
  3345. datetree. For example, to store archived items directly in the
  3346. datetree, use \"~/org/datetree.org::datetree/\".
  3347. \"basement::** Finished Tasks\"
  3348. Archive in file ./basement (relative path), as level 3 trees
  3349. below the level 2 heading \"** Finished Tasks\".
  3350. You may define it locally by setting an ARCHIVE property. If
  3351. such a property is found in the file or in an entry, and anywhere
  3352. up the hierarchy, it will be used.
  3353. You can also set it for the whole file using the keyword-syntax:
  3354. #+ARCHIVE: basement::** Finished Tasks"
  3355. :group 'org-archive
  3356. :type 'string)
  3357. (defcustom org-agenda-skip-archived-trees t
  3358. "Non-nil means the agenda will skip any items located in archived trees.
  3359. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3360. variable is no longer recommended, you should leave it at the value t.
  3361. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3362. :group 'org-archive
  3363. :group 'org-agenda-skip
  3364. :type 'boolean)
  3365. (defcustom org-columns-skip-archived-trees t
  3366. "Non-nil means ignore archived trees when creating column view."
  3367. :group 'org-archive
  3368. :group 'org-properties
  3369. :type 'boolean)
  3370. (defcustom org-cycle-open-archived-trees nil
  3371. "Non-nil means `org-cycle' will open archived trees.
  3372. An archived tree is a tree marked with the tag ARCHIVE.
  3373. When nil, archived trees will stay folded. You can still open them with
  3374. normal outline commands like `show-all', but not with the cycling commands."
  3375. :group 'org-archive
  3376. :group 'org-cycle
  3377. :type 'boolean)
  3378. (defcustom org-sparse-tree-open-archived-trees nil
  3379. "Non-nil means sparse tree construction shows matches in archived trees.
  3380. When nil, matches in these trees are highlighted, but the trees are kept in
  3381. collapsed state."
  3382. :group 'org-archive
  3383. :group 'org-sparse-trees
  3384. :type 'boolean)
  3385. (defcustom org-sparse-tree-default-date-type nil
  3386. "The default date type when building a sparse tree.
  3387. When this is nil, a date is a scheduled or a deadline timestamp.
  3388. Otherwise, these types are allowed:
  3389. all: all timestamps
  3390. active: only active timestamps (<...>)
  3391. inactive: only inactive timestamps ([...])
  3392. scheduled: only scheduled timestamps
  3393. deadline: only deadline timestamps"
  3394. :type '(choice (const :tag "Scheduled or deadline" nil)
  3395. (const :tag "All timestamps" all)
  3396. (const :tag "Only active timestamps" active)
  3397. (const :tag "Only inactive timestamps" inactive)
  3398. (const :tag "Only scheduled timestamps" scheduled)
  3399. (const :tag "Only deadline timestamps" deadline)
  3400. (const :tag "Only closed timestamps" closed))
  3401. :version "26.1"
  3402. :package-version '(Org . "8.3")
  3403. :group 'org-sparse-trees)
  3404. (defun org-cycle-hide-archived-subtrees (state)
  3405. "Re-hide all archived subtrees after a visibility state change.
  3406. STATE should be one of the symbols listed in the docstring of
  3407. `org-cycle-hook'."
  3408. (when (and (not org-cycle-open-archived-trees)
  3409. (not (memq state '(overview folded))))
  3410. (save-excursion
  3411. (let* ((globalp (memq state '(contents all)))
  3412. (beg (if globalp (point-min) (point)))
  3413. (end (if globalp (point-max) (org-end-of-subtree t))))
  3414. (org-hide-archived-subtrees beg end)
  3415. (goto-char beg)
  3416. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3417. (message "%s" (substitute-command-keys
  3418. "Subtree is archived and stays closed. Use \
  3419. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3420. (defun org-force-cycle-archived ()
  3421. "Cycle subtree even if it is archived."
  3422. (interactive)
  3423. (setq this-command 'org-cycle)
  3424. (let ((org-cycle-open-archived-trees t))
  3425. (call-interactively 'org-cycle)))
  3426. (defun org-hide-archived-subtrees (beg end)
  3427. "Re-hide all archived subtrees after a visibility state change."
  3428. (org-with-wide-buffer
  3429. (let ((case-fold-search nil)
  3430. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3431. (goto-char beg)
  3432. ;; Include headline point is currently on.
  3433. (beginning-of-line)
  3434. (while (and (< (point) end) (re-search-forward re end t))
  3435. (when (member org-archive-tag (org-get-tags nil t))
  3436. (org-flag-subtree t)
  3437. (org-end-of-subtree t))))))
  3438. (defun org-flag-subtree (flag)
  3439. (save-excursion
  3440. (org-back-to-heading t)
  3441. (org-flag-region (line-end-position)
  3442. (progn (org-end-of-subtree t) (point))
  3443. flag
  3444. 'outline)))
  3445. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3446. ;; Declare Column View Code
  3447. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3448. (declare-function org-columns-compute "org-colview" (property))
  3449. ;; Declare ID code
  3450. (declare-function org-id-store-link "org-id")
  3451. (declare-function org-id-locations-load "org-id")
  3452. (declare-function org-id-locations-save "org-id")
  3453. (defvar org-id-track-globally)
  3454. ;;; Variables for pre-computed regular expressions, all buffer local
  3455. (defvar-local org-todo-regexp nil
  3456. "Matches any of the TODO state keywords.
  3457. Since TODO keywords are case-sensitive, `case-fold-search' is
  3458. expected to be bound to nil when matching against this regexp.")
  3459. (defvar-local org-not-done-regexp nil
  3460. "Matches any of the TODO state keywords except the last one.
  3461. Since TODO keywords are case-sensitive, `case-fold-search' is
  3462. expected to be bound to nil when matching against this regexp.")
  3463. (defvar-local org-not-done-heading-regexp nil
  3464. "Matches a TODO headline that is not done.
  3465. Since TODO keywords are case-sensitive, `case-fold-search' is
  3466. expected to be bound to nil when matching against this regexp.")
  3467. (defvar-local org-todo-line-regexp nil
  3468. "Matches a headline and puts TODO state into group 2 if present.
  3469. Since TODO keywords are case-sensitive, `case-fold-search' is
  3470. expected to be bound to nil when matching against this regexp.")
  3471. (defvar-local org-complex-heading-regexp nil
  3472. "Matches a headline and puts everything into groups:
  3473. group 1: Stars
  3474. group 2: The TODO keyword, maybe
  3475. group 3: Priority cookie
  3476. group 4: True headline
  3477. group 5: Tags
  3478. Since TODO keywords are case-sensitive, `case-fold-search' is
  3479. expected to be bound to nil when matching against this regexp.")
  3480. (defvar-local org-complex-heading-regexp-format nil
  3481. "Printf format to make regexp to match an exact headline.
  3482. This regexp will match the headline of any node which has the
  3483. exact headline text that is put into the format, but may have any
  3484. TODO state, priority and tags.")
  3485. (defvar-local org-todo-line-tags-regexp nil
  3486. "Matches a headline and puts TODO state into group 2 if present.
  3487. Also put tags into group 4 if tags are present.")
  3488. (defconst org-plain-time-of-day-regexp
  3489. (concat
  3490. "\\(\\<[012]?[0-9]"
  3491. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3492. "\\(--?"
  3493. "\\(\\<[012]?[0-9]"
  3494. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3495. "\\)?")
  3496. "Regular expression to match a plain time or time range.
  3497. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3498. groups carry important information:
  3499. 0 the full match
  3500. 1 the first time, range or not
  3501. 8 the second time, if it is a range.")
  3502. (defconst org-plain-time-extension-regexp
  3503. (concat
  3504. "\\(\\<[012]?[0-9]"
  3505. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3506. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3507. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3508. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3509. groups carry important information:
  3510. 0 the full match
  3511. 7 hours of duration
  3512. 9 minutes of duration")
  3513. (defconst org-stamp-time-of-day-regexp
  3514. (concat
  3515. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3516. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3517. "\\(--?"
  3518. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3519. "Regular expression to match a timestamp time or time range.
  3520. After a match, the following groups carry important information:
  3521. 0 the full match
  3522. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3523. 2 the first time, range or not
  3524. 4 the second time, if it is a range.")
  3525. (defconst org-startup-options
  3526. '(("fold" org-startup-folded t)
  3527. ("overview" org-startup-folded t)
  3528. ("nofold" org-startup-folded nil)
  3529. ("showall" org-startup-folded nil)
  3530. ("showeverything" org-startup-folded showeverything)
  3531. ("content" org-startup-folded content)
  3532. ("indent" org-startup-indented t)
  3533. ("noindent" org-startup-indented nil)
  3534. ("num" org-startup-numeroted t)
  3535. ("nonum" org-startup-numeroted nil)
  3536. ("hidestars" org-hide-leading-stars t)
  3537. ("showstars" org-hide-leading-stars nil)
  3538. ("odd" org-odd-levels-only t)
  3539. ("oddeven" org-odd-levels-only nil)
  3540. ("align" org-startup-align-all-tables t)
  3541. ("noalign" org-startup-align-all-tables nil)
  3542. ("shrink" org-startup-shrink-all-tables t)
  3543. ("inlineimages" org-startup-with-inline-images t)
  3544. ("noinlineimages" org-startup-with-inline-images nil)
  3545. ("latexpreview" org-startup-with-latex-preview t)
  3546. ("nolatexpreview" org-startup-with-latex-preview nil)
  3547. ("customtime" org-display-custom-times t)
  3548. ("logdone" org-log-done time)
  3549. ("lognotedone" org-log-done note)
  3550. ("nologdone" org-log-done nil)
  3551. ("lognoteclock-out" org-log-note-clock-out t)
  3552. ("nolognoteclock-out" org-log-note-clock-out nil)
  3553. ("logrepeat" org-log-repeat state)
  3554. ("lognoterepeat" org-log-repeat note)
  3555. ("logdrawer" org-log-into-drawer t)
  3556. ("nologdrawer" org-log-into-drawer nil)
  3557. ("logstatesreversed" org-log-states-order-reversed t)
  3558. ("nologstatesreversed" org-log-states-order-reversed nil)
  3559. ("nologrepeat" org-log-repeat nil)
  3560. ("logreschedule" org-log-reschedule time)
  3561. ("lognotereschedule" org-log-reschedule note)
  3562. ("nologreschedule" org-log-reschedule nil)
  3563. ("logredeadline" org-log-redeadline time)
  3564. ("lognoteredeadline" org-log-redeadline note)
  3565. ("nologredeadline" org-log-redeadline nil)
  3566. ("logrefile" org-log-refile time)
  3567. ("lognoterefile" org-log-refile note)
  3568. ("nologrefile" org-log-refile nil)
  3569. ("fninline" org-footnote-define-inline t)
  3570. ("nofninline" org-footnote-define-inline nil)
  3571. ("fnlocal" org-footnote-section nil)
  3572. ("fnauto" org-footnote-auto-label t)
  3573. ("fnprompt" org-footnote-auto-label nil)
  3574. ("fnconfirm" org-footnote-auto-label confirm)
  3575. ("fnplain" org-footnote-auto-label plain)
  3576. ("fnadjust" org-footnote-auto-adjust t)
  3577. ("nofnadjust" org-footnote-auto-adjust nil)
  3578. ("constcgs" constants-unit-system cgs)
  3579. ("constSI" constants-unit-system SI)
  3580. ("noptag" org-tag-persistent-alist nil)
  3581. ("hideblocks" org-hide-block-startup t)
  3582. ("nohideblocks" org-hide-block-startup nil)
  3583. ("beamer" org-startup-with-beamer-mode t)
  3584. ("entitiespretty" org-pretty-entities t)
  3585. ("entitiesplain" org-pretty-entities nil))
  3586. "Variable associated with STARTUP options for Org.
  3587. Each element is a list of three items: the startup options (as written
  3588. in the #+STARTUP line), the corresponding variable, and the value to set
  3589. this variable to if the option is found. An optional forth element PUSH
  3590. means to push this value onto the list in the variable.")
  3591. (defcustom org-group-tags t
  3592. "When non-nil (the default), use group tags.
  3593. This can be turned on/off through `org-toggle-tags-groups'."
  3594. :group 'org-tags
  3595. :group 'org-startup
  3596. :type 'boolean)
  3597. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3598. (defun org-toggle-tags-groups ()
  3599. "Toggle support for group tags.
  3600. Support for group tags is controlled by the option
  3601. `org-group-tags', which is non-nil by default."
  3602. (interactive)
  3603. (setq org-group-tags (not org-group-tags))
  3604. (cond ((and (derived-mode-p 'org-agenda-mode)
  3605. org-group-tags)
  3606. (org-agenda-redo))
  3607. ((derived-mode-p 'org-mode)
  3608. (let ((org-inhibit-startup t)) (org-mode))))
  3609. (message "Groups tags support has been turned %s"
  3610. (if org-group-tags "on" "off")))
  3611. (defun org--tag-add-to-alist (alist1 alist2)
  3612. "Merge tags from ALIST1 into ALIST2.
  3613. Duplicates tags outside a group are removed. Keywords and order
  3614. are preserved.
  3615. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3616. See `org-tag-alist' for their structure."
  3617. (cond
  3618. ((null alist2) alist1)
  3619. ((null alist1) alist2)
  3620. (t
  3621. (let ((to-add nil)
  3622. (group-flag nil))
  3623. (dolist (tag-pair alist1)
  3624. (pcase tag-pair
  3625. (`(,(or :startgrouptag :startgroup))
  3626. (setq group-flag t)
  3627. (push tag-pair to-add))
  3628. (`(,(or :endgrouptag :endgroup))
  3629. (setq group-flag nil)
  3630. (push tag-pair to-add))
  3631. (`(,(or :grouptags :newline))
  3632. (push tag-pair to-add))
  3633. (`(,tag . ,_)
  3634. ;; Remove duplicates from ALIST1, unless they are in
  3635. ;; a group. Indeed, it makes sense to have a tag appear in
  3636. ;; multiple groups.
  3637. (when (or group-flag (not (assoc tag alist2)))
  3638. (push tag-pair to-add)))
  3639. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3640. ;; Preserve order of ALIST1.
  3641. (append (nreverse to-add) alist2)))))
  3642. (defun org-priority-to-value (s)
  3643. "Convert priority string S to its numeric value."
  3644. (or (save-match-data
  3645. (and (string-match "\\([0-9]+\\)" s)
  3646. (string-to-number (match-string 1 s))))
  3647. (string-to-char s)))
  3648. (defun org-set-regexps-and-options (&optional tags-only)
  3649. "Precompute regular expressions used in the current buffer.
  3650. When optional argument TAGS-ONLY is non-nil, only compute tags
  3651. related expressions."
  3652. (when (derived-mode-p 'org-mode)
  3653. (let ((alist (org-collect-keywords
  3654. (append '("FILETAGS" "TAGS")
  3655. (and (not tags-only)
  3656. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3657. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3658. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3659. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3660. ;; Startup options. Get this early since it does change
  3661. ;; behavior for other options (e.g., tags).
  3662. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3663. (cdr (assoc "STARTUP" alist)))))
  3664. (dolist (option startup)
  3665. (pcase (assoc-string option org-startup-options t)
  3666. (`(,_ ,variable ,value t)
  3667. (unless (listp (symbol-value variable))
  3668. (set (make-local-variable variable) nil))
  3669. (add-to-list variable value))
  3670. (`(,_ ,variable ,value . ,_)
  3671. (set (make-local-variable variable) value))
  3672. (_ nil))))
  3673. (setq-local org-file-tags
  3674. (mapcar #'org-add-prop-inherited
  3675. (cl-mapcan (lambda (value)
  3676. (cl-mapcan
  3677. (lambda (k) (org-split-string k ":"))
  3678. (split-string value)))
  3679. (cdr (assoc "FILETAGS" alist)))))
  3680. (setq org-current-tag-alist
  3681. (org--tag-add-to-alist
  3682. org-tag-persistent-alist
  3683. (let ((tags (mapconcat #'identity
  3684. (cdr (assoc "TAGS" alist))
  3685. "\n")))
  3686. (if (org-string-nw-p tags) (org-tag-string-to-alist tags)
  3687. org-tag-alist))))
  3688. (setq org-tag-groups-alist
  3689. (org-tag-alist-to-groups org-current-tag-alist))
  3690. (unless tags-only
  3691. ;; Properties.
  3692. (let ((properties nil))
  3693. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3694. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3695. (setq properties (org--update-property-plist
  3696. (match-string-no-properties 1 value)
  3697. (match-string-no-properties 2 value)
  3698. properties))))
  3699. (setq-local org-keyword-properties properties))
  3700. ;; Archive location.
  3701. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3702. (when archive (setq-local org-archive-location archive)))
  3703. ;; Category.
  3704. (let ((category (cdr (assoc "CATEGORY" alist))))
  3705. (when category
  3706. (setq-local org-category (intern category))
  3707. (setq-local org-keyword-properties
  3708. (org--update-property-plist
  3709. "CATEGORY" category org-keyword-properties))))
  3710. ;; Columns.
  3711. (let ((column (cdr (assoc "COLUMNS" alist))))
  3712. (when column (setq-local org-columns-default-format column)))
  3713. ;; Constants.
  3714. (let ((store nil))
  3715. (dolist (pair (cl-mapcan #'split-string
  3716. (cdr (assoc "CONSTANTS" alist))))
  3717. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3718. (let* ((name (match-string 1 pair))
  3719. (value (match-string 2 pair))
  3720. (old (assoc name store)))
  3721. (if old (setcdr old value)
  3722. (push (cons name value) store)))))
  3723. (setq org-table-formula-constants-local store))
  3724. ;; Link abbreviations.
  3725. (let ((links
  3726. (delq nil
  3727. (mapcar
  3728. (lambda (value)
  3729. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3730. (cons (match-string-no-properties 1 value)
  3731. (match-string-no-properties 2 value))))
  3732. (cdr (assoc "LINK" alist))))))
  3733. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3734. ;; Priorities.
  3735. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3736. (pcase (and value (split-string value))
  3737. (`(,high ,low ,default . ,_)
  3738. (setq-local org-highest-priority (org-priority-to-value high))
  3739. (setq-local org-lowest-priority (org-priority-to-value low))
  3740. (setq-local org-default-priority (org-priority-to-value default)))))
  3741. ;; Scripts.
  3742. (let ((value (cdr (assoc "OPTIONS" alist))))
  3743. (dolist (option value)
  3744. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3745. (setq-local org-use-sub-superscripts
  3746. (read (match-string 1 option))))))
  3747. ;; TODO keywords.
  3748. (setq-local org-todo-kwd-alist nil)
  3749. (setq-local org-todo-key-alist nil)
  3750. (setq-local org-todo-key-trigger nil)
  3751. (setq-local org-todo-keywords-1 nil)
  3752. (setq-local org-done-keywords nil)
  3753. (setq-local org-todo-heads nil)
  3754. (setq-local org-todo-sets nil)
  3755. (setq-local org-todo-log-states nil)
  3756. (let ((todo-sequences
  3757. (or (append (mapcar (lambda (value)
  3758. (cons 'type (split-string value)))
  3759. (cdr (assoc "TYP_TODO" alist)))
  3760. (mapcar (lambda (value)
  3761. (cons 'sequence (split-string value)))
  3762. (append (cdr (assoc "TODO" alist))
  3763. (cdr (assoc "SEQ_TODO" alist)))))
  3764. (let ((d (default-value 'org-todo-keywords)))
  3765. (if (not (stringp (car d))) d
  3766. ;; XXX: Backward compatibility code.
  3767. (list (cons org-todo-interpretation d)))))))
  3768. (dolist (sequence todo-sequences)
  3769. (let* ((sequence (or (run-hook-with-args-until-success
  3770. 'org-todo-setup-filter-hook sequence)
  3771. sequence))
  3772. (sequence-type (car sequence))
  3773. (keywords (cdr sequence))
  3774. (sep (member "|" keywords))
  3775. names alist)
  3776. (dolist (k (remove "|" keywords))
  3777. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3778. k)
  3779. (error "Invalid TODO keyword %s" k))
  3780. (let ((name (match-string 1 k))
  3781. (key (match-string 2 k))
  3782. (log (org-extract-log-state-settings k)))
  3783. (push name names)
  3784. (push (cons name (and key (string-to-char key))) alist)
  3785. (when log (push log org-todo-log-states))))
  3786. (let* ((names (nreverse names))
  3787. (done (if sep (org-remove-keyword-keys (cdr sep))
  3788. (last names)))
  3789. (head (car names))
  3790. (tail (list sequence-type head (car done) (org-last done))))
  3791. (add-to-list 'org-todo-heads head 'append)
  3792. (push names org-todo-sets)
  3793. (setq org-done-keywords (append org-done-keywords done nil))
  3794. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3795. (setq org-todo-key-alist
  3796. (append org-todo-key-alist
  3797. (and alist
  3798. (append '((:startgroup))
  3799. (nreverse alist)
  3800. '((:endgroup))))))
  3801. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3802. (setq org-todo-sets (nreverse org-todo-sets)
  3803. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3804. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3805. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3806. ;; Compute the regular expressions and other local variables.
  3807. ;; Using `org-outline-regexp-bol' would complicate them much,
  3808. ;; because of the fixed white space at the end of that string.
  3809. (unless org-done-keywords
  3810. (setq org-done-keywords
  3811. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3812. (setq org-not-done-keywords
  3813. (org-delete-all org-done-keywords
  3814. (copy-sequence org-todo-keywords-1))
  3815. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3816. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3817. org-not-done-heading-regexp
  3818. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3819. org-todo-line-regexp
  3820. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3821. org-complex-heading-regexp
  3822. (concat "^\\(\\*+\\)"
  3823. "\\(?: +" org-todo-regexp "\\)?"
  3824. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3825. "\\(?: +\\(.*?\\)\\)??"
  3826. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3827. "[ \t]*$")
  3828. org-complex-heading-regexp-format
  3829. (concat "^\\(\\*+\\)"
  3830. "\\(?: +" org-todo-regexp "\\)?"
  3831. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3832. "\\(?: +"
  3833. ;; Stats cookies can be stuck to body.
  3834. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3835. "\\(%s\\)"
  3836. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3837. "\\)"
  3838. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3839. "[ \t]*$")
  3840. org-todo-line-tags-regexp
  3841. (concat "^\\(\\*+\\)"
  3842. "\\(?: +" org-todo-regexp "\\)?"
  3843. "\\(?: +\\(.*?\\)\\)??"
  3844. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3845. "[ \t]*$"))
  3846. (org-compute-latex-and-related-regexp)))))
  3847. (defun org-collect-keywords (keywords &optional unique directory)
  3848. "Return values for KEYWORDS in current buffer, as an alist.
  3849. KEYWORDS is a list of strings. Return value is a list of
  3850. elements with the pattern:
  3851. (NAME . LIST-OF-VALUES)
  3852. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3853. is a list of non-empty values, as strings, in order of appearance
  3854. in the buffer.
  3855. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3856. value, empty or not, appearing in the buffer, as a string.
  3857. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3858. (VALUE . DIRECTORY)
  3859. where VALUE is the regular value, and DIRECTORY is the variable
  3860. `default-directory' for the buffer containing the keyword. This
  3861. is important for values containing relative file names, since the
  3862. function follows SETUPFILE keywords, and may change its working
  3863. directory."
  3864. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3865. (unique (mapcar #'upcase unique))
  3866. (alist (org--collect-keywords-1
  3867. keywords unique directory
  3868. (and buffer-file-name (list buffer-file-name))
  3869. nil)))
  3870. ;; Re-order results.
  3871. (dolist (entry alist)
  3872. (pcase entry
  3873. (`(,_ . ,(and value (pred consp)))
  3874. (setcdr entry (nreverse value)))))
  3875. (nreverse alist)))
  3876. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3877. (org-with-point-at 1
  3878. (let ((case-fold-search t)
  3879. (regexp (org-make-options-regexp keywords)))
  3880. (while (and keywords (re-search-forward regexp nil t))
  3881. (let ((element (org-element-at-point)))
  3882. (when (eq 'keyword (org-element-type element))
  3883. (let ((value (org-element-property :value element)))
  3884. (pcase (org-element-property :key element)
  3885. ("SETUPFILE"
  3886. (when (and (org-string-nw-p value)
  3887. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3888. (let* ((uri (org-strip-quotes value))
  3889. (uri-is-url (org-file-url-p uri))
  3890. (uri (if uri-is-url
  3891. uri
  3892. (expand-file-name uri))))
  3893. (unless (member uri files)
  3894. (with-temp-buffer
  3895. (unless uri-is-url
  3896. (setq default-directory (file-name-directory uri)))
  3897. (let ((contents (org-file-contents uri :noerror)))
  3898. (when contents
  3899. (insert contents)
  3900. ;; Fake Org mode: `org-element-at-point'
  3901. ;; doesn't need full set-up.
  3902. (let ((major-mode 'org-mode))
  3903. (setq alist
  3904. (org--collect-keywords-1
  3905. keywords unique directory
  3906. (cons uri files)
  3907. alist))))))))))
  3908. (keyword
  3909. (let ((entry (assoc keyword alist))
  3910. (final
  3911. (cond ((not (member keyword directory)) value)
  3912. (buffer-file-name
  3913. (cons value
  3914. (file-name-directory buffer-file-name)))
  3915. (t (cons value default-directory)))))
  3916. (cond ((member keyword unique)
  3917. (push (cons keyword final) alist)
  3918. (setq keywords (remove keyword keywords))
  3919. (setq regexp (org-make-options-regexp keywords)))
  3920. ((not (org-string-nw-p value)) nil)
  3921. ((null entry) (push (list keyword final) alist))
  3922. (t (push final (cdr entry)))))))))))
  3923. alist)))
  3924. (defun org-tag-string-to-alist (s)
  3925. "Return tag alist associated to string S.
  3926. S is a value for TAGS keyword or produced with
  3927. `org-tag-alist-to-string'. Return value is an alist suitable for
  3928. `org-tag-alist' or `org-tag-persistent-alist'."
  3929. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3930. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3931. "\\(?:(\\(.\\))\\)?\\'"))
  3932. alist group-flag)
  3933. (dolist (tokens lines (cdr (nreverse alist)))
  3934. (push '(:newline) alist)
  3935. (while tokens
  3936. (let ((token (pop tokens)))
  3937. (pcase token
  3938. ("{"
  3939. (push '(:startgroup) alist)
  3940. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3941. ("}"
  3942. (push '(:endgroup) alist)
  3943. (setq group-flag nil))
  3944. ("["
  3945. (push '(:startgrouptag) alist)
  3946. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3947. ("]"
  3948. (push '(:endgrouptag) alist)
  3949. (setq group-flag nil))
  3950. (":"
  3951. (push '(:grouptags) alist))
  3952. ((guard (string-match tag-re token))
  3953. (let ((tag (match-string 1 token))
  3954. (key (and (match-beginning 2)
  3955. (string-to-char (match-string 2 token)))))
  3956. ;; Push all tags in groups, no matter if they already
  3957. ;; appear somewhere else in the list.
  3958. (when (or group-flag (not (assoc tag alist)))
  3959. (push (cons tag key) alist))))))))))
  3960. (defun org-tag-alist-to-string (alist &optional skip-key)
  3961. "Return tag string associated to ALIST.
  3962. ALIST is an alist, as defined in `org-tag-alist' or
  3963. `org-tag-persistent-alist', or produced with
  3964. `org-tag-string-to-alist'.
  3965. Return value is a string suitable as a value for \"TAGS\"
  3966. keyword.
  3967. When optional argument SKIP-KEY is non-nil, skip selection keys
  3968. next to tags."
  3969. (mapconcat (lambda (token)
  3970. (pcase token
  3971. (`(:startgroup) "{")
  3972. (`(:endgroup) "}")
  3973. (`(:startgrouptag) "[")
  3974. (`(:endgrouptag) "]")
  3975. (`(:grouptags) ":")
  3976. (`(:newline) "\\n")
  3977. ((and
  3978. (guard (not skip-key))
  3979. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3980. (format "%s(%c)" tag key))
  3981. (`(,(and tag (pred stringp)) . ,_) tag)
  3982. (_ (user-error "Invalid tag token: %S" token))))
  3983. alist
  3984. " "))
  3985. (defun org-tag-alist-to-groups (alist)
  3986. "Return group alist from tag ALIST.
  3987. ALIST is an alist, as defined in `org-tag-alist' or
  3988. `org-tag-persistent-alist', or produced with
  3989. `org-tag-string-to-alist'. Return value is an alist following
  3990. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3991. a string, summarizing TAGS, as a list of strings."
  3992. (let (groups group-status current-group)
  3993. (dolist (token alist (nreverse groups))
  3994. (pcase token
  3995. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3996. (`(,(or :endgroup :endgrouptag))
  3997. (when (eq group-status 'append)
  3998. (push (nreverse current-group) groups))
  3999. (setq group-status nil current-group nil))
  4000. (`(:grouptags) (setq group-status 'append))
  4001. ((and `(,tag . ,_) (guard group-status))
  4002. (if (eq group-status 'append) (push tag current-group)
  4003. (setq current-group (list tag))))
  4004. (_ nil)))))
  4005. (defvar org--file-cache (make-hash-table :test #'equal)
  4006. "Hash table to store contents of files referenced via a URL.
  4007. This is the cache of file URLs read using `org-file-contents'.")
  4008. (defun org-reset-file-cache ()
  4009. "Reset the cache of files downloaded by `org-file-contents'."
  4010. (clrhash org--file-cache))
  4011. (defun org-file-url-p (file)
  4012. "Non-nil if FILE is a URL."
  4013. (require 'ffap)
  4014. (string-match-p ffap-url-regexp file))
  4015. (defun org-file-contents (file &optional noerror nocache)
  4016. "Return the contents of FILE, as a string.
  4017. FILE can be a file name or URL.
  4018. If FILE is a URL, download the contents. If the URL contents are
  4019. already cached in the `org--file-cache' hash table, the download step
  4020. is skipped.
  4021. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4022. from file or URL, and return nil.
  4023. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4024. is available. This option applies only if FILE is a URL."
  4025. (let* ((is-url (org-file-url-p file))
  4026. (cache (and is-url
  4027. (not nocache)
  4028. (gethash file org--file-cache))))
  4029. (cond
  4030. (cache)
  4031. (is-url
  4032. (with-current-buffer (url-retrieve-synchronously file)
  4033. (goto-char (point-min))
  4034. ;; Move point to after the url-retrieve header.
  4035. (search-forward "\n\n" nil :move)
  4036. ;; Search for the success code only in the url-retrieve header.
  4037. (if (save-excursion
  4038. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4039. ;; Update the cache `org--file-cache' and return contents.
  4040. (puthash file
  4041. (buffer-substring-no-properties (point) (point-max))
  4042. org--file-cache)
  4043. (funcall (if noerror #'message #'user-error)
  4044. "Unable to fetch file from %S"
  4045. file)
  4046. nil)))
  4047. (t
  4048. (with-temp-buffer
  4049. (condition-case nil
  4050. (progn
  4051. (insert-file-contents file)
  4052. (buffer-string))
  4053. (file-error
  4054. (funcall (if noerror #'message #'user-error)
  4055. "Unable to read file %S"
  4056. file)
  4057. nil)))))))
  4058. (defun org-extract-log-state-settings (x)
  4059. "Extract the log state setting from a TODO keyword string.
  4060. This will extract info from a string like \"WAIT(w@/!)\"."
  4061. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4062. (let ((kw (match-string 1 x))
  4063. (log1 (and (match-end 3) (match-string 3 x)))
  4064. (log2 (and (match-end 4) (match-string 4 x))))
  4065. (and (or log1 log2)
  4066. (list kw
  4067. (and log1 (if (equal log1 "!") 'time 'note))
  4068. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4069. (defun org-remove-keyword-keys (list)
  4070. "Remove a pair of parenthesis at the end of each string in LIST."
  4071. (mapcar (lambda (x)
  4072. (if (string-match "(.*)$" x)
  4073. (substring x 0 (match-beginning 0))
  4074. x))
  4075. list))
  4076. (defun org-assign-fast-keys (alist)
  4077. "Assign fast keys to a keyword-key alist.
  4078. Respect keys that are already there."
  4079. (let (new e (alt ?0))
  4080. (while (setq e (pop alist))
  4081. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4082. (cdr e)) ;; Key already assigned.
  4083. (push e new)
  4084. (let ((clist (string-to-list (downcase (car e))))
  4085. (used (append new alist)))
  4086. (when (= (car clist) ?@)
  4087. (pop clist))
  4088. (while (and clist (rassoc (car clist) used))
  4089. (pop clist))
  4090. (unless clist
  4091. (while (rassoc alt used)
  4092. (cl-incf alt)))
  4093. (push (cons (car e) (or (car clist) alt)) new))))
  4094. (nreverse new)))
  4095. ;;; Some variables used in various places
  4096. (defvar org-window-configuration nil
  4097. "Used in various places to store a window configuration.")
  4098. (defvar org-selected-window nil
  4099. "Used in various places to store a window configuration.")
  4100. (defvar org-finish-function nil
  4101. "Function to be called when `C-c C-c' is used.
  4102. This is for getting out of special buffers like capture.")
  4103. (defvar org-last-state)
  4104. ;; Defined somewhere in this file, but used before definition.
  4105. (defvar org-entities) ;; defined in org-entities.el
  4106. (defvar org-struct-menu)
  4107. (defvar org-org-menu)
  4108. (defvar org-tbl-menu)
  4109. ;;;; Define the Org mode
  4110. (defun org-before-change-function (_beg _end)
  4111. "Every change indicates that a table might need an update."
  4112. (setq org-table-may-need-update t))
  4113. (defvar org-mode-map)
  4114. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4115. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4116. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4117. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4118. (defvar bidi-paragraph-direction)
  4119. (defvar buffer-face-mode-face)
  4120. (require 'outline)
  4121. ;; Other stuff we need.
  4122. (require 'time-date)
  4123. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4124. (require 'easymenu)
  4125. (autoload 'easy-menu-add "easymenu")
  4126. (require 'overlay)
  4127. (require 'org-entities)
  4128. (require 'org-faces)
  4129. (require 'org-list)
  4130. (require 'org-pcomplete)
  4131. (require 'org-src)
  4132. (require 'org-footnote)
  4133. (require 'org-macro)
  4134. ;; babel
  4135. (require 'ob)
  4136. ;;;###autoload
  4137. (define-derived-mode org-mode outline-mode "Org"
  4138. "Outline-based notes management and organizer, alias
  4139. \"Carsten's outline-mode for keeping track of everything.\"
  4140. Org mode develops organizational tasks around a NOTES file which
  4141. contains information about projects as plain text. Org mode is
  4142. implemented on top of Outline mode, which is ideal to keep the content
  4143. of large files well structured. It supports ToDo items, deadlines and
  4144. time stamps, which magically appear in the diary listing of the Emacs
  4145. calendar. Tables are easily created with a built-in table editor.
  4146. Plain text URL-like links connect to websites, emails (VM), Usenet
  4147. messages (Gnus), BBDB entries, and any files related to the project.
  4148. For printing and sharing of notes, an Org file (or a part of it)
  4149. can be exported as a structured ASCII or HTML file.
  4150. The following commands are available:
  4151. \\{org-mode-map}"
  4152. (org-load-modules-maybe)
  4153. (org-install-agenda-files-menu)
  4154. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4155. (add-to-invisibility-spec '(org-hide-block . t))
  4156. (add-to-invisibility-spec '(org-hide-drawer . t))
  4157. (setq-local outline-regexp org-outline-regexp)
  4158. (setq-local outline-level 'org-outline-level)
  4159. (setq bidi-paragraph-direction 'left-to-right)
  4160. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4161. (unless org-display-table
  4162. (setq org-display-table (make-display-table)))
  4163. (set-display-table-slot
  4164. org-display-table 4
  4165. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4166. org-ellipsis)))
  4167. (setq buffer-display-table org-display-table))
  4168. (org-set-regexps-and-options)
  4169. (org-set-font-lock-defaults)
  4170. (when (and org-tag-faces (not org-tags-special-faces-re))
  4171. ;; tag faces set outside customize.... force initialization.
  4172. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4173. ;; Calc embedded
  4174. (setq-local calc-embedded-open-mode "# ")
  4175. ;; Modify a few syntax entries
  4176. (modify-syntax-entry ?\" "\"")
  4177. (modify-syntax-entry ?\\ "_")
  4178. (modify-syntax-entry ?~ "_")
  4179. (modify-syntax-entry ?< "(>")
  4180. (modify-syntax-entry ?> ")<")
  4181. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4182. ;; Activate before-change-function
  4183. (setq-local org-table-may-need-update t)
  4184. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4185. ;; Check for running clock before killing a buffer
  4186. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4187. ;; Initialize macros templates.
  4188. (org-macro-initialize-templates)
  4189. ;; Initialize radio targets.
  4190. (org-update-radio-target-regexp)
  4191. ;; Indentation.
  4192. (setq-local indent-line-function 'org-indent-line)
  4193. (setq-local indent-region-function 'org-indent-region)
  4194. ;; Filling and auto-filling.
  4195. (org-setup-filling)
  4196. ;; Comments.
  4197. (org-setup-comments-handling)
  4198. ;; Initialize cache.
  4199. (org-element-cache-reset)
  4200. ;; Beginning/end of defun
  4201. (setq-local beginning-of-defun-function 'org-backward-element)
  4202. (setq-local end-of-defun-function
  4203. (lambda ()
  4204. (if (not (org-at-heading-p))
  4205. (org-forward-element)
  4206. (org-forward-element)
  4207. (forward-char -1))))
  4208. ;; Next error for sparse trees
  4209. (setq-local next-error-function 'org-occur-next-match)
  4210. ;; Make commit log messages from Org documents easier.
  4211. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4212. ;; Make sure dependence stuff works reliably, even for users who set it
  4213. ;; too late :-(
  4214. (if org-enforce-todo-dependencies
  4215. (add-hook 'org-blocker-hook
  4216. 'org-block-todo-from-children-or-siblings-or-parent)
  4217. (remove-hook 'org-blocker-hook
  4218. 'org-block-todo-from-children-or-siblings-or-parent))
  4219. (if org-enforce-todo-checkbox-dependencies
  4220. (add-hook 'org-blocker-hook
  4221. 'org-block-todo-from-checkboxes)
  4222. (remove-hook 'org-blocker-hook
  4223. 'org-block-todo-from-checkboxes))
  4224. ;; Align options lines
  4225. (setq-local
  4226. align-mode-rules-list
  4227. '((org-in-buffer-settings
  4228. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4229. (modes . '(org-mode)))))
  4230. ;; Make isearch reveal context
  4231. (setq-local outline-isearch-open-invisible-function
  4232. (lambda (&rest _) (org-show-context 'isearch)))
  4233. ;; Setup the pcomplete hooks
  4234. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4235. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4236. (setq-local pcomplete-default-completion-function #'ignore)
  4237. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4238. (setq-local pcomplete-termination-string "")
  4239. (add-hook 'completion-at-point-functions
  4240. #'pcomplete-completions-at-point nil t)
  4241. (setq-local buffer-face-mode-face 'org-default)
  4242. ;; If empty file that did not turn on Org mode automatically, make
  4243. ;; it to.
  4244. (when (and org-insert-mode-line-in-empty-file
  4245. (called-interactively-p 'any)
  4246. (= (point-min) (point-max)))
  4247. (insert "# -*- mode: org -*-\n\n"))
  4248. (unless org-inhibit-startup
  4249. (org-unmodified
  4250. (when org-startup-with-beamer-mode (org-beamer-mode))
  4251. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4252. (org-table-map-tables
  4253. (cond ((and org-startup-align-all-tables
  4254. org-startup-shrink-all-tables)
  4255. (lambda () (org-table-align) (org-table-shrink)))
  4256. (org-startup-align-all-tables #'org-table-align)
  4257. (t #'org-table-shrink))
  4258. t))
  4259. (when org-startup-with-inline-images (org-display-inline-images))
  4260. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4261. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4262. (when org-startup-truncated (setq truncate-lines t))
  4263. (when org-startup-numeroted (require 'org-num) (org-num-mode 1))
  4264. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4265. ;; Activate `org-table-header-line-mode'
  4266. (when org-table-header-line-p
  4267. (org-table-header-line-mode 1))
  4268. ;; Try to set `org-hide' face correctly.
  4269. (let ((foreground (org-find-invisible-foreground)))
  4270. (when foreground
  4271. (set-face-foreground 'org-hide foreground))))
  4272. ;; Update `customize-package-emacs-version-alist'
  4273. (add-to-list 'customize-package-emacs-version-alist
  4274. '(Org ("8.0" . "24.4")
  4275. ("8.1" . "24.4")
  4276. ("8.2" . "24.4")
  4277. ("8.2.7" . "24.4")
  4278. ("8.3" . "26.1")
  4279. ("9.0" . "26.1")
  4280. ("9.1" . "26.1")
  4281. ("9.2" . "27.1")
  4282. ("9.3" . "27.1")
  4283. ("9.4" . "28.1")))
  4284. (defvar org-mode-transpose-word-syntax-table
  4285. (let ((st (make-syntax-table text-mode-syntax-table)))
  4286. (dolist (c org-emphasis-alist st)
  4287. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4288. (when (fboundp 'abbrev-table-put)
  4289. (abbrev-table-put org-mode-abbrev-table
  4290. :parents (list text-mode-abbrev-table)))
  4291. (defun org-find-invisible-foreground ()
  4292. (let ((candidates (remove
  4293. "unspecified-bg"
  4294. (nconc
  4295. (list (face-background 'default)
  4296. (face-background 'org-default))
  4297. (mapcar
  4298. (lambda (alist)
  4299. (when (boundp alist)
  4300. (cdr (assq 'background-color (symbol-value alist)))))
  4301. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4302. (list (face-foreground 'org-hide))))))
  4303. (car (remove nil candidates))))
  4304. (defun org-current-time (&optional rounding-minutes past)
  4305. "Current time, possibly rounded to ROUNDING-MINUTES.
  4306. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4307. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4308. the rounding returns a past time."
  4309. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4310. (car org-time-stamp-rounding-minutes)))
  4311. (now (current-time)))
  4312. (if (< r 1)
  4313. now
  4314. (let* ((time (decode-time now))
  4315. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4316. (nthcdr 2 time))))
  4317. (if (or (not past) (org-time-less-p res now))
  4318. res
  4319. (org-time-subtract res (* r 60)))))))
  4320. (defun org-today ()
  4321. "Return today date, considering `org-extend-today-until'."
  4322. (time-to-days
  4323. (org-time-since (* 3600 org-extend-today-until))))
  4324. ;;;; Font-Lock stuff, including the activators
  4325. (require 'font-lock)
  4326. (defconst org-match-sexp-depth 3
  4327. "Number of stacked braces for sub/superscript matching.")
  4328. (defun org-create-multibrace-regexp (left right n)
  4329. "Create a regular expression which will match a balanced sexp.
  4330. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4331. as single character strings.
  4332. The regexp returned will match the entire expression including the
  4333. delimiters. It will also define a single group which contains the
  4334. match except for the outermost delimiters. The maximum depth of
  4335. stacked delimiters is N. Escaping delimiters is not possible."
  4336. (let* ((nothing (concat "[^" left right "]*?"))
  4337. (or "\\|")
  4338. (re nothing)
  4339. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4340. (while (> n 1)
  4341. (setq n (1- n)
  4342. re (concat re or next)
  4343. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4344. (concat left "\\(" re "\\)" right)))
  4345. (defconst org-match-substring-regexp
  4346. (concat
  4347. "\\(\\S-\\)\\([_^]\\)\\("
  4348. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4349. "\\|"
  4350. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4351. "\\|"
  4352. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4353. "The regular expression matching a sub- or superscript.")
  4354. (defconst org-match-substring-with-braces-regexp
  4355. (concat
  4356. "\\(\\S-\\)\\([_^]\\)"
  4357. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4358. "The regular expression matching a sub- or superscript, forcing braces.")
  4359. (defvar org-emph-face nil)
  4360. (defun org-do-emphasis-faces (limit)
  4361. "Run through the buffer and emphasize strings."
  4362. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4363. (car org-emphasis-regexp-components))))
  4364. (catch :exit
  4365. (while (re-search-forward quick-re limit t)
  4366. (let* ((marker (match-string 2))
  4367. (verbatim? (member marker '("~" "="))))
  4368. (when (save-excursion
  4369. (goto-char (match-beginning 0))
  4370. (and
  4371. ;; Do not match table hlines.
  4372. (not (and (equal marker "+")
  4373. (org-match-line
  4374. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4375. ;; Do not match headline stars. Do not consider
  4376. ;; stars of a headline as closing marker for bold
  4377. ;; markup either.
  4378. (not (and (equal marker "*")
  4379. (save-excursion
  4380. (forward-char)
  4381. (skip-chars-backward "*")
  4382. (looking-at-p org-outline-regexp-bol))))
  4383. ;; Match full emphasis markup regexp.
  4384. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4385. ;; Do not span over paragraph boundaries.
  4386. (not (string-match-p org-element-paragraph-separate
  4387. (match-string 2)))
  4388. ;; Do not span over cells in table rows.
  4389. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4390. (string-match-p "|" (match-string 4))))))
  4391. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4392. (m (if org-hide-emphasis-markers 4 2)))
  4393. (font-lock-prepend-text-property
  4394. (match-beginning m) (match-end m) 'face face)
  4395. (when verbatim?
  4396. (org-remove-flyspell-overlays-in
  4397. (match-beginning 0) (match-end 0))
  4398. (remove-text-properties (match-beginning 2) (match-end 2)
  4399. '(display t invisible t intangible t)))
  4400. (add-text-properties (match-beginning 2) (match-end 2)
  4401. '(font-lock-multiline t org-emphasis t))
  4402. (when (and org-hide-emphasis-markers
  4403. (not (org-at-comment-p)))
  4404. (add-text-properties (match-end 4) (match-beginning 5)
  4405. '(invisible org-link))
  4406. (add-text-properties (match-beginning 3) (match-end 3)
  4407. '(invisible org-link)))
  4408. (throw :exit t))))))))
  4409. (defun org-emphasize (&optional char)
  4410. "Insert or change an emphasis, i.e. a font like bold or italic.
  4411. If there is an active region, change that region to a new emphasis.
  4412. If there is no region, just insert the marker characters and position
  4413. the cursor between them.
  4414. CHAR should be the marker character. If it is a space, it means to
  4415. remove the emphasis of the selected region.
  4416. If CHAR is not given (for example in an interactive call) it will be
  4417. prompted for."
  4418. (interactive)
  4419. (let ((erc org-emphasis-regexp-components)
  4420. (string "") beg end move s)
  4421. (if (org-region-active-p)
  4422. (setq beg (region-beginning)
  4423. end (region-end)
  4424. string (buffer-substring beg end))
  4425. (setq move t))
  4426. (unless char
  4427. (message "Emphasis marker or tag: [%s]"
  4428. (mapconcat #'car org-emphasis-alist ""))
  4429. (setq char (read-char-exclusive)))
  4430. (if (equal char ?\s)
  4431. (setq s ""
  4432. move nil)
  4433. (unless (assoc (char-to-string char) org-emphasis-alist)
  4434. (user-error "No such emphasis marker: \"%c\"" char))
  4435. (setq s (char-to-string char)))
  4436. (while (and (> (length string) 1)
  4437. (equal (substring string 0 1) (substring string -1))
  4438. (assoc (substring string 0 1) org-emphasis-alist))
  4439. (setq string (substring string 1 -1)))
  4440. (setq string (concat s string s))
  4441. (when beg (delete-region beg end))
  4442. (unless (or (bolp)
  4443. (string-match (concat "[" (nth 0 erc) "\n]")
  4444. (char-to-string (char-before (point)))))
  4445. (insert " "))
  4446. (unless (or (eobp)
  4447. (string-match (concat "[" (nth 1 erc) "\n]")
  4448. (char-to-string (char-after (point)))))
  4449. (insert " ") (backward-char 1))
  4450. (insert string)
  4451. (and move (backward-char 1))))
  4452. (defconst org-nonsticky-props
  4453. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4454. (defsubst org-rear-nonsticky-at (pos)
  4455. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4456. (defun org-activate-links (limit)
  4457. "Add link properties to links.
  4458. This includes angle, plain, and bracket links."
  4459. (catch :exit
  4460. (while (re-search-forward org-link-any-re limit t)
  4461. (let* ((start (match-beginning 0))
  4462. (end (match-end 0))
  4463. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4464. (visible-end (or (match-end 3) (match-end 2)))
  4465. (style (cond ((eq ?< (char-after start)) 'angle)
  4466. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4467. (t 'plain))))
  4468. (when (and (memq style org-highlight-links)
  4469. ;; Do not span over paragraph boundaries.
  4470. (not (string-match-p org-element-paragraph-separate
  4471. (match-string 0)))
  4472. ;; Do not confuse plain links with tags.
  4473. (not (and (eq style 'plain)
  4474. (let ((face (get-text-property
  4475. (max (1- start) (point-min)) 'face)))
  4476. (if (consp face) (memq 'org-tag face)
  4477. (eq 'org-tag face))))))
  4478. (let* ((link-object (save-excursion
  4479. (goto-char start)
  4480. (save-match-data (org-element-link-parser))))
  4481. (link (org-element-property :raw-link link-object))
  4482. (type (org-element-property :type link-object))
  4483. (path (org-element-property :path link-object))
  4484. (properties ;for link's visible part
  4485. (list
  4486. 'face (pcase (org-link-get-parameter type :face)
  4487. ((and (pred functionp) face) (funcall face path))
  4488. ((and (pred facep) face) face)
  4489. ((and (pred consp) face) face) ;anonymous
  4490. (_ 'org-link))
  4491. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4492. 'highlight)
  4493. 'keymap (or (org-link-get-parameter type :keymap)
  4494. org-mouse-map)
  4495. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4496. ((and (pred stringp) echo) echo)
  4497. ((and (pred functionp) echo) echo)
  4498. (_ (concat "LINK: " link)))
  4499. 'htmlize-link (pcase (org-link-get-parameter type
  4500. :htmlize-link)
  4501. ((and (pred functionp) f) (funcall f))
  4502. (_ `(:uri ,link)))
  4503. 'font-lock-multiline t)))
  4504. (org-remove-flyspell-overlays-in start end)
  4505. (org-rear-nonsticky-at end)
  4506. (if (not (eq 'bracket style))
  4507. (add-text-properties start end properties)
  4508. ;; Handle invisible parts in bracket links.
  4509. (remove-text-properties start end '(invisible nil))
  4510. (let ((hidden
  4511. (append `(invisible
  4512. ,(or (org-link-get-parameter type :display)
  4513. 'org-link))
  4514. properties)))
  4515. (add-text-properties start visible-start hidden)
  4516. (add-text-properties visible-start visible-end properties)
  4517. (add-text-properties visible-end end hidden)
  4518. (org-rear-nonsticky-at visible-start)
  4519. (org-rear-nonsticky-at visible-end)))
  4520. (let ((f (org-link-get-parameter type :activate-func)))
  4521. (when (functionp f)
  4522. (funcall f start end path (eq style 'bracket))))
  4523. (throw :exit t))))) ;signal success
  4524. nil))
  4525. (defun org-activate-code (limit)
  4526. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4527. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4528. (remove-text-properties (match-beginning 0) (match-end 0)
  4529. '(display t invisible t intangible t))
  4530. t))
  4531. (defcustom org-src-fontify-natively t
  4532. "When non-nil, fontify code in code blocks.
  4533. See also the `org-block' face."
  4534. :type 'boolean
  4535. :version "26.1"
  4536. :package-version '(Org . "8.3")
  4537. :group 'org-appearance
  4538. :group 'org-babel)
  4539. (defcustom org-allow-promoting-top-level-subtree nil
  4540. "When non-nil, allow promoting a top level subtree.
  4541. The leading star of the top level headline will be replaced
  4542. by a #."
  4543. :type 'boolean
  4544. :version "24.1"
  4545. :group 'org-appearance)
  4546. (defun org-fontify-meta-lines-and-blocks (limit)
  4547. (condition-case nil
  4548. (org-fontify-meta-lines-and-blocks-1 limit)
  4549. (error (message "Org mode fontification error in %S at %d"
  4550. (current-buffer)
  4551. (line-number-at-pos)))))
  4552. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4553. "Fontify #+ lines and blocks."
  4554. (let ((case-fold-search t))
  4555. (when (re-search-forward
  4556. (rx bol (group (zero-or-more blank) "#"
  4557. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4558. space
  4559. eol))
  4560. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4561. (zero-or-more blank)
  4562. (group (group (zero-or-more (not (any " \t\n"))))
  4563. (zero-or-more blank)
  4564. (group (zero-or-more any)))))
  4565. limit t)
  4566. (let ((beg (match-beginning 0))
  4567. (end-of-beginline (match-end 0))
  4568. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4569. (block-end nil) ; will include \n after end of block content
  4570. (lang (match-string 7)) ; the language, if it is an src block
  4571. (bol-after-beginline (line-beginning-position 2))
  4572. (dc1 (downcase (match-string 2)))
  4573. (dc3 (downcase (match-string 3)))
  4574. (whole-blockline org-fontify-whole-block-delimiter-line)
  4575. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4576. (cond
  4577. ((and (match-end 4) (equal dc3 "+begin"))
  4578. ;; Truly a block
  4579. (setq block-type (downcase (match-string 5))
  4580. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4581. (when (re-search-forward
  4582. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4583. (seq (zero-or-more blank)
  4584. "#+end"
  4585. ,(match-string 4)
  4586. word-end
  4587. (zero-or-more any)))))
  4588. nil t) ;; on purpose, we look further than LIMIT
  4589. ;; We do have a matching #+end line
  4590. (setq beg-of-endline (match-beginning 0)
  4591. end-of-endline (match-end 0)
  4592. nl-before-endline (1- (match-beginning 0)))
  4593. (setq block-end (match-beginning 0)) ; includes the final newline.
  4594. (when quoting
  4595. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4596. (remove-text-properties beg end-of-endline
  4597. '(display t invisible t intangible t)))
  4598. (add-text-properties
  4599. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4600. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4601. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4602. (cond
  4603. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4604. (org-src-font-lock-fontify-block lang block-start block-end)
  4605. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4606. (quoting
  4607. (add-text-properties
  4608. bol-after-beginline beg-of-endline
  4609. (list 'face
  4610. (list :inherit
  4611. (let ((face-name
  4612. (intern (format "org-block-%s" lang))))
  4613. (append (and (facep face-name) (list face-name))
  4614. '(org-block)))))))
  4615. ((not org-fontify-quote-and-verse-blocks))
  4616. ((string= block-type "quote")
  4617. (add-face-text-property
  4618. bol-after-beginline beg-of-endline 'org-quote t))
  4619. ((string= block-type "verse")
  4620. (add-face-text-property
  4621. bol-after-beginline beg-of-endline 'org-verse t)))
  4622. ;; Fontify the #+begin and #+end lines of the blocks
  4623. (add-text-properties
  4624. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4625. '(face org-block-begin-line))
  4626. (unless (string-prefix-p "*" (match-string 1))
  4627. (add-text-properties
  4628. beg-of-endline
  4629. (if whole-blockline
  4630. (let ((beg-of-next-line (1+ end-of-endline)))
  4631. (min (point-max) beg-of-next-line))
  4632. (min (point-max) end-of-endline))
  4633. '(face org-block-end-line)))
  4634. t))
  4635. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4636. (org-remove-flyspell-overlays-in
  4637. (match-beginning 0)
  4638. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4639. (add-text-properties
  4640. beg (match-end 3)
  4641. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4642. '(font-lock-fontified t invisible t)
  4643. '(font-lock-fontified t face org-document-info-keyword)))
  4644. (add-text-properties
  4645. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4646. (if (string-equal dc1 "+title:")
  4647. '(font-lock-fontified t face org-document-title)
  4648. '(font-lock-fontified t face org-document-info))))
  4649. ((string-prefix-p "+caption" dc1)
  4650. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4651. (remove-text-properties (match-beginning 0) (match-end 0)
  4652. '(display t invisible t intangible t))
  4653. ;; Handle short captions.
  4654. (save-excursion
  4655. (beginning-of-line)
  4656. (looking-at (rx (group (zero-or-more blank)
  4657. "#+caption"
  4658. (optional "[" (zero-or-more any) "]")
  4659. ":")
  4660. (zero-or-more blank))))
  4661. (add-text-properties (line-beginning-position) (match-end 1)
  4662. '(font-lock-fontified t face org-meta-line))
  4663. (add-text-properties (match-end 0) (line-end-position)
  4664. '(font-lock-fontified t face org-block))
  4665. t)
  4666. ((member dc3 '(" " ""))
  4667. ; Just a comment, the plus was not there
  4668. (org-remove-flyspell-overlays-in beg (match-end 0))
  4669. (add-text-properties
  4670. beg (match-end 0)
  4671. '(font-lock-fontified t face font-lock-comment-face)))
  4672. (t ;; just any other in-buffer setting, but not indented
  4673. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4674. (remove-text-properties (match-beginning 0) (match-end 0)
  4675. '(display t invisible t intangible t))
  4676. (add-text-properties beg (match-end 0)
  4677. '(font-lock-fontified t face org-meta-line))
  4678. t))))))
  4679. (defun org-fontify-drawers (limit)
  4680. "Fontify drawers."
  4681. (when (re-search-forward org-drawer-regexp limit t)
  4682. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4683. '(font-lock-fontified t face org-drawer))
  4684. (org-remove-flyspell-overlays-in
  4685. (line-beginning-position) (line-beginning-position 2))
  4686. t))
  4687. (defun org-fontify-macros (limit)
  4688. "Fontify macros."
  4689. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4690. (let ((begin (match-beginning 0))
  4691. (opening-end (match-beginning 1)))
  4692. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4693. (match-string 1))
  4694. (let ((end (match-end 1))
  4695. (closing-start (match-beginning 1)))
  4696. (add-text-properties
  4697. begin end
  4698. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4699. (org-remove-flyspell-overlays-in begin end)
  4700. (when org-hide-macro-markers
  4701. (add-text-properties begin opening-end '(invisible t))
  4702. (add-text-properties closing-start end '(invisible t)))
  4703. t)))))
  4704. (defun org-fontify-extend-region (beg end _old-len)
  4705. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4706. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4707. (extend (lambda (r1 r2 dir)
  4708. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4709. (replace-regexp-in-string "[][]" r2
  4710. (match-string-no-properties 0)))))
  4711. (re-search-forward (regexp-quote re) nil t dir)))))
  4712. (save-match-data
  4713. (save-excursion
  4714. (goto-char beg)
  4715. (back-to-indentation)
  4716. (cond ((looking-at end-re)
  4717. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4718. ((looking-at begin-re)
  4719. (cons beg (or (funcall extend "end" "]" 1) end)))
  4720. (t (cons beg end)))))))
  4721. (defun org-activate-footnote-links (limit)
  4722. "Add text properties for footnotes."
  4723. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4724. (when fn
  4725. (let* ((beg (nth 1 fn))
  4726. (end (nth 2 fn))
  4727. (label (car fn))
  4728. (referencep (/= (line-beginning-position) beg)))
  4729. (when (and referencep (nth 3 fn))
  4730. (save-excursion
  4731. (goto-char beg)
  4732. (search-forward (or label "fn:"))
  4733. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4734. (add-text-properties beg end
  4735. (list 'mouse-face 'highlight
  4736. 'keymap org-mouse-map
  4737. 'help-echo
  4738. (if referencep "Footnote reference"
  4739. "Footnote definition")
  4740. 'font-lock-fontified t
  4741. 'font-lock-multiline t
  4742. 'face 'org-footnote))))))
  4743. (defun org-activate-dates (limit)
  4744. "Add text properties for dates."
  4745. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4746. (not (equal (char-before (match-beginning 0)) 91)))
  4747. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4748. (add-text-properties (match-beginning 0) (match-end 0)
  4749. (list 'mouse-face 'highlight
  4750. 'keymap org-mouse-map))
  4751. (org-rear-nonsticky-at (match-end 0))
  4752. (when org-display-custom-times
  4753. ;; If it's a date range, activate custom time for second date.
  4754. (when (match-end 3)
  4755. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4756. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4757. t))
  4758. (defun org-activate-target-links (limit)
  4759. "Add text properties for target matches."
  4760. (when org-target-link-regexp
  4761. (let ((case-fold-search t))
  4762. ;; `org-target-link-regexp' matches one character before the
  4763. ;; actual target.
  4764. (unless (bolp) (forward-char -1))
  4765. (when (re-search-forward org-target-link-regexp limit t)
  4766. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4767. (add-text-properties (match-beginning 1) (match-end 1)
  4768. (list 'mouse-face 'highlight
  4769. 'keymap org-mouse-map
  4770. 'help-echo "Radio target link"
  4771. 'org-linked-text t))
  4772. (org-rear-nonsticky-at (match-end 1))
  4773. t))))
  4774. (defvar org-latex-and-related-regexp nil
  4775. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4776. (defun org-compute-latex-and-related-regexp ()
  4777. "Compute regular expression for LaTeX, entities and sub/superscript.
  4778. Result depends on variable `org-highlight-latex-and-related'."
  4779. (let ((re-sub
  4780. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4781. ((eq org-use-sub-superscripts '{})
  4782. (list org-match-substring-with-braces-regexp))
  4783. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4784. (re-latex
  4785. (when (or (memq 'latex org-highlight-latex-and-related)
  4786. (memq 'native org-highlight-latex-and-related))
  4787. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4788. (delq nil
  4789. (mapcar (lambda (x)
  4790. (and (member (car x) matchers) (nth 1 x)))
  4791. org-latex-regexps)))))
  4792. (re-entities
  4793. (when (memq 'entities org-highlight-latex-and-related)
  4794. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4795. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4796. (setq-local org-latex-and-related-regexp
  4797. (mapconcat #'identity
  4798. (append re-latex re-entities re-sub)
  4799. "\\|"))))
  4800. (defun org-do-latex-and-related (limit)
  4801. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4802. Stop at first highlighted object, if any. Return t if some
  4803. highlighting was done, nil otherwise."
  4804. (when (org-string-nw-p org-latex-and-related-regexp)
  4805. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4806. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4807. (catch 'found
  4808. (while (and (< (point) limit)
  4809. (re-search-forward org-latex-and-related-regexp nil t))
  4810. (cond
  4811. ((cl-some (lambda (f)
  4812. (memq f '(org-code org-verbatim underline
  4813. org-special-keyword)))
  4814. (save-excursion
  4815. (goto-char (1+ (match-beginning 0)))
  4816. (face-at-point nil t))))
  4817. ;; Try to limit false positives. In this case, ignore
  4818. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4819. ;; contain an empty line.
  4820. ((save-excursion
  4821. (goto-char (match-beginning 0))
  4822. (and (looking-at-p latex-prefix-re)
  4823. (save-match-data
  4824. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4825. (t
  4826. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4827. '(?_ ?^))
  4828. 1
  4829. 0))
  4830. (start (+ offset (match-beginning 0)))
  4831. (end (match-end 0)))
  4832. (if (memq 'native org-highlight-latex-and-related)
  4833. (org-src-font-lock-fontify-block "latex" start end)
  4834. (font-lock-prepend-text-property start end
  4835. 'face 'org-latex-and-related))
  4836. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4837. '(font-lock-multiline t))
  4838. (throw 'found t)))))
  4839. nil))))
  4840. (defun org-restart-font-lock ()
  4841. "Restart `font-lock-mode', to force refontification."
  4842. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4843. (font-lock-mode -1)
  4844. (font-lock-mode 1)))
  4845. (defun org-activate-tags (limit)
  4846. (when (re-search-forward org-tag-line-re limit t)
  4847. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4848. (add-text-properties (match-beginning 1) (match-end 1)
  4849. (list 'mouse-face 'highlight
  4850. 'keymap org-mouse-map))
  4851. (org-rear-nonsticky-at (match-end 1))
  4852. t))
  4853. (defun org-outline-level ()
  4854. "Compute the outline level of the heading at point.
  4855. If this is called at a normal headline, the level is the number
  4856. of stars. Use `org-reduced-level' to remove the effect of
  4857. `org-odd-levels'. Unlike to `org-current-level', this function
  4858. takes into consideration inlinetasks."
  4859. (org-with-wide-buffer
  4860. (end-of-line)
  4861. (if (re-search-backward org-outline-regexp-bol nil t)
  4862. (1- (- (match-end 0) (match-beginning 0)))
  4863. 0)))
  4864. (defvar org-font-lock-keywords nil)
  4865. (defsubst org-re-property (property &optional literal allow-null value)
  4866. "Return a regexp matching a PROPERTY line.
  4867. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4868. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4869. non-nil, match properties even without a value.
  4870. Match group 3 is set to the value when it exists. If there is no
  4871. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4872. With optional argument VALUE, match only property lines with
  4873. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4874. unless LITERAL is non-nil."
  4875. (concat
  4876. "^\\(?4:[ \t]*\\)"
  4877. (format "\\(?1::\\(?2:%s\\):\\)"
  4878. (if literal property (regexp-quote property)))
  4879. (cond (value
  4880. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4881. (if literal value (regexp-quote value))))
  4882. (allow-null
  4883. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4884. (t
  4885. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4886. (defconst org-property-re
  4887. (org-re-property "\\S-+" 'literal t)
  4888. "Regular expression matching a property line.
  4889. There are four matching groups:
  4890. 1: :PROPKEY: including the leading and trailing colon,
  4891. 2: PROPKEY without the leading and trailing colon,
  4892. 3: PROPVAL without leading or trailing spaces,
  4893. 4: the indentation of the current line,
  4894. 5: trailing whitespace.")
  4895. (defvar org-font-lock-hook nil
  4896. "Functions to be called for special font lock stuff.")
  4897. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4898. (defvar org-font-lock-set-keywords-hook nil
  4899. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4900. This is called after `org-font-lock-extra-keywords' is defined, but before
  4901. it is installed to be used by font lock. This can be useful if something
  4902. needs to be inserted at a specific position in the font-lock sequence.")
  4903. (defun org-font-lock-hook (limit)
  4904. "Run `org-font-lock-hook' within LIMIT."
  4905. (run-hook-with-args 'org-font-lock-hook limit))
  4906. (defun org-set-font-lock-defaults ()
  4907. "Set font lock defaults for the current buffer."
  4908. (let* ((em org-fontify-emphasized-text)
  4909. (lk org-highlight-links)
  4910. (org-font-lock-extra-keywords
  4911. (list
  4912. ;; Call the hook
  4913. '(org-font-lock-hook)
  4914. ;; Headlines
  4915. `(,(if org-fontify-whole-heading-line
  4916. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4917. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4918. (1 (org-get-level-face 1))
  4919. (2 (org-get-level-face 2))
  4920. (3 (org-get-level-face 3)))
  4921. ;; Table lines
  4922. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4923. (1 'org-table t))
  4924. ;; Table internals
  4925. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4926. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4927. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4928. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4929. ;; Properties
  4930. (list org-property-re
  4931. '(1 'org-special-keyword t)
  4932. '(3 'org-property-value t))
  4933. ;; Drawers
  4934. '(org-fontify-drawers)
  4935. ;; Link related fontification.
  4936. '(org-activate-links)
  4937. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4938. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4939. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4940. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4941. ;; Targets.
  4942. (list org-radio-target-regexp '(0 'org-target t))
  4943. (list org-target-regexp '(0 'org-target t))
  4944. ;; Diary sexps.
  4945. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4946. ;; Macro
  4947. '(org-fontify-macros)
  4948. ;; TODO keyword
  4949. (list (format org-heading-keyword-regexp-format
  4950. org-todo-regexp)
  4951. '(2 (org-get-todo-face 2) t))
  4952. ;; TODO
  4953. (when org-fontify-todo-headline
  4954. (list (format org-heading-keyword-regexp-format
  4955. (concat
  4956. "\\(?:"
  4957. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4958. "\\)"))
  4959. '(2 'org-headline-todo t)))
  4960. ;; DONE
  4961. (when org-fontify-done-headline
  4962. (list (format org-heading-keyword-regexp-format
  4963. (concat
  4964. "\\(?:"
  4965. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4966. "\\)"))
  4967. '(2 'org-headline-done t)))
  4968. ;; Priorities
  4969. '(org-font-lock-add-priority-faces)
  4970. ;; Tags
  4971. '(org-font-lock-add-tag-faces)
  4972. ;; Tags groups
  4973. (when (and org-group-tags org-tag-groups-alist)
  4974. (list (concat org-outline-regexp-bol ".+\\(:"
  4975. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4976. ":\\).*$")
  4977. '(1 'org-tag-group prepend)))
  4978. ;; Special keywords
  4979. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4980. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4981. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4982. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4983. ;; Emphasis
  4984. (when em '(org-do-emphasis-faces))
  4985. ;; Checkboxes
  4986. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4987. 1 'org-checkbox prepend)
  4988. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4989. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4990. (0 (org-get-checkbox-statistics-face) t)))
  4991. ;; Description list items
  4992. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4993. 1 'org-list-dt prepend)
  4994. ;; ARCHIVEd headings
  4995. (list (concat
  4996. org-outline-regexp-bol
  4997. "\\(.*:" org-archive-tag ":.*\\)")
  4998. '(1 'org-archived prepend))
  4999. ;; Specials
  5000. '(org-do-latex-and-related)
  5001. '(org-fontify-entities)
  5002. '(org-raise-scripts)
  5003. ;; Code
  5004. '(org-activate-code (1 'org-code t))
  5005. ;; COMMENT
  5006. (list (format
  5007. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5008. org-todo-regexp
  5009. org-comment-string)
  5010. '(9 'org-special-keyword t))
  5011. ;; Blocks and meta lines
  5012. '(org-fontify-meta-lines-and-blocks))))
  5013. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5014. (run-hooks 'org-font-lock-set-keywords-hook)
  5015. ;; Now set the full font-lock-keywords
  5016. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5017. (setq-local font-lock-defaults
  5018. '(org-font-lock-keywords t nil nil backward-paragraph))
  5019. (setq-local font-lock-extend-after-change-region-function
  5020. #'org-fontify-extend-region)
  5021. (kill-local-variable 'font-lock-keywords)
  5022. nil))
  5023. (defun org-toggle-pretty-entities ()
  5024. "Toggle the composition display of entities as UTF8 characters."
  5025. (interactive)
  5026. (setq-local org-pretty-entities (not org-pretty-entities))
  5027. (org-restart-font-lock)
  5028. (if org-pretty-entities
  5029. (message "Entities are now displayed as UTF8 characters")
  5030. (save-restriction
  5031. (widen)
  5032. (decompose-region (point-min) (point-max))
  5033. (message "Entities are now displayed as plain text"))))
  5034. (defvar-local org-custom-properties-overlays nil
  5035. "List of overlays used for custom properties.")
  5036. (defun org-toggle-custom-properties-visibility ()
  5037. "Display or hide properties in `org-custom-properties'."
  5038. (interactive)
  5039. (if org-custom-properties-overlays
  5040. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5041. (setq org-custom-properties-overlays nil))
  5042. (when org-custom-properties
  5043. (org-with-wide-buffer
  5044. (goto-char (point-min))
  5045. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5046. (while (re-search-forward regexp nil t)
  5047. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5048. (when (and end (< (point) end))
  5049. ;; Hide first custom property in current drawer.
  5050. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5051. (overlay-put o 'invisible t)
  5052. (overlay-put o 'org-custom-property t)
  5053. (push o org-custom-properties-overlays))
  5054. ;; Hide additional custom properties in the same drawer.
  5055. (while (re-search-forward regexp end t)
  5056. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5057. (overlay-put o 'invisible t)
  5058. (overlay-put o 'org-custom-property t)
  5059. (push o org-custom-properties-overlays)))))
  5060. ;; Each entry is limited to a single property drawer.
  5061. (outline-next-heading)))))))
  5062. (defun org-fontify-entities (limit)
  5063. "Find an entity to fontify."
  5064. (let (ee)
  5065. (when org-pretty-entities
  5066. (catch 'match
  5067. ;; "\_ "-family is left out on purpose. Only the first one,
  5068. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5069. ;; confusing when adding a second white space character.
  5070. (while (re-search-forward
  5071. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5072. limit t)
  5073. (when (and (not (org-at-comment-p))
  5074. (setq ee (org-entity-get (match-string 1)))
  5075. (= (length (nth 6 ee)) 1))
  5076. (let* ((end (if (equal (match-string 2) "{}")
  5077. (match-end 2)
  5078. (match-end 1))))
  5079. (add-text-properties
  5080. (match-beginning 0) end
  5081. (list 'font-lock-fontified t))
  5082. (compose-region (match-beginning 0) end
  5083. (nth 6 ee) nil)
  5084. (backward-char 1)
  5085. (throw 'match t))))
  5086. nil))))
  5087. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5088. "Fontify string S like in Org mode."
  5089. (with-temp-buffer
  5090. (insert s)
  5091. (let ((org-odd-levels-only odd-levels))
  5092. (org-mode)
  5093. (org-font-lock-ensure)
  5094. (buffer-string))))
  5095. (defun org-get-level-face (n)
  5096. "Get the right face for match N in font-lock matching of headlines."
  5097. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5098. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5099. (org-f (if org-cycle-level-faces
  5100. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5101. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5102. (cond
  5103. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5104. ((eq n 2) org-f)
  5105. (t (unless org-level-color-stars-only org-f)))))
  5106. (defun org-face-from-face-or-color (context inherit face-or-color)
  5107. "Create a face list that inherits INHERIT, but sets the foreground color.
  5108. When FACE-OR-COLOR is not a string, just return it."
  5109. (if (stringp face-or-color)
  5110. (list :inherit inherit
  5111. (cdr (assoc context org-faces-easy-properties))
  5112. face-or-color)
  5113. face-or-color))
  5114. (defun org-get-todo-face (kwd)
  5115. "Get the right face for a TODO keyword KWD.
  5116. If KWD is a number, get the corresponding match group."
  5117. (when (numberp kwd) (setq kwd (match-string kwd)))
  5118. (or (org-face-from-face-or-color
  5119. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5120. (and (member kwd org-done-keywords) 'org-done)
  5121. 'org-todo))
  5122. (defun org-get-priority-face (priority)
  5123. "Get the right face for PRIORITY.
  5124. PRIORITY is a character."
  5125. (or (org-face-from-face-or-color
  5126. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5127. 'org-priority))
  5128. (defun org-get-tag-face (tag)
  5129. "Get the right face for TAG.
  5130. If TAG is a number, get the corresponding match group."
  5131. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5132. (or (org-face-from-face-or-color
  5133. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5134. 'org-tag)))
  5135. (defvar org-priority-regexp) ; defined later in the file
  5136. (defun org-font-lock-add-priority-faces (limit)
  5137. "Add the special priority faces."
  5138. (while (re-search-forward org-priority-regexp limit t)
  5139. (add-text-properties
  5140. (match-beginning 1) (match-end 1)
  5141. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5142. 'font-lock-fontified t))))
  5143. (defun org-font-lock-add-tag-faces (limit)
  5144. "Add the special tag faces."
  5145. (when (and org-tag-faces org-tags-special-faces-re)
  5146. (while (re-search-forward org-tags-special-faces-re limit t)
  5147. (add-text-properties (match-beginning 1) (match-end 1)
  5148. (list 'face (org-get-tag-face 1)
  5149. 'font-lock-fontified t))
  5150. (backward-char 1))))
  5151. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5152. "Remove fontification and activation overlays from links."
  5153. (font-lock-default-unfontify-region beg end)
  5154. (let* ((buffer-undo-list t)
  5155. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5156. (inhibit-modification-hooks t)
  5157. deactivate-mark buffer-file-name buffer-file-truename)
  5158. (decompose-region beg end)
  5159. (remove-text-properties beg end
  5160. '(mouse-face t keymap t org-linked-text t
  5161. invisible t intangible t
  5162. org-emphasis t))
  5163. (org-remove-font-lock-display-properties beg end)))
  5164. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5165. ((raise 0.3) (height 0.7))
  5166. ((raise -0.5))
  5167. ((raise 0.5)))
  5168. "Display properties for showing superscripts and subscripts.")
  5169. (defun org-remove-font-lock-display-properties (beg end)
  5170. "Remove specific display properties that have been added by font lock.
  5171. The will remove the raise properties that are used to show superscripts
  5172. and subscripts."
  5173. (let (next prop)
  5174. (while (< beg end)
  5175. (setq next (next-single-property-change beg 'display nil end)
  5176. prop (get-text-property beg 'display))
  5177. (when (member prop org-script-display)
  5178. (put-text-property beg next 'display nil))
  5179. (setq beg next))))
  5180. (defun org-raise-scripts (limit)
  5181. "Add raise properties to sub/superscripts."
  5182. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5183. (re-search-forward
  5184. (if (eq org-use-sub-superscripts t)
  5185. org-match-substring-regexp
  5186. org-match-substring-with-braces-regexp)
  5187. limit t))
  5188. (let* ((pos (point)) table-p comment-p
  5189. (mpos (match-beginning 3))
  5190. (emph-p (get-text-property mpos 'org-emphasis))
  5191. (link-p (get-text-property mpos 'mouse-face))
  5192. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5193. (goto-char (point-at-bol))
  5194. (setq table-p (looking-at-p org-table-dataline-regexp)
  5195. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5196. (goto-char pos)
  5197. ;; Handle a_b^c
  5198. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5199. (unless (or comment-p emph-p link-p keyw-p)
  5200. (put-text-property (match-beginning 3) (match-end 0)
  5201. 'display
  5202. (if (equal (char-after (match-beginning 2)) ?^)
  5203. (nth (if table-p 3 1) org-script-display)
  5204. (nth (if table-p 2 0) org-script-display)))
  5205. (add-text-properties (match-beginning 2) (match-end 2)
  5206. (list 'invisible t))
  5207. (when (and (eq (char-after (match-beginning 3)) ?{)
  5208. (eq (char-before (match-end 3)) ?}))
  5209. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5210. (list 'invisible t))
  5211. (add-text-properties (1- (match-end 3)) (match-end 3)
  5212. (list 'invisible t))))
  5213. t)))
  5214. (defun org-remove-empty-overlays-at (pos)
  5215. "Remove outline overlays that do not contain non-white stuff."
  5216. (dolist (o (overlays-at pos))
  5217. (and (eq 'outline (overlay-get o 'invisible))
  5218. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5219. (overlay-end o))))
  5220. (delete-overlay o))))
  5221. (defun org-show-empty-lines-in-parent ()
  5222. "Move to the parent and re-show empty lines before visible headlines."
  5223. (save-excursion
  5224. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5225. (org-cycle-show-empty-lines context))))
  5226. (defun org-files-list ()
  5227. "Return `org-agenda-files' list, plus all open Org files.
  5228. This is useful for operations that need to scan all of a user's
  5229. open and agenda-wise Org files."
  5230. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5231. (dolist (buf (buffer-list))
  5232. (with-current-buffer buf
  5233. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5234. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5235. :test #'equal))))
  5236. files))
  5237. (defsubst org-entry-beginning-position ()
  5238. "Return the beginning position of the current entry."
  5239. (save-excursion (org-back-to-heading t) (point)))
  5240. (defsubst org-entry-end-position ()
  5241. "Return the end position of the current entry."
  5242. (save-excursion (outline-next-heading) (point)))
  5243. (defun org-subtree-end-visible-p ()
  5244. "Is the end of the current subtree visible?"
  5245. (pos-visible-in-window-p
  5246. (save-excursion (org-end-of-subtree t) (point))))
  5247. (defun org-first-headline-recenter ()
  5248. "Move cursor to the first headline and recenter the headline."
  5249. (let ((window (get-buffer-window)))
  5250. (when window
  5251. (goto-char (point-min))
  5252. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5253. (set-window-start window (line-beginning-position))))))
  5254. ;;; Visibility (headlines, blocks, drawers)
  5255. ;;;; Headlines visibility
  5256. (defun org-show-entry ()
  5257. "Show the body directly following this heading.
  5258. Show the heading too, if it is currently invisible."
  5259. (interactive)
  5260. (save-excursion
  5261. (ignore-errors
  5262. (org-back-to-heading t)
  5263. (org-flag-region
  5264. (line-end-position 0)
  5265. (save-excursion
  5266. (if (re-search-forward
  5267. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5268. (match-beginning 1)
  5269. (point-max)))
  5270. nil
  5271. 'outline))))
  5272. (defun org-show-children (&optional level)
  5273. "Show all direct subheadings of this heading.
  5274. Prefix arg LEVEL is how many levels below the current level
  5275. should be shown. Default is enough to cause the following
  5276. heading to appear."
  5277. (interactive "p")
  5278. (save-excursion
  5279. (org-back-to-heading t)
  5280. (let* ((current-level (funcall outline-level))
  5281. (max-level (org-get-valid-level
  5282. current-level
  5283. (if level (prefix-numeric-value level) 1)))
  5284. (end (save-excursion (org-end-of-subtree t t)))
  5285. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5286. (past-first-child nil)
  5287. ;; Make sure to skip inlinetasks.
  5288. (re (format regexp-fmt
  5289. current-level
  5290. (cond
  5291. ((not (featurep 'org-inlinetask)) "")
  5292. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5293. 3))
  5294. (t (1- org-inlinetask-min-level))))))
  5295. ;; Display parent heading.
  5296. (org-flag-heading nil)
  5297. (forward-line)
  5298. ;; Display children. First child may be deeper than expected
  5299. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5300. ;; MAX-LEVEL accordingly.
  5301. (while (re-search-forward re end t)
  5302. (unless past-first-child
  5303. (setq re (format regexp-fmt
  5304. current-level
  5305. (max (funcall outline-level) max-level)))
  5306. (setq past-first-child t))
  5307. (org-flag-heading nil)))))
  5308. (defun org-show-subtree ()
  5309. "Show everything after this heading at deeper levels."
  5310. (interactive)
  5311. (org-flag-region
  5312. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5313. ;;;; Blocks and drawers visibility
  5314. (defun org--hide-wrapper-toggle (element category force no-error)
  5315. "Toggle visibility for ELEMENT.
  5316. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5317. either `block' or `drawer'. When FORCE is `off', show the block
  5318. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5319. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5320. Return a non-nil value when toggling is successful."
  5321. (cond
  5322. ((memq (org-element-type element)
  5323. (pcase category
  5324. (`drawer '(drawer property-drawer))
  5325. (`block '(center-block
  5326. comment-block dynamic-block example-block export-block
  5327. quote-block special-block src-block verse-block))
  5328. (_ (error "Unknown category: %S" category))))
  5329. (let* ((post (org-element-property :post-affiliated element))
  5330. (start (save-excursion
  5331. (goto-char post)
  5332. (line-end-position)))
  5333. (end (save-excursion
  5334. (goto-char (org-element-property :end element))
  5335. (skip-chars-backward " \t\n")
  5336. (line-end-position))))
  5337. ;; Do nothing when not before or at the block opening line or at
  5338. ;; the block closing line.
  5339. (unless (let ((eol (line-end-position)))
  5340. (and (> eol start) (/= eol end)))
  5341. (let* ((spec (if (eq category 'drawer)
  5342. 'org-hide-drawer
  5343. 'org-hide-block))
  5344. (flag
  5345. (cond ((eq force 'off) nil)
  5346. (force t)
  5347. ((eq (get-char-property start 'invisible) spec) nil)
  5348. (t t))))
  5349. (org-flag-region start end flag spec))
  5350. ;; When the block is hidden away, make sure point is left in
  5351. ;; a visible part of the buffer.
  5352. (when (invisible-p (max (1- (point)) (point-min)))
  5353. (goto-char post))
  5354. ;; Signal success.
  5355. t)))
  5356. (no-error nil)
  5357. (t
  5358. (user-error (if (eq category 'drawer)
  5359. "Not at a drawer"
  5360. "Not at a block")))))
  5361. (defun org-hide-block-toggle (&optional force no-error element)
  5362. "Toggle the visibility of the current block.
  5363. When optional argument FORCE is `off', make block visible. If it
  5364. is non-nil, hide it unconditionally. Throw an error when not at
  5365. a block, unless NO-ERROR is non-nil. When optional argument
  5366. ELEMENT is provided, consider it instead of the current block.
  5367. Return a non-nil value when toggling is successful."
  5368. (interactive)
  5369. (org--hide-wrapper-toggle
  5370. (or element (org-element-at-point)) 'block force no-error))
  5371. (defun org-hide-drawer-toggle (&optional force no-error element)
  5372. "Toggle the visibility of the current drawer.
  5373. When optional argument FORCE is `off', make drawer visible. If
  5374. it is non-nil, hide it unconditionally. Throw an error when not
  5375. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5376. ELEMENT is provided, consider it instead of the current drawer.
  5377. Return a non-nil value when toggling is successful."
  5378. (interactive)
  5379. (org--hide-wrapper-toggle
  5380. (or element (org-element-at-point)) 'drawer force no-error))
  5381. (defun org-hide-block-all ()
  5382. "Fold all blocks in the current buffer."
  5383. (interactive)
  5384. (org-show-all '(blocks))
  5385. (org-block-map 'org-hide-block-toggle))
  5386. (defun org-cycle-hide-drawers (state &optional exceptions)
  5387. "Re-hide all drawers after a visibility state change.
  5388. STATE should be one of the symbols listed in the docstring of
  5389. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5390. a list of strings specifying which drawers should not be hidden."
  5391. (when (and (derived-mode-p 'org-mode)
  5392. (not (memq state '(overview folded contents))))
  5393. (save-excursion
  5394. (let* ((globalp (eq state 'all))
  5395. (beg (if globalp (point-min) (point)))
  5396. (end (if globalp (point-max)
  5397. (if (eq state 'children)
  5398. (save-excursion (outline-next-heading) (point))
  5399. (org-end-of-subtree t)))))
  5400. (goto-char beg)
  5401. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5402. (unless (member-ignore-case (match-string 1) exceptions)
  5403. (let ((drawer (org-element-at-point)))
  5404. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5405. (org-hide-drawer-toggle t nil drawer)
  5406. ;; Make sure to skip drawer entirely or we might flag
  5407. ;; it another time when matching its ending line with
  5408. ;; `org-drawer-regexp'.
  5409. (goto-char (org-element-property :end drawer))))))))))
  5410. ;;;; Visibility cycling
  5411. (defvar-local org-cycle-global-status nil)
  5412. (put 'org-cycle-global-status 'org-state t)
  5413. (defvar-local org-cycle-subtree-status nil)
  5414. (put 'org-cycle-subtree-status 'org-state t)
  5415. (defun org-show-all (&optional types)
  5416. "Show all contents in the visible part of the buffer.
  5417. By default, the function expands headings, blocks and drawers.
  5418. When optional argument TYPE is a list of symbols among `blocks',
  5419. `drawers' and `headings', to only expand one specific type."
  5420. (interactive)
  5421. (dolist (type (or types '(blocks drawers headings)))
  5422. (org-flag-region (point-min) (point-max) nil
  5423. (pcase type
  5424. (`blocks 'org-hide-block)
  5425. (`drawers 'org-hide-drawer)
  5426. (`headings 'outline)
  5427. (_ (error "Invalid type: %S" type))))))
  5428. ;;;###autoload
  5429. (defun org-cycle (&optional arg)
  5430. "TAB-action and visibility cycling for Org mode.
  5431. This is the command invoked in Org mode by the `TAB' key. Its main
  5432. purpose is outline visibility cycling, but it also invokes other actions
  5433. in special contexts.
  5434. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5435. the entire
  5436. buffer through 3 states (global cycling)
  5437. 1. OVERVIEW: Show only top-level headlines.
  5438. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5439. 3. SHOW ALL: Show everything.
  5440. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5441. switch to the startup visibility,
  5442. determined by the variable `org-startup-folded', and by any VISIBILITY
  5443. properties in the buffer.
  5444. With a `\\[universal-argument] \\[universal-argument] \
  5445. \\[universal-argument]' prefix argument, show the entire buffer, including
  5446. any drawers.
  5447. When inside a table, re-align the table and move to the next field.
  5448. When point is at the beginning of a headline, rotate the subtree started
  5449. by this line through 3 different states (local cycling)
  5450. 1. FOLDED: Only the main headline is shown.
  5451. 2. CHILDREN: The main headline and the direct children are shown.
  5452. From this state, you can move to one of the children
  5453. and zoom in further.
  5454. 3. SUBTREE: Show the entire subtree, including body text.
  5455. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5456. When point is at the beginning of an empty headline and the variable
  5457. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5458. of the headline by demoting and promoting it to likely levels. This
  5459. speeds up creation document structure by pressing `TAB' once or several
  5460. times right after creating a new headline.
  5461. When there is a numeric prefix, go up to a heading with level ARG, do
  5462. a `show-subtree' and return to the previous cursor position. If ARG
  5463. is negative, go up that many levels.
  5464. When point is not at the beginning of a headline, execute the global
  5465. binding for `TAB', which is re-indenting the line. See the option
  5466. `org-cycle-emulate-tab' for details.
  5467. As a special case, if point is at the very beginning of the buffer, if
  5468. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5469. is non-nil, this function acts as if called with prefix argument \
  5470. \(`\\[universal-argument] TAB',
  5471. same as `S-TAB') also when called without prefix argument."
  5472. (interactive "P")
  5473. (org-load-modules-maybe)
  5474. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5475. (and org-cycle-level-after-item/entry-creation
  5476. (or (org-cycle-level)
  5477. (org-cycle-item-indentation))))
  5478. (let* ((limit-level
  5479. (or org-cycle-max-level
  5480. (and (boundp 'org-inlinetask-min-level)
  5481. org-inlinetask-min-level
  5482. (1- org-inlinetask-min-level))))
  5483. (nstars
  5484. (and limit-level
  5485. (if org-odd-levels-only
  5486. (1- (* 2 limit-level))
  5487. limit-level)))
  5488. (org-outline-regexp
  5489. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5490. (cond
  5491. ((equal arg '(16))
  5492. (setq last-command 'dummy)
  5493. (org-set-startup-visibility)
  5494. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5495. ((equal arg '(64))
  5496. (org-show-all)
  5497. (org-unlogged-message "Entire buffer visible, including drawers"))
  5498. ((equal arg '(4)) (org-cycle-internal-global))
  5499. ;; Show-subtree, ARG levels up from here.
  5500. ((integerp arg)
  5501. (save-excursion
  5502. (org-back-to-heading)
  5503. (outline-up-heading (if (< arg 0) (- arg)
  5504. (- (funcall outline-level) arg)))
  5505. (org-show-subtree)))
  5506. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5507. ((and org-cycle-global-at-bob
  5508. (bobp)
  5509. (not (looking-at org-outline-regexp)))
  5510. (let ((org-cycle-hook
  5511. (remq 'org-optimize-window-after-visibility-change
  5512. org-cycle-hook)))
  5513. (org-cycle-internal-global)))
  5514. ;; Try CDLaTeX TAB completion.
  5515. ((org-try-cdlatex-tab))
  5516. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5517. ((and (featurep 'org-inlinetask)
  5518. (org-inlinetask-at-task-p)
  5519. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5520. (org-inlinetask-toggle-visibility))
  5521. (t
  5522. (let ((pos (point))
  5523. (element (org-element-at-point)))
  5524. (cond
  5525. ;; Try toggling visibility for block at point.
  5526. ((org-hide-block-toggle nil t element))
  5527. ;; Try toggling visibility for block at point.
  5528. ((org-hide-drawer-toggle nil t element))
  5529. ;; Table: enter it or move to the next field.
  5530. ((and (org-match-line "[ \t]*[|+]")
  5531. (org-element-lineage element '(table) t))
  5532. (if (and (eq 'table (org-element-type element))
  5533. (eq 'table.el (org-element-property :type element)))
  5534. (message (substitute-command-keys "\\<org-mode-map>\
  5535. Use `\\[org-edit-special]' to edit table.el tables"))
  5536. (org-table-justify-field-maybe)
  5537. (call-interactively #'org-table-next-field)))
  5538. ((run-hook-with-args-until-success
  5539. 'org-tab-after-check-for-table-hook))
  5540. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5541. ((and (or (and org-cycle-include-plain-lists
  5542. (let ((item (org-element-lineage element
  5543. '(item plain-list)
  5544. t)))
  5545. (and item
  5546. (= (line-beginning-position)
  5547. (org-element-property :post-affiliated
  5548. item)))))
  5549. (save-excursion (move-beginning-of-line 1)
  5550. (looking-at org-outline-regexp)))
  5551. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5552. (org-cycle-internal-local))
  5553. ;; From there: TAB emulation and template completion.
  5554. (buffer-read-only (org-back-to-heading))
  5555. ((run-hook-with-args-until-success
  5556. 'org-tab-after-check-for-cycling-hook))
  5557. ((run-hook-with-args-until-success
  5558. 'org-tab-before-tab-emulation-hook))
  5559. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5560. (or (not (bolp))
  5561. (not (looking-at org-outline-regexp))))
  5562. (call-interactively (global-key-binding (kbd "TAB"))))
  5563. ((or (eq org-cycle-emulate-tab t)
  5564. (and (memq org-cycle-emulate-tab '(white whitestart))
  5565. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5566. (or (and (eq org-cycle-emulate-tab 'white)
  5567. (= (match-end 0) (point-at-eol)))
  5568. (and (eq org-cycle-emulate-tab 'whitestart)
  5569. (>= (match-end 0) pos)))))
  5570. (call-interactively (global-key-binding (kbd "TAB"))))
  5571. (t
  5572. (save-excursion
  5573. (org-back-to-heading)
  5574. (org-cycle))))))))))
  5575. (defun org-cycle-internal-global ()
  5576. "Do the global cycling action."
  5577. ;; Hack to avoid display of messages for .org attachments in Gnus
  5578. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5579. (cond
  5580. ((and (eq last-command this-command)
  5581. (eq org-cycle-global-status 'overview))
  5582. ;; We just created the overview - now do table of contents
  5583. ;; This can be slow in very large buffers, so indicate action
  5584. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5585. (unless ga (org-unlogged-message "CONTENTS..."))
  5586. (org-content)
  5587. (unless ga (org-unlogged-message "CONTENTS...done"))
  5588. (setq org-cycle-global-status 'contents)
  5589. (run-hook-with-args 'org-cycle-hook 'contents))
  5590. ((and (eq last-command this-command)
  5591. (eq org-cycle-global-status 'contents))
  5592. ;; We just showed the table of contents - now show everything
  5593. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5594. (org-show-all '(headings blocks))
  5595. (unless ga (org-unlogged-message "SHOW ALL"))
  5596. (setq org-cycle-global-status 'all)
  5597. (run-hook-with-args 'org-cycle-hook 'all))
  5598. (t
  5599. ;; Default action: go to overview
  5600. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5601. (org-overview)
  5602. (unless ga (org-unlogged-message "OVERVIEW"))
  5603. (setq org-cycle-global-status 'overview)
  5604. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5605. (defvar org-called-with-limited-levels nil
  5606. "Non-nil when `org-with-limited-levels' is currently active.")
  5607. (defun org-cycle-internal-local ()
  5608. "Do the local cycling action."
  5609. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5610. ;; First, determine end of headline (EOH), end of subtree or item
  5611. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5612. (save-excursion
  5613. (if (org-at-item-p)
  5614. (progn
  5615. (beginning-of-line)
  5616. (setq struct (org-list-struct))
  5617. (setq eoh (point-at-eol))
  5618. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5619. (setq has-children (org-list-has-child-p (point) struct)))
  5620. (org-back-to-heading)
  5621. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5622. (setq eos (save-excursion (org-end-of-subtree t t)
  5623. (when (bolp) (backward-char)) (point)))
  5624. (setq has-children
  5625. (or
  5626. (save-excursion
  5627. (let ((level (funcall outline-level)))
  5628. (outline-next-heading)
  5629. (and (org-at-heading-p t)
  5630. (> (funcall outline-level) level))))
  5631. (and (eq org-cycle-include-plain-lists 'integrate)
  5632. (save-excursion
  5633. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5634. ;; Determine end invisible part of buffer (EOL)
  5635. (beginning-of-line 2)
  5636. (while (and (not (eobp)) ;This is like `next-line'.
  5637. (get-char-property (1- (point)) 'invisible))
  5638. (goto-char (next-single-char-property-change (point) 'invisible))
  5639. (and (eolp) (beginning-of-line 2)))
  5640. (setq eol (point)))
  5641. ;; Find out what to do next and set `this-command'
  5642. (cond
  5643. ((= eos eoh)
  5644. ;; Nothing is hidden behind this heading
  5645. (unless (org-before-first-heading-p)
  5646. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5647. (org-unlogged-message "EMPTY ENTRY")
  5648. (setq org-cycle-subtree-status nil)
  5649. (save-excursion
  5650. (goto-char eos)
  5651. (outline-next-heading)
  5652. (when (org-invisible-p) (org-flag-heading nil))))
  5653. ((and (or (>= eol eos)
  5654. (not (string-match "\\S-" (buffer-substring eol eos))))
  5655. (or has-children
  5656. (not (setq children-skipped
  5657. org-cycle-skip-children-state-if-no-children))))
  5658. ;; Entire subtree is hidden in one line: children view
  5659. (unless (org-before-first-heading-p)
  5660. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5661. (if (org-at-item-p)
  5662. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5663. (org-show-entry)
  5664. (org-with-limited-levels (org-show-children))
  5665. (org-show-set-visibility 'canonical)
  5666. ;; Fold every list in subtree to top-level items.
  5667. (when (eq org-cycle-include-plain-lists 'integrate)
  5668. (save-excursion
  5669. (org-back-to-heading)
  5670. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5671. (beginning-of-line 1)
  5672. (let* ((struct (org-list-struct))
  5673. (prevs (org-list-prevs-alist struct))
  5674. (end (org-list-get-bottom-point struct)))
  5675. (dolist (e (org-list-get-all-items (point) struct prevs))
  5676. (org-list-set-item-visibility e struct 'folded))
  5677. (goto-char (if (< end eos) end eos)))))))
  5678. (org-unlogged-message "CHILDREN")
  5679. (save-excursion
  5680. (goto-char eos)
  5681. (outline-next-heading)
  5682. (when (org-invisible-p) (org-flag-heading nil)))
  5683. (setq org-cycle-subtree-status 'children)
  5684. (unless (org-before-first-heading-p)
  5685. (run-hook-with-args 'org-cycle-hook 'children)))
  5686. ((or children-skipped
  5687. (and (eq last-command this-command)
  5688. (eq org-cycle-subtree-status 'children)))
  5689. ;; We just showed the children, or no children are there,
  5690. ;; now show everything.
  5691. (unless (org-before-first-heading-p)
  5692. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5693. (org-flag-region eoh eos nil 'outline)
  5694. (org-unlogged-message
  5695. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5696. (setq org-cycle-subtree-status 'subtree)
  5697. (unless (org-before-first-heading-p)
  5698. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5699. (t
  5700. ;; Default action: hide the subtree.
  5701. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5702. (org-flag-region eoh eos t 'outline)
  5703. (org-unlogged-message "FOLDED")
  5704. (setq org-cycle-subtree-status 'folded)
  5705. (unless (org-before-first-heading-p)
  5706. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5707. ;;;###autoload
  5708. (defun org-global-cycle (&optional arg)
  5709. "Cycle the global visibility. For details see `org-cycle'.
  5710. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5711. With a numeric prefix, show all headlines up to that level."
  5712. (interactive "P")
  5713. (let ((org-cycle-include-plain-lists
  5714. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5715. (cond
  5716. ((integerp arg)
  5717. (org-show-all '(headings blocks))
  5718. (outline-hide-sublevels arg)
  5719. (setq org-cycle-global-status 'contents))
  5720. ((equal arg '(4))
  5721. (org-set-startup-visibility)
  5722. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5723. (t
  5724. (org-cycle '(4))))))
  5725. (defun org-set-startup-visibility ()
  5726. "Set the visibility required by startup options and properties."
  5727. (cond
  5728. ((eq org-startup-folded t)
  5729. (org-overview))
  5730. ((eq org-startup-folded 'content)
  5731. (org-content))
  5732. ((or (eq org-startup-folded 'showeverything)
  5733. (eq org-startup-folded nil))
  5734. (org-show-all)))
  5735. (unless (eq org-startup-folded 'showeverything)
  5736. (when org-hide-block-startup (org-hide-block-all))
  5737. (org-set-visibility-according-to-property)
  5738. (org-cycle-hide-archived-subtrees 'all)
  5739. (org-cycle-hide-drawers 'all)
  5740. (org-cycle-show-empty-lines t)))
  5741. (defun org-set-visibility-according-to-property ()
  5742. "Switch subtree visibility according to VISIBILITY property."
  5743. (interactive)
  5744. (let ((regexp (org-re-property "VISIBILITY")))
  5745. (org-with-point-at 1
  5746. (while (re-search-forward regexp nil t)
  5747. (let ((state (match-string 3)))
  5748. (if (not (org-at-property-p)) (outline-next-heading)
  5749. (save-excursion
  5750. (org-back-to-heading t)
  5751. (org-flag-subtree t)
  5752. (org-reveal)
  5753. (pcase state
  5754. ("folded"
  5755. (org-flag-subtree t))
  5756. ("children"
  5757. (org-show-hidden-entry)
  5758. (org-show-children))
  5759. ("content"
  5760. (save-excursion
  5761. (save-restriction
  5762. (org-narrow-to-subtree)
  5763. (org-content))))
  5764. ((or "all" "showall")
  5765. (outline-show-subtree))
  5766. (_ nil)))
  5767. (org-end-of-subtree)))))))
  5768. (defun org-overview ()
  5769. "Switch to overview mode, showing only top-level headlines.
  5770. This shows all headlines with a level equal or greater than the level
  5771. of the first headline in the buffer. This is important, because if the
  5772. first headline is not level one, then (hide-sublevels 1) gives confusing
  5773. results."
  5774. (interactive)
  5775. (save-excursion
  5776. (let ((level
  5777. (save-excursion
  5778. (goto-char (point-min))
  5779. (when (re-search-forward org-outline-regexp-bol nil t)
  5780. (goto-char (match-beginning 0))
  5781. (funcall outline-level)))))
  5782. (and level (outline-hide-sublevels level)))))
  5783. (defun org-content (&optional arg)
  5784. "Show all headlines in the buffer, like a table of contents.
  5785. With numerical argument N, show content up to level N."
  5786. (interactive "P")
  5787. (org-overview)
  5788. (save-excursion
  5789. ;; Visit all headings and show their offspring
  5790. (and (integerp arg) (org-overview))
  5791. (goto-char (point-max))
  5792. (catch 'exit
  5793. (while (and (progn (condition-case nil
  5794. (outline-previous-visible-heading 1)
  5795. (error (goto-char (point-min))))
  5796. t)
  5797. (looking-at org-outline-regexp))
  5798. (if (integerp arg)
  5799. (org-show-children (1- arg))
  5800. (outline-show-branches))
  5801. (when (bobp) (throw 'exit nil))))))
  5802. (defun org-optimize-window-after-visibility-change (state)
  5803. "Adjust the window after a change in outline visibility.
  5804. This function is the default value of the hook `org-cycle-hook'."
  5805. (when (get-buffer-window (current-buffer))
  5806. (cond
  5807. ((eq state 'content) nil)
  5808. ((eq state 'all) nil)
  5809. ((eq state 'folded) nil)
  5810. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5811. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5812. (defun org-clean-visibility-after-subtree-move ()
  5813. "Fix visibility issues after moving a subtree."
  5814. ;; First, find a reasonable region to look at:
  5815. ;; Start two siblings above, end three below
  5816. (let* ((beg (save-excursion
  5817. (and (org-get-last-sibling)
  5818. (org-get-last-sibling))
  5819. (point)))
  5820. (end (save-excursion
  5821. (and (org-get-next-sibling)
  5822. (org-get-next-sibling)
  5823. (org-get-next-sibling))
  5824. (if (org-at-heading-p)
  5825. (point-at-eol)
  5826. (point))))
  5827. (level (looking-at "\\*+"))
  5828. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5829. (save-excursion
  5830. (save-restriction
  5831. (narrow-to-region beg end)
  5832. (when re
  5833. ;; Properly fold already folded siblings
  5834. (goto-char (point-min))
  5835. (while (re-search-forward re nil t)
  5836. (when (and (not (org-invisible-p))
  5837. (org-invisible-p (line-end-position)))
  5838. (outline-hide-entry))))
  5839. (org-cycle-hide-drawers 'all)
  5840. (org-cycle-show-empty-lines 'overview)))))
  5841. (defun org-cycle-show-empty-lines (state)
  5842. "Show empty lines above all visible headlines.
  5843. The region to be covered depends on STATE when called through
  5844. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5845. entire buffer covered. Note that an empty line is only shown if there
  5846. are at least `org-cycle-separator-lines' empty lines before the headline."
  5847. (when (/= org-cycle-separator-lines 0)
  5848. (save-excursion
  5849. (let* ((n (abs org-cycle-separator-lines))
  5850. (re (cond
  5851. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5852. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5853. (t (let ((ns (number-to-string (- n 2))))
  5854. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5855. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5856. beg end)
  5857. (cond
  5858. ((memq state '(overview contents t))
  5859. (setq beg (point-min) end (point-max)))
  5860. ((memq state '(children folded))
  5861. (setq beg (point)
  5862. end (progn (org-end-of-subtree t t)
  5863. (line-beginning-position 2)))))
  5864. (when beg
  5865. (goto-char beg)
  5866. (while (re-search-forward re end t)
  5867. (unless (get-char-property (match-end 1) 'invisible)
  5868. (let ((e (match-end 1))
  5869. (b (if (>= org-cycle-separator-lines 0)
  5870. (match-beginning 1)
  5871. (save-excursion
  5872. (goto-char (match-beginning 0))
  5873. (skip-chars-backward " \t\n")
  5874. (line-end-position)))))
  5875. (org-flag-region b e nil 'outline))))))))
  5876. ;; Never hide empty lines at the end of the file.
  5877. (save-excursion
  5878. (goto-char (point-max))
  5879. (outline-previous-heading)
  5880. (outline-end-of-heading)
  5881. (when (and (looking-at "[ \t\n]+")
  5882. (= (match-end 0) (point-max)))
  5883. (org-flag-region (point) (match-end 0) nil 'outline))))
  5884. ;;;; Reveal point location
  5885. (defun org-show-context (&optional key)
  5886. "Make sure point and context are visible.
  5887. Optional argument KEY, when non-nil, is a symbol. See
  5888. `org-show-context-detail' for allowed values and how much is to
  5889. be shown."
  5890. (org-show-set-visibility
  5891. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5892. ((cdr (assq key org-show-context-detail)))
  5893. (t (cdr (assq 'default org-show-context-detail))))))
  5894. (defun org-show-set-visibility (detail)
  5895. "Set visibility around point according to DETAIL.
  5896. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5897. `tree', `canonical' or t. See `org-show-context-detail' for more
  5898. information."
  5899. ;; Show current heading and possibly its entry, following headline
  5900. ;; or all children.
  5901. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5902. (org-flag-heading nil)
  5903. (org-show-entry)
  5904. ;; If point is hidden within a drawer or a block, make sure to
  5905. ;; expose it.
  5906. (dolist (o (overlays-at (point)))
  5907. (when (memq (overlay-get o 'invisible)
  5908. '(org-hide-block org-hide-drawer outline))
  5909. (delete-overlay o)))
  5910. (unless (org-before-first-heading-p)
  5911. (org-with-limited-levels
  5912. (cl-case detail
  5913. ((tree canonical t) (org-show-children))
  5914. ((nil minimal ancestors))
  5915. (t (save-excursion
  5916. (outline-next-heading)
  5917. (org-flag-heading nil)))))))
  5918. ;; Show all siblings.
  5919. (when (eq detail 'lineage) (org-show-siblings))
  5920. ;; Show ancestors, possibly with their children.
  5921. (when (memq detail '(ancestors lineage tree canonical t))
  5922. (save-excursion
  5923. (while (org-up-heading-safe)
  5924. (org-flag-heading nil)
  5925. (when (memq detail '(canonical t)) (org-show-entry))
  5926. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5927. (defvar org-reveal-start-hook nil
  5928. "Hook run before revealing a location.")
  5929. (defun org-reveal (&optional siblings)
  5930. "Show current entry, hierarchy above it, and the following headline.
  5931. This can be used to show a consistent set of context around
  5932. locations exposed with `org-show-context'.
  5933. With optional argument SIBLINGS, on each level of the hierarchy all
  5934. siblings are shown. This repairs the tree structure to what it would
  5935. look like when opened with hierarchical calls to `org-cycle'.
  5936. With a \\[universal-argument] \\[universal-argument] prefix, \
  5937. go to the parent and show the entire tree."
  5938. (interactive "P")
  5939. (run-hooks 'org-reveal-start-hook)
  5940. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5941. ((equal siblings '(16))
  5942. (save-excursion
  5943. (when (org-up-heading-safe)
  5944. (org-show-subtree)
  5945. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5946. (t (org-show-set-visibility 'lineage))))
  5947. ;;; Indirect buffer display of subtrees
  5948. (defvar org-indirect-dedicated-frame nil
  5949. "This is the frame being used for indirect tree display.")
  5950. (defvar org-last-indirect-buffer nil)
  5951. (defun org-tree-to-indirect-buffer (&optional arg)
  5952. "Create indirect buffer and narrow it to current subtree.
  5953. With a numerical prefix ARG, go up to this level and then take that tree.
  5954. If ARG is negative, go up that many levels.
  5955. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5956. indirect buffer previously made with this command, to avoid proliferation of
  5957. indirect buffers. However, when you call the command with a \
  5958. `\\[universal-argument]' prefix, or
  5959. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5960. so that you can work with several indirect buffers at the same time. If
  5961. `org-indirect-buffer-display' is `dedicated-frame', the \
  5962. `\\[universal-argument]' prefix also
  5963. requests that a new frame be made for the new buffer, so that the dedicated
  5964. frame is not changed."
  5965. (interactive "P")
  5966. (let ((cbuf (current-buffer))
  5967. (cwin (selected-window))
  5968. (pos (point))
  5969. beg end level heading ibuf)
  5970. (save-excursion
  5971. (org-back-to-heading t)
  5972. (when (numberp arg)
  5973. (setq level (org-outline-level))
  5974. (when (< arg 0) (setq arg (+ level arg)))
  5975. (while (> (setq level (org-outline-level)) arg)
  5976. (org-up-heading-safe)))
  5977. (setq beg (point)
  5978. heading (org-get-heading 'no-tags))
  5979. (org-end-of-subtree t t)
  5980. (when (org-at-heading-p) (backward-char 1))
  5981. (setq end (point)))
  5982. (when (and (buffer-live-p org-last-indirect-buffer)
  5983. (not (eq org-indirect-buffer-display 'new-frame))
  5984. (not arg))
  5985. (kill-buffer org-last-indirect-buffer))
  5986. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5987. org-last-indirect-buffer ibuf)
  5988. (cond
  5989. ((or (eq org-indirect-buffer-display 'new-frame)
  5990. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5991. (select-frame (make-frame))
  5992. (delete-other-windows)
  5993. (pop-to-buffer-same-window ibuf)
  5994. (org-set-frame-title heading))
  5995. ((eq org-indirect-buffer-display 'dedicated-frame)
  5996. (raise-frame
  5997. (select-frame (or (and org-indirect-dedicated-frame
  5998. (frame-live-p org-indirect-dedicated-frame)
  5999. org-indirect-dedicated-frame)
  6000. (setq org-indirect-dedicated-frame (make-frame)))))
  6001. (delete-other-windows)
  6002. (pop-to-buffer-same-window ibuf)
  6003. (org-set-frame-title (concat "Indirect: " heading)))
  6004. ((eq org-indirect-buffer-display 'current-window)
  6005. (pop-to-buffer-same-window ibuf))
  6006. ((eq org-indirect-buffer-display 'other-window)
  6007. (pop-to-buffer ibuf))
  6008. (t (error "Invalid value")))
  6009. (narrow-to-region beg end)
  6010. (org-show-all '(headings blocks))
  6011. (goto-char pos)
  6012. (run-hook-with-args 'org-cycle-hook 'all)
  6013. (and (window-live-p cwin) (select-window cwin))))
  6014. (defun org-get-indirect-buffer (&optional buffer heading)
  6015. (setq buffer (or buffer (current-buffer)))
  6016. (let ((n 1) (base (buffer-name buffer)) bname)
  6017. (while (buffer-live-p
  6018. (get-buffer
  6019. (setq bname
  6020. (concat base "-"
  6021. (if heading (concat heading "-" (number-to-string n))
  6022. (number-to-string n))))))
  6023. (setq n (1+ n)))
  6024. (condition-case nil
  6025. (make-indirect-buffer buffer bname 'clone)
  6026. (error (make-indirect-buffer buffer bname)))))
  6027. (defun org-set-frame-title (title)
  6028. "Set the title of the current frame to the string TITLE."
  6029. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6030. ;;;; Structure editing
  6031. ;;; Inserting headlines
  6032. (defun org--blank-before-heading-p (&optional parent)
  6033. "Non-nil when an empty line should precede a new heading here.
  6034. When optional argument PARENT is non-nil, consider parent
  6035. headline instead of current one."
  6036. (pcase (assq 'heading org-blank-before-new-entry)
  6037. (`(heading . auto)
  6038. (save-excursion
  6039. (org-with-limited-levels
  6040. (unless (and (org-before-first-heading-p)
  6041. (not (outline-next-heading)))
  6042. (org-back-to-heading t)
  6043. (when parent (org-up-heading-safe))
  6044. (cond ((not (bobp))
  6045. (org-previous-line-empty-p))
  6046. ((outline-next-heading)
  6047. (org-previous-line-empty-p))
  6048. ;; Ignore trailing spaces on last buffer line.
  6049. ((progn (skip-chars-backward " \t") (bolp))
  6050. (org-previous-line-empty-p))
  6051. (t nil))))))
  6052. (`(heading . ,value) value)
  6053. (_ nil)))
  6054. (defun org-insert-heading (&optional arg invisible-ok top)
  6055. "Insert a new heading or an item with the same depth at point.
  6056. If point is at the beginning of a heading, insert a new heading
  6057. or a new headline above the current one. When at the beginning
  6058. of a regular line of text, turn it into a heading.
  6059. If point is in the middle of a line, split it and create a new
  6060. headline with the text in the current line after point (see
  6061. `org-M-RET-may-split-line' on how to modify this behavior). As
  6062. a special case, on a headline, splitting can only happen on the
  6063. title itself. E.g., this excludes breaking stars or tags.
  6064. With a `\\[universal-argument]' prefix, set \
  6065. `org-insert-heading-respect-content' to
  6066. a non-nil value for the duration of the command. This forces the
  6067. insertion of a heading after the current subtree, independently
  6068. on the location of point.
  6069. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6070. insert the heading at the end of the tree
  6071. above the current heading. For example, if point is within a
  6072. 2nd-level heading, then it will insert a 2nd-level heading at
  6073. the end of the 1st-level parent subtree.
  6074. When INVISIBLE-OK is set, stop at invisible headlines when going
  6075. back. This is important for non-interactive uses of the
  6076. command.
  6077. When optional argument TOP is non-nil, insert a level 1 heading,
  6078. unconditionally."
  6079. (interactive "P")
  6080. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6081. (level (org-current-level))
  6082. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6083. (cond
  6084. ((or org-insert-heading-respect-content
  6085. (member arg '((4) (16)))
  6086. (and (not invisible-ok)
  6087. (invisible-p (max (1- (point)) (point-min)))))
  6088. ;; Position point at the location of insertion. Make sure we
  6089. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6090. (org-with-limited-levels
  6091. (if (not level) (outline-next-heading) ;before first headline
  6092. (org-back-to-heading invisible-ok)
  6093. (when (equal arg '(16)) (org-up-heading-safe))
  6094. (org-end-of-subtree)))
  6095. (unless (bolp) (insert "\n"))
  6096. (unless (and blank? (org-previous-line-empty-p))
  6097. (org-N-empty-lines-before-current (if blank? 1 0)))
  6098. (insert stars " ")
  6099. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6100. ;; is visible.
  6101. (unless invisible-ok
  6102. (pcase (get-char-property-and-overlay (point) 'invisible)
  6103. (`(outline . ,o)
  6104. (move-overlay o (overlay-start o) (line-end-position 0)))
  6105. (_ nil))))
  6106. ;; At a headline...
  6107. ((org-at-heading-p)
  6108. (cond ((bolp)
  6109. (when blank? (save-excursion (insert "\n")))
  6110. (save-excursion (insert stars " \n"))
  6111. (unless (and blank? (org-previous-line-empty-p))
  6112. (org-N-empty-lines-before-current (if blank? 1 0)))
  6113. (end-of-line))
  6114. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6115. (org-match-line org-complex-heading-regexp)
  6116. (org-pos-in-match-range (point) 4))
  6117. ;; Grab the text that should moved to the new headline.
  6118. ;; Preserve tags.
  6119. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6120. (if (looking-at "[ \t]*$") (replace-match "")
  6121. (org-align-tags))
  6122. (end-of-line)
  6123. (when blank? (insert "\n"))
  6124. (insert "\n" stars " ")
  6125. (when (org-string-nw-p split) (insert split))))
  6126. (t
  6127. (end-of-line)
  6128. (when blank? (insert "\n"))
  6129. (insert "\n" stars " "))))
  6130. ;; On regular text, turn line into a headline or split, if
  6131. ;; appropriate.
  6132. ((bolp)
  6133. (insert stars " ")
  6134. (unless (and blank? (org-previous-line-empty-p))
  6135. (org-N-empty-lines-before-current (if blank? 1 0))))
  6136. (t
  6137. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6138. (end-of-line))
  6139. (insert "\n" stars " ")
  6140. (unless (and blank? (org-previous-line-empty-p))
  6141. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6142. (run-hooks 'org-insert-heading-hook))
  6143. (defun org-N-empty-lines-before-current (n)
  6144. "Make the number of empty lines before current exactly N.
  6145. So this will delete or add empty lines."
  6146. (let ((column (current-column)))
  6147. (beginning-of-line)
  6148. (unless (bobp)
  6149. (let ((start (save-excursion
  6150. (skip-chars-backward " \r\t\n")
  6151. (line-end-position))))
  6152. (delete-region start (line-end-position 0))))
  6153. (insert (make-string n ?\n))
  6154. (move-to-column column)))
  6155. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6156. "Return the heading of the current entry, without the stars.
  6157. When NO-TAGS is non-nil, don't include tags.
  6158. When NO-TODO is non-nil, don't include TODO keywords.
  6159. When NO-PRIORITY is non-nil, don't include priority cookie.
  6160. When NO-COMMENT is non-nil, don't include COMMENT string.
  6161. Return nil before first heading."
  6162. (unless (org-before-first-heading-p)
  6163. (save-excursion
  6164. (org-back-to-heading t)
  6165. (let ((case-fold-search nil))
  6166. (looking-at org-complex-heading-regexp)
  6167. (let ((todo (and (not no-todo) (match-string 2)))
  6168. (priority (and (not no-priority) (match-string 3)))
  6169. (headline (pcase (match-string 4)
  6170. (`nil "")
  6171. ((and (guard no-comment) h)
  6172. (replace-regexp-in-string
  6173. (eval-when-compile
  6174. (format "\\`%s[ \t]+" org-comment-string))
  6175. "" h))
  6176. (h h)))
  6177. (tags (and (not no-tags) (match-string 5))))
  6178. (mapconcat #'identity
  6179. (delq nil (list todo priority headline tags))
  6180. " "))))))
  6181. (defun org-heading-components ()
  6182. "Return the components of the current heading.
  6183. This is a list with the following elements:
  6184. - the level as an integer
  6185. - the reduced level, different if `org-odd-levels-only' is set.
  6186. - the TODO keyword, or nil
  6187. - the priority character, like ?A, or nil if no priority is given
  6188. - the headline text itself, or the tags string if no headline text
  6189. - the tags string, or nil."
  6190. (save-excursion
  6191. (org-back-to-heading t)
  6192. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6193. (list (length (match-string 1))
  6194. (org-reduced-level (length (match-string 1)))
  6195. (match-string-no-properties 2)
  6196. (and (match-end 3) (aref (match-string 3) 2))
  6197. (match-string-no-properties 4)
  6198. (match-string-no-properties 5)))))
  6199. (defun org-get-entry ()
  6200. "Get the entry text, after heading, entire subtree."
  6201. (save-excursion
  6202. (org-back-to-heading t)
  6203. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6204. (defun org-edit-headline (&optional heading)
  6205. "Edit the current headline.
  6206. Set it to HEADING when provided."
  6207. (interactive)
  6208. (org-with-wide-buffer
  6209. (org-back-to-heading t)
  6210. (let ((case-fold-search nil))
  6211. (when (looking-at org-complex-heading-regexp)
  6212. (let* ((old (match-string-no-properties 4))
  6213. (new (save-match-data
  6214. (org-trim (or heading (read-string "Edit: " old))))))
  6215. (unless (equal old new)
  6216. (if old (replace-match new t t nil 4)
  6217. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6218. (insert " " new))
  6219. (org-align-tags)
  6220. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6221. (defun org-insert-heading-after-current ()
  6222. "Insert a new heading with same level as current, after current subtree."
  6223. (interactive)
  6224. (org-back-to-heading)
  6225. (org-insert-heading)
  6226. (org-move-subtree-down)
  6227. (end-of-line 1))
  6228. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6229. "Insert heading with `org-insert-heading-respect-content' set to t."
  6230. (interactive)
  6231. (org-insert-heading '(4) invisible-ok))
  6232. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6233. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6234. (interactive)
  6235. (org-insert-todo-heading force-state '(4)))
  6236. (defun org-insert-todo-heading (arg &optional force-heading)
  6237. "Insert a new heading with the same level and TODO state as current heading.
  6238. If the heading has no TODO state, or if the state is DONE, use
  6239. the first state (TODO by default). Also with one prefix arg,
  6240. force first state. With two prefix args, force inserting at the
  6241. end of the parent subtree.
  6242. When called at a plain list item, insert a new item with an
  6243. unchecked check box."
  6244. (interactive "P")
  6245. (when (or force-heading (not (org-insert-item 'checkbox)))
  6246. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6247. force-heading))
  6248. (save-excursion
  6249. (org-forward-heading-same-level -1)
  6250. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6251. (let* ((new-mark-x
  6252. (if (or (equal arg '(4))
  6253. (not (match-beginning 2))
  6254. (member (match-string 2) org-done-keywords))
  6255. (car org-todo-keywords-1)
  6256. (match-string 2)))
  6257. (new-mark
  6258. (or
  6259. (run-hook-with-args-until-success
  6260. 'org-todo-get-default-hook new-mark-x nil)
  6261. new-mark-x)))
  6262. (beginning-of-line 1)
  6263. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6264. (if org-treat-insert-todo-heading-as-state-change
  6265. (org-todo new-mark)
  6266. (insert new-mark " "))))
  6267. (when org-provide-todo-statistics
  6268. (org-update-parent-todo-statistics))))
  6269. (defun org-insert-subheading (arg)
  6270. "Insert a new subheading and demote it.
  6271. Works for outline headings and for plain lists alike."
  6272. (interactive "P")
  6273. (org-insert-heading arg)
  6274. (cond
  6275. ((org-at-heading-p) (org-do-demote))
  6276. ((org-at-item-p) (org-indent-item))))
  6277. (defun org-insert-todo-subheading (arg)
  6278. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6279. Works for outline headings and for plain lists alike."
  6280. (interactive "P")
  6281. (org-insert-todo-heading arg)
  6282. (cond
  6283. ((org-at-heading-p) (org-do-demote))
  6284. ((org-at-item-p) (org-indent-item))))
  6285. ;;; Promotion and Demotion
  6286. (defvar org-after-demote-entry-hook nil
  6287. "Hook run after an entry has been demoted.
  6288. The cursor will be at the beginning of the entry.
  6289. When a subtree is being demoted, the hook will be called for each node.")
  6290. (defvar org-after-promote-entry-hook nil
  6291. "Hook run after an entry has been promoted.
  6292. The cursor will be at the beginning of the entry.
  6293. When a subtree is being promoted, the hook will be called for each node.")
  6294. (defun org-promote-subtree ()
  6295. "Promote the entire subtree.
  6296. See also `org-promote'."
  6297. (interactive)
  6298. (save-excursion
  6299. (org-with-limited-levels (org-map-tree 'org-promote)))
  6300. (org-fix-position-after-promote))
  6301. (defun org-demote-subtree ()
  6302. "Demote the entire subtree.
  6303. See `org-demote' and `org-promote'."
  6304. (interactive)
  6305. (save-excursion
  6306. (org-with-limited-levels (org-map-tree 'org-demote)))
  6307. (org-fix-position-after-promote))
  6308. (defun org-do-promote ()
  6309. "Promote the current heading higher up the tree.
  6310. If the region is active in `transient-mark-mode', promote all
  6311. headings in the region."
  6312. (interactive)
  6313. (save-excursion
  6314. (if (org-region-active-p)
  6315. (org-map-region 'org-promote (region-beginning) (region-end))
  6316. (org-promote)))
  6317. (org-fix-position-after-promote))
  6318. (defun org-do-demote ()
  6319. "Demote the current heading lower down the tree.
  6320. If the region is active in `transient-mark-mode', demote all
  6321. headings in the region."
  6322. (interactive)
  6323. (save-excursion
  6324. (if (org-region-active-p)
  6325. (org-map-region 'org-demote (region-beginning) (region-end))
  6326. (org-demote)))
  6327. (org-fix-position-after-promote))
  6328. (defun org-fix-position-after-promote ()
  6329. "Fix cursor position and indentation after demoting/promoting."
  6330. (let ((pos (point)))
  6331. (when (save-excursion
  6332. (beginning-of-line)
  6333. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6334. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6335. (cond ((eobp) (insert " "))
  6336. ((eolp) (insert " "))
  6337. ((equal (char-after) ?\s) (forward-char 1))))))
  6338. (defun org-current-level ()
  6339. "Return the level of the current entry, or nil if before the first headline.
  6340. The level is the number of stars at the beginning of the
  6341. headline. Use `org-reduced-level' to remove the effect of
  6342. `org-odd-levels'. Unlike to `org-outline-level', this function
  6343. ignores inlinetasks."
  6344. (let ((level (org-with-limited-levels (org-outline-level))))
  6345. (and (> level 0) level)))
  6346. (defun org-get-previous-line-level ()
  6347. "Return the outline depth of the last headline before the current line.
  6348. Returns 0 for the first headline in the buffer, and nil if before the
  6349. first headline."
  6350. (and (org-current-level)
  6351. (or (and (/= (line-beginning-position) (point-min))
  6352. (save-excursion (beginning-of-line 0) (org-current-level)))
  6353. 0)))
  6354. (defun org-reduced-level (l)
  6355. "Compute the effective level of a heading.
  6356. This takes into account the setting of `org-odd-levels-only'."
  6357. (cond
  6358. ((zerop l) 0)
  6359. (org-odd-levels-only (1+ (floor (/ l 2))))
  6360. (t l)))
  6361. (defun org-level-increment ()
  6362. "Return the number of stars that will be added or removed at a
  6363. time to headlines when structure editing, based on the value of
  6364. `org-odd-levels-only'."
  6365. (if org-odd-levels-only 2 1))
  6366. (defun org-get-valid-level (level &optional change)
  6367. "Rectify a level change under the influence of `org-odd-levels-only'.
  6368. LEVEL is a current level, CHANGE is by how much the level should
  6369. be modified. Even if CHANGE is nil, LEVEL may be returned
  6370. modified because even level numbers will become the next higher
  6371. odd number. Returns values greater than 0."
  6372. (if org-odd-levels-only
  6373. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6374. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6375. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6376. (max 1 (+ level (or change 0)))))
  6377. (defun org-promote ()
  6378. "Promote the current heading higher up the tree."
  6379. (org-with-wide-buffer
  6380. (org-back-to-heading t)
  6381. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6382. after-change-functions))
  6383. (level (save-match-data (funcall outline-level)))
  6384. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6385. (diff (abs (- level (length up-head) -1))))
  6386. (cond
  6387. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6388. (replace-match "# " nil t))
  6389. ((= level 1)
  6390. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6391. (t (replace-match up-head nil t)))
  6392. (unless (= level 1)
  6393. (when org-auto-align-tags (org-align-tags))
  6394. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6395. (run-hooks 'org-after-promote-entry-hook))))
  6396. (defun org-demote ()
  6397. "Demote the current heading lower down the tree."
  6398. (org-with-wide-buffer
  6399. (org-back-to-heading t)
  6400. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6401. after-change-functions))
  6402. (level (save-match-data (funcall outline-level)))
  6403. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6404. (diff (abs (- level (length down-head) -1))))
  6405. (replace-match down-head nil t)
  6406. (when org-auto-align-tags (org-align-tags))
  6407. (when org-adapt-indentation (org-fixup-indentation diff))
  6408. (run-hooks 'org-after-demote-entry-hook))))
  6409. (defun org-cycle-level ()
  6410. "Cycle the level of an empty headline through possible states.
  6411. This goes first to child, then to parent, level, then up the hierarchy.
  6412. After top level, it switches back to sibling level."
  6413. (interactive)
  6414. (let ((org-adapt-indentation nil))
  6415. (when (org-point-at-end-of-empty-headline)
  6416. (setq this-command 'org-cycle-level) ; Only needed for caching
  6417. (let ((cur-level (org-current-level))
  6418. (prev-level (org-get-previous-line-level)))
  6419. (cond
  6420. ;; If first headline in file, promote to top-level.
  6421. ((= prev-level 0)
  6422. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6423. do (org-do-promote)))
  6424. ;; If same level as prev, demote one.
  6425. ((= prev-level cur-level)
  6426. (org-do-demote))
  6427. ;; If parent is top-level, promote to top level if not already.
  6428. ((= prev-level 1)
  6429. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6430. do (org-do-promote)))
  6431. ;; If top-level, return to prev-level.
  6432. ((= cur-level 1)
  6433. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6434. do (org-do-demote)))
  6435. ;; If less than prev-level, promote one.
  6436. ((< cur-level prev-level)
  6437. (org-do-promote))
  6438. ;; If deeper than prev-level, promote until higher than
  6439. ;; prev-level.
  6440. ((> cur-level prev-level)
  6441. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6442. do (org-do-promote))))
  6443. t))))
  6444. (defun org-map-tree (fun)
  6445. "Call FUN for every heading underneath the current one."
  6446. (org-back-to-heading t)
  6447. (let ((level (funcall outline-level)))
  6448. (save-excursion
  6449. (funcall fun)
  6450. (while (and (progn
  6451. (outline-next-heading)
  6452. (> (funcall outline-level) level))
  6453. (not (eobp)))
  6454. (funcall fun)))))
  6455. (defun org-map-region (fun beg end)
  6456. "Call FUN for every heading between BEG and END."
  6457. (let ((org-ignore-region t))
  6458. (save-excursion
  6459. (setq end (copy-marker end))
  6460. (goto-char beg)
  6461. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6462. (< (point) end))
  6463. (funcall fun))
  6464. (while (and (progn
  6465. (outline-next-heading)
  6466. (< (point) end))
  6467. (not (eobp)))
  6468. (funcall fun)))))
  6469. (defun org-fixup-indentation (diff)
  6470. "Change the indentation in the current entry by DIFF.
  6471. DIFF is an integer. Indentation is done according to the
  6472. following rules:
  6473. - Planning information and property drawers are always indented
  6474. according to the new level of the headline;
  6475. - Footnote definitions and their contents are ignored;
  6476. - Inlinetasks' boundaries are not shifted;
  6477. - Empty lines are ignored;
  6478. - Other lines' indentation are shifted by DIFF columns, unless
  6479. it would introduce a structural change in the document, in
  6480. which case no shifting is done at all.
  6481. Assume point is at a heading or an inlinetask beginning."
  6482. (org-with-wide-buffer
  6483. (narrow-to-region (line-beginning-position)
  6484. (save-excursion
  6485. (if (org-with-limited-levels (org-at-heading-p))
  6486. (org-with-limited-levels (outline-next-heading))
  6487. (org-inlinetask-goto-end))
  6488. (point)))
  6489. (forward-line)
  6490. ;; Indent properly planning info and property drawer.
  6491. (when (looking-at-p org-planning-line-re)
  6492. (org-indent-line)
  6493. (forward-line))
  6494. (when (looking-at org-property-drawer-re)
  6495. (goto-char (match-end 0))
  6496. (forward-line)
  6497. (org-indent-region (match-beginning 0) (match-end 0)))
  6498. (when (looking-at org-logbook-drawer-re)
  6499. (goto-char (match-end 0))
  6500. (forward-line)
  6501. (org-indent-region (match-beginning 0) (match-end 0)))
  6502. (catch 'no-shift
  6503. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6504. (throw 'no-shift nil))
  6505. ;; If DIFF is negative, first check if a shift is possible at all
  6506. ;; (e.g., it doesn't break structure). This can only happen if
  6507. ;; some contents are not properly indented.
  6508. (let ((case-fold-search t))
  6509. (when (< diff 0)
  6510. (let ((diff (- diff))
  6511. (forbidden-re (concat org-outline-regexp
  6512. "\\|"
  6513. (substring org-footnote-definition-re 1))))
  6514. (save-excursion
  6515. (while (not (eobp))
  6516. (cond
  6517. ((looking-at-p "[ \t]*$") (forward-line))
  6518. ((and (looking-at-p org-footnote-definition-re)
  6519. (let ((e (org-element-at-point)))
  6520. (and (eq (org-element-type e) 'footnote-definition)
  6521. (goto-char (org-element-property :end e))))))
  6522. ((looking-at-p org-outline-regexp) (forward-line))
  6523. ;; Give up if shifting would move before column 0 or
  6524. ;; if it would introduce a headline or a footnote
  6525. ;; definition.
  6526. (t
  6527. (skip-chars-forward " \t")
  6528. (let ((ind (current-column)))
  6529. (when (or (< ind diff)
  6530. (and (= ind diff) (looking-at-p forbidden-re)))
  6531. (throw 'no-shift nil)))
  6532. ;; Ignore contents of example blocks and source
  6533. ;; blocks if their indentation is meant to be
  6534. ;; preserved. Jump to block's closing line.
  6535. (beginning-of-line)
  6536. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6537. (let ((e (org-element-at-point)))
  6538. (and (memq (org-element-type e)
  6539. '(example-block src-block))
  6540. (or org-src-preserve-indentation
  6541. (org-element-property :preserve-indent e))
  6542. (goto-char (org-element-property :end e))
  6543. (progn (skip-chars-backward " \r\t\n")
  6544. (beginning-of-line)
  6545. t))))
  6546. (forward-line))))))))
  6547. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6548. ;; by DIFF. Also skip contents of source or example blocks
  6549. ;; when indentation is meant to be preserved.
  6550. (while (not (eobp))
  6551. (cond
  6552. ((and (looking-at-p org-footnote-definition-re)
  6553. (let ((e (org-element-at-point)))
  6554. (and (eq (org-element-type e) 'footnote-definition)
  6555. (goto-char (org-element-property :end e))))))
  6556. ((looking-at-p org-outline-regexp) (forward-line))
  6557. ((looking-at-p "[ \t]*$") (forward-line))
  6558. (t
  6559. (indent-line-to (+ (current-indentation) diff))
  6560. (beginning-of-line)
  6561. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6562. (let ((e (org-element-at-point)))
  6563. (and (memq (org-element-type e)
  6564. '(example-block src-block))
  6565. (or org-src-preserve-indentation
  6566. (org-element-property :preserve-indent e))
  6567. (goto-char (org-element-property :end e))
  6568. (progn (skip-chars-backward " \r\t\n")
  6569. (beginning-of-line)
  6570. t))))
  6571. (forward-line)))))))))
  6572. (defun org-convert-to-odd-levels ()
  6573. "Convert an Org file with all levels allowed to one with odd levels.
  6574. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6575. level 5 etc."
  6576. (interactive)
  6577. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6578. (let ((outline-level 'org-outline-level)
  6579. (org-odd-levels-only nil) n)
  6580. (save-excursion
  6581. (goto-char (point-min))
  6582. (while (re-search-forward "^\\*\\*+ " nil t)
  6583. (setq n (- (length (match-string 0)) 2))
  6584. (while (>= (setq n (1- n)) 0)
  6585. (org-demote))
  6586. (end-of-line 1))))))
  6587. (defun org-convert-to-oddeven-levels ()
  6588. "Convert an Org file with only odd levels to one with odd/even levels.
  6589. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6590. file contains a section with an even level, conversion would
  6591. destroy the structure of the file. An error is signaled in this
  6592. case."
  6593. (interactive)
  6594. (goto-char (point-min))
  6595. ;; First check if there are no even levels
  6596. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6597. (org-show-set-visibility 'canonical)
  6598. (error "Not all levels are odd in this file. Conversion not possible"))
  6599. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6600. (let ((outline-regexp org-outline-regexp)
  6601. (outline-level 'org-outline-level)
  6602. (org-odd-levels-only nil) n)
  6603. (save-excursion
  6604. (goto-char (point-min))
  6605. (while (re-search-forward "^\\*\\*+ " nil t)
  6606. (setq n (/ (1- (length (match-string 0))) 2))
  6607. (while (>= (setq n (1- n)) 0)
  6608. (org-promote))
  6609. (end-of-line 1))))))
  6610. (defun org-tr-level (n)
  6611. "Make N odd if required."
  6612. (if org-odd-levels-only (1+ (/ n 2)) n))
  6613. ;;; Vertical tree motion, cutting and pasting of subtrees
  6614. (defun org-move-subtree-up (&optional arg)
  6615. "Move the current subtree up past ARG headlines of the same level."
  6616. (interactive "p")
  6617. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6618. (defun org-move-subtree-down (&optional arg)
  6619. "Move the current subtree down past ARG headlines of the same level."
  6620. (interactive "p")
  6621. (setq arg (prefix-numeric-value arg))
  6622. (org-preserve-local-variables
  6623. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6624. 'org-get-last-sibling))
  6625. (ins-point (make-marker))
  6626. (cnt (abs arg))
  6627. (col (current-column))
  6628. beg end txt folded)
  6629. ;; Select the tree
  6630. (org-back-to-heading)
  6631. (setq beg (point))
  6632. (save-match-data
  6633. (save-excursion (outline-end-of-heading)
  6634. (setq folded (org-invisible-p)))
  6635. (progn (org-end-of-subtree nil t)
  6636. (unless (eobp) (backward-char))))
  6637. (outline-next-heading)
  6638. (setq end (point))
  6639. (goto-char beg)
  6640. ;; Find insertion point, with error handling
  6641. (while (> cnt 0)
  6642. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6643. (goto-char beg)
  6644. (user-error "Cannot move past superior level or buffer limit"))
  6645. (setq cnt (1- cnt)))
  6646. (when (> arg 0)
  6647. ;; Moving forward - still need to move over subtree
  6648. (org-end-of-subtree t t)
  6649. (save-excursion
  6650. (org-back-over-empty-lines)
  6651. (or (bolp) (newline))))
  6652. (move-marker ins-point (point))
  6653. (setq txt (buffer-substring beg end))
  6654. (org-save-markers-in-region beg end)
  6655. (delete-region beg end)
  6656. (org-remove-empty-overlays-at beg)
  6657. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6658. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6659. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6660. (let ((bbb (point)))
  6661. (insert-before-markers txt)
  6662. (org-reinstall-markers-in-region bbb)
  6663. (move-marker ins-point bbb))
  6664. (or (bolp) (insert "\n"))
  6665. (goto-char ins-point)
  6666. (org-skip-whitespace)
  6667. (move-marker ins-point nil)
  6668. (if folded
  6669. (org-flag-subtree t)
  6670. (org-show-entry)
  6671. (org-show-children))
  6672. (org-clean-visibility-after-subtree-move)
  6673. ;; move back to the initial column we were at
  6674. (move-to-column col))))
  6675. (defvar org-subtree-clip ""
  6676. "Clipboard for cut and paste of subtrees.
  6677. This is actually only a copy of the kill, because we use the normal kill
  6678. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6679. (defvar org-subtree-clip-folded nil
  6680. "Was the last copied subtree folded?
  6681. This is used to fold the tree back after pasting.")
  6682. (defun org-cut-subtree (&optional n)
  6683. "Cut the current subtree into the clipboard.
  6684. With prefix arg N, cut this many sequential subtrees.
  6685. This is a short-hand for marking the subtree and then cutting it."
  6686. (interactive "p")
  6687. (org-copy-subtree n 'cut))
  6688. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6689. "Copy the current subtree into the clipboard.
  6690. With prefix arg N, copy this many sequential subtrees.
  6691. This is a short-hand for marking the subtree and then copying it.
  6692. If CUT is non-nil, actually cut the subtree.
  6693. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6694. of some markers in the region, even if CUT is non-nil. This is
  6695. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6696. (interactive "p")
  6697. (org-preserve-local-variables
  6698. (let (beg end folded (beg0 (point)))
  6699. (if (called-interactively-p 'any)
  6700. (org-back-to-heading nil) ; take what looks like a subtree
  6701. (org-back-to-heading t)) ; take what is really there
  6702. (setq beg (point))
  6703. (skip-chars-forward " \t\r\n")
  6704. (save-match-data
  6705. (if nosubtrees
  6706. (outline-next-heading)
  6707. (save-excursion (outline-end-of-heading)
  6708. (setq folded (org-invisible-p)))
  6709. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6710. (org-end-of-subtree t t)))
  6711. ;; Include the end of an inlinetask
  6712. (when (and (featurep 'org-inlinetask)
  6713. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6714. "END[ \t]*$")))
  6715. (end-of-line))
  6716. (setq end (point))
  6717. (goto-char beg0)
  6718. (when (> end beg)
  6719. (setq org-subtree-clip-folded folded)
  6720. (when (or cut force-store-markers)
  6721. (org-save-markers-in-region beg end))
  6722. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6723. (setq org-subtree-clip (current-kill 0))
  6724. (message "%s: Subtree(s) with %d characters"
  6725. (if cut "Cut" "Copied")
  6726. (length org-subtree-clip))))))
  6727. (defun org-paste-subtree (&optional level tree for-yank remove)
  6728. "Paste the clipboard as a subtree, with modification of headline level.
  6729. The entire subtree is promoted or demoted in order to match a new headline
  6730. level.
  6731. If the cursor is at the beginning of a headline, the same level as
  6732. that headline is used to paste the tree.
  6733. If not, the new level is derived from the *visible* headings
  6734. before and after the insertion point, and taken to be the inferior headline
  6735. level of the two. So if the previous visible heading is level 3 and the
  6736. next is level 4 (or vice versa), level 4 will be used for insertion.
  6737. This makes sure that the subtree remains an independent subtree and does
  6738. not swallow low level entries.
  6739. You can also force a different level, either by using a numeric prefix
  6740. argument, or by inserting the heading marker by hand. For example, if the
  6741. cursor is after \"*****\", then the tree will be shifted to level 5.
  6742. If optional TREE is given, use this text instead of the kill ring.
  6743. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6744. move back over whitespace before inserting, and move point to the end of
  6745. the inserted text when done.
  6746. When REMOVE is non-nil, remove the subtree from the clipboard."
  6747. (interactive "P")
  6748. (setq tree (or tree (and kill-ring (current-kill 0))))
  6749. (unless (org-kill-is-subtree-p tree)
  6750. (user-error
  6751. (substitute-command-keys
  6752. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6753. (org-with-limited-levels
  6754. (let* ((visp (not (org-invisible-p)))
  6755. (txt tree)
  6756. (old-level (if (string-match org-outline-regexp-bol txt)
  6757. (- (match-end 0) (match-beginning 0) 1)
  6758. -1))
  6759. (force-level
  6760. (cond
  6761. (level (prefix-numeric-value level))
  6762. ;; When point is after the stars in an otherwise empty
  6763. ;; headline, use the number of stars as the forced level.
  6764. ((and (org-match-line "^\\*+[ \t]*$")
  6765. (not (eq ?* (char-after))))
  6766. (org-outline-level))
  6767. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6768. (previous-level
  6769. (save-excursion
  6770. (org-previous-visible-heading 1)
  6771. (if (org-at-heading-p) (org-outline-level) 1)))
  6772. (next-level
  6773. (save-excursion
  6774. (if (org-at-heading-p) (org-outline-level)
  6775. (org-next-visible-heading 1)
  6776. (if (org-at-heading-p) (org-outline-level) 1))))
  6777. (new-level (or force-level (max previous-level next-level)))
  6778. (shift (if (or (= old-level -1)
  6779. (= new-level -1)
  6780. (= old-level new-level))
  6781. 0
  6782. (- new-level old-level)))
  6783. (delta (if (> shift 0) -1 1))
  6784. (func (if (> shift 0) #'org-demote #'org-promote))
  6785. (org-odd-levels-only nil)
  6786. beg end newend)
  6787. ;; Remove the forced level indicator.
  6788. (when (and force-level (not level))
  6789. (delete-region (line-beginning-position) (point)))
  6790. ;; Paste before the next visible heading or at end of buffer,
  6791. ;; unless point is at the beginning of a headline.
  6792. (unless (and (bolp) (org-at-heading-p))
  6793. (org-next-visible-heading 1)
  6794. (unless (bolp) (insert "\n")))
  6795. (setq beg (point))
  6796. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6797. (insert-before-markers txt)
  6798. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6799. (setq newend (point))
  6800. (org-reinstall-markers-in-region beg)
  6801. (setq end (point))
  6802. (goto-char beg)
  6803. (skip-chars-forward " \t\n\r")
  6804. (setq beg (point))
  6805. (when (and (org-invisible-p) visp)
  6806. (save-excursion (outline-show-heading)))
  6807. ;; Shift if necessary.
  6808. (unless (= shift 0)
  6809. (save-restriction
  6810. (narrow-to-region beg end)
  6811. (while (not (= shift 0))
  6812. (org-map-region func (point-min) (point-max))
  6813. (setq shift (+ delta shift)))
  6814. (goto-char (point-min))
  6815. (setq newend (point-max))))
  6816. (when (or for-yank (called-interactively-p 'interactive))
  6817. (message "Clipboard pasted as level %d subtree" new-level))
  6818. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6819. kill-ring
  6820. (equal org-subtree-clip (current-kill 0))
  6821. org-subtree-clip-folded)
  6822. ;; The tree was folded before it was killed/copied
  6823. (org-flag-subtree t))
  6824. (when for-yank (goto-char newend))
  6825. (when remove (pop kill-ring)))))
  6826. (defun org-kill-is-subtree-p (&optional txt)
  6827. "Check if the current kill is an outline subtree, or a set of trees.
  6828. Returns nil if kill does not start with a headline, or if the first
  6829. headline level is not the largest headline level in the tree.
  6830. So this will actually accept several entries of equal levels as well,
  6831. which is OK for `org-paste-subtree'.
  6832. If optional TXT is given, check this string instead of the current kill."
  6833. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6834. (re (org-get-limited-outline-regexp))
  6835. (^re (concat "^" re))
  6836. (start-level (and kill
  6837. (string-match
  6838. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6839. kill)
  6840. (- (match-end 2) (match-beginning 2) 1)))
  6841. (start (1+ (or (match-beginning 2) -1))))
  6842. (if (not start-level)
  6843. (progn
  6844. nil) ;; does not even start with a heading
  6845. (catch 'exit
  6846. (while (setq start (string-match ^re kill (1+ start)))
  6847. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6848. (throw 'exit nil)))
  6849. t))))
  6850. (defvar org-markers-to-move nil
  6851. "Markers that should be moved with a cut-and-paste operation.
  6852. Those markers are stored together with their positions relative to
  6853. the start of the region.")
  6854. (defun org-save-markers-in-region (beg end)
  6855. "Check markers in region.
  6856. If these markers are between BEG and END, record their position relative
  6857. to BEG, so that after moving the block of text, we can put the markers back
  6858. into place.
  6859. This function gets called just before an entry or tree gets cut from the
  6860. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6861. called immediately, to move the markers with the entries."
  6862. (setq org-markers-to-move nil)
  6863. (when (featurep 'org-clock)
  6864. (org-clock-save-markers-for-cut-and-paste beg end))
  6865. (when (featurep 'org-agenda)
  6866. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6867. (defun org-check-and-save-marker (marker beg end)
  6868. "Check if MARKER is between BEG and END.
  6869. If yes, remember the marker and the distance to BEG."
  6870. (when (and (marker-buffer marker)
  6871. (equal (marker-buffer marker) (current-buffer))
  6872. (>= marker beg) (< marker end))
  6873. (push (cons marker (- marker beg)) org-markers-to-move)))
  6874. (defun org-reinstall-markers-in-region (beg)
  6875. "Move all remembered markers to their position relative to BEG."
  6876. (dolist (x org-markers-to-move)
  6877. (move-marker (car x) (+ beg (cdr x))))
  6878. (setq org-markers-to-move nil))
  6879. (defun org-narrow-to-subtree ()
  6880. "Narrow buffer to the current subtree."
  6881. (interactive)
  6882. (save-excursion
  6883. (save-match-data
  6884. (org-with-limited-levels
  6885. (narrow-to-region
  6886. (progn (org-back-to-heading t) (point))
  6887. (progn (org-end-of-subtree t t)
  6888. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6889. (point)))))))
  6890. (defun org-toggle-narrow-to-subtree ()
  6891. "Narrow to the subtree at point or widen a narrowed buffer."
  6892. (interactive)
  6893. (if (buffer-narrowed-p)
  6894. (progn (widen) (message "Buffer widen"))
  6895. (org-narrow-to-subtree)
  6896. (message "Buffer narrowed to current subtree")))
  6897. (defun org-narrow-to-block ()
  6898. "Narrow buffer to the current block."
  6899. (interactive)
  6900. (let* ((case-fold-search t)
  6901. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6902. "^[ \t]*#\\+end_.*")))
  6903. (if blockp
  6904. (narrow-to-region (car blockp) (cdr blockp))
  6905. (user-error "Not in a block"))))
  6906. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6907. "Clone the task (subtree) at point N times.
  6908. The clones will be inserted as siblings.
  6909. In interactive use, the user will be prompted for the number of
  6910. clones to be produced. If the entry has a timestamp, the user
  6911. will also be prompted for a time shift, which may be a repeater
  6912. as used in time stamps, for example `+3d'. To disable this,
  6913. you can call the function with a universal prefix argument.
  6914. When a valid repeater is given and the entry contains any time
  6915. stamps, the clones will become a sequence in time, with time
  6916. stamps in the subtree shifted for each clone produced. If SHIFT
  6917. is nil or the empty string, time stamps will be left alone. The
  6918. ID property of the original subtree is removed.
  6919. In each clone, all the CLOCK entries will be removed. This
  6920. prevents Org from considering that the clocked times overlap.
  6921. If the original subtree did contain time stamps with a repeater,
  6922. the following will happen:
  6923. - the repeater will be removed in each clone
  6924. - an additional clone will be produced, with the current, unshifted
  6925. date(s) in the entry.
  6926. - the original entry will be placed *after* all the clones, with
  6927. repeater intact.
  6928. - the start days in the repeater in the original entry will be shifted
  6929. to past the last clone.
  6930. In this way you can spell out a number of instances of a repeating task,
  6931. and still retain the repeater to cover future instances of the task.
  6932. As described above, N+1 clones are produced when the original
  6933. subtree has a repeater. Setting N to 0, then, can be used to
  6934. remove the repeater from a subtree and create a shifted clone
  6935. with the original repeater."
  6936. (interactive "nNumber of clones to produce: ")
  6937. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6938. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6939. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6940. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6941. (shift
  6942. (or shift
  6943. (if (and (not (equal current-prefix-arg '(4)))
  6944. (save-excursion
  6945. (goto-char beg)
  6946. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6947. (read-from-minibuffer
  6948. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6949. ""))) ;No time shift
  6950. (doshift
  6951. (and (org-string-nw-p shift)
  6952. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6953. shift)
  6954. (user-error "Invalid shift specification %s" shift)))))
  6955. (goto-char end-of-tree)
  6956. (unless (bolp) (insert "\n"))
  6957. (let* ((end (point))
  6958. (template (buffer-substring beg end))
  6959. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6960. (shift-what (pcase (and doshift (match-string 2 shift))
  6961. (`nil nil)
  6962. ("d" 'day)
  6963. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6964. ("m" 'month)
  6965. ("y" 'year)
  6966. (_ (error "Unsupported time unit"))))
  6967. (nmin 1)
  6968. (nmax n)
  6969. (n-no-remove -1)
  6970. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6971. (idprop (org-entry-get beg "ID")))
  6972. (when (and doshift
  6973. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6974. template))
  6975. (delete-region beg end)
  6976. (setq end beg)
  6977. (setq nmin 0)
  6978. (setq nmax (1+ nmax))
  6979. (setq n-no-remove nmax))
  6980. (goto-char end)
  6981. (cl-loop for n from nmin to nmax do
  6982. (insert
  6983. ;; Prepare clone.
  6984. (with-temp-buffer
  6985. (insert template)
  6986. (org-mode)
  6987. (goto-char (point-min))
  6988. (org-show-subtree)
  6989. (and idprop (if org-clone-delete-id
  6990. (org-entry-delete nil "ID")
  6991. (org-id-get-create t)))
  6992. (unless (= n 0)
  6993. (while (re-search-forward org-clock-line-re nil t)
  6994. (delete-region (line-beginning-position)
  6995. (line-beginning-position 2)))
  6996. (goto-char (point-min))
  6997. (while (re-search-forward org-drawer-regexp nil t)
  6998. (org-remove-empty-drawer-at (point))))
  6999. (goto-char (point-min))
  7000. (when doshift
  7001. (while (re-search-forward org-ts-regexp-both nil t)
  7002. (org-timestamp-change (* n shift-n) shift-what))
  7003. (unless (= n n-no-remove)
  7004. (goto-char (point-min))
  7005. (while (re-search-forward org-ts-regexp nil t)
  7006. (save-excursion
  7007. (goto-char (match-beginning 0))
  7008. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7009. (delete-region (match-beginning 1) (match-end 1)))))))
  7010. (buffer-string)))))
  7011. (goto-char beg)))
  7012. ;;; Outline path
  7013. (defvar org-outline-path-cache nil
  7014. "Alist between buffer positions and outline paths.
  7015. It value is an alist (POSITION . PATH) where POSITION is the
  7016. buffer position at the beginning of an entry and PATH is a list
  7017. of strings describing the outline path for that entry, in reverse
  7018. order.")
  7019. (defun org--get-outline-path-1 (&optional use-cache)
  7020. "Return outline path to current headline.
  7021. Outline path is a list of strings, in reverse order. When
  7022. optional argument USE-CACHE is non-nil, make use of a cache. See
  7023. `org-get-outline-path' for details.
  7024. Assume buffer is widened and point is on a headline."
  7025. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7026. (let ((p (point))
  7027. (heading (let ((case-fold-search nil))
  7028. (looking-at org-complex-heading-regexp)
  7029. (if (not (match-end 4)) ""
  7030. ;; Remove statistics cookies.
  7031. (org-trim
  7032. (org-link-display-format
  7033. (replace-regexp-in-string
  7034. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7035. (match-string-no-properties 4))))))))
  7036. (if (org-up-heading-safe)
  7037. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7038. (when use-cache
  7039. (push (cons p path) org-outline-path-cache))
  7040. path)
  7041. ;; This is a new root node. Since we assume we are moving
  7042. ;; forward, we can drop previous cache so as to limit number
  7043. ;; of associations there.
  7044. (let ((path (list heading)))
  7045. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7046. path)))))
  7047. (defun org-get-outline-path (&optional with-self use-cache)
  7048. "Return the outline path to the current entry.
  7049. An outline path is a list of ancestors for current headline, as
  7050. a list of strings. Statistics cookies are removed and links are
  7051. replaced with their description, if any, or their path otherwise.
  7052. When optional argument WITH-SELF is non-nil, the path also
  7053. includes the current headline.
  7054. When optional argument USE-CACHE is non-nil, cache outline paths
  7055. between calls to this function so as to avoid backtracking. This
  7056. argument is useful when planning to find more than one outline
  7057. path in the same document. In that case, there are two
  7058. conditions to satisfy:
  7059. - `org-outline-path-cache' is set to nil before starting the
  7060. process;
  7061. - outline paths are computed by increasing buffer positions."
  7062. (org-with-wide-buffer
  7063. (and (or (and with-self (org-back-to-heading t))
  7064. (org-up-heading-safe))
  7065. (reverse (org--get-outline-path-1 use-cache)))))
  7066. (defun org-format-outline-path (path &optional width prefix separator)
  7067. "Format the outline path PATH for display.
  7068. WIDTH is the maximum number of characters that is available.
  7069. PREFIX is a prefix to be included in the returned string,
  7070. such as the file name.
  7071. SEPARATOR is inserted between the different parts of the path,
  7072. the default is \"/\"."
  7073. (setq width (or width 79))
  7074. (setq path (delq nil path))
  7075. (unless (> width 0)
  7076. (user-error "Argument `width' must be positive"))
  7077. (setq separator (or separator "/"))
  7078. (let* ((org-odd-levels-only nil)
  7079. (fpath (concat
  7080. prefix (and prefix path separator)
  7081. (mapconcat
  7082. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7083. (cl-loop for head in path
  7084. for n from 0
  7085. collect (org-add-props
  7086. head nil 'face
  7087. (nth (% n org-n-level-faces) org-level-faces)))
  7088. separator))))
  7089. (when (> (length fpath) width)
  7090. (if (< width 7)
  7091. ;; It's unlikely that `width' will be this small, but don't
  7092. ;; waste characters by adding ".." if it is.
  7093. (setq fpath (substring fpath 0 width))
  7094. (setf (substring fpath (- width 2)) "..")))
  7095. fpath))
  7096. (defun org-display-outline-path (&optional file current separator just-return-string)
  7097. "Display the current outline path in the echo area.
  7098. If FILE is non-nil, prepend the output with the file name.
  7099. If CURRENT is non-nil, append the current heading to the output.
  7100. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7101. the different parts of the path and defaults to \"/\".
  7102. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7103. (interactive "P")
  7104. (let* (case-fold-search
  7105. (bfn (buffer-file-name (buffer-base-buffer)))
  7106. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7107. res)
  7108. (when current (setq path (append path
  7109. (save-excursion
  7110. (org-back-to-heading t)
  7111. (when (looking-at org-complex-heading-regexp)
  7112. (list (match-string 4)))))))
  7113. (setq res
  7114. (org-format-outline-path
  7115. path
  7116. (1- (frame-width))
  7117. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7118. separator))
  7119. (if just-return-string
  7120. (org-no-properties res)
  7121. (org-unlogged-message "%s" res))))
  7122. ;;; Outline Sorting
  7123. (defun org-sort (&optional with-case)
  7124. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7125. Optional argument WITH-CASE means sort case-sensitively."
  7126. (interactive "P")
  7127. (org-call-with-arg
  7128. (cond ((org-at-table-p) #'org-table-sort-lines)
  7129. ((org-at-item-p) #'org-sort-list)
  7130. (t #'org-sort-entries))
  7131. with-case))
  7132. (defun org-sort-remove-invisible (s)
  7133. "Remove invisible part of links and emphasis markers from string S."
  7134. (remove-text-properties 0 (length s) org-rm-props s)
  7135. (replace-regexp-in-string
  7136. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7137. (replace-regexp-in-string
  7138. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7139. (org-link-display-format s)
  7140. t t) t t))
  7141. (defvar org-after-sorting-entries-or-items-hook nil
  7142. "Hook that is run after a bunch of entries or items have been sorted.
  7143. When children are sorted, the cursor is in the parent line when this
  7144. hook gets called. When a region or a plain list is sorted, the cursor
  7145. will be in the first entry of the sorted region/list.")
  7146. (defun org-sort-entries
  7147. (&optional with-case sorting-type getkey-func compare-func property
  7148. interactive?)
  7149. "Sort entries on a certain level of an outline tree.
  7150. If there is an active region, the entries in the region are sorted.
  7151. Else, if the cursor is before the first entry, sort the top-level items.
  7152. Else, the children of the entry at point are sorted.
  7153. Sorting can be alphabetically, numerically, by date/time as given by
  7154. a time stamp, by a property, by priority order, or by a custom function.
  7155. The command prompts for the sorting type unless it has been given to the
  7156. function through the SORTING-TYPE argument, which needs to be a character,
  7157. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7158. the precise meaning of each character:
  7159. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7160. c By creation time, which is assumed to be the first inactive time stamp
  7161. at the beginning of a line.
  7162. d By deadline date/time.
  7163. k By clocking time.
  7164. n Numerically, by converting the beginning of the entry/item to a number.
  7165. o By order of TODO keywords.
  7166. p By priority according to the cookie.
  7167. r By the value of a property.
  7168. s By scheduled date/time.
  7169. t By date/time, either the first active time stamp in the entry, or, if
  7170. none exist, by the first inactive one.
  7171. Capital letters will reverse the sort order.
  7172. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7173. called with point at the beginning of the record. It must return a
  7174. value that is compatible with COMPARE-FUNC, the function used to
  7175. compare entries.
  7176. Comparing entries ignores case by default. However, with an optional argument
  7177. WITH-CASE, the sorting considers case as well.
  7178. Sorting is done against the visible part of the headlines, it ignores hidden
  7179. links.
  7180. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7181. A non-nil value for INTERACTIVE? is used to signal that this
  7182. function is being called interactively."
  7183. (interactive (list current-prefix-arg nil nil nil nil t))
  7184. (let ((case-func (if with-case 'identity 'downcase))
  7185. start beg end stars re re2
  7186. txt what tmp)
  7187. ;; Find beginning and end of region to sort
  7188. (cond
  7189. ((org-region-active-p)
  7190. ;; we will sort the region
  7191. (setq end (region-end)
  7192. what "region")
  7193. (goto-char (region-beginning))
  7194. (unless (org-at-heading-p) (outline-next-heading))
  7195. (setq start (point)))
  7196. ((or (org-at-heading-p)
  7197. (ignore-errors (progn (org-back-to-heading) t)))
  7198. ;; we will sort the children of the current headline
  7199. (org-back-to-heading)
  7200. (setq start (point)
  7201. end (progn (org-end-of-subtree t t)
  7202. (or (bolp) (insert "\n"))
  7203. (when (>= (org-back-over-empty-lines) 1)
  7204. (forward-line 1))
  7205. (point))
  7206. what "children")
  7207. (goto-char start)
  7208. (outline-show-subtree)
  7209. (outline-next-heading))
  7210. (t
  7211. ;; we will sort the top-level entries in this file
  7212. (goto-char (point-min))
  7213. (or (org-at-heading-p) (outline-next-heading))
  7214. (setq start (point))
  7215. (goto-char (point-max))
  7216. (beginning-of-line 1)
  7217. (when (looking-at ".*?\\S-")
  7218. ;; File ends in a non-white line
  7219. (end-of-line 1)
  7220. (insert "\n"))
  7221. (setq end (point-max))
  7222. (setq what "top-level")
  7223. (goto-char start)
  7224. (org-show-all '(headings blocks))))
  7225. (setq beg (point))
  7226. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7227. (looking-at "\\(\\*+\\)")
  7228. (setq stars (match-string 1)
  7229. re (concat "^" (regexp-quote stars) " +")
  7230. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7231. txt (buffer-substring beg end))
  7232. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7233. (when (and (not (equal stars "*")) (string-match re2 txt))
  7234. (user-error "Region to sort contains a level above the first entry"))
  7235. (unless sorting-type
  7236. (message
  7237. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7238. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7239. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7240. what)
  7241. (setq sorting-type (read-char-exclusive)))
  7242. (unless getkey-func
  7243. (and (= (downcase sorting-type) ?f)
  7244. (setq getkey-func
  7245. (or (and interactive?
  7246. (org-read-function
  7247. "Function for extracting keys: "))
  7248. (error "Missing key extractor")))))
  7249. (and (= (downcase sorting-type) ?r)
  7250. (not property)
  7251. (setq property
  7252. (completing-read "Property: "
  7253. (mapcar #'list (org-buffer-property-keys t))
  7254. nil t)))
  7255. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7256. (message "Sorting entries...")
  7257. (save-restriction
  7258. (narrow-to-region start end)
  7259. (let ((restore-clock?
  7260. ;; The clock marker is lost when using `sort-subr'; mark
  7261. ;; the clock with temporary `:org-clock-marker-backup'
  7262. ;; text property.
  7263. (when (and (eq (org-clock-is-active) (current-buffer))
  7264. (<= start (marker-position org-clock-marker))
  7265. (>= end (marker-position org-clock-marker)))
  7266. (with-silent-modifications
  7267. (put-text-property (1- org-clock-marker) org-clock-marker
  7268. :org-clock-marker-backup t))
  7269. t))
  7270. (dcst (downcase sorting-type))
  7271. (case-fold-search nil)
  7272. (now (current-time)))
  7273. (org-preserve-local-variables
  7274. (sort-subr
  7275. (/= dcst sorting-type)
  7276. ;; This function moves to the beginning character of the
  7277. ;; "record" to be sorted.
  7278. (lambda nil
  7279. (if (re-search-forward re nil t)
  7280. (goto-char (match-beginning 0))
  7281. (goto-char (point-max))))
  7282. ;; This function moves to the last character of the "record" being
  7283. ;; sorted.
  7284. (lambda nil
  7285. (save-match-data
  7286. (condition-case nil
  7287. (outline-forward-same-level 1)
  7288. (error
  7289. (goto-char (point-max))))))
  7290. ;; This function returns the value that gets sorted against.
  7291. (lambda ()
  7292. (cond
  7293. ((= dcst ?n)
  7294. (string-to-number
  7295. (org-sort-remove-invisible (org-get-heading t t t t))))
  7296. ((= dcst ?a)
  7297. (funcall case-func
  7298. (org-sort-remove-invisible (org-get-heading t t t t))))
  7299. ((= dcst ?k)
  7300. (or (get-text-property (point) :org-clock-minutes) 0))
  7301. ((= dcst ?t)
  7302. (let ((end (save-excursion (outline-next-heading) (point))))
  7303. (if (or (re-search-forward org-ts-regexp end t)
  7304. (re-search-forward org-ts-regexp-both end t))
  7305. (org-time-string-to-seconds (match-string 0))
  7306. (float-time now))))
  7307. ((= dcst ?c)
  7308. (let ((end (save-excursion (outline-next-heading) (point))))
  7309. (if (re-search-forward
  7310. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7311. end t)
  7312. (org-time-string-to-seconds (match-string 0))
  7313. (float-time now))))
  7314. ((= dcst ?s)
  7315. (let ((end (save-excursion (outline-next-heading) (point))))
  7316. (if (re-search-forward org-scheduled-time-regexp end t)
  7317. (org-time-string-to-seconds (match-string 1))
  7318. (float-time now))))
  7319. ((= dcst ?d)
  7320. (let ((end (save-excursion (outline-next-heading) (point))))
  7321. (if (re-search-forward org-deadline-time-regexp end t)
  7322. (org-time-string-to-seconds (match-string 1))
  7323. (float-time now))))
  7324. ((= dcst ?p)
  7325. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7326. (string-to-char (match-string 2))
  7327. org-priority-default))
  7328. ((= dcst ?r)
  7329. (or (org-entry-get nil property) ""))
  7330. ((= dcst ?o)
  7331. (when (looking-at org-complex-heading-regexp)
  7332. (let* ((m (match-string 2))
  7333. (s (if (member m org-done-keywords) '- '+)))
  7334. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7335. ((= dcst ?f)
  7336. (if getkey-func
  7337. (progn
  7338. (setq tmp (funcall getkey-func))
  7339. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7340. tmp)
  7341. (error "Invalid key function `%s'" getkey-func)))
  7342. (t (error "Invalid sorting type `%c'" sorting-type))))
  7343. nil
  7344. (cond
  7345. ((= dcst ?a) 'org-string-collate-lessp)
  7346. ((= dcst ?f)
  7347. (or compare-func
  7348. (and interactive?
  7349. (org-read-function
  7350. (concat "Function for comparing keys "
  7351. "(empty for default `sort-subr' predicate): ")
  7352. 'allow-empty))))
  7353. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7354. (org-cycle-hide-drawers 'all)
  7355. (when restore-clock?
  7356. (move-marker org-clock-marker
  7357. (1+ (next-single-property-change
  7358. start :org-clock-marker-backup)))
  7359. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7360. '(:org-clock-marker-backup t)))))
  7361. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7362. (message "Sorting entries...done")))
  7363. (defun org-contextualize-keys (alist contexts)
  7364. "Return valid elements in ALIST depending on CONTEXTS.
  7365. `org-agenda-custom-commands' or `org-capture-templates' are the
  7366. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7367. or `org-capture-templates-contexts' are the associated contexts
  7368. definitions."
  7369. (let ((contexts
  7370. ;; normalize contexts
  7371. (mapcar
  7372. (lambda(c) (cond ((listp (cadr c))
  7373. (list (car c) (car c) (nth 1 c)))
  7374. ((string= "" (cadr c))
  7375. (list (car c) (car c) (nth 2 c)))
  7376. (t c)))
  7377. contexts))
  7378. (a alist) r s)
  7379. ;; loop over all commands or templates
  7380. (dolist (c a)
  7381. (let (vrules repl)
  7382. (cond
  7383. ((not (assoc (car c) contexts))
  7384. (push c r))
  7385. ((and (assoc (car c) contexts)
  7386. (setq vrules (org-contextualize-validate-key
  7387. (car c) contexts)))
  7388. (mapc (lambda (vr)
  7389. (unless (equal (car vr) (cadr vr))
  7390. (setq repl vr)))
  7391. vrules)
  7392. (if (not repl) (push c r)
  7393. (push (cadr repl) s)
  7394. (push
  7395. (cons (car c)
  7396. (cdr (or (assoc (cadr repl) alist)
  7397. (error "Undefined key `%s' as contextual replacement for `%s'"
  7398. (cadr repl) (car c)))))
  7399. r))))))
  7400. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7401. (delq
  7402. nil
  7403. (delete-dups
  7404. (mapcar (lambda (x)
  7405. (let ((tpl (car x)))
  7406. (unless (delq
  7407. nil
  7408. (mapcar (lambda (y)
  7409. (equal y tpl))
  7410. s))
  7411. x)))
  7412. (reverse r))))))
  7413. (defun org-contextualize-validate-key (key contexts)
  7414. "Check CONTEXTS for agenda or capture KEY."
  7415. (let (res)
  7416. (dolist (r contexts)
  7417. (dolist (rr (car (last r)))
  7418. (when
  7419. (and (equal key (car r))
  7420. (if (functionp rr) (funcall rr)
  7421. (or (and (eq (car rr) 'in-file)
  7422. (buffer-file-name)
  7423. (string-match (cdr rr) (buffer-file-name)))
  7424. (and (eq (car rr) 'in-mode)
  7425. (string-match (cdr rr) (symbol-name major-mode)))
  7426. (and (eq (car rr) 'in-buffer)
  7427. (string-match (cdr rr) (buffer-name)))
  7428. (when (and (eq (car rr) 'not-in-file)
  7429. (buffer-file-name))
  7430. (not (string-match (cdr rr) (buffer-file-name))))
  7431. (when (eq (car rr) 'not-in-mode)
  7432. (not (string-match (cdr rr) (symbol-name major-mode))))
  7433. (when (eq (car rr) 'not-in-buffer)
  7434. (not (string-match (cdr rr) (buffer-name)))))))
  7435. (push r res))))
  7436. (delete-dups (delq nil res))))
  7437. ;; Defined to provide a value for defcustom, since there is no
  7438. ;; string-collate-greaterp in Emacs.
  7439. (defun org-string-collate-greaterp (s1 s2)
  7440. "Return non-nil if S1 is greater than S2 in collation order."
  7441. (not (org-string-collate-lessp s1 s2)))
  7442. ;;;###autoload
  7443. (defun org-run-like-in-org-mode (cmd)
  7444. "Run a command, pretending that the current buffer is in Org mode.
  7445. This will temporarily bind local variables that are typically bound in
  7446. Org mode to the values they have in Org mode, and then interactively
  7447. call CMD."
  7448. (org-load-modules-maybe)
  7449. (let (binds)
  7450. (dolist (var (org-get-local-variables))
  7451. (when (or (not (boundp (car var)))
  7452. (eq (symbol-value (car var))
  7453. (default-value (car var))))
  7454. (push (list (car var) `(quote ,(cadr var))) binds)))
  7455. (eval `(let ,binds
  7456. (call-interactively (quote ,cmd))))))
  7457. (defun org-get-category (&optional pos force-refresh)
  7458. "Get the category applying to position POS."
  7459. (save-match-data
  7460. (when force-refresh (org-refresh-category-properties))
  7461. (let ((pos (or pos (point))))
  7462. (or (get-text-property pos 'org-category)
  7463. (progn (org-refresh-category-properties)
  7464. (get-text-property pos 'org-category))))))
  7465. ;;; Refresh properties
  7466. (defun org-refresh-properties (dprop tprop)
  7467. "Refresh buffer text properties.
  7468. DPROP is the drawer property and TPROP is either the
  7469. corresponding text property to set, or an alist with each element
  7470. being a text property (as a symbol) and a function to apply to
  7471. the value of the drawer property."
  7472. (let* ((case-fold-search t)
  7473. (inhibit-read-only t)
  7474. (inherit? (org-property-inherit-p dprop))
  7475. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7476. (global-or-keyword (and inherit?
  7477. (org--property-global-or-keyword-value dprop nil))))
  7478. (with-silent-modifications
  7479. (org-with-point-at 1
  7480. ;; Set global and keyword based values to the whole buffer.
  7481. (when global-or-keyword
  7482. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7483. ;; Set values based on property-drawers throughout the document.
  7484. (while (re-search-forward property-re nil t)
  7485. (when (org-at-property-p)
  7486. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7487. (outline-next-heading))))))
  7488. (defun org-refresh-property (tprop p &optional inherit)
  7489. "Refresh the buffer text property TPROP from the drawer property P.
  7490. The refresh happens only for the current entry, or the whole
  7491. sub-tree if optional argument INHERIT is non-nil.
  7492. If point is before first headline, the function applies to the
  7493. part before the first headline. In that particular case, when
  7494. optional argument INHERIT is non-nil, it refreshes properties for
  7495. the whole buffer."
  7496. (save-excursion
  7497. (org-back-to-heading-or-point-min t)
  7498. (let ((start (point))
  7499. (end (save-excursion
  7500. (cond ((and inherit (org-before-first-heading-p))
  7501. (point-max))
  7502. (inherit
  7503. (org-end-of-subtree t t))
  7504. ((outline-next-heading))
  7505. ((point-max))))))
  7506. (if (symbolp tprop)
  7507. ;; TPROP is a text property symbol.
  7508. (put-text-property start end tprop p)
  7509. ;; TPROP is an alist with (property . function) elements.
  7510. (pcase-dolist (`(,prop . ,f) tprop)
  7511. (put-text-property start end prop (funcall f p)))))))
  7512. (defun org-refresh-category-properties ()
  7513. "Refresh category text properties in the buffer."
  7514. (let ((case-fold-search t)
  7515. (inhibit-read-only t)
  7516. (default-category
  7517. (cond ((null org-category)
  7518. (if buffer-file-name
  7519. (file-name-sans-extension
  7520. (file-name-nondirectory buffer-file-name))
  7521. "???"))
  7522. ((symbolp org-category) (symbol-name org-category))
  7523. (t org-category))))
  7524. (with-silent-modifications
  7525. (org-with-wide-buffer
  7526. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7527. ;; keyword. If none is found, fall-back to `org-category' or
  7528. ;; buffer file name, or set it by the document property drawer.
  7529. (put-text-property
  7530. (point-min) (point-max)
  7531. 'org-category
  7532. (catch 'buffer-category
  7533. (goto-char (point-max))
  7534. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7535. (let ((element (org-element-at-point)))
  7536. (when (eq (org-element-type element) 'keyword)
  7537. (throw 'buffer-category
  7538. (org-element-property :value element)))))
  7539. default-category))
  7540. ;; Set categories from the document property drawer or
  7541. ;; property drawers in the outline. If category is found in
  7542. ;; the property drawer for the whole buffer that value
  7543. ;; overrides the keyword-based value set above.
  7544. (goto-char (point-min))
  7545. (let ((regexp (org-re-property "CATEGORY")))
  7546. (while (re-search-forward regexp nil t)
  7547. (let ((value (match-string-no-properties 3)))
  7548. (when (org-at-property-p)
  7549. (put-text-property
  7550. (save-excursion (org-back-to-heading-or-point-min t))
  7551. (save-excursion (if (org-before-first-heading-p)
  7552. (point-max)
  7553. (org-end-of-subtree t t)))
  7554. 'org-category
  7555. value)))))))))
  7556. (defun org-refresh-stats-properties ()
  7557. "Refresh stats text properties in the buffer."
  7558. (with-silent-modifications
  7559. (org-with-point-at 1
  7560. (let ((regexp (concat org-outline-regexp-bol
  7561. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7562. (while (re-search-forward regexp nil t)
  7563. (let* ((numerator (string-to-number (match-string 1)))
  7564. (denominator (and (match-end 2)
  7565. (string-to-number (match-string 2))))
  7566. (stats (cond ((not denominator) numerator) ;percent
  7567. ((= denominator 0) 0)
  7568. (t (/ (* numerator 100) denominator)))))
  7569. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7570. 'org-stats stats)))))))
  7571. (defun org-refresh-effort-properties ()
  7572. "Refresh effort properties."
  7573. (org-refresh-properties
  7574. org-effort-property
  7575. '((effort . identity)
  7576. (effort-minutes . org-duration-to-minutes))))
  7577. (defun org-find-file-at-mouse (ev)
  7578. "Open file link or URL at mouse."
  7579. (interactive "e")
  7580. (mouse-set-point ev)
  7581. (org-open-at-point 'in-emacs))
  7582. (defun org-open-at-mouse (ev)
  7583. "Open file link or URL at mouse.
  7584. See the docstring of `org-open-file' for details."
  7585. (interactive "e")
  7586. (mouse-set-point ev)
  7587. (when (eq major-mode 'org-agenda-mode)
  7588. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7589. (org-open-at-point))
  7590. (defvar org-window-config-before-follow-link nil
  7591. "The window configuration before following a link.
  7592. This is saved in case the need arises to restore it.")
  7593. (defun org--file-default-apps ()
  7594. "Return the default applications for this operating system."
  7595. (pcase system-type
  7596. (`darwin org-file-apps-macos)
  7597. (`windows-nt org-file-apps-windowsnt)
  7598. (_ org-file-apps-gnu)))
  7599. (defun org--file-apps-entry-dlink-p (entry)
  7600. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7601. It assumes that is the case when the entry uses a regular
  7602. expression which has at least one grouping construct and the
  7603. action is either a Lisp form or a command string containing
  7604. \"%1\", i.e., using at least one subexpression match as
  7605. a parameter."
  7606. (pcase entry
  7607. (`(,selector . ,action)
  7608. (and (stringp selector)
  7609. (> (regexp-opt-depth selector) 0)
  7610. (or (and (stringp action)
  7611. (string-match "%[0-9]" action))
  7612. (consp action))))
  7613. (_ nil)))
  7614. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7615. "Convert extensions to regular expressions in the cars of LIST.
  7616. Also, weed out any non-string entries, because the return value
  7617. is used only for regexp matching.
  7618. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7619. point to the symbol `emacs', indicating that the file should be
  7620. opened in Emacs."
  7621. (append
  7622. (delq nil
  7623. (mapcar (lambda (x)
  7624. (unless (not (stringp (car x)))
  7625. (if (string-match "\\W" (car x))
  7626. x
  7627. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7628. list))
  7629. (when add-auto-mode
  7630. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7631. ;;;###autoload
  7632. (defun org-open-file (path &optional in-emacs line search)
  7633. "Open the file at PATH.
  7634. First, this expands any special file name abbreviations. Then the
  7635. configuration variable `org-file-apps' is checked if it contains an
  7636. entry for this file type, and if yes, the corresponding command is launched.
  7637. If no application is found, Emacs simply visits the file.
  7638. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7639. With a double \\[universal-argument] \\[universal-argument] \
  7640. prefix arg, Org tries to avoid opening in Emacs
  7641. and to use an external application to visit the file.
  7642. Optional LINE specifies a line to go to, optional SEARCH a string
  7643. to search for. If LINE or SEARCH is given, the file will be
  7644. opened in Emacs, unless an entry from `org-file-apps' that makes
  7645. use of groups in a regexp matches.
  7646. If you want to change the way frames are used when following a
  7647. link, please customize `org-link-frame-setup'.
  7648. If the file does not exist, throw an error."
  7649. (let* ((file (if (equal path "") buffer-file-name
  7650. (substitute-in-file-name (expand-file-name path))))
  7651. (file-apps (append org-file-apps (org--file-default-apps)))
  7652. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7653. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7654. file-apps))
  7655. (remp (and (assq 'remote apps) (file-remote-p file)))
  7656. (dirp (unless remp (file-directory-p file)))
  7657. (file (if (and dirp org-open-directory-means-index-dot-org)
  7658. (concat (file-name-as-directory file) "index.org")
  7659. file))
  7660. (a-m-a-p (assq 'auto-mode apps))
  7661. (dfile (downcase file))
  7662. ;; Reconstruct the original link from the PATH, LINE and
  7663. ;; SEARCH args.
  7664. (link (cond (line (concat file "::" (number-to-string line)))
  7665. (search (concat file "::" search))
  7666. (t file)))
  7667. (dlink (downcase link))
  7668. (ext
  7669. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7670. (match-string 1 dfile)))
  7671. (save-position-maybe
  7672. (let ((old-buffer (current-buffer))
  7673. (old-pos (point))
  7674. (old-mode major-mode))
  7675. (lambda ()
  7676. (and (derived-mode-p 'org-mode)
  7677. (eq old-mode 'org-mode)
  7678. (or (not (eq old-buffer (current-buffer)))
  7679. (not (eq old-pos (point))))
  7680. (org-mark-ring-push old-pos old-buffer)))))
  7681. cmd link-match-data)
  7682. (cond
  7683. ((member in-emacs '((16) system))
  7684. (setq cmd (cdr (assq 'system apps))))
  7685. (in-emacs (setq cmd 'emacs))
  7686. (t
  7687. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7688. (and dirp (cdr (assq 'directory apps)))
  7689. ;; First, try matching against apps-dlink if we
  7690. ;; get a match here, store the match data for
  7691. ;; later.
  7692. (let ((match (assoc-default dlink apps-dlink
  7693. 'string-match)))
  7694. (if match
  7695. (progn (setq link-match-data (match-data))
  7696. match)
  7697. (progn (setq in-emacs (or in-emacs line search))
  7698. nil))) ; if we have no match in apps-dlink,
  7699. ; always open the file in emacs if line or search
  7700. ; is given (for backwards compatibility)
  7701. (assoc-default dfile
  7702. (org--file-apps-regexp-alist apps a-m-a-p)
  7703. 'string-match)
  7704. (cdr (assoc ext apps))
  7705. (cdr (assq t apps))))))
  7706. (when (eq cmd 'system)
  7707. (setq cmd (cdr (assq 'system apps))))
  7708. (when (eq cmd 'default)
  7709. (setq cmd (cdr (assoc t apps))))
  7710. (when (eq cmd 'mailcap)
  7711. (require 'mailcap)
  7712. (mailcap-parse-mailcaps)
  7713. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7714. (command (mailcap-mime-info mime-type)))
  7715. (if (stringp command)
  7716. (setq cmd command)
  7717. (setq cmd 'emacs))))
  7718. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7719. (not (file-exists-p file))
  7720. (not org-open-non-existing-files))
  7721. (user-error "No such file: %s" file))
  7722. (cond
  7723. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7724. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7725. (while (string-match "['\"]%s['\"]" cmd)
  7726. (setq cmd (replace-match "%s" t t cmd)))
  7727. (setq cmd (replace-regexp-in-string
  7728. "%s"
  7729. (shell-quote-argument (convert-standard-filename file))
  7730. cmd
  7731. nil t))
  7732. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7733. (save-match-data
  7734. (let ((match-index 1)
  7735. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7736. (set-match-data link-match-data)
  7737. (while (<= match-index number-of-groups)
  7738. (let ((regex (concat "%" (number-to-string match-index)))
  7739. (replace-with (match-string match-index dlink)))
  7740. (while (string-match regex cmd)
  7741. (setq cmd (replace-match replace-with t t cmd))))
  7742. (setq match-index (+ match-index 1)))))
  7743. (save-window-excursion
  7744. (message "Running %s...done" cmd)
  7745. (start-process-shell-command cmd nil cmd)
  7746. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7747. ((or (stringp cmd)
  7748. (eq cmd 'emacs))
  7749. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7750. (widen)
  7751. (cond (line (org-goto-line line)
  7752. (when (derived-mode-p 'org-mode) (org-reveal)))
  7753. (search (condition-case err
  7754. (org-link-search search)
  7755. ;; Save position before error-ing out so user
  7756. ;; can easily move back to the original buffer.
  7757. (error (funcall save-position-maybe)
  7758. (error (nth 1 err)))))))
  7759. ((functionp cmd)
  7760. (save-match-data
  7761. (set-match-data link-match-data)
  7762. (condition-case nil
  7763. (funcall cmd file link)
  7764. ;; FIXME: Remove this check when most default installations
  7765. ;; of Emacs have at least Org 9.0.
  7766. ((debug wrong-number-of-arguments wrong-type-argument
  7767. invalid-function)
  7768. (user-error "Please see Org News for version 9.0 about \
  7769. `org-file-apps'--Lisp error: %S" cmd)))))
  7770. ((consp cmd)
  7771. ;; FIXME: Remove this check when most default installations of
  7772. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7773. ;; fall back to `org-link-frame-setup' for an old usage of
  7774. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7775. (user-error "Please see Org News for version 9.0 about \
  7776. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7777. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7778. (funcall save-position-maybe)))
  7779. ;;;###autoload
  7780. (defun org-open-at-point-global ()
  7781. "Follow a link or a time-stamp like Org mode does.
  7782. Also follow links and emails as seen by `thing-at-point'.
  7783. This command can be called in any mode to follow an external
  7784. link or a time-stamp that has Org mode syntax. Its behavior
  7785. is undefined when called on internal links like fuzzy links.
  7786. Raise a user error when there is nothing to follow."
  7787. (interactive)
  7788. (let ((tap-url (thing-at-point 'url))
  7789. (tap-email (thing-at-point 'email)))
  7790. (cond ((org-in-regexp org-link-any-re)
  7791. (org-link-open-from-string (match-string-no-properties 0)))
  7792. ((or (org-in-regexp org-ts-regexp-both nil t)
  7793. (org-in-regexp org-tsr-regexp-both nil t))
  7794. (org-follow-timestamp-link))
  7795. (tap-url (org-link-open-from-string tap-url))
  7796. (tap-email (org-link-open-from-string
  7797. (concat "mailto:" tap-email)))
  7798. (t (user-error "No link found")))))
  7799. (defvar org-open-at-point-functions nil
  7800. "Hook that is run when following a link at point.
  7801. Functions in this hook must return t if they identify and follow
  7802. a link at point. If they don't find anything interesting at point,
  7803. they must return nil.")
  7804. (defun org-open-at-point (&optional arg)
  7805. "Open link, timestamp, footnote or tags at point.
  7806. When point is on a link, follow it. Normally, files will be
  7807. opened by an appropriate application. If the optional prefix
  7808. argument ARG is non-nil, Emacs will visit the file. With
  7809. a double prefix argument, try to open outside of Emacs, in the
  7810. application the system uses for this file type.
  7811. When point is on a timestamp, open the agenda at the day
  7812. specified.
  7813. When point is a footnote definition, move to the first reference
  7814. found. If it is on a reference, move to the associated
  7815. definition.
  7816. When point is on a headline, display a list of every link in the
  7817. entry, so it is possible to pick one, or all, of them. If point
  7818. is on a tag, call `org-tags-view' instead.
  7819. On top of syntactically correct links, this function also tries
  7820. to open links and time-stamps in comments, node properties, and
  7821. keywords if point is on something looking like a timestamp or
  7822. a link."
  7823. (interactive "P")
  7824. (org-load-modules-maybe)
  7825. (setq org-window-config-before-follow-link (current-window-configuration))
  7826. (org-remove-occur-highlights nil nil t)
  7827. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7828. (let* ((context
  7829. ;; Only consider supported types, even if they are not the
  7830. ;; closest one.
  7831. (org-element-lineage
  7832. (org-element-context)
  7833. '(clock comment comment-block footnote-definition
  7834. footnote-reference headline inline-src-block inlinetask
  7835. keyword link node-property planning src-block timestamp)
  7836. t))
  7837. (type (org-element-type context))
  7838. (value (org-element-property :value context)))
  7839. (cond
  7840. ((not type) (user-error "No link found"))
  7841. ;; No valid link at point. For convenience, look if something
  7842. ;; looks like a link under point in some specific places.
  7843. ((memq type '(comment comment-block node-property keyword))
  7844. (call-interactively #'org-open-at-point-global))
  7845. ;; On a headline or an inlinetask, but not on a timestamp,
  7846. ;; a link, a footnote reference.
  7847. ((memq type '(headline inlinetask))
  7848. (org-match-line org-complex-heading-regexp)
  7849. (let ((tags-beg (match-beginning 5))
  7850. (tags-end (match-end 5)))
  7851. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7852. ;; On tags.
  7853. (org-tags-view
  7854. arg
  7855. (save-excursion
  7856. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7857. (end-tag (search-forward ":" tags-end nil 2)))
  7858. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7859. ;; Not on tags.
  7860. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7861. (`(nil . ,_)
  7862. (require 'org-attach)
  7863. (when (org-attach-dir)
  7864. (message "Opening attachment")
  7865. (if (equal arg '(4))
  7866. (org-attach-reveal-in-emacs)
  7867. (org-attach-reveal))))
  7868. (`(,links . ,links-end)
  7869. (dolist (link (if (stringp links) (list links) links))
  7870. (search-forward link nil links-end)
  7871. (goto-char (match-beginning 0))
  7872. (org-open-at-point arg)))))))
  7873. ;; On a footnote reference or at definition's label.
  7874. ((or (eq type 'footnote-reference)
  7875. (and (eq type 'footnote-definition)
  7876. (save-excursion
  7877. ;; Do not validate action when point is on the
  7878. ;; spaces right after the footnote label, in order
  7879. ;; to be on par with behavior on links.
  7880. (skip-chars-forward " \t")
  7881. (let ((begin
  7882. (org-element-property :contents-begin context)))
  7883. (if begin (< (point) begin)
  7884. (= (org-element-property :post-affiliated context)
  7885. (line-beginning-position)))))))
  7886. (org-footnote-action))
  7887. ;; On a planning line. Check if we are really on a timestamp.
  7888. ((and (eq type 'planning)
  7889. (org-in-regexp org-ts-regexp-both nil t))
  7890. (org-follow-timestamp-link))
  7891. ;; On a clock line, make sure point is on the timestamp
  7892. ;; before opening it.
  7893. ((and (eq type 'clock)
  7894. value
  7895. (>= (point) (org-element-property :begin value))
  7896. (<= (point) (org-element-property :end value)))
  7897. (org-follow-timestamp-link))
  7898. ((eq type 'src-block) (org-babel-open-src-block-result))
  7899. ;; Do nothing on white spaces after an object.
  7900. ((>= (point)
  7901. (save-excursion
  7902. (goto-char (org-element-property :end context))
  7903. (skip-chars-backward " \t")
  7904. (point)))
  7905. (user-error "No link found"))
  7906. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7907. ((eq type 'timestamp) (org-follow-timestamp-link))
  7908. ((eq type 'link) (org-link-open context arg))
  7909. (t (user-error "No link found")))))
  7910. (run-hook-with-args 'org-follow-link-hook))
  7911. ;;;###autoload
  7912. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7913. "Offer links in the current entry and return the selected link.
  7914. If there is only one link, return it.
  7915. If NTH is an integer, return the NTH link found.
  7916. If ZERO is a string, check also this string for a link, and if
  7917. there is one, return it."
  7918. (with-current-buffer buffer
  7919. (org-with-wide-buffer
  7920. (goto-char marker)
  7921. (let ((cnt ?0)
  7922. have-zero end links link c)
  7923. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7924. (push (match-string 0 zero) links)
  7925. (setq cnt (1- cnt) have-zero t))
  7926. (save-excursion
  7927. (org-back-to-heading t)
  7928. (setq end (save-excursion (outline-next-heading) (point)))
  7929. (while (re-search-forward org-link-any-re end t)
  7930. (push (match-string 0) links))
  7931. (setq links (org-uniquify (reverse links))))
  7932. (cond
  7933. ((null links)
  7934. (message "No links"))
  7935. ((equal (length links) 1)
  7936. (setq link (car links)))
  7937. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7938. (setq link (nth (if have-zero nth (1- nth)) links)))
  7939. (t ; we have to select a link
  7940. (save-excursion
  7941. (save-window-excursion
  7942. (delete-other-windows)
  7943. (with-output-to-temp-buffer "*Select Link*"
  7944. (dolist (l links)
  7945. (cond
  7946. ((not (string-match org-link-bracket-re l))
  7947. (princ (format "[%c] %s\n" (cl-incf cnt)
  7948. (org-unbracket-string "<" ">" l))))
  7949. ((match-end 2)
  7950. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7951. (match-string 2 l) (match-string 1 l))))
  7952. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7953. (match-string 1 l)))))))
  7954. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7955. (message "Select link to open, RET to open all:")
  7956. (setq c (read-char-exclusive))
  7957. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7958. (when (equal c ?q) (user-error "Abort"))
  7959. (if (equal c ?\C-m)
  7960. (setq link links)
  7961. (setq nth (- c ?0))
  7962. (when have-zero (setq nth (1+ nth)))
  7963. (unless (and (integerp nth) (>= (length links) nth))
  7964. (user-error "Invalid link selection"))
  7965. (setq link (nth (1- nth) links)))))
  7966. (cons link end)))))
  7967. ;;; File search
  7968. (defun org-do-occur (regexp &optional cleanup)
  7969. "Call the Emacs command `occur'.
  7970. If CLEANUP is non-nil, remove the printout of the regular expression
  7971. in the *Occur* buffer. This is useful if the regex is long and not useful
  7972. to read."
  7973. (occur regexp)
  7974. (when cleanup
  7975. (let ((cwin (selected-window)) win beg end)
  7976. (when (setq win (get-buffer-window "*Occur*"))
  7977. (select-window win))
  7978. (goto-char (point-min))
  7979. (when (re-search-forward "match[a-z]+" nil t)
  7980. (setq beg (match-end 0))
  7981. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7982. (setq end (1- (match-beginning 0)))))
  7983. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7984. (goto-char (point-min))
  7985. (select-window cwin))))
  7986. ;;; The Mark Ring
  7987. (defvar org-mark-ring nil
  7988. "Mark ring for positions before jumps in Org mode.")
  7989. (defvar org-mark-ring-last-goto nil
  7990. "Last position in the mark ring used to go back.")
  7991. ;; Fill and close the ring
  7992. (setq org-mark-ring nil)
  7993. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7994. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7995. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7996. org-mark-ring)
  7997. (defun org-mark-ring-push (&optional pos buffer)
  7998. "Put the current position into the mark ring and rotate it.
  7999. Also push position into the Emacs mark ring. If optional
  8000. argument POS and BUFFER are not nil, mark this location instead."
  8001. (interactive)
  8002. (let ((pos (or pos (point)))
  8003. (buffer (or buffer (current-buffer))))
  8004. (with-current-buffer buffer
  8005. (org-with-point-at pos (push-mark nil t)))
  8006. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8007. (move-marker (car org-mark-ring) pos buffer))
  8008. (message
  8009. (substitute-command-keys
  8010. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8011. (defun org-mark-ring-goto (&optional n)
  8012. "Jump to the previous position in the mark ring.
  8013. With prefix arg N, jump back that many stored positions. When
  8014. called several times in succession, walk through the entire ring.
  8015. Org mode commands jumping to a different position in the current file,
  8016. or to another Org file, automatically push the old position onto the ring."
  8017. (interactive "p")
  8018. (let (p m)
  8019. (if (eq last-command this-command)
  8020. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8021. (setq p org-mark-ring))
  8022. (setq org-mark-ring-last-goto p)
  8023. (setq m (car p))
  8024. (pop-to-buffer-same-window (marker-buffer m))
  8025. (goto-char m)
  8026. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8027. ;;; Following specific links
  8028. (defvar org-agenda-buffer-tmp-name)
  8029. (defvar org-agenda-start-on-weekday)
  8030. (defun org-follow-timestamp-link ()
  8031. "Open an agenda view for the time-stamp date/range at point."
  8032. (cond
  8033. ((org-at-date-range-p t)
  8034. (let ((org-agenda-start-on-weekday)
  8035. (t1 (match-string 1))
  8036. (t2 (match-string 2)) tt1 tt2)
  8037. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8038. tt2 (time-to-days (org-time-string-to-time t2)))
  8039. (let ((org-agenda-buffer-tmp-name
  8040. (format "*Org Agenda(a:%s)"
  8041. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8042. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8043. ((org-at-timestamp-p 'lax)
  8044. (let ((org-agenda-buffer-tmp-name
  8045. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8046. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8047. (substring (match-string 1) 0 10)))
  8048. 1)))
  8049. (t (error "This should not happen"))))
  8050. ;;; Following file links
  8051. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8052. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8053. (declare-function mailcap-mime-info
  8054. "mailcap" (string &optional request no-decode))
  8055. (defvar org-wait nil)
  8056. ;;;; Refiling
  8057. (defun org-get-org-file ()
  8058. "Read a filename, with default directory `org-directory'."
  8059. (let ((default (or org-default-notes-file remember-data-file)))
  8060. (read-file-name (format "File name [%s]: " default)
  8061. (file-name-as-directory org-directory)
  8062. default)))
  8063. (defun org-notes-order-reversed-p ()
  8064. "Check if the current file should receive notes in reversed order."
  8065. (cond
  8066. ((not org-reverse-note-order) nil)
  8067. ((eq t org-reverse-note-order) t)
  8068. ((not (listp org-reverse-note-order)) nil)
  8069. (t (catch 'exit
  8070. (dolist (entry org-reverse-note-order)
  8071. (when (string-match (car entry) buffer-file-name)
  8072. (throw 'exit (cdr entry))))))))
  8073. (defvar org-agenda-new-buffers nil
  8074. "Buffers created to visit agenda files.")
  8075. (declare-function org-string-nw-p "org-macs" (s))
  8076. ;;;; Dynamic blocks
  8077. (defun org-find-dblock (name)
  8078. "Find the first dynamic block with name NAME in the buffer.
  8079. If not found, stay at current position and return nil."
  8080. (let ((case-fold-search t) pos)
  8081. (save-excursion
  8082. (goto-char (point-min))
  8083. (setq pos (and (re-search-forward
  8084. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8085. (match-beginning 0))))
  8086. (when pos (goto-char pos))
  8087. pos))
  8088. (defun org-create-dblock (plist)
  8089. "Create a dynamic block section, with parameters taken from PLIST.
  8090. PLIST must contain a :name entry which is used as the name of the block."
  8091. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8092. (end-of-line 1)
  8093. (newline))
  8094. (let ((col (current-column))
  8095. (name (plist-get plist :name)))
  8096. (insert "#+BEGIN: " name)
  8097. (while plist
  8098. (if (eq (car plist) :name)
  8099. (setq plist (cddr plist))
  8100. (insert " " (prin1-to-string (pop plist)))))
  8101. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8102. (beginning-of-line -2)))
  8103. (defun org-prepare-dblock ()
  8104. "Prepare dynamic block for refresh.
  8105. This empties the block, puts the cursor at the insert position and returns
  8106. the property list including an extra property :name with the block name."
  8107. (unless (looking-at org-dblock-start-re)
  8108. (user-error "Not at a dynamic block"))
  8109. (let* ((begdel (1+ (match-end 0)))
  8110. (name (org-no-properties (match-string 1)))
  8111. (params (append (list :name name)
  8112. (read (concat "(" (match-string 3) ")")))))
  8113. (save-excursion
  8114. (beginning-of-line 1)
  8115. (skip-chars-forward " \t")
  8116. (setq params (plist-put params :indentation-column (current-column))))
  8117. (unless (re-search-forward org-dblock-end-re nil t)
  8118. (error "Dynamic block not terminated"))
  8119. (setq params
  8120. (append params
  8121. (list :content (buffer-substring
  8122. begdel (match-beginning 0)))))
  8123. (delete-region begdel (match-beginning 0))
  8124. (goto-char begdel)
  8125. (open-line 1)
  8126. params))
  8127. (defun org-map-dblocks (&optional command)
  8128. "Apply COMMAND to all dynamic blocks in the current buffer.
  8129. If COMMAND is not given, use `org-update-dblock'."
  8130. (let ((cmd (or command 'org-update-dblock)))
  8131. (save-excursion
  8132. (goto-char (point-min))
  8133. (while (re-search-forward org-dblock-start-re nil t)
  8134. (goto-char (match-beginning 0))
  8135. (save-excursion
  8136. (condition-case nil
  8137. (funcall cmd)
  8138. (error (message "Error during update of dynamic block"))))
  8139. (unless (re-search-forward org-dblock-end-re nil t)
  8140. (error "Dynamic block not terminated"))))))
  8141. (defvar org-dynamic-block-alist nil
  8142. "Alist defining all the Org dynamic blocks.
  8143. The key is the dynamic block type name, as a string. The value
  8144. is the function used to insert the dynamic block.
  8145. Use `org-dynamic-block-define' to populate it.")
  8146. (defun org-dynamic-block-function (type)
  8147. "Return function associated to a given dynamic block type.
  8148. TYPE is the dynamic block type, as a string."
  8149. (cdr (assoc type org-dynamic-block-alist)))
  8150. (defun org-dynamic-block-types ()
  8151. "List all defined dynamic block types."
  8152. (mapcar #'car org-dynamic-block-alist))
  8153. (defun org-dynamic-block-define (type func)
  8154. "Define dynamic block TYPE with FUNC.
  8155. TYPE is a string. FUNC is the function creating the dynamic
  8156. block of such type."
  8157. (pcase (assoc type org-dynamic-block-alist)
  8158. (`nil (push (cons type func) org-dynamic-block-alist))
  8159. (def (setcdr def func))))
  8160. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8161. "Insert a dynamic block of type TYPE.
  8162. When used interactively, select the dynamic block types among
  8163. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8164. is non-nil, call the dynamic block function interactively."
  8165. (interactive (list (completing-read "Dynamic block: "
  8166. (org-dynamic-block-types))
  8167. t))
  8168. (pcase (org-dynamic-block-function type)
  8169. (`nil (error "No such dynamic block: %S" type))
  8170. ((and f (pred functionp))
  8171. (if interactive-p (call-interactively f) (funcall f)))
  8172. (_ (error "Invalid function for dynamic block %S" type))))
  8173. (defun org-dblock-update (&optional arg)
  8174. "User command for updating dynamic blocks.
  8175. Update the dynamic block at point. With prefix ARG, update all dynamic
  8176. blocks in the buffer."
  8177. (interactive "P")
  8178. (if arg
  8179. (org-update-all-dblocks)
  8180. (or (looking-at org-dblock-start-re)
  8181. (org-beginning-of-dblock))
  8182. (org-update-dblock)))
  8183. (defun org-update-dblock ()
  8184. "Update the dynamic block at point.
  8185. This means to empty the block, parse for parameters and then call
  8186. the correct writing function."
  8187. (interactive)
  8188. (save-excursion
  8189. (let* ((win (selected-window))
  8190. (pos (point))
  8191. (line (org-current-line))
  8192. (params (org-prepare-dblock))
  8193. (name (plist-get params :name))
  8194. (indent (plist-get params :indentation-column))
  8195. (cmd (intern (concat "org-dblock-write:" name))))
  8196. (message "Updating dynamic block `%s' at line %d..." name line)
  8197. (funcall cmd params)
  8198. (message "Updating dynamic block `%s' at line %d...done" name line)
  8199. (goto-char pos)
  8200. (when (and indent (> indent 0))
  8201. (setq indent (make-string indent ?\ ))
  8202. (save-excursion
  8203. (select-window win)
  8204. (org-beginning-of-dblock)
  8205. (forward-line 1)
  8206. (while (not (looking-at org-dblock-end-re))
  8207. (insert indent)
  8208. (beginning-of-line 2))
  8209. (when (looking-at org-dblock-end-re)
  8210. (and (looking-at "[ \t]+")
  8211. (replace-match ""))
  8212. (insert indent)))))))
  8213. (defun org-beginning-of-dblock ()
  8214. "Find the beginning of the dynamic block at point.
  8215. Error if there is no such block at point."
  8216. (let ((pos (point))
  8217. beg)
  8218. (end-of-line 1)
  8219. (if (and (re-search-backward org-dblock-start-re nil t)
  8220. (setq beg (match-beginning 0))
  8221. (re-search-forward org-dblock-end-re nil t)
  8222. (> (match-end 0) pos))
  8223. (goto-char beg)
  8224. (goto-char pos)
  8225. (error "Not in a dynamic block"))))
  8226. (defun org-update-all-dblocks ()
  8227. "Update all dynamic blocks in the buffer.
  8228. This function can be used in a hook."
  8229. (interactive)
  8230. (when (derived-mode-p 'org-mode)
  8231. (org-map-dblocks 'org-update-dblock)))
  8232. ;;;; Completion
  8233. (declare-function org-export-backend-options "ox" (cl-x) t)
  8234. (defun org-get-export-keywords ()
  8235. "Return a list of all currently understood export keywords.
  8236. Export keywords include options, block names, attributes and
  8237. keywords relative to each registered export back-end."
  8238. (let (keywords)
  8239. (dolist (backend
  8240. (bound-and-true-p org-export-registered-backends)
  8241. (delq nil keywords))
  8242. ;; Back-end name (for keywords, like #+LATEX:)
  8243. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8244. (dolist (option-entry (org-export-backend-options backend))
  8245. ;; Back-end options.
  8246. (push (nth 1 option-entry) keywords)))))
  8247. (defconst org-options-keywords
  8248. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8249. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8250. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8251. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8252. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8253. (defcustom org-structure-template-alist
  8254. '(("a" . "export ascii")
  8255. ("c" . "center")
  8256. ("C" . "comment")
  8257. ("e" . "example")
  8258. ("E" . "export")
  8259. ("h" . "export html")
  8260. ("l" . "export latex")
  8261. ("q" . "quote")
  8262. ("s" . "src")
  8263. ("v" . "verse"))
  8264. "An alist of keys and block types.
  8265. `org-insert-structure-template' will display a menu with this
  8266. list of templates to choose from. The block type is inserted,
  8267. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8268. The menu keys are defined by the car of each entry in this alist.
  8269. If two entries have the keys \"a\" and \"aa\" respectively, the
  8270. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8271. latter will be inserted by typing \"aa\". If an entry with the
  8272. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8273. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8274. block can be inserted by pressing TAB after the string \"<KEY\"."
  8275. :group 'org-edit-structure
  8276. :type '(repeat
  8277. (cons (string :tag "Key")
  8278. (string :tag "Template")))
  8279. :package-version '(Org . "9.2"))
  8280. (defun org--check-org-structure-template-alist (&optional checklist)
  8281. "Check whether `org-structure-template-alist' is set up correctly.
  8282. In particular, check if the Org 9.2 format is used as opposed to
  8283. previous format.
  8284. "
  8285. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8286. (or (eval checklist)
  8287. org-structure-template-alist))))
  8288. (when elm
  8289. (org-display-warning
  8290. (format "
  8291. Please update the entries of `%s'.
  8292. In Org 9.2 the format was changed from something like
  8293. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8294. to something like
  8295. (\"s\" . \"src\")
  8296. Please refer to the documentation of `org-structure-template-alist'.
  8297. The following entries must be updated:
  8298. %s"
  8299. (or checklist 'org-structure-template-alist)
  8300. (pp-to-string elm))))))
  8301. (defun org--insert-structure-template-mks ()
  8302. "Present `org-structure-template-alist' with `org-mks'.
  8303. Menus are added if keys require more than one keystroke. Tabs
  8304. are added to single key entries when more than one stroke is
  8305. needed. Keys longer than two characters are reduced to two
  8306. characters."
  8307. (org--check-org-structure-template-alist)
  8308. (let* (case-fold-search
  8309. (templates (append org-structure-template-alist
  8310. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8311. (keys (mapcar #'car templates))
  8312. (start-letters
  8313. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8314. ;; Sort each element of `org-structure-template-alist' into
  8315. ;; sublists according to the first letter.
  8316. (superlist
  8317. (mapcar (lambda (letter)
  8318. (list letter
  8319. (cl-remove-if-not
  8320. (apply-partially #'string-match-p (concat "^" letter))
  8321. templates :key #'car)))
  8322. start-letters)))
  8323. (org-mks
  8324. (apply #'append
  8325. ;; Make an `org-mks' table. If only one element is
  8326. ;; present in a sublist, make it part of the top-menu,
  8327. ;; otherwise make a submenu according to the starting
  8328. ;; letter and populate it.
  8329. (mapcar (lambda (sublist)
  8330. (if (eq 1 (length (cadr sublist)))
  8331. (mapcar (lambda (elm)
  8332. (list (substring (car elm) 0 1)
  8333. (cdr elm) ""))
  8334. (cadr sublist))
  8335. ;; Create submenu.
  8336. (let* ((topkey (car sublist))
  8337. (elms (cadr sublist))
  8338. (keys (mapcar #'car elms))
  8339. (long (> (length elms) 3)))
  8340. (append
  8341. (list
  8342. ;; Make a description of the submenu.
  8343. (list topkey
  8344. (concat
  8345. (mapconcat #'cdr
  8346. (cl-subseq elms 0 (if long 3 (length elms)))
  8347. ", ")
  8348. (when long ", ..."))))
  8349. ;; List of entries in submenu.
  8350. (cl-mapcar #'list
  8351. (org--insert-structure-template-unique-keys keys)
  8352. (mapcar #'cdr elms)
  8353. (make-list (length elms) ""))))))
  8354. superlist))
  8355. "Select a key\n============"
  8356. "Key: ")))
  8357. (defun org--insert-structure-template-unique-keys (keys)
  8358. "Make a list of unique, two characters long elements from KEYS.
  8359. Elements of length one have a tab appended. Elements of length
  8360. two are kept as is. Longer elements are truncated to length two.
  8361. If an element cannot be made unique, an error is raised."
  8362. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8363. menu-keys)
  8364. (dolist (key ordered-keys)
  8365. (let ((potential-key
  8366. (cl-case (length key)
  8367. (1 (concat key "\t"))
  8368. (2 key)
  8369. (otherwise
  8370. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8371. (mapcar (apply-partially #'concat (substring key 0 1))
  8372. (split-string (substring key 1) "" t)))))))
  8373. (if (or (not potential-key) (assoc potential-key menu-keys))
  8374. (user-error "Could not make unique key for %s." key)
  8375. (push (cons potential-key key) menu-keys))))
  8376. (mapcar #'car
  8377. (cl-sort menu-keys #'<
  8378. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8379. (defun org-insert-structure-template (type)
  8380. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8381. Select a block from `org-structure-template-alist' then type
  8382. either RET, TAB or SPC to write the block type. With an active
  8383. region, wrap the region in the block. Otherwise, insert an empty
  8384. block."
  8385. (interactive
  8386. (list (pcase (org--insert-structure-template-mks)
  8387. (`("\t" . ,_) (read-string "Structure type: "))
  8388. (`(,_ ,choice . ,_) choice))))
  8389. (let* ((region? (use-region-p))
  8390. (region-start (and region? (region-beginning)))
  8391. (region-end (and region? (copy-marker (region-end))))
  8392. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8393. (verbatim? (string-match-p
  8394. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8395. type)))
  8396. (when region? (goto-char region-start))
  8397. (let ((column (current-indentation)))
  8398. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8399. (beginning-of-line)
  8400. (insert "\n"))
  8401. (save-excursion
  8402. (indent-to column)
  8403. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8404. (when region?
  8405. (when verbatim? (org-escape-code-in-region (point) region-end))
  8406. (goto-char region-end)
  8407. ;; Ignore empty lines at the end of the region.
  8408. (skip-chars-backward " \r\t\n")
  8409. (end-of-line))
  8410. (unless (bolp) (insert "\n"))
  8411. (indent-to column)
  8412. (insert (format "#+end_%s" (car (split-string type))))
  8413. (if (looking-at "[ \t]*$") (replace-match "")
  8414. (insert "\n"))
  8415. (when (and (eobp) (not (bolp))) (insert "\n")))
  8416. (if extended? (end-of-line)
  8417. (forward-line)
  8418. (skip-chars-forward " \t")))))
  8419. ;;;; TODO, DEADLINE, Comments
  8420. (defun org-toggle-comment ()
  8421. "Change the COMMENT state of an entry."
  8422. (interactive)
  8423. (save-excursion
  8424. (org-back-to-heading)
  8425. (let ((case-fold-search nil))
  8426. (looking-at org-complex-heading-regexp))
  8427. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8428. (skip-chars-forward " \t")
  8429. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8430. (if (org-in-commented-heading-p t)
  8431. (delete-region (point)
  8432. (progn (search-forward " " (line-end-position) 'move)
  8433. (skip-chars-forward " \t")
  8434. (point)))
  8435. (insert org-comment-string)
  8436. (unless (eolp) (insert " ")))))
  8437. (defvar org-last-todo-state-is-todo nil
  8438. "This is non-nil when the last TODO state change led to a TODO state.
  8439. If the last change removed the TODO tag or switched to DONE, then
  8440. this is nil.")
  8441. (defvar org-todo-setup-filter-hook nil
  8442. "Hook for functions that pre-filter todo specs.
  8443. Each function takes a todo spec and returns either nil or the spec
  8444. transformed into canonical form." )
  8445. (defvar org-todo-get-default-hook nil
  8446. "Hook for functions that get a default item for todo.
  8447. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8448. nil or a string to be used for the todo mark." )
  8449. (defvar org-agenda-headline-snapshot-before-repeat)
  8450. (defun org-current-effective-time ()
  8451. "Return current time adjusted for `org-extend-today-until' variable."
  8452. (let* ((ct (org-current-time))
  8453. (dct (decode-time ct))
  8454. (ct1
  8455. (cond
  8456. (org-use-last-clock-out-time-as-effective-time
  8457. (or (org-clock-get-last-clock-out-time) ct))
  8458. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8459. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8460. (t ct))))
  8461. ct1))
  8462. (defun org-todo-yesterday (&optional arg)
  8463. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8464. (interactive "P")
  8465. (if (eq major-mode 'org-agenda-mode)
  8466. (apply 'org-agenda-todo-yesterday arg)
  8467. (let* ((org-use-effective-time t)
  8468. (hour (nth 2 (decode-time (org-current-time))))
  8469. (org-extend-today-until (1+ hour)))
  8470. (org-todo arg))))
  8471. (defvar org-block-entry-blocking ""
  8472. "First entry preventing the TODO state change.")
  8473. (defun org-cancel-repeater ()
  8474. "Cancel a repeater by setting its numeric value to zero."
  8475. (interactive)
  8476. (save-excursion
  8477. (org-back-to-heading t)
  8478. (let ((bound1 (point))
  8479. (bound0 (save-excursion (outline-next-heading) (point))))
  8480. (when (and (re-search-forward
  8481. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8482. org-deadline-time-regexp "\\)\\|\\("
  8483. org-ts-regexp "\\)")
  8484. bound0 t)
  8485. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8486. bound1 t))
  8487. (replace-match "0" t nil nil 1)))))
  8488. (defvar org-state)
  8489. (defvar org-blocked-by-checkboxes)
  8490. (defun org-todo (&optional arg)
  8491. "Change the TODO state of an item.
  8492. The state of an item is given by a keyword at the start of the heading,
  8493. like
  8494. *** TODO Write paper
  8495. *** DONE Call mom
  8496. The different keywords are specified in the variable `org-todo-keywords'.
  8497. By default the available states are \"TODO\" and \"DONE\". So, for this
  8498. example: when the item starts with TODO, it is changed to DONE.
  8499. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8500. DONE are present, add TODO at the beginning of the heading.
  8501. You can set up single-character keys to fast-select the new state. See the
  8502. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8503. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8504. and take a
  8505. logging note.
  8506. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8507. next set of TODO \
  8508. keywords (nextset).
  8509. Another way to achieve this is `S-C-<right>'.
  8510. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8511. prefix, circumvent any state blocking.
  8512. With numeric prefix arg, switch to the Nth state.
  8513. With a numeric prefix arg of 0, inhibit note taking for the change.
  8514. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8515. When called through ELisp, arg is also interpreted in the following way:
  8516. `none' -> empty state
  8517. \"\" -> switch to empty state
  8518. `done' -> switch to DONE
  8519. `nextset' -> switch to the next set of keywords
  8520. `previousset' -> switch to the previous set of keywords
  8521. \"WAITING\" -> switch to the specified keyword, but only if it
  8522. really is a member of `org-todo-keywords'."
  8523. (interactive "P")
  8524. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8525. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8526. 'region-start-level 'region))
  8527. org-loop-over-headlines-in-active-region)
  8528. (org-map-entries
  8529. `(org-todo ,arg)
  8530. org-loop-over-headlines-in-active-region
  8531. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8532. (when (equal arg '(16)) (setq arg 'nextset))
  8533. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8534. (let ((org-blocker-hook org-blocker-hook)
  8535. commentp
  8536. case-fold-search)
  8537. (when (equal arg '(64))
  8538. (setq arg nil org-blocker-hook nil))
  8539. (when (and org-blocker-hook
  8540. (or org-inhibit-blocking
  8541. (org-entry-get nil "NOBLOCKING")))
  8542. (setq org-blocker-hook nil))
  8543. (save-excursion
  8544. (catch 'exit
  8545. (org-back-to-heading t)
  8546. (when (org-in-commented-heading-p t)
  8547. (org-toggle-comment)
  8548. (setq commentp t))
  8549. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8550. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8551. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8552. (let* ((match-data (match-data))
  8553. (startpos (copy-marker (line-beginning-position)))
  8554. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8555. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8556. (org-log-done org-log-done)
  8557. (org-log-repeat org-log-repeat)
  8558. (org-todo-log-states org-todo-log-states)
  8559. (org-inhibit-logging
  8560. (if (equal arg 0)
  8561. (progn (setq arg nil) 'note) org-inhibit-logging))
  8562. (this (match-string 1))
  8563. (hl-pos (match-beginning 0))
  8564. (head (org-get-todo-sequence-head this))
  8565. (ass (assoc head org-todo-kwd-alist))
  8566. (interpret (nth 1 ass))
  8567. (done-word (nth 3 ass))
  8568. (final-done-word (nth 4 ass))
  8569. (org-last-state (or this ""))
  8570. (completion-ignore-case t)
  8571. (member (member this org-todo-keywords-1))
  8572. (tail (cdr member))
  8573. (org-state (cond
  8574. ((eq arg 'right)
  8575. ;; Next state
  8576. (if this
  8577. (if tail (car tail) nil)
  8578. (car org-todo-keywords-1)))
  8579. ((eq arg 'left)
  8580. ;; Previous state
  8581. (unless (equal member org-todo-keywords-1)
  8582. (if this
  8583. (nth (- (length org-todo-keywords-1)
  8584. (length tail) 2)
  8585. org-todo-keywords-1)
  8586. (org-last org-todo-keywords-1))))
  8587. (arg
  8588. ;; User or caller requests a specific state.
  8589. (cond
  8590. ((equal arg "") nil)
  8591. ((eq arg 'none) nil)
  8592. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8593. ((eq arg 'nextset)
  8594. (or (car (cdr (member head org-todo-heads)))
  8595. (car org-todo-heads)))
  8596. ((eq arg 'previousset)
  8597. (let ((org-todo-heads (reverse org-todo-heads)))
  8598. (or (car (cdr (member head org-todo-heads)))
  8599. (car org-todo-heads))))
  8600. ((car (member arg org-todo-keywords-1)))
  8601. ((stringp arg)
  8602. (user-error "State `%s' not valid in this file" arg))
  8603. ((nth (1- (prefix-numeric-value arg))
  8604. org-todo-keywords-1))))
  8605. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8606. ;; Use fast selection.
  8607. (org-fast-todo-selection this))
  8608. ((null member) (or head (car org-todo-keywords-1)))
  8609. ((equal this final-done-word) nil) ;-> make empty
  8610. ((null tail) nil) ;-> first entry
  8611. ((memq interpret '(type priority))
  8612. (if (eq this-command last-command)
  8613. (car tail)
  8614. (if (> (length tail) 0)
  8615. (or done-word (car org-done-keywords))
  8616. nil)))
  8617. (t
  8618. (car tail))))
  8619. (org-state (or
  8620. (run-hook-with-args-until-success
  8621. 'org-todo-get-default-hook org-state org-last-state)
  8622. org-state))
  8623. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8624. (change-plist (list :type 'todo-state-change :from this :to org-state
  8625. :position startpos))
  8626. dolog now-done-p)
  8627. (when org-blocker-hook
  8628. (let (org-blocked-by-checkboxes block-reason)
  8629. (setq org-last-todo-state-is-todo
  8630. (not (member this org-done-keywords)))
  8631. (unless (save-excursion
  8632. (save-match-data
  8633. (org-with-wide-buffer
  8634. (run-hook-with-args-until-failure
  8635. 'org-blocker-hook change-plist))))
  8636. (setq block-reason (if org-blocked-by-checkboxes
  8637. "contained checkboxes"
  8638. (format "\"%s\"" org-block-entry-blocking)))
  8639. (if (called-interactively-p 'interactive)
  8640. (user-error "TODO state change from %s to %s blocked (by %s)"
  8641. this org-state block-reason)
  8642. ;; Fail silently.
  8643. (message "TODO state change from %s to %s blocked (by %s)"
  8644. this org-state block-reason)
  8645. (throw 'exit nil)))))
  8646. (store-match-data match-data)
  8647. (replace-match next t t)
  8648. (cond ((and org-state (equal this org-state))
  8649. (message "TODO state was already %s" (org-trim next)))
  8650. ((not (pos-visible-in-window-p hl-pos))
  8651. (message "TODO state changed to %s" (org-trim next))))
  8652. (unless head
  8653. (setq head (org-get-todo-sequence-head org-state)
  8654. ass (assoc head org-todo-kwd-alist)
  8655. interpret (nth 1 ass)
  8656. done-word (nth 3 ass)
  8657. final-done-word (nth 4 ass)))
  8658. (when (memq arg '(nextset previousset))
  8659. (message "Keyword-Set %d/%d: %s"
  8660. (- (length org-todo-sets) -1
  8661. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8662. (length org-todo-sets)
  8663. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8664. (setq org-last-todo-state-is-todo
  8665. (not (member org-state org-done-keywords)))
  8666. (setq now-done-p (and (member org-state org-done-keywords)
  8667. (not (member this org-done-keywords))))
  8668. (and logging (org-local-logging logging))
  8669. (when (or (and (or org-todo-log-states org-log-done)
  8670. (not (eq org-inhibit-logging t))
  8671. (not (memq arg '(nextset previousset))))
  8672. force-log)
  8673. ;; We need to look at recording a time and note.
  8674. (setq dolog (or (if force-log 'note)
  8675. (nth 1 (assoc org-state org-todo-log-states))
  8676. (nth 2 (assoc this org-todo-log-states))))
  8677. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8678. (setq dolog 'time))
  8679. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8680. (and org-state
  8681. (member org-state org-not-done-keywords)
  8682. (not (member this org-not-done-keywords))))
  8683. ;; This is now a todo state and was not one before
  8684. ;; If there was a CLOSED time stamp, get rid of it.
  8685. (org-add-planning-info nil nil 'closed))
  8686. (when (and now-done-p org-log-done)
  8687. ;; It is now done, and it was not done before.
  8688. (org-add-planning-info 'closed (org-current-effective-time))
  8689. (when (and (not dolog) (eq 'note org-log-done))
  8690. (org-add-log-setup 'done org-state this 'note)))
  8691. (when (and org-state dolog)
  8692. ;; This is a non-nil state, and we need to log it.
  8693. (org-add-log-setup 'state org-state this dolog)))
  8694. ;; Fixup tag positioning.
  8695. (org-todo-trigger-tag-changes org-state)
  8696. (when org-auto-align-tags (org-align-tags))
  8697. (when org-provide-todo-statistics
  8698. (org-update-parent-todo-statistics))
  8699. (when (bound-and-true-p org-clock-out-when-done)
  8700. (org-clock-out-if-current))
  8701. (run-hooks 'org-after-todo-state-change-hook)
  8702. (when (and arg (not (member org-state org-done-keywords)))
  8703. (setq head (org-get-todo-sequence-head org-state)))
  8704. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8705. ;; Do we need to trigger a repeat?
  8706. (when now-done-p
  8707. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8708. ;; This is for the agenda, take a snapshot of the headline.
  8709. (save-match-data
  8710. (setq org-agenda-headline-snapshot-before-repeat
  8711. (org-get-heading))))
  8712. (org-auto-repeat-maybe org-state))
  8713. ;; Fixup cursor location if close to the keyword.
  8714. (when (and (outline-on-heading-p)
  8715. (not (bolp))
  8716. (save-excursion (beginning-of-line 1)
  8717. (looking-at org-todo-line-regexp))
  8718. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8719. (goto-char (or (match-end 2) (match-end 1)))
  8720. (and (looking-at " ")
  8721. (not (looking-at " *:"))
  8722. (just-one-space)))
  8723. (when org-trigger-hook
  8724. (save-excursion
  8725. (run-hook-with-args 'org-trigger-hook change-plist)))
  8726. (when commentp (org-toggle-comment))))))))
  8727. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8728. "Block turning an entry into a TODO, using the hierarchy.
  8729. This checks whether the current task should be blocked from state
  8730. changes. Such blocking occurs when:
  8731. 1. The task has children which are not all in a completed state.
  8732. 2. A task has a parent with the property :ORDERED:, and there
  8733. are siblings prior to the current task with incomplete
  8734. status.
  8735. 3. The parent of the task is blocked because it has siblings that should
  8736. be done first, or is child of a block grandparent TODO entry."
  8737. (if (not org-enforce-todo-dependencies)
  8738. t ; if locally turned off don't block
  8739. (catch 'dont-block
  8740. ;; If this is not a todo state change, or if this entry is already DONE,
  8741. ;; do not block
  8742. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8743. (member (plist-get change-plist :from)
  8744. (cons 'done org-done-keywords))
  8745. (member (plist-get change-plist :to)
  8746. (cons 'todo org-not-done-keywords))
  8747. (not (plist-get change-plist :to)))
  8748. (throw 'dont-block t))
  8749. ;; If this task has children, and any are undone, it's blocked
  8750. (save-excursion
  8751. (org-back-to-heading t)
  8752. (let ((this-level (funcall outline-level)))
  8753. (outline-next-heading)
  8754. (let ((child-level (funcall outline-level)))
  8755. (while (and (not (eobp))
  8756. (> child-level this-level))
  8757. ;; this todo has children, check whether they are all
  8758. ;; completed
  8759. (when (and (not (org-entry-is-done-p))
  8760. (org-entry-is-todo-p))
  8761. (setq org-block-entry-blocking (org-get-heading))
  8762. (throw 'dont-block nil))
  8763. (outline-next-heading)
  8764. (setq child-level (funcall outline-level))))))
  8765. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8766. ;; any previous siblings are undone, it's blocked
  8767. (save-excursion
  8768. (org-back-to-heading t)
  8769. (let* ((pos (point))
  8770. (parent-pos (and (org-up-heading-safe) (point)))
  8771. (case-fold-search nil))
  8772. (unless parent-pos (throw 'dont-block t)) ; no parent
  8773. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8774. (forward-line 1)
  8775. (re-search-forward org-not-done-heading-regexp pos t))
  8776. (setq org-block-entry-blocking (match-string 0))
  8777. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8778. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8779. (while t
  8780. (goto-char parent-pos)
  8781. (unless (looking-at org-not-done-heading-regexp)
  8782. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8783. (setq pos (point))
  8784. (setq parent-pos (and (org-up-heading-safe) (point)))
  8785. (unless parent-pos (throw 'dont-block t)) ; no parent
  8786. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8787. (forward-line 1)
  8788. (re-search-forward org-not-done-heading-regexp pos t)
  8789. (setq org-block-entry-blocking (org-get-heading)))
  8790. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8791. (defcustom org-track-ordered-property-with-tag nil
  8792. "Should the ORDERED property also be shown as a tag?
  8793. The ORDERED property decides if an entry should require subtasks to be
  8794. completed in sequence. Since a property is not very visible, setting
  8795. this option means that toggling the ORDERED property with the command
  8796. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8797. not relevant for the behavior, but it makes things more visible.
  8798. Note that toggling the tag with tags commands will not change the property
  8799. and therefore not influence behavior!
  8800. This can be t, meaning the tag ORDERED should be used. It can also be a
  8801. string to select a different tag for this task."
  8802. :group 'org-todo
  8803. :type '(choice
  8804. (const :tag "No tracking" nil)
  8805. (const :tag "Track with ORDERED tag" t)
  8806. (string :tag "Use other tag")))
  8807. (defun org-toggle-ordered-property ()
  8808. "Toggle the ORDERED property of the current entry.
  8809. For better visibility, you can track the value of this property with a tag.
  8810. See variable `org-track-ordered-property-with-tag'."
  8811. (interactive)
  8812. (let* ((t1 org-track-ordered-property-with-tag)
  8813. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8814. (save-excursion
  8815. (org-back-to-heading)
  8816. (if (org-entry-get nil "ORDERED")
  8817. (progn
  8818. (org-delete-property "ORDERED")
  8819. (and tag (org-toggle-tag tag 'off))
  8820. (message "Subtasks can be completed in arbitrary order"))
  8821. (org-entry-put nil "ORDERED" "t")
  8822. (and tag (org-toggle-tag tag 'on))
  8823. (message "Subtasks must be completed in sequence")))))
  8824. (defun org-block-todo-from-checkboxes (change-plist)
  8825. "Block turning an entry into a TODO, using checkboxes.
  8826. This checks whether the current task should be blocked from state
  8827. changes because there are unchecked boxes in this entry."
  8828. (if (not org-enforce-todo-checkbox-dependencies)
  8829. t ; if locally turned off don't block
  8830. (catch 'dont-block
  8831. ;; If this is not a todo state change, or if this entry is already DONE,
  8832. ;; do not block
  8833. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8834. (member (plist-get change-plist :from)
  8835. (cons 'done org-done-keywords))
  8836. (member (plist-get change-plist :to)
  8837. (cons 'todo org-not-done-keywords))
  8838. (not (plist-get change-plist :to)))
  8839. (throw 'dont-block t))
  8840. ;; If this task has checkboxes that are not checked, it's blocked
  8841. (save-excursion
  8842. (org-back-to-heading t)
  8843. (let ((beg (point)) end)
  8844. (outline-next-heading)
  8845. (setq end (point))
  8846. (goto-char beg)
  8847. (when (org-list-search-forward
  8848. (concat (org-item-beginning-re)
  8849. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8850. "\\[[- ]\\]")
  8851. end t)
  8852. (when (boundp 'org-blocked-by-checkboxes)
  8853. (setq org-blocked-by-checkboxes t))
  8854. (throw 'dont-block nil))))
  8855. t))) ; do not block
  8856. (defun org-entry-blocked-p ()
  8857. "Non-nil if entry at point is blocked."
  8858. (and (not (org-entry-get nil "NOBLOCKING"))
  8859. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8860. (not (run-hook-with-args-until-failure
  8861. 'org-blocker-hook
  8862. (list :type 'todo-state-change
  8863. :position (point)
  8864. :from 'todo
  8865. :to 'done)))))
  8866. (defun org-update-statistics-cookies (all)
  8867. "Update the statistics cookie, either from TODO or from checkboxes.
  8868. This should be called with the cursor in a line with a statistics
  8869. cookie. When called with a \\[universal-argument] prefix, update
  8870. all statistics cookies in the buffer."
  8871. (interactive "P")
  8872. (if all
  8873. (progn
  8874. (org-update-checkbox-count 'all)
  8875. (org-map-entries 'org-update-parent-todo-statistics))
  8876. (if (not (org-at-heading-p))
  8877. (org-update-checkbox-count)
  8878. (let ((pos (point-marker))
  8879. end l1 l2)
  8880. (ignore-errors (org-back-to-heading t))
  8881. (if (not (org-at-heading-p))
  8882. (org-update-checkbox-count)
  8883. (setq l1 (org-outline-level))
  8884. (setq end (save-excursion
  8885. (outline-next-heading)
  8886. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8887. (point)))
  8888. (if (and (save-excursion
  8889. (re-search-forward
  8890. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8891. (not (save-excursion (re-search-forward
  8892. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8893. (org-update-checkbox-count)
  8894. (if (and l2 (> l2 l1))
  8895. (progn
  8896. (goto-char end)
  8897. (org-update-parent-todo-statistics))
  8898. (goto-char pos)
  8899. (beginning-of-line 1)
  8900. (while (re-search-forward
  8901. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8902. (point-at-eol) t)
  8903. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8904. (goto-char pos)
  8905. (move-marker pos nil)))))
  8906. (defvar org-entry-property-inherited-from) ;; defined below
  8907. (defun org-update-parent-todo-statistics ()
  8908. "Update any statistics cookie in the parent of the current headline.
  8909. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8910. the entire subtree and this will travel up the hierarchy and update
  8911. statistics everywhere."
  8912. (let* ((prop (save-excursion (org-up-heading-safe)
  8913. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8914. (recursive (or (not org-hierarchical-todo-statistics)
  8915. (and prop (string-match "\\<recursive\\>" prop))))
  8916. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8917. 0))
  8918. (first t)
  8919. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8920. level ltoggle l1 new ndel
  8921. (cnt-all 0) (cnt-done 0) is-percent kwd
  8922. checkbox-beg cookie-present)
  8923. (catch 'exit
  8924. (save-excursion
  8925. (beginning-of-line 1)
  8926. (setq ltoggle (funcall outline-level))
  8927. ;; Three situations are to consider:
  8928. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8929. ;; to the top-level ancestor on the headline;
  8930. ;; 2. If parent has "recursive" property, repeat up to the
  8931. ;; headline setting that property, taking inheritance into
  8932. ;; account;
  8933. ;; 3. Else, move up to direct parent and proceed only once.
  8934. (while (and (setq level (org-up-heading-safe))
  8935. (or recursive first)
  8936. (>= (point) lim))
  8937. (setq first nil cookie-present nil)
  8938. (unless (and level
  8939. (not (string-match
  8940. "\\<checkbox\\>"
  8941. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8942. "")))))
  8943. (throw 'exit nil))
  8944. (while (re-search-forward box-re (point-at-eol) t)
  8945. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8946. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8947. (save-match-data
  8948. (unless (outline-next-heading) (throw 'exit nil))
  8949. (while (and (looking-at org-complex-heading-regexp)
  8950. (> (setq l1 (length (match-string 1))) level))
  8951. (setq kwd (and (or recursive (= l1 ltoggle))
  8952. (match-string 2)))
  8953. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8954. (and (eq org-provide-todo-statistics t)
  8955. (or (member kwd org-done-keywords)))
  8956. (and (listp org-provide-todo-statistics)
  8957. (stringp (car org-provide-todo-statistics))
  8958. (or (member kwd org-provide-todo-statistics)
  8959. (member kwd org-done-keywords)))
  8960. (and (listp org-provide-todo-statistics)
  8961. (listp (car org-provide-todo-statistics))
  8962. (or (member kwd (car org-provide-todo-statistics))
  8963. (and (member kwd org-done-keywords)
  8964. (member kwd (cadr org-provide-todo-statistics))))))
  8965. (setq cnt-all (1+ cnt-all))
  8966. (and (eq org-provide-todo-statistics t)
  8967. kwd
  8968. (setq cnt-all (1+ cnt-all))))
  8969. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8970. (member kwd org-done-keywords))
  8971. (and (listp org-provide-todo-statistics)
  8972. (listp (car org-provide-todo-statistics))
  8973. (member kwd org-done-keywords)
  8974. (member kwd (cadr org-provide-todo-statistics)))
  8975. (and (listp org-provide-todo-statistics)
  8976. (stringp (car org-provide-todo-statistics))
  8977. (member kwd org-done-keywords)))
  8978. (setq cnt-done (1+ cnt-done)))
  8979. (outline-next-heading)))
  8980. (setq new
  8981. (if is-percent
  8982. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8983. (max 1 cnt-all)))
  8984. (format "[%d/%d]" cnt-done cnt-all))
  8985. ndel (- (match-end 0) checkbox-beg))
  8986. (goto-char checkbox-beg)
  8987. (insert new)
  8988. (delete-region (point) (+ (point) ndel))
  8989. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8990. (when cookie-present
  8991. (run-hook-with-args 'org-after-todo-statistics-hook
  8992. cnt-done (- cnt-all cnt-done))))))
  8993. (run-hooks 'org-todo-statistics-hook)))
  8994. (defvar org-after-todo-statistics-hook nil
  8995. "Hook that is called after a TODO statistics cookie has been updated.
  8996. Each function is called with two arguments: the number of not-done entries
  8997. and the number of done entries.
  8998. For example, the following function, when added to this hook, will switch
  8999. an entry to DONE when all children are done, and back to TODO when new
  9000. entries are set to a TODO status. Note that this hook is only called
  9001. when there is a statistics cookie in the headline!
  9002. (defun org-summary-todo (n-done n-not-done)
  9003. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9004. (let (org-log-done org-log-states) ; turn off logging
  9005. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9006. ")
  9007. (defvar org-todo-statistics-hook nil
  9008. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9009. This hook runs even if there is no statistics cookie present, in which case
  9010. `org-after-todo-statistics-hook' would not run.")
  9011. (defun org-todo-trigger-tag-changes (state)
  9012. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9013. (let ((l org-todo-state-tags-triggers)
  9014. changes)
  9015. (when (or (not state) (equal state ""))
  9016. (setq changes (append changes (cdr (assoc "" l)))))
  9017. (when (and (stringp state) (> (length state) 0))
  9018. (setq changes (append changes (cdr (assoc state l)))))
  9019. (when (member state org-not-done-keywords)
  9020. (setq changes (append changes (cdr (assq 'todo l)))))
  9021. (when (member state org-done-keywords)
  9022. (setq changes (append changes (cdr (assq 'done l)))))
  9023. (dolist (c changes)
  9024. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9025. (defun org-local-logging (value)
  9026. "Get logging settings from a property VALUE."
  9027. ;; Directly set the variables, they are already local.
  9028. (setq org-log-done nil
  9029. org-log-repeat nil
  9030. org-todo-log-states nil)
  9031. (dolist (w (split-string value))
  9032. (let (a)
  9033. (cond
  9034. ((setq a (assoc w org-startup-options))
  9035. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9036. (set (nth 1 a) (nth 2 a))))
  9037. ((setq a (org-extract-log-state-settings w))
  9038. (and (member (car a) org-todo-keywords-1)
  9039. (push a org-todo-log-states)))))))
  9040. (defun org-get-todo-sequence-head (kwd)
  9041. "Return the head of the TODO sequence to which KWD belongs.
  9042. If KWD is not set, check if there is a text property remembering the
  9043. right sequence."
  9044. (let (p)
  9045. (cond
  9046. ((not kwd)
  9047. (or (get-text-property (point-at-bol) 'org-todo-head)
  9048. (progn
  9049. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9050. nil (point-at-eol)))
  9051. (get-text-property p 'org-todo-head))))
  9052. ((not (member kwd org-todo-keywords-1))
  9053. (car org-todo-keywords-1))
  9054. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9055. (defun org-fast-todo-selection (&optional current-state)
  9056. "Fast TODO keyword selection with single keys.
  9057. Returns the new TODO keyword, or nil if no state change should occur.
  9058. When CURRENT-STATE is given and selection letters are not unique globally,
  9059. prefer a state in the current sequence over on in another sequence."
  9060. (let* ((fulltable org-todo-key-alist)
  9061. (head (org-get-todo-sequence-head current-state))
  9062. (done-keywords org-done-keywords) ;; needed for the faces.
  9063. (maxlen (apply 'max (mapcar
  9064. (lambda (x)
  9065. (if (stringp (car x)) (string-width (car x)) 0))
  9066. fulltable)))
  9067. (expert (equal org-use-fast-todo-selection 'expert))
  9068. (prompt "")
  9069. (fwidth (+ maxlen 3 1 3))
  9070. (ncol (/ (- (window-width) 4) fwidth))
  9071. tg cnt e c tbl subtable
  9072. groups ingroup in-current-sequence)
  9073. (save-excursion
  9074. (save-window-excursion
  9075. (if expert
  9076. (set-buffer (get-buffer-create " *Org todo*"))
  9077. (delete-other-windows)
  9078. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9079. (org-switch-to-buffer-other-window " *Org todo*"))
  9080. (erase-buffer)
  9081. (setq-local org-done-keywords done-keywords)
  9082. (setq tbl fulltable cnt 0)
  9083. (while (setq e (pop tbl))
  9084. (cond
  9085. ((equal e '(:startgroup))
  9086. (push '() groups) (setq ingroup t)
  9087. (unless (= cnt 0)
  9088. (setq cnt 0)
  9089. (insert "\n"))
  9090. (setq prompt (concat prompt "{"))
  9091. (insert "{ "))
  9092. ((equal e '(:endgroup))
  9093. (setq ingroup nil cnt 0 in-current-sequence nil)
  9094. (setq prompt (concat prompt "}"))
  9095. (insert "}\n"))
  9096. ((equal e '(:newline))
  9097. (unless (= cnt 0)
  9098. (setq cnt 0)
  9099. (insert "\n")
  9100. (setq e (car tbl))
  9101. (while (equal (car tbl) '(:newline))
  9102. (insert "\n")
  9103. (setq tbl (cdr tbl)))))
  9104. (t
  9105. (setq tg (car e) c (cdr e))
  9106. (if (equal tg head) (setq in-current-sequence t))
  9107. (when ingroup (push tg (car groups)))
  9108. (when in-current-sequence (push e subtable))
  9109. (setq tg (org-add-props tg nil 'face
  9110. (org-get-todo-face tg)))
  9111. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9112. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9113. (insert "[" c "] " tg (make-string
  9114. (- fwidth 4 (length tg)) ?\ ))
  9115. (when (and (= (setq cnt (1+ cnt)) ncol)
  9116. ;; Avoid lines with just a closing delimiter.
  9117. (not (equal (car tbl) '(:endgroup))))
  9118. (insert "\n")
  9119. (when ingroup (insert " "))
  9120. (setq cnt 0)))))
  9121. (insert "\n")
  9122. (goto-char (point-min))
  9123. (unless expert (org-fit-window-to-buffer))
  9124. (message (concat "[a-z..]:Set [SPC]:clear"
  9125. (if expert (concat "\n" prompt) "")))
  9126. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9127. (setq subtable (nreverse subtable))
  9128. (cond
  9129. ((or (= c ?\C-g)
  9130. (and (= c ?q) (not (rassoc c fulltable))))
  9131. (setq quit-flag t))
  9132. ((= c ?\ ) nil)
  9133. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9134. tg (car e))
  9135. tg)
  9136. (t (setq quit-flag t)))))))
  9137. (defun org-entry-is-todo-p ()
  9138. (member (org-get-todo-state) org-not-done-keywords))
  9139. (defun org-entry-is-done-p ()
  9140. (member (org-get-todo-state) org-done-keywords))
  9141. (defun org-get-todo-state ()
  9142. "Return the TODO keyword of the current subtree."
  9143. (save-excursion
  9144. (org-back-to-heading t)
  9145. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9146. (match-end 2)
  9147. (match-string 2))))
  9148. (defun org-at-date-range-p (&optional inactive-ok)
  9149. "Non-nil if point is inside a date range.
  9150. When optional argument INACTIVE-OK is non-nil, also consider
  9151. inactive time ranges.
  9152. When this function returns a non-nil value, match data is set
  9153. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9154. on INACTIVE-OK."
  9155. (interactive)
  9156. (save-excursion
  9157. (catch 'exit
  9158. (let ((pos (point)))
  9159. (skip-chars-backward "^[<\r\n")
  9160. (skip-chars-backward "<[")
  9161. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9162. (>= (match-end 0) pos)
  9163. (throw 'exit t))
  9164. (skip-chars-backward "^<[\r\n")
  9165. (skip-chars-backward "<[")
  9166. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9167. (>= (match-end 0) pos)
  9168. (throw 'exit t)))
  9169. nil)))
  9170. (defun org-get-repeat (&optional timestamp)
  9171. "Check if there is a time-stamp with repeater in this entry.
  9172. Return the repeater, as a string, or nil. Also return nil when
  9173. this function is called before first heading.
  9174. When optional argument TIMESTAMP is a string, extract the
  9175. repeater from there instead."
  9176. (save-match-data
  9177. (cond (timestamp
  9178. (and (string-match org-repeat-re timestamp)
  9179. (match-string-no-properties 1 timestamp)))
  9180. ((org-before-first-heading-p) nil)
  9181. (t
  9182. (save-excursion
  9183. (org-back-to-heading t)
  9184. (let ((end (org-entry-end-position)))
  9185. (catch :repeat
  9186. (while (re-search-forward org-repeat-re end t)
  9187. (when (save-match-data (org-at-timestamp-p 'agenda))
  9188. (throw :repeat (match-string-no-properties 1)))))))))))
  9189. (defvar org-last-changed-timestamp)
  9190. (defvar org-last-inserted-timestamp)
  9191. (defvar org-log-post-message)
  9192. (defvar org-log-note-purpose)
  9193. (defvar org-log-note-how nil)
  9194. (defvar org-log-note-extra)
  9195. (defun org-auto-repeat-maybe (done-word)
  9196. "Check if the current headline contains a repeated time-stamp.
  9197. If yes, set TODO state back to what it was and change the base date
  9198. of repeating deadline/scheduled time stamps to new date.
  9199. This function is run automatically after each state change to a DONE state."
  9200. (let* ((repeat (org-get-repeat))
  9201. (aa (assoc org-last-state org-todo-kwd-alist))
  9202. (interpret (nth 1 aa))
  9203. (head (nth 2 aa))
  9204. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9205. (msg "Entry repeats: ")
  9206. (org-log-done nil)
  9207. (org-todo-log-states nil)
  9208. (end (copy-marker (org-entry-end-position))))
  9209. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9210. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9211. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9212. (and (stringp org-todo-repeat-to-state)
  9213. org-todo-repeat-to-state)
  9214. (and org-todo-repeat-to-state org-last-state))))
  9215. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9216. to-state)
  9217. ((eq interpret 'type) org-last-state)
  9218. (head)
  9219. (t 'none))))
  9220. (org-back-to-heading t)
  9221. (org-add-planning-info nil nil 'closed)
  9222. ;; When `org-log-repeat' is non-nil or entry contains
  9223. ;; a clock, set LAST_REPEAT property.
  9224. (when (or org-log-repeat
  9225. (catch :clock
  9226. (save-excursion
  9227. (while (re-search-forward org-clock-line-re end t)
  9228. (when (org-at-clock-log-p) (throw :clock t))))))
  9229. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9230. (org-time-stamp-format t t))))
  9231. (when org-log-repeat
  9232. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9233. (memq 'org-add-log-note post-command-hook))
  9234. ;; We are already setup for some record.
  9235. (when (eq org-log-repeat 'note)
  9236. ;; Make sure we take a note, not only a time stamp.
  9237. (setq org-log-note-how 'note))
  9238. ;; Set up for taking a record.
  9239. (org-add-log-setup 'state
  9240. (or done-word (car org-done-keywords))
  9241. org-last-state
  9242. org-log-repeat)))
  9243. ;; Time-stamps without a repeater are usually skipped. However,
  9244. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9245. ;; longer relevant.
  9246. (save-excursion
  9247. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9248. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9249. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9250. ;; Update every time-stamp with a repeater in the entry.
  9251. (let ((planning-re (regexp-opt
  9252. (list org-scheduled-string org-deadline-string))))
  9253. (while (re-search-forward org-repeat-re end t)
  9254. (let* ((ts (match-string 0))
  9255. (type (if (not (org-at-planning-p)) "Plain:"
  9256. (save-excursion
  9257. (re-search-backward
  9258. planning-re (line-beginning-position) t)
  9259. (match-string 0)))))
  9260. (when (and (org-at-timestamp-p 'agenda)
  9261. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9262. (let ((n (string-to-number (match-string 2 ts)))
  9263. (what (match-string 3 ts)))
  9264. (when (equal what "w") (setq n (* n 7) what "d"))
  9265. (when (and (equal what "h")
  9266. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9267. ts)))
  9268. (user-error
  9269. "Cannot repeat in %d hour(s) because no hour has been set"
  9270. n))
  9271. ;; Preparation, see if we need to modify the start
  9272. ;; date for the change.
  9273. (when (match-end 1)
  9274. (let ((time (save-match-data (org-time-string-to-time ts)))
  9275. (repeater-type (match-string 1 ts)))
  9276. (cond
  9277. ((equal "." repeater-type)
  9278. ;; Shift starting date to today, or now if
  9279. ;; repeater is by hours.
  9280. (if (equal what "h")
  9281. (org-timestamp-change
  9282. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9283. (org-timestamp-change
  9284. (- (org-today) (time-to-days time)) 'day)))
  9285. ((equal "+" repeater-type)
  9286. (let ((nshiftmax 10)
  9287. (nshift 0))
  9288. (while (or (= nshift 0)
  9289. (not (org-time-less-p nil time)))
  9290. (when (= nshiftmax (cl-incf nshift))
  9291. (or (y-or-n-p
  9292. (format "%d repeater intervals were not \
  9293. enough to shift date past today. Continue? "
  9294. nshift))
  9295. (user-error "Abort")))
  9296. (org-timestamp-change n (cdr (assoc what whata)))
  9297. (org-in-regexp org-ts-regexp3)
  9298. (setq ts (match-string 1))
  9299. (setq time
  9300. (save-match-data
  9301. (org-time-string-to-time ts)))))
  9302. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9303. ;; Rematch, so that we have everything in place
  9304. ;; for the real shift.
  9305. (org-in-regexp org-ts-regexp3)
  9306. (setq ts (match-string 1))
  9307. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9308. ts)))))
  9309. (save-excursion
  9310. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9311. (setq msg
  9312. (concat msg type " " org-last-changed-timestamp " ")))))))
  9313. (run-hooks 'org-todo-repeat-hook)
  9314. (setq org-log-post-message msg)
  9315. (message msg))))
  9316. (defun org-show-todo-tree (arg)
  9317. "Make a compact tree which shows all headlines marked with TODO.
  9318. The tree will show the lines where the regexp matches, and all higher
  9319. headlines above the match.
  9320. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9321. With a numeric prefix N, construct a sparse tree for the Nth element
  9322. of `org-todo-keywords-1'."
  9323. (interactive "P")
  9324. (let ((case-fold-search nil)
  9325. (kwd-re
  9326. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9327. ((equal arg '(4))
  9328. (let ((kwd
  9329. (completing-read "Keyword (or KWD1|KWD2|...): "
  9330. (mapcar #'list org-todo-keywords-1))))
  9331. (concat "\\("
  9332. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9333. "\\)\\>")))
  9334. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9335. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9336. org-todo-keywords-1)))
  9337. (t (user-error "Invalid prefix argument: %s" arg)))))
  9338. (message "%d TODO entries found"
  9339. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9340. (defun org--deadline-or-schedule (arg type time)
  9341. "Insert DEADLINE or SCHEDULE information in current entry.
  9342. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9343. `org-schedule' for information about ARG and TIME arguments."
  9344. (let* ((deadline? (eq type 'deadline))
  9345. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9346. (log (if deadline? org-log-redeadline org-log-reschedule))
  9347. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9348. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9349. ;; Save repeater cookie from either TIME or current scheduled
  9350. ;; time stamp. We are going to insert it back at the end of
  9351. ;; the process.
  9352. (repeater (or (and (org-string-nw-p time)
  9353. ;; We use `org-repeat-re' because we need
  9354. ;; to tell the difference between a real
  9355. ;; repeater and a time delta, e.g. "+2d".
  9356. (string-match org-repeat-re time)
  9357. (match-string 1 time))
  9358. (and (org-string-nw-p old-date)
  9359. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9360. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9361. old-date)
  9362. (match-string 1 old-date)))))
  9363. (pcase arg
  9364. (`(4)
  9365. (if (not old-date)
  9366. (message (if deadline? "Entry had no deadline to remove"
  9367. "Entry was not scheduled"))
  9368. (when (and old-date log)
  9369. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9370. nil old-date log))
  9371. (org-remove-timestamp-with-keyword keyword)
  9372. (message (if deadline? "Entry no longer has a deadline."
  9373. "Entry is no longer scheduled."))))
  9374. (`(16)
  9375. (save-excursion
  9376. (org-back-to-heading t)
  9377. (let ((regexp (if deadline? org-deadline-time-regexp
  9378. org-scheduled-time-regexp)))
  9379. (if (not (re-search-forward regexp (line-end-position 2) t))
  9380. (user-error (if deadline? "No deadline information to update"
  9381. "No scheduled information to update"))
  9382. (let* ((rpl0 (match-string 1))
  9383. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9384. (msg (if deadline? "Warn starting from" "Delay until")))
  9385. (replace-match
  9386. (concat keyword
  9387. " <" rpl
  9388. (format " -%dd"
  9389. (abs (- (time-to-days
  9390. (save-match-data
  9391. (org-read-date
  9392. nil t nil msg old-date-time)))
  9393. (time-to-days old-date-time))))
  9394. ">") t t))))))
  9395. (_
  9396. (org-add-planning-info type time 'closed)
  9397. (when (and old-date
  9398. log
  9399. (not (equal old-date org-last-inserted-timestamp)))
  9400. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9401. org-last-inserted-timestamp
  9402. old-date
  9403. log))
  9404. (when repeater
  9405. (save-excursion
  9406. (org-back-to-heading t)
  9407. (when (re-search-forward
  9408. (concat keyword " " org-last-inserted-timestamp)
  9409. (line-end-position 2)
  9410. t)
  9411. (goto-char (1- (match-end 0)))
  9412. (insert " " repeater)
  9413. (setq org-last-inserted-timestamp
  9414. (concat (substring org-last-inserted-timestamp 0 -1)
  9415. " " repeater
  9416. (substring org-last-inserted-timestamp -1))))))
  9417. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9418. org-last-inserted-timestamp)))))
  9419. (defun org-deadline (arg &optional time)
  9420. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9421. With one universal prefix argument, remove any deadline from the item.
  9422. With two universal prefix arguments, prompt for a warning delay.
  9423. With argument TIME, set the deadline at the corresponding date. TIME
  9424. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9425. (interactive "P")
  9426. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9427. (org-map-entries
  9428. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9429. nil
  9430. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9431. 'region-start-level
  9432. 'region)
  9433. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9434. (org--deadline-or-schedule arg 'deadline time)))
  9435. (defun org-schedule (arg &optional time)
  9436. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9437. With one universal prefix argument, remove any scheduling date from the item.
  9438. With two universal prefix arguments, prompt for a delay cookie.
  9439. With argument TIME, scheduled at the corresponding date. TIME can
  9440. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9441. (interactive "P")
  9442. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9443. (org-map-entries
  9444. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9445. nil
  9446. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9447. 'region-start-level
  9448. 'region)
  9449. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9450. (org--deadline-or-schedule arg 'scheduled time)))
  9451. (defun org-get-scheduled-time (pom &optional inherit)
  9452. "Get the scheduled time as a time tuple, of a format suitable
  9453. for calling org-schedule with, or if there is no scheduling,
  9454. returns nil."
  9455. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9456. (when time
  9457. (org-time-string-to-time time))))
  9458. (defun org-get-deadline-time (pom &optional inherit)
  9459. "Get the deadline as a time tuple, of a format suitable for
  9460. calling org-deadline with, or if there is no scheduling, returns
  9461. nil."
  9462. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9463. (when time
  9464. (org-time-string-to-time time))))
  9465. (defun org-remove-timestamp-with-keyword (keyword)
  9466. "Remove all time stamps with KEYWORD in the current entry."
  9467. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9468. beg)
  9469. (save-excursion
  9470. (org-back-to-heading t)
  9471. (setq beg (point))
  9472. (outline-next-heading)
  9473. (while (re-search-backward re beg t)
  9474. (replace-match "")
  9475. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9476. (equal (char-before) ?\ ))
  9477. (backward-delete-char 1)
  9478. (when (string-match "^[ \t]*$" (buffer-substring
  9479. (point-at-bol) (point-at-eol)))
  9480. (delete-region (point-at-bol)
  9481. (min (point-max) (1+ (point-at-eol))))))))))
  9482. (defvar org-time-was-given) ; dynamically scoped parameter
  9483. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9484. (defun org-at-planning-p ()
  9485. "Non-nil when point is on a planning info line."
  9486. ;; This is as accurate and faster than `org-element-at-point' since
  9487. ;; planning info location is fixed in the section.
  9488. (org-with-wide-buffer
  9489. (beginning-of-line)
  9490. (and (looking-at-p org-planning-line-re)
  9491. (eq (point)
  9492. (ignore-errors
  9493. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9494. (org-back-to-heading t)
  9495. (org-with-limited-levels (org-back-to-heading t)))
  9496. (line-beginning-position 2))))))
  9497. (defun org-add-planning-info (what &optional time &rest remove)
  9498. "Insert new timestamp with keyword in the planning line.
  9499. WHAT indicates what kind of time stamp to add. It is a symbol
  9500. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9501. the time to use. If none is given, the user is prompted for
  9502. a date. REMOVE indicates what kind of entries to remove. An old
  9503. WHAT entry will also be removed."
  9504. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9505. (when (and (memq what '(scheduled deadline))
  9506. (or (not time)
  9507. (and (stringp time)
  9508. (string-match "^[-+]+[0-9]" time))))
  9509. ;; Try to get a default date/time from existing timestamp
  9510. (save-excursion
  9511. (org-back-to-heading t)
  9512. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9513. (when (re-search-forward (if (eq what 'scheduled)
  9514. org-scheduled-time-regexp
  9515. org-deadline-time-regexp)
  9516. end t)
  9517. (setq ts (match-string 1)
  9518. default-time (org-time-string-to-time ts)
  9519. default-input (and ts (org-get-compact-tod ts)))))))
  9520. (when what
  9521. (setq time
  9522. (if (stringp time)
  9523. ;; This is a string (relative or absolute), set
  9524. ;; proper date.
  9525. (apply #'encode-time
  9526. (org-read-date-analyze
  9527. time default-time (decode-time default-time)))
  9528. ;; If necessary, get the time from the user
  9529. (or time (org-read-date nil 'to-time nil
  9530. (cl-case what
  9531. (deadline "DEADLINE")
  9532. (scheduled "SCHEDULED")
  9533. (otherwise nil))
  9534. default-time default-input)))))
  9535. (org-with-wide-buffer
  9536. (org-back-to-heading t)
  9537. (let ((planning? (save-excursion
  9538. (forward-line)
  9539. (looking-at-p org-planning-line-re))))
  9540. (cond
  9541. (planning?
  9542. (forward-line)
  9543. ;; Move to current indentation.
  9544. (skip-chars-forward " \t")
  9545. ;; Check if we have to remove something.
  9546. (dolist (type (if what (cons what remove) remove))
  9547. (save-excursion
  9548. (when (re-search-forward
  9549. (cl-case type
  9550. (closed org-closed-time-regexp)
  9551. (deadline org-deadline-time-regexp)
  9552. (scheduled org-scheduled-time-regexp)
  9553. (otherwise (error "Invalid planning type: %s" type)))
  9554. (line-end-position)
  9555. t)
  9556. ;; Delete until next keyword or end of line.
  9557. (delete-region
  9558. (match-beginning 0)
  9559. (if (re-search-forward org-keyword-time-not-clock-regexp
  9560. (line-end-position)
  9561. t)
  9562. (match-beginning 0)
  9563. (line-end-position))))))
  9564. ;; If there is nothing more to add and no more keyword is
  9565. ;; left, remove the line completely.
  9566. (if (and (looking-at-p "[ \t]*$") (not what))
  9567. (delete-region (line-beginning-position)
  9568. (line-beginning-position 2))
  9569. ;; If we removed last keyword, do not leave trailing white
  9570. ;; space at the end of line.
  9571. (let ((p (point)))
  9572. (save-excursion
  9573. (end-of-line)
  9574. (unless (= (skip-chars-backward " \t" p) 0)
  9575. (delete-region (point) (line-end-position)))))))
  9576. (what
  9577. (end-of-line)
  9578. (insert "\n")
  9579. (when org-adapt-indentation
  9580. (indent-to-column (1+ (org-outline-level)))))
  9581. (t nil)))
  9582. (when what
  9583. ;; Insert planning keyword.
  9584. (insert (cl-case what
  9585. (closed org-closed-string)
  9586. (deadline org-deadline-string)
  9587. (scheduled org-scheduled-string)
  9588. (otherwise (error "Invalid planning type: %s" what)))
  9589. " ")
  9590. ;; Insert associated timestamp.
  9591. (let ((ts (org-insert-time-stamp
  9592. time
  9593. (or org-time-was-given
  9594. (and (eq what 'closed) org-log-done-with-time))
  9595. (eq what 'closed)
  9596. nil nil (list org-end-time-was-given))))
  9597. (unless (eolp) (insert " "))
  9598. ts)))))
  9599. (defvar org-log-note-marker (make-marker)
  9600. "Marker pointing at the entry where the note is to be inserted.")
  9601. (defvar org-log-note-purpose nil)
  9602. (defvar org-log-note-state nil)
  9603. (defvar org-log-note-previous-state nil)
  9604. (defvar org-log-note-extra nil)
  9605. (defvar org-log-note-window-configuration nil)
  9606. (defvar org-log-note-return-to (make-marker))
  9607. (defvar org-log-note-effective-time nil
  9608. "Remembered current time so that dynamically scoped
  9609. `org-extend-today-until' affects timestamps in state change log")
  9610. (defvar org-log-post-message nil
  9611. "Message to be displayed after a log note has been stored.
  9612. The auto-repeater uses this.")
  9613. (defun org-add-note ()
  9614. "Add a note to the current entry.
  9615. This is done in the same way as adding a state change note."
  9616. (interactive)
  9617. (org-add-log-setup 'note))
  9618. (defun org-log-beginning (&optional create)
  9619. "Return expected start of log notes in current entry.
  9620. When optional argument CREATE is non-nil, the function creates
  9621. a drawer to store notes, if necessary. Returned position ignores
  9622. narrowing."
  9623. (org-with-wide-buffer
  9624. (let ((drawer (org-log-into-drawer)))
  9625. (cond
  9626. (drawer
  9627. (org-end-of-meta-data)
  9628. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9629. (end (if (org-at-heading-p) (point)
  9630. (save-excursion (outline-next-heading) (point))))
  9631. (case-fold-search t))
  9632. (catch 'exit
  9633. ;; Try to find existing drawer.
  9634. (while (re-search-forward regexp end t)
  9635. (let ((element (org-element-at-point)))
  9636. (when (eq (org-element-type element) 'drawer)
  9637. (let ((cend (org-element-property :contents-end element)))
  9638. (when (and (not org-log-states-order-reversed) cend)
  9639. (goto-char cend)))
  9640. (throw 'exit nil))))
  9641. ;; No drawer found. Create one, if permitted.
  9642. (when create
  9643. (unless (bolp) (insert "\n"))
  9644. (let ((beg (point)))
  9645. (insert ":" drawer ":\n:END:\n")
  9646. (org-indent-region beg (point))
  9647. (org-flag-region
  9648. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  9649. (end-of-line -1)))))
  9650. (t
  9651. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9652. (skip-chars-forward " \t\n")
  9653. (beginning-of-line)
  9654. (unless org-log-states-order-reversed
  9655. (org-skip-over-state-notes)
  9656. (skip-chars-backward " \t\n")
  9657. (forward-line)))))
  9658. (if (bolp) (point) (line-beginning-position 2))))
  9659. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9660. "Set up the post command hook to take a note.
  9661. If this is about to TODO state change, the new state is expected in STATE.
  9662. HOW is an indicator what kind of note should be created.
  9663. EXTRA is additional text that will be inserted into the notes buffer."
  9664. (move-marker org-log-note-marker (point))
  9665. (setq org-log-note-purpose purpose
  9666. org-log-note-state state
  9667. org-log-note-previous-state prev-state
  9668. org-log-note-how how
  9669. org-log-note-extra extra
  9670. org-log-note-effective-time (org-current-effective-time))
  9671. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9672. (defun org-skip-over-state-notes ()
  9673. "Skip past the list of State notes in an entry."
  9674. (when (ignore-errors (goto-char (org-in-item-p)))
  9675. (let* ((struct (org-list-struct))
  9676. (prevs (org-list-prevs-alist struct))
  9677. (regexp
  9678. (concat "[ \t]*- +"
  9679. (replace-regexp-in-string
  9680. " +" " +"
  9681. (org-replace-escapes
  9682. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9683. `(("%d" . ,org-ts-regexp-inactive)
  9684. ("%D" . ,org-ts-regexp)
  9685. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9686. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9687. ("%t" . ,org-ts-regexp-inactive)
  9688. ("%T" . ,org-ts-regexp)
  9689. ("%u" . ".*?")
  9690. ("%U" . ".*?")))))))
  9691. (while (looking-at-p regexp)
  9692. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9693. (org-list-get-item-end (point) struct)))))))
  9694. (defun org-add-log-note (&optional _purpose)
  9695. "Pop up a window for taking a note, and add this note later."
  9696. (remove-hook 'post-command-hook 'org-add-log-note)
  9697. (setq org-log-note-window-configuration (current-window-configuration))
  9698. (delete-other-windows)
  9699. (move-marker org-log-note-return-to (point))
  9700. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9701. (goto-char org-log-note-marker)
  9702. (org-switch-to-buffer-other-window "*Org Note*")
  9703. (erase-buffer)
  9704. (if (memq org-log-note-how '(time state))
  9705. (org-store-log-note)
  9706. (let ((org-inhibit-startup t)) (org-mode))
  9707. (insert (format "# Insert note for %s.
  9708. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9709. (cl-case org-log-note-purpose
  9710. (clock-out "stopped clock")
  9711. (done "closed todo item")
  9712. (reschedule "rescheduling")
  9713. (delschedule "no longer scheduled")
  9714. (redeadline "changing deadline")
  9715. (deldeadline "removing deadline")
  9716. (refile "refiling")
  9717. (note "this entry")
  9718. (state
  9719. (format "state change from \"%s\" to \"%s\""
  9720. (or org-log-note-previous-state "")
  9721. (or org-log-note-state "")))
  9722. (t (error "This should not happen")))))
  9723. (when org-log-note-extra (insert org-log-note-extra))
  9724. (setq-local org-finish-function 'org-store-log-note)
  9725. (run-hooks 'org-log-buffer-setup-hook)))
  9726. (defvar org-note-abort nil) ; dynamically scoped
  9727. (defun org-store-log-note ()
  9728. "Finish taking a log note, and insert it to where it belongs."
  9729. (let ((txt (prog1 (buffer-string)
  9730. (kill-buffer)))
  9731. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9732. lines)
  9733. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9734. (setq txt (replace-match "" t t txt)))
  9735. (when (string-match "\\s-+\\'" txt)
  9736. (setq txt (replace-match "" t t txt)))
  9737. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9738. (when (org-string-nw-p note)
  9739. (setq note
  9740. (org-replace-escapes
  9741. note
  9742. (list (cons "%u" (user-login-name))
  9743. (cons "%U" user-full-name)
  9744. (cons "%t" (format-time-string
  9745. (org-time-stamp-format 'long 'inactive)
  9746. org-log-note-effective-time))
  9747. (cons "%T" (format-time-string
  9748. (org-time-stamp-format 'long nil)
  9749. org-log-note-effective-time))
  9750. (cons "%d" (format-time-string
  9751. (org-time-stamp-format nil 'inactive)
  9752. org-log-note-effective-time))
  9753. (cons "%D" (format-time-string
  9754. (org-time-stamp-format nil nil)
  9755. org-log-note-effective-time))
  9756. (cons "%s" (cond
  9757. ((not org-log-note-state) "")
  9758. ((string-match-p org-ts-regexp
  9759. org-log-note-state)
  9760. (format "\"[%s]\""
  9761. (substring org-log-note-state 1 -1)))
  9762. (t (format "\"%s\"" org-log-note-state))))
  9763. (cons "%S"
  9764. (cond
  9765. ((not org-log-note-previous-state) "")
  9766. ((string-match-p org-ts-regexp
  9767. org-log-note-previous-state)
  9768. (format "\"[%s]\""
  9769. (substring
  9770. org-log-note-previous-state 1 -1)))
  9771. (t (format "\"%s\""
  9772. org-log-note-previous-state)))))))
  9773. (when lines (setq note (concat note " \\\\")))
  9774. (push note lines))
  9775. (when (and lines (not org-note-abort))
  9776. (with-current-buffer (marker-buffer org-log-note-marker)
  9777. (org-with-wide-buffer
  9778. ;; Find location for the new note.
  9779. (goto-char org-log-note-marker)
  9780. (set-marker org-log-note-marker nil)
  9781. ;; Note associated to a clock is to be located right after
  9782. ;; the clock. Do not move point.
  9783. (unless (eq org-log-note-purpose 'clock-out)
  9784. (goto-char (org-log-beginning t)))
  9785. ;; Make sure point is at the beginning of an empty line.
  9786. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9787. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9788. ;; In an existing list, add a new item at the top level.
  9789. ;; Otherwise, indent line like a regular one.
  9790. (let ((itemp (org-in-item-p)))
  9791. (if itemp
  9792. (indent-line-to
  9793. (let ((struct (save-excursion
  9794. (goto-char itemp) (org-list-struct))))
  9795. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9796. (org-indent-line)))
  9797. (insert (org-list-bullet-string "-") (pop lines))
  9798. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9799. (dolist (line lines)
  9800. (insert "\n")
  9801. (indent-line-to ind)
  9802. (insert line)))
  9803. (message "Note stored")
  9804. (org-back-to-heading t))
  9805. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9806. ;; from within `org-add-log-note' because `buffer-undo-list'
  9807. ;; is then modified outside of `org-with-remote-undo'.
  9808. (when (eq this-command 'org-agenda-todo)
  9809. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9810. ;; Don't add undo information when called from `org-agenda-todo'.
  9811. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9812. (set-window-configuration org-log-note-window-configuration)
  9813. (with-current-buffer (marker-buffer org-log-note-return-to)
  9814. (goto-char org-log-note-return-to))
  9815. (move-marker org-log-note-return-to nil)
  9816. (when org-log-post-message (message "%s" org-log-post-message))))
  9817. (defun org-remove-empty-drawer-at (pos)
  9818. "Remove an empty drawer at position POS.
  9819. POS may also be a marker."
  9820. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9821. (org-with-wide-buffer
  9822. (goto-char pos)
  9823. (let ((drawer (org-element-at-point)))
  9824. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9825. (not (org-element-property :contents-begin drawer)))
  9826. (delete-region (org-element-property :begin drawer)
  9827. (progn (goto-char (org-element-property :end drawer))
  9828. (skip-chars-backward " \r\t\n")
  9829. (forward-line)
  9830. (point))))))))
  9831. (defvar org-ts-type nil)
  9832. (defun org-sparse-tree (&optional arg type)
  9833. "Create a sparse tree, prompt for the details.
  9834. This command can create sparse trees. You first need to select the type
  9835. of match used to create the tree:
  9836. t Show all TODO entries.
  9837. T Show entries with a specific TODO keyword.
  9838. m Show entries selected by a tags/property match.
  9839. p Enter a property name and its value (both with completion on existing
  9840. names/values) and show entries with that property.
  9841. r Show entries matching a regular expression (`/' can be used as well).
  9842. b Show deadlines and scheduled items before a date.
  9843. a Show deadlines and scheduled items after a date.
  9844. d Show deadlines due within `org-deadline-warning-days'.
  9845. D Show deadlines and scheduled items between a date range."
  9846. (interactive "P")
  9847. (setq type (or type org-sparse-tree-default-date-type))
  9848. (setq org-ts-type type)
  9849. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9850. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9851. [c]ycle through date types: %s"
  9852. (cl-case type
  9853. (all "all timestamps")
  9854. (scheduled "only scheduled")
  9855. (deadline "only deadline")
  9856. (active "only active timestamps")
  9857. (inactive "only inactive timestamps")
  9858. (closed "with a closed time-stamp")
  9859. (otherwise "scheduled/deadline")))
  9860. (let ((answer (read-char-exclusive)))
  9861. (cl-case answer
  9862. (?c
  9863. (org-sparse-tree
  9864. arg
  9865. (cadr
  9866. (memq type '(nil all scheduled deadline active inactive closed)))))
  9867. (?d (call-interactively 'org-check-deadlines))
  9868. (?b (call-interactively 'org-check-before-date))
  9869. (?a (call-interactively 'org-check-after-date))
  9870. (?D (call-interactively 'org-check-dates-range))
  9871. (?t (call-interactively 'org-show-todo-tree))
  9872. (?T (org-show-todo-tree '(4)))
  9873. (?m (call-interactively 'org-match-sparse-tree))
  9874. ((?p ?P)
  9875. (let* ((kwd (completing-read
  9876. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9877. (value (completing-read
  9878. "Value: " (mapcar #'list (org-property-values kwd)))))
  9879. (unless (string-match "\\`{.*}\\'" value)
  9880. (setq value (concat "\"" value "\"")))
  9881. (org-match-sparse-tree arg (concat kwd "=" value))))
  9882. ((?r ?R ?/) (call-interactively 'org-occur))
  9883. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9884. (defvar-local org-occur-highlights nil
  9885. "List of overlays used for occur matches.")
  9886. (defvar-local org-occur-parameters nil
  9887. "Parameters of the active org-occur calls.
  9888. This is a list, each call to org-occur pushes as cons cell,
  9889. containing the regular expression and the callback, onto the list.
  9890. The list can contain several entries if `org-occur' has been called
  9891. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9892. will only contain one set of parameters. When the highlights are
  9893. removed (for example with `C-c C-c', or with the next edit (depending
  9894. on `org-remove-highlights-with-change'), this variable is emptied
  9895. as well.")
  9896. (defun org-occur (regexp &optional keep-previous callback)
  9897. "Make a compact tree which shows all matches of REGEXP.
  9898. The tree will show the lines where the regexp matches, and any other context
  9899. defined in `org-show-context-detail', which see.
  9900. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9901. done by a previous call to `org-occur' will be kept, to allow stacking of
  9902. calls to this command.
  9903. Optional argument CALLBACK can be a function of no argument. In this case,
  9904. it is called with point at the end of the match, match data being set
  9905. accordingly. Current match is shown only if the return value is non-nil.
  9906. The function must neither move point nor alter narrowing."
  9907. (interactive "sRegexp: \nP")
  9908. (when (equal regexp "")
  9909. (user-error "Regexp cannot be empty"))
  9910. (unless keep-previous
  9911. (org-remove-occur-highlights nil nil t))
  9912. (push (cons regexp callback) org-occur-parameters)
  9913. (let ((cnt 0))
  9914. (save-excursion
  9915. (goto-char (point-min))
  9916. (when (or (not keep-previous) ; do not want to keep
  9917. (not org-occur-highlights)) ; no previous matches
  9918. ;; hide everything
  9919. (org-overview))
  9920. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9921. (isearch-no-upper-case-p regexp t)
  9922. org-occur-case-fold-search)))
  9923. (while (re-search-forward regexp nil t)
  9924. (when (or (not callback)
  9925. (save-match-data (funcall callback)))
  9926. (setq cnt (1+ cnt))
  9927. (when org-highlight-sparse-tree-matches
  9928. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9929. (org-show-context 'occur-tree)))))
  9930. (when org-remove-highlights-with-change
  9931. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9932. nil 'local))
  9933. (unless org-sparse-tree-open-archived-trees
  9934. (org-hide-archived-subtrees (point-min) (point-max)))
  9935. (run-hooks 'org-occur-hook)
  9936. (when (called-interactively-p 'interactive)
  9937. (message "%d match(es) for regexp %s" cnt regexp))
  9938. cnt))
  9939. (defun org-occur-next-match (&optional n _reset)
  9940. "Function for `next-error-function' to find sparse tree matches.
  9941. N is the number of matches to move, when negative move backwards.
  9942. This function always goes back to the starting point when no
  9943. match is found."
  9944. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9945. (search-func (if (< n 0)
  9946. 'previous-single-char-property-change
  9947. 'next-single-char-property-change))
  9948. (n (abs n))
  9949. (pos (point))
  9950. p1)
  9951. (catch 'exit
  9952. (while (setq p1 (funcall search-func (point) 'org-type))
  9953. (when (equal p1 limit)
  9954. (goto-char pos)
  9955. (user-error "No more matches"))
  9956. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9957. (setq n (1- n))
  9958. (when (= n 0)
  9959. (goto-char p1)
  9960. (throw 'exit (point))))
  9961. (goto-char p1))
  9962. (goto-char p1)
  9963. (user-error "No more matches"))))
  9964. (defun org-highlight-new-match (beg end)
  9965. "Highlight from BEG to END and mark the highlight is an occur headline."
  9966. (let ((ov (make-overlay beg end)))
  9967. (overlay-put ov 'face 'secondary-selection)
  9968. (overlay-put ov 'org-type 'org-occur)
  9969. (push ov org-occur-highlights)))
  9970. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9971. "Remove the occur highlights from the buffer.
  9972. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9973. from the `before-change-functions' in the current buffer."
  9974. (interactive)
  9975. (unless org-inhibit-highlight-removal
  9976. (mapc #'delete-overlay org-occur-highlights)
  9977. (setq org-occur-highlights nil)
  9978. (setq org-occur-parameters nil)
  9979. (unless noremove
  9980. (remove-hook 'before-change-functions
  9981. 'org-remove-occur-highlights 'local))))
  9982. ;;;; Priorities
  9983. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9984. "Regular expression matching the priority indicator.
  9985. A priority indicator can be e.g. [#A] or [#1].
  9986. This regular expression matches these groups:
  9987. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9988. 1 : the priority cookie, e.g. \"[#A]\"
  9989. 2 : the value of the priority cookie, e.g. \"A\".")
  9990. (defun org-priority-up ()
  9991. "Increase the priority of the current item."
  9992. (interactive)
  9993. (org-priority 'up))
  9994. (defun org-priority-down ()
  9995. "Decrease the priority of the current item."
  9996. (interactive)
  9997. (org-priority 'down))
  9998. (defun org-priority (&optional action show)
  9999. "Change the priority of an item.
  10000. When called interactively with a `\\[universal-argument]' prefix,
  10001. show the priority in the minibuffer instead of changing it.
  10002. When called programmatically, ACTION can be `set', `up', `down',
  10003. or a character."
  10004. (interactive "P")
  10005. (when show
  10006. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10007. ;; passed the SHOW argument should be removed.
  10008. (warn "`org-priority' called with deprecated SHOW argument"))
  10009. (if (equal action '(4))
  10010. (org-priority-show)
  10011. (unless org-priority-enable-commands
  10012. (user-error "Priority commands are disabled"))
  10013. (setq action (or action 'set))
  10014. (let ((nump (< org-priority-lowest 65))
  10015. current new news have remove)
  10016. (save-excursion
  10017. (org-back-to-heading t)
  10018. (when (looking-at org-priority-regexp)
  10019. (let ((ms (match-string 2)))
  10020. (setq current (org-priority-to-value ms)
  10021. have t)))
  10022. (cond
  10023. ((eq action 'remove)
  10024. (setq remove t new ?\ ))
  10025. ((or (eq action 'set)
  10026. (integerp action))
  10027. (if (not (eq action 'set))
  10028. (setq new action)
  10029. (setq
  10030. new
  10031. (if nump
  10032. (string-to-number
  10033. (read-string (format "Priority %s-%s, SPC to remove: "
  10034. (number-to-string org-priority-highest)
  10035. (number-to-string org-priority-lowest))))
  10036. (progn (message "Priority %c-%c, SPC to remove: "
  10037. org-priority-highest org-priority-lowest)
  10038. (save-match-data
  10039. (setq new (read-char-exclusive)))))))
  10040. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10041. (= (upcase org-priority-lowest) org-priority-lowest))
  10042. (setq new (upcase new)))
  10043. (cond ((equal new ?\s) (setq remove t))
  10044. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10045. (user-error
  10046. (if nump
  10047. "Priority must be between `%s' and `%s'"
  10048. "Priority must be between `%c' and `%c'")
  10049. org-priority-highest org-priority-lowest))))
  10050. ((eq action 'up)
  10051. (setq new (if have
  10052. (1- current) ; normal cycling
  10053. ;; last priority was empty
  10054. (if (eq last-command this-command)
  10055. org-priority-lowest ; wrap around empty to lowest
  10056. ;; default
  10057. (if org-priority-start-cycle-with-default
  10058. org-priority-default
  10059. (1- org-priority-default))))))
  10060. ((eq action 'down)
  10061. (setq new (if have
  10062. (1+ current) ; normal cycling
  10063. ;; last priority was empty
  10064. (if (eq last-command this-command)
  10065. org-priority-highest ; wrap around empty to highest
  10066. ;; default
  10067. (if org-priority-start-cycle-with-default
  10068. org-priority-default
  10069. (1+ org-priority-default))))))
  10070. (t (user-error "Invalid action")))
  10071. (when (or (< (upcase new) org-priority-highest)
  10072. (> (upcase new) org-priority-lowest))
  10073. (if (and (memq action '(up down))
  10074. (not have) (not (eq last-command this-command)))
  10075. ;; `new' is from default priority
  10076. (error
  10077. "The default can not be set, see `org-priority-default' why")
  10078. ;; normal cycling: `new' is beyond highest/lowest priority
  10079. ;; and is wrapped around to the empty priority
  10080. (setq remove t)))
  10081. ;; Numerical priorities are limited to 64, beyond that number,
  10082. ;; assume the priority cookie is a character.
  10083. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10084. (if have
  10085. (if remove
  10086. (replace-match "" t t nil 1)
  10087. (replace-match news t t nil 2))
  10088. (if remove
  10089. (user-error "No priority cookie found in line")
  10090. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10091. (if (match-end 2)
  10092. (progn
  10093. (goto-char (match-end 2))
  10094. (insert " [#" news "]"))
  10095. (goto-char (match-beginning 3))
  10096. (insert "[#" news "] "))))
  10097. (org-align-tags))
  10098. (if remove
  10099. (message "Priority removed")
  10100. (message "Priority of current item set to %s" news)))))
  10101. (defalias 'org-show-priority 'org-priority-show)
  10102. (defun org-priority-show ()
  10103. "Show the priority of the current item.
  10104. This priority is composed of the main priority given with the [#A] cookies,
  10105. and by additional input from the age of a schedules or deadline entry."
  10106. (interactive)
  10107. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10108. (org-get-at-bol 'priority)
  10109. (save-excursion
  10110. (save-match-data
  10111. (beginning-of-line)
  10112. (and (looking-at org-heading-regexp)
  10113. (org-get-priority (match-string 0))))))))
  10114. (message "Priority is %d" (if pri pri -1000))))
  10115. (defun org-get-priority (s)
  10116. "Find priority cookie and return priority.
  10117. S is a string against which you can match `org-priority-regexp'.
  10118. If `org-priority-get-priority-function' is set to a custom
  10119. function, use it. Otherwise process S and output the priority
  10120. value, an integer."
  10121. (save-match-data
  10122. (if (functionp org-priority-get-priority-function)
  10123. (funcall org-priority-get-priority-function s)
  10124. (if (not (string-match org-priority-regexp s))
  10125. (* 1000 (- org-priority-lowest org-priority-default))
  10126. (* 1000 (- org-priority-lowest
  10127. (org-priority-to-value (match-string 2 s))))))))
  10128. ;;;; Tags
  10129. (defvar org-agenda-archives-mode)
  10130. (defvar org-map-continue-from nil
  10131. "Position from where mapping should continue.
  10132. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10133. (defvar org-scanner-tags nil
  10134. "The current tag list while the tags scanner is running.")
  10135. (defvar org-trust-scanner-tags nil
  10136. "Should `org-get-tags' use the tags for the scanner.
  10137. This is for internal dynamical scoping only.
  10138. When this is non-nil, the function `org-get-tags' will return the value
  10139. of `org-scanner-tags' instead of building the list by itself. This
  10140. can lead to large speed-ups when the tags scanner is used in a file with
  10141. many entries, and when the list of tags is retrieved, for example to
  10142. obtain a list of properties. Building the tags list for each entry in such
  10143. a file becomes an N^2 operation - but with this variable set, it scales
  10144. as N.")
  10145. (defvar org--matcher-tags-todo-only nil)
  10146. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10147. "Scan headline tags with inheritance and produce output ACTION.
  10148. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10149. or `agenda' to produce an entry list for an agenda view. It can also be
  10150. a Lisp form or a function that should be called at each matched headline, in
  10151. this case the return value is a list of all return values from these calls.
  10152. MATCHER is a function accepting three arguments, returning
  10153. a non-nil value whenever a given set of tags qualifies a headline
  10154. for inclusion. See `org-make-tags-matcher' for more information.
  10155. As a special case, it can also be set to t (respectively nil) in
  10156. order to match all (respectively none) headline.
  10157. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10158. included in the output.
  10159. START-LEVEL can be a string with asterisks, reducing the scope to
  10160. headlines matching this string."
  10161. (require 'org-agenda)
  10162. (let* ((re (concat "^"
  10163. (if start-level
  10164. ;; Get the correct level to match
  10165. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10166. org-outline-regexp)
  10167. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10168. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10169. (props (list 'face 'default
  10170. 'done-face 'org-agenda-done
  10171. 'undone-face 'default
  10172. 'mouse-face 'highlight
  10173. 'org-not-done-regexp org-not-done-regexp
  10174. 'org-todo-regexp org-todo-regexp
  10175. 'org-complex-heading-regexp org-complex-heading-regexp
  10176. 'help-echo
  10177. (format "mouse-2 or RET jump to Org file %S"
  10178. (abbreviate-file-name
  10179. (or (buffer-file-name (buffer-base-buffer))
  10180. (buffer-name (buffer-base-buffer)))))))
  10181. (org-map-continue-from nil)
  10182. lspos tags tags-list
  10183. (tags-alist (list (cons 0 org-file-tags)))
  10184. (llast 0) rtn rtn1 level category i txt
  10185. todo marker entry priority
  10186. ts-date ts-date-type ts-date-pair)
  10187. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10188. (setq action (list 'lambda nil action)))
  10189. (save-excursion
  10190. (goto-char (point-min))
  10191. (when (eq action 'sparse-tree)
  10192. (org-overview)
  10193. (org-remove-occur-highlights))
  10194. (while (let (case-fold-search)
  10195. (re-search-forward re nil t))
  10196. (setq org-map-continue-from nil)
  10197. (catch :skip
  10198. ;; Ignore closing parts of inline tasks.
  10199. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10200. (throw :skip t))
  10201. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10202. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10203. (goto-char (setq lspos (match-beginning 0)))
  10204. (setq level (org-reduced-level (org-outline-level))
  10205. category (org-get-category))
  10206. (when (eq action 'agenda)
  10207. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10208. ts-date (car ts-date-pair)
  10209. ts-date-type (cdr ts-date-pair)))
  10210. (setq i llast llast level)
  10211. ;; remove tag lists from same and sublevels
  10212. (while (>= i level)
  10213. (when (setq entry (assoc i tags-alist))
  10214. (setq tags-alist (delete entry tags-alist)))
  10215. (setq i (1- i)))
  10216. ;; add the next tags
  10217. (when tags
  10218. (setq tags (org-split-string tags ":")
  10219. tags-alist
  10220. (cons (cons level tags) tags-alist)))
  10221. ;; compile tags for current headline
  10222. (setq tags-list
  10223. (if org-use-tag-inheritance
  10224. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10225. tags)
  10226. org-scanner-tags tags-list)
  10227. (when org-use-tag-inheritance
  10228. (setcdr (car tags-alist)
  10229. (mapcar (lambda (x)
  10230. (setq x (copy-sequence x))
  10231. (org-add-prop-inherited x))
  10232. (cdar tags-alist))))
  10233. (when (and tags org-use-tag-inheritance
  10234. (or (not (eq t org-use-tag-inheritance))
  10235. org-tags-exclude-from-inheritance))
  10236. ;; Selective inheritance, remove uninherited ones.
  10237. (setcdr (car tags-alist)
  10238. (org-remove-uninherited-tags (cdar tags-alist))))
  10239. (when (and
  10240. ;; eval matcher only when the todo condition is OK
  10241. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10242. (if (functionp matcher)
  10243. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10244. (funcall matcher todo tags-list level))
  10245. matcher))
  10246. ;; Call the skipper, but return t if it does not
  10247. ;; skip, so that the `and' form continues evaluating.
  10248. (progn
  10249. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10250. t)
  10251. ;; Check if timestamps are deselecting this entry
  10252. (or (not todo-only)
  10253. (and (member todo org-todo-keywords-1)
  10254. (or (not org-agenda-tags-todo-honor-ignore-options)
  10255. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10256. ;; select this headline
  10257. (cond
  10258. ((eq action 'sparse-tree)
  10259. (and org-highlight-sparse-tree-matches
  10260. (org-get-heading) (match-end 0)
  10261. (org-highlight-new-match
  10262. (match-beginning 1) (match-end 1)))
  10263. (org-show-context 'tags-tree))
  10264. ((eq action 'agenda)
  10265. (setq txt (org-agenda-format-item
  10266. ""
  10267. (concat
  10268. (if (eq org-tags-match-list-sublevels 'indented)
  10269. (make-string (1- level) ?.) "")
  10270. (org-get-heading))
  10271. (make-string level ?\s)
  10272. category
  10273. tags-list)
  10274. priority (org-get-priority txt))
  10275. (goto-char lspos)
  10276. (setq marker (org-agenda-new-marker))
  10277. (org-add-props txt props
  10278. 'org-marker marker 'org-hd-marker marker 'org-category category
  10279. 'todo-state todo
  10280. 'ts-date ts-date
  10281. 'priority priority
  10282. 'type (concat "tagsmatch" ts-date-type))
  10283. (push txt rtn))
  10284. ((functionp action)
  10285. (setq org-map-continue-from nil)
  10286. (save-excursion
  10287. (setq rtn1 (funcall action))
  10288. (push rtn1 rtn)))
  10289. (t (user-error "Invalid action")))
  10290. ;; if we are to skip sublevels, jump to end of subtree
  10291. (unless org-tags-match-list-sublevels
  10292. (org-end-of-subtree t)
  10293. (backward-char 1))))
  10294. ;; Get the correct position from where to continue
  10295. (if org-map-continue-from
  10296. (goto-char org-map-continue-from)
  10297. (and (= (point) lspos) (end-of-line 1)))))
  10298. (when (and (eq action 'sparse-tree)
  10299. (not org-sparse-tree-open-archived-trees))
  10300. (org-hide-archived-subtrees (point-min) (point-max)))
  10301. (nreverse rtn)))
  10302. (defun org-remove-uninherited-tags (tags)
  10303. "Remove all tags that are not inherited from the list TAGS."
  10304. (cond
  10305. ((eq org-use-tag-inheritance t)
  10306. (if org-tags-exclude-from-inheritance
  10307. (org-delete-all org-tags-exclude-from-inheritance tags)
  10308. tags))
  10309. ((not org-use-tag-inheritance) nil)
  10310. ((stringp org-use-tag-inheritance)
  10311. (delq nil (mapcar
  10312. (lambda (x)
  10313. (if (and (string-match org-use-tag-inheritance x)
  10314. (not (member x org-tags-exclude-from-inheritance)))
  10315. x nil))
  10316. tags)))
  10317. ((listp org-use-tag-inheritance)
  10318. (delq nil (mapcar
  10319. (lambda (x)
  10320. (if (member x org-use-tag-inheritance) x nil))
  10321. tags)))))
  10322. (defun org-match-sparse-tree (&optional todo-only match)
  10323. "Create a sparse tree according to tags string MATCH.
  10324. MATCH is a string with match syntax. It can contain a selection
  10325. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10326. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10327. those. See the manual for details.
  10328. If optional argument TODO-ONLY is non-nil, only select lines that
  10329. are also TODO tasks."
  10330. (interactive "P")
  10331. (org-agenda-prepare-buffers (list (current-buffer)))
  10332. (let ((org--matcher-tags-todo-only todo-only))
  10333. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10334. org--matcher-tags-todo-only)))
  10335. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10336. (defvar org-cached-props nil)
  10337. (defun org-cached-entry-get (pom property)
  10338. (if (or (eq t org-use-property-inheritance)
  10339. (and (stringp org-use-property-inheritance)
  10340. (let ((case-fold-search t))
  10341. (string-match-p org-use-property-inheritance property)))
  10342. (and (listp org-use-property-inheritance)
  10343. (member-ignore-case property org-use-property-inheritance)))
  10344. ;; Caching is not possible, check it directly.
  10345. (org-entry-get pom property 'inherit)
  10346. ;; Get all properties, so we can do complicated checks easily.
  10347. (cdr (assoc-string property
  10348. (or org-cached-props
  10349. (setq org-cached-props (org-entry-properties pom)))
  10350. t))))
  10351. (defun org-global-tags-completion-table (&optional files)
  10352. "Return the list of all tags in all agenda buffer/files.
  10353. Optional FILES argument is a list of files which can be used
  10354. instead of the agenda files."
  10355. (save-excursion
  10356. (org-uniquify
  10357. (delq nil
  10358. (apply #'append
  10359. (mapcar
  10360. (lambda (file)
  10361. (set-buffer (find-file-noselect file))
  10362. (org--tag-add-to-alist
  10363. (org-get-buffer-tags)
  10364. (mapcar (lambda (x)
  10365. (and (stringp (car-safe x))
  10366. (list (car-safe x))))
  10367. org-current-tag-alist)))
  10368. (if (car-safe files) files
  10369. (org-agenda-files))))))))
  10370. (defun org-make-tags-matcher (match)
  10371. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10372. Returns a cons of the selection string MATCH and a function
  10373. implementing the matcher.
  10374. The matcher is to be called at an Org entry, with point on the
  10375. headline, and returns non-nil if the entry matches the selection
  10376. string MATCH. It must be called with three arguments: the TODO
  10377. keyword at the entry (or nil if none), the list of all tags at
  10378. the entry including inherited ones and the reduced level of the
  10379. headline. Additionally, the category of the entry, if any, must
  10380. be specified as the text property `org-category' on the headline.
  10381. This function sets the variable `org--matcher-tags-todo-only' to
  10382. a non-nil value if the matcher restricts matching to TODO
  10383. entries, otherwise it is not touched.
  10384. See also `org-scan-tags'."
  10385. (unless match
  10386. ;; Get a new match request, with completion against the global
  10387. ;; tags table and the local tags in current buffer.
  10388. (let ((org-last-tags-completion-table
  10389. (org--tag-add-to-alist
  10390. (org-get-buffer-tags)
  10391. (org-global-tags-completion-table))))
  10392. (setq match
  10393. (completing-read
  10394. "Match: "
  10395. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10396. (let ((match0 match)
  10397. (re (concat
  10398. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10399. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10400. "\\([<>=]\\{1,2\\}\\)"
  10401. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10402. "\\|" org-tag-re "\\)"))
  10403. (start 0)
  10404. tagsmatch todomatch tagsmatcher todomatcher)
  10405. ;; Expand group tags.
  10406. (setq match (org-tags-expand match))
  10407. ;; Check if there is a TODO part of this match, which would be the
  10408. ;; part after a "/". To make sure that this slash is not part of
  10409. ;; a property value to be matched against, we also check that
  10410. ;; there is no / after that slash. First, find the last slash.
  10411. (let ((s 0))
  10412. (while (string-match "/+" match s)
  10413. (setq start (match-beginning 0))
  10414. (setq s (match-end 0))))
  10415. (if (and (string-match "/+" match start)
  10416. (not (string-match-p "\"" match start)))
  10417. ;; Match contains also a TODO-matching request.
  10418. (progn
  10419. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10420. (setq todomatch (substring match (match-end 0)))
  10421. (when (string-prefix-p "!" todomatch)
  10422. (setq org--matcher-tags-todo-only t)
  10423. (setq todomatch (substring todomatch 1)))
  10424. (when (string-match "\\`\\s-*\\'" todomatch)
  10425. (setq todomatch nil)))
  10426. ;; Only matching tags.
  10427. (setq tagsmatch match)
  10428. (setq todomatch nil))
  10429. ;; Make the tags matcher.
  10430. (when (org-string-nw-p tagsmatch)
  10431. (let ((orlist nil)
  10432. (orterms (org-split-string tagsmatch "|"))
  10433. term)
  10434. (while (setq term (pop orterms))
  10435. (while (and (equal (substring term -1) "\\") orterms)
  10436. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10437. (while (string-match re term)
  10438. (let* ((rest (substring term (match-end 0)))
  10439. (minus (and (match-end 1)
  10440. (equal (match-string 1 term) "-")))
  10441. (tag (save-match-data
  10442. (replace-regexp-in-string
  10443. "\\\\-" "-" (match-string 2 term))))
  10444. (regexp (eq (string-to-char tag) ?{))
  10445. (levelp (match-end 4))
  10446. (propp (match-end 5))
  10447. (mm
  10448. (cond
  10449. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10450. (levelp
  10451. `(,(org-op-to-function (match-string 3 term))
  10452. level
  10453. ,(string-to-number (match-string 4 term))))
  10454. (propp
  10455. (let* ((gv (pcase (upcase (match-string 5 term))
  10456. ("CATEGORY"
  10457. '(get-text-property (point) 'org-category))
  10458. ("TODO" 'todo)
  10459. (p `(org-cached-entry-get nil ,p))))
  10460. (pv (match-string 7 term))
  10461. (regexp (eq (string-to-char pv) ?{))
  10462. (strp (eq (string-to-char pv) ?\"))
  10463. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10464. (po (org-op-to-function (match-string 6 term)
  10465. (if timep 'time strp))))
  10466. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10467. (when timep (setq pv (org-matcher-time pv)))
  10468. (cond ((and regexp (eq po '/=))
  10469. `(not (string-match ,pv (or ,gv ""))))
  10470. (regexp `(string-match ,pv (or ,gv "")))
  10471. (strp `(,po (or ,gv "") ,pv))
  10472. (t
  10473. `(,po
  10474. (string-to-number (or ,gv ""))
  10475. ,(string-to-number pv))))))
  10476. (t `(member ,tag tags-list)))))
  10477. (push (if minus `(not ,mm) mm) tagsmatcher)
  10478. (setq term rest)))
  10479. (push `(and ,@tagsmatcher) orlist)
  10480. (setq tagsmatcher nil))
  10481. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10482. ;; Make the TODO matcher.
  10483. (when (org-string-nw-p todomatch)
  10484. (let ((orlist nil))
  10485. (dolist (term (org-split-string todomatch "|"))
  10486. (while (string-match re term)
  10487. (let* ((minus (and (match-end 1)
  10488. (equal (match-string 1 term) "-")))
  10489. (kwd (match-string 2 term))
  10490. (regexp (eq (string-to-char kwd) ?{))
  10491. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10492. `(equal todo ,kwd))))
  10493. (push (if minus `(not ,mm) mm) todomatcher))
  10494. (setq term (substring term (match-end 0))))
  10495. (push (if (> (length todomatcher) 1)
  10496. (cons 'and todomatcher)
  10497. (car todomatcher))
  10498. orlist)
  10499. (setq todomatcher nil))
  10500. (setq todomatcher (cons 'or orlist))))
  10501. ;; Return the string and function of the matcher. If no
  10502. ;; tags-specific or todo-specific matcher exists, match
  10503. ;; everything.
  10504. (let ((matcher (if (and tagsmatcher todomatcher)
  10505. `(and ,tagsmatcher ,todomatcher)
  10506. (or tagsmatcher todomatcher t))))
  10507. (when org--matcher-tags-todo-only
  10508. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10509. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10510. (defun org--tags-expand-group (group tag-groups expanded)
  10511. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10512. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10513. an accumulator used in recursive calls."
  10514. (dolist (tag group)
  10515. (unless (member tag expanded)
  10516. (let ((group (assoc tag tag-groups)))
  10517. (push tag expanded)
  10518. (when group
  10519. (setq expanded
  10520. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10521. expanded)
  10522. (defun org-tags-expand (match &optional single-as-list downcased)
  10523. "Expand group tags in MATCH.
  10524. This replaces every group tag in MATCH with a regexp tag search.
  10525. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10526. will be replaced like this:
  10527. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10528. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10529. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10530. Replacing by a regexp preserves the structure of the match.
  10531. E.g., this expansion
  10532. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10533. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10534. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10535. A group tag in MATCH can contain regular expressions of its own.
  10536. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10537. will be replaced like this:
  10538. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10539. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10540. assumed to be a single group tag, and the function will return
  10541. the list of tags in this group.
  10542. When DOWNCASED is non-nil, expand downcased TAGS."
  10543. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10544. (let ((tag-groups
  10545. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10546. (if (not downcased) g
  10547. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10548. (cond
  10549. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10550. (org-group-tags
  10551. (let* ((case-fold-search t)
  10552. (tag-syntax org-mode-syntax-table)
  10553. (group-keys (mapcar #'car tag-groups))
  10554. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10555. (return-match (if downcased (downcase match) match)))
  10556. ;; Mark regexp-expressions in the match-expression so that we
  10557. ;; do not replace them later on.
  10558. (let ((s 0))
  10559. (while (string-match "{.+?}" return-match s)
  10560. (setq s (match-end 0))
  10561. (add-text-properties
  10562. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10563. ;; @ and _ are allowed as word-components in tags.
  10564. (modify-syntax-entry ?@ "w" tag-syntax)
  10565. (modify-syntax-entry ?_ "w" tag-syntax)
  10566. ;; For each tag token found in MATCH, compute a regexp and it
  10567. (with-syntax-table tag-syntax
  10568. (replace-regexp-in-string
  10569. key-regexp
  10570. (lambda (m)
  10571. (if (get-text-property (match-beginning 2) 'regexp m)
  10572. m ;regexp tag: ignore
  10573. (let* ((operator (match-string 1 m))
  10574. (tag-token (let ((tag (match-string 2 m)))
  10575. (list (if downcased (downcase tag) tag))))
  10576. regexp-tags regular-tags)
  10577. ;; Partition tags between regexp and regular tags.
  10578. ;; Remove curly bracket syntax from regexp tags.
  10579. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10580. (save-match-data
  10581. (if (string-match "{\\(.+?\\)}" tag)
  10582. (push (match-string 1 tag) regexp-tags)
  10583. (push tag regular-tags))))
  10584. ;; Replace tag token by the appropriate regexp.
  10585. ;; Regular tags need to be regexp-quoted, whereas
  10586. ;; regexp-tags are inserted as-is.
  10587. (let ((regular (regexp-opt regular-tags))
  10588. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10589. (concat operator
  10590. (cond
  10591. ((null regular-tags) (format "{%s}" regexp))
  10592. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10593. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10594. return-match
  10595. t t))))
  10596. (t match))))
  10597. (defun org-op-to-function (op &optional stringp)
  10598. "Turn an operator into the appropriate function."
  10599. (setq op
  10600. (cond
  10601. ((equal op "<" ) '(< org-string< org-time<))
  10602. ((equal op ">" ) '(> org-string> org-time>))
  10603. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10604. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10605. ((member op '("=" "==")) '(= string= org-time=))
  10606. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10607. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10608. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10609. (defvar org-tags-overlay (make-overlay 1 1))
  10610. (delete-overlay org-tags-overlay)
  10611. (defun org-add-prop-inherited (s)
  10612. (add-text-properties 0 (length s) '(inherited t) s)
  10613. s)
  10614. (defun org-toggle-tag (tag &optional onoff)
  10615. "Toggle the tag TAG for the current line.
  10616. If ONOFF is `on' or `off', don't toggle but set to this state."
  10617. (save-excursion
  10618. (org-back-to-heading t)
  10619. (let ((current
  10620. ;; Reverse the tags list so any new tag is appended to the
  10621. ;; current list of tags.
  10622. (nreverse (org-get-tags nil t)))
  10623. res)
  10624. (pcase onoff
  10625. (`off (setq current (delete tag current)))
  10626. ((or `on (guard (not (member tag current))))
  10627. (setq res t)
  10628. (cl-pushnew tag current :test #'equal))
  10629. (_ (setq current (delete tag current))))
  10630. (org-set-tags (nreverse current))
  10631. res)))
  10632. (defun org--align-tags-here (to-col)
  10633. "Align tags on the current headline to TO-COL.
  10634. Assume point is on a headline. Preserve point when aligning
  10635. tags."
  10636. (when (org-match-line org-tag-line-re)
  10637. (let* ((tags-start (match-beginning 1))
  10638. (blank-start (save-excursion
  10639. (goto-char tags-start)
  10640. (skip-chars-backward " \t")
  10641. (point)))
  10642. (new (max (if (>= to-col 0) to-col
  10643. (- (abs to-col) (string-width (match-string 1))))
  10644. ;; Introduce at least one space after the heading
  10645. ;; or the stars.
  10646. (save-excursion
  10647. (goto-char blank-start)
  10648. (1+ (current-column)))))
  10649. (current
  10650. (save-excursion (goto-char tags-start) (current-column)))
  10651. (origin (point-marker))
  10652. (column (current-column))
  10653. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10654. (when (/= new current)
  10655. (delete-region blank-start tags-start)
  10656. (goto-char blank-start)
  10657. (let ((indent-tabs-mode nil)) (indent-to new))
  10658. ;; Try to move back to original position. If point was in the
  10659. ;; blanks before the tags, ORIGIN marker is of no use because
  10660. ;; it now points to BLANK-START. Use COLUMN instead.
  10661. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10662. (defun org-set-tags-command (&optional arg)
  10663. "Set the tags for the current visible entry.
  10664. When called with `\\[universal-argument]' prefix argument ARG, \
  10665. realign all tags
  10666. in the current buffer.
  10667. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10668. unconditionally do not
  10669. offer the fast tag selection interface.
  10670. If a region is active, set tags in the region according to the
  10671. setting of `org-loop-over-headlines-in-active-region'.
  10672. This function is for interactive use only;
  10673. in Lisp code use `org-set-tags' instead."
  10674. (interactive "P")
  10675. (let ((org-use-fast-tag-selection
  10676. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10677. (cond
  10678. ((equal '(4) arg) (org-align-tags t))
  10679. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10680. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10681. (org-map-entries
  10682. #'org-set-tags-command
  10683. nil
  10684. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10685. 'region-start-level
  10686. 'region)
  10687. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10688. (t
  10689. (save-excursion
  10690. (org-back-to-heading)
  10691. (let* ((all-tags (org-get-tags))
  10692. (table (setq org-last-tags-completion-table
  10693. (org--tag-add-to-alist
  10694. (and org-complete-tags-always-offer-all-agenda-tags
  10695. (org-global-tags-completion-table
  10696. (org-agenda-files)))
  10697. (or org-current-tag-alist (org-get-buffer-tags)))))
  10698. (current-tags
  10699. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10700. all-tags))
  10701. (inherited-tags
  10702. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10703. all-tags))
  10704. (tags
  10705. (replace-regexp-in-string
  10706. ;; Ignore all forbidden characters in tags.
  10707. "[^[:alnum:]_@#%]+" ":"
  10708. (if (or (eq t org-use-fast-tag-selection)
  10709. (and org-use-fast-tag-selection
  10710. (delq nil (mapcar #'cdr table))))
  10711. (org-fast-tag-selection
  10712. current-tags
  10713. inherited-tags
  10714. table
  10715. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10716. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10717. (org-trim (completing-read
  10718. "Tags: "
  10719. #'org-tags-completion-function
  10720. nil nil (org-make-tag-string current-tags)
  10721. 'org-tags-history)))))))
  10722. (org-set-tags tags)))))
  10723. ;; `save-excursion' may not replace the point at the right
  10724. ;; position.
  10725. (when (save-excursion (skip-chars-backward "*") (bolp))
  10726. (forward-char))))
  10727. (defun org-align-tags (&optional all)
  10728. "Align tags in current entry.
  10729. When optional argument ALL is non-nil, align all tags in the
  10730. visible part of the buffer."
  10731. (let ((get-indent-column
  10732. (lambda ()
  10733. (let ((offset (if (bound-and-true-p org-indent-mode)
  10734. (* (1- org-indent-indentation-per-level)
  10735. (1- (org-current-level)))
  10736. 0)))
  10737. (+ org-tags-column
  10738. (if (> org-tags-column 0) (- offset) offset))))))
  10739. (if (and (not all) (org-at-heading-p))
  10740. (org--align-tags-here (funcall get-indent-column))
  10741. (save-excursion
  10742. (if all
  10743. (progn
  10744. (goto-char (point-min))
  10745. (while (re-search-forward org-tag-line-re nil t)
  10746. (org--align-tags-here (funcall get-indent-column))))
  10747. (org-back-to-heading t)
  10748. (org--align-tags-here (funcall get-indent-column)))))))
  10749. (defun org-set-tags (tags)
  10750. "Set the tags of the current entry to TAGS, replacing current tags.
  10751. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10752. If TAGS is nil or the empty string, all tags are removed.
  10753. This function assumes point is on a headline."
  10754. (org-with-wide-buffer
  10755. (let ((tags (pcase tags
  10756. ((pred listp) tags)
  10757. ((pred stringp) (split-string (org-trim tags) ":" t))
  10758. (_ (error "Invalid tag specification: %S" tags))))
  10759. (old-tags (org-get-tags nil t))
  10760. (tags-change? nil))
  10761. (when (functionp org-tags-sort-function)
  10762. (setq tags (sort tags org-tags-sort-function)))
  10763. (setq tags-change? (not (equal tags old-tags)))
  10764. (when tags-change?
  10765. ;; Delete previous tags and any trailing white space.
  10766. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10767. (line-end-position)))
  10768. (skip-chars-backward " \t")
  10769. (delete-region (point) (line-end-position))
  10770. ;; Deleting white spaces may break an otherwise empty headline.
  10771. ;; Re-introduce one space in this case.
  10772. (unless (org-at-heading-p) (insert " "))
  10773. (when tags
  10774. (save-excursion (insert " " (org-make-tag-string tags)))
  10775. ;; When text is being inserted on an invisible region
  10776. ;; boundary, it can be inadvertently sucked into
  10777. ;; invisibility.
  10778. (unless (org-invisible-p (line-beginning-position))
  10779. (org-flag-region (point) (line-end-position) nil 'outline))))
  10780. ;; Align tags, if any.
  10781. (when tags (org-align-tags))
  10782. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10783. (defun org-change-tag-in-region (beg end tag off)
  10784. "Add or remove TAG for each entry in the region.
  10785. This works in the agenda, and also in an Org buffer."
  10786. (interactive
  10787. (list (region-beginning) (region-end)
  10788. (let ((org-last-tags-completion-table
  10789. (if (derived-mode-p 'org-mode)
  10790. (org--tag-add-to-alist
  10791. (org-get-buffer-tags)
  10792. (org-global-tags-completion-table))
  10793. (org-global-tags-completion-table))))
  10794. (completing-read
  10795. "Tag: " 'org-tags-completion-function nil nil nil
  10796. 'org-tags-history))
  10797. (progn
  10798. (message "[s]et or [r]emove? ")
  10799. (equal (read-char-exclusive) ?r))))
  10800. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10801. (let ((agendap (equal major-mode 'org-agenda-mode))
  10802. l1 l2 m buf pos newhead (cnt 0))
  10803. (goto-char end)
  10804. (setq l2 (1- (org-current-line)))
  10805. (goto-char beg)
  10806. (setq l1 (org-current-line))
  10807. (cl-loop for l from l1 to l2 do
  10808. (org-goto-line l)
  10809. (setq m (get-text-property (point) 'org-hd-marker))
  10810. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10811. (and agendap m))
  10812. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10813. pos (if agendap m (point)))
  10814. (with-current-buffer buf
  10815. (save-excursion
  10816. (save-restriction
  10817. (goto-char pos)
  10818. (setq cnt (1+ cnt))
  10819. (org-toggle-tag tag (if off 'off 'on))
  10820. (setq newhead (org-get-heading)))))
  10821. (and agendap (org-agenda-change-all-lines newhead m))))
  10822. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10823. (defun org-tags-completion-function (string _predicate &optional flag)
  10824. "Complete tag STRING.
  10825. FLAG specifies the type of completion operation to perform. This
  10826. function is passed as a collection function to `completing-read',
  10827. which see."
  10828. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10829. (confirm (lambda (x) (stringp (car x))))
  10830. (prefix ""))
  10831. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10832. (setq prefix (match-string 1 string))
  10833. (setq string (match-string 2 string)))
  10834. (pcase flag
  10835. (`t (all-completions string org-last-tags-completion-table confirm))
  10836. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10837. (`nil
  10838. (pcase (try-completion string org-last-tags-completion-table confirm)
  10839. ((and completion (pred stringp))
  10840. (concat prefix
  10841. completion
  10842. (if (and org-add-colon-after-tag-completion
  10843. (assoc completion org-last-tags-completion-table))
  10844. ":"
  10845. "")))
  10846. (completion completion)))
  10847. (_ nil))))
  10848. (defun org-fast-tag-insert (kwd tags face &optional end)
  10849. "Insert KWD, and the TAGS, the latter with face FACE.
  10850. Also insert END."
  10851. (insert (format "%-12s" (concat kwd ":"))
  10852. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10853. (or end "")))
  10854. (defun org-fast-tag-show-exit (flag)
  10855. (save-excursion
  10856. (org-goto-line 3)
  10857. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10858. (replace-match ""))
  10859. (when flag
  10860. (end-of-line 1)
  10861. (org-move-to-column (- (window-width) 19) t)
  10862. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10863. (defun org-set-current-tags-overlay (current prefix)
  10864. "Add an overlay to CURRENT tag with PREFIX."
  10865. (let ((s (org-make-tag-string current)))
  10866. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10867. (org-overlay-display org-tags-overlay (concat prefix s))))
  10868. (defvar org-last-tag-selection-key nil)
  10869. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10870. "Fast tag selection with single keys.
  10871. CURRENT is the current list of tags in the headline, INHERITED is the
  10872. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10873. possibly with grouping information. TODO-TABLE is a similar table with
  10874. TODO keywords, should these have keys assigned to them.
  10875. If the keys are nil, a-z are automatically assigned.
  10876. Returns the new tags string, or nil to not change the current settings."
  10877. (let* ((fulltable (append table todo-table))
  10878. (maxlen (if (null fulltable) 0
  10879. (apply #'max
  10880. (mapcar (lambda (x)
  10881. (if (stringp (car x)) (string-width (car x))
  10882. 0))
  10883. fulltable))))
  10884. (buf (current-buffer))
  10885. (expert (eq org-fast-tag-selection-single-key 'expert))
  10886. (buffer-tags nil)
  10887. (fwidth (+ maxlen 3 1 3))
  10888. (ncol (/ (- (window-width) 4) fwidth))
  10889. (i-face 'org-done)
  10890. (c-face 'org-todo)
  10891. tg cnt e c char c1 c2 ntable tbl rtn
  10892. ov-start ov-end ov-prefix
  10893. (exit-after-next org-fast-tag-selection-single-key)
  10894. (done-keywords org-done-keywords)
  10895. groups ingroup intaggroup)
  10896. (save-excursion
  10897. (beginning-of-line)
  10898. (if (looking-at org-tag-line-re)
  10899. (setq ov-start (match-beginning 1)
  10900. ov-end (match-end 1)
  10901. ov-prefix "")
  10902. (setq ov-start (1- (point-at-eol))
  10903. ov-end (1+ ov-start))
  10904. (skip-chars-forward "^\n\r")
  10905. (setq ov-prefix
  10906. (concat
  10907. (buffer-substring (1- (point)) (point))
  10908. (if (> (current-column) org-tags-column)
  10909. " "
  10910. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10911. (move-overlay org-tags-overlay ov-start ov-end)
  10912. (save-excursion
  10913. (save-window-excursion
  10914. (if expert
  10915. (set-buffer (get-buffer-create " *Org tags*"))
  10916. (delete-other-windows)
  10917. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10918. (org-switch-to-buffer-other-window " *Org tags*"))
  10919. (erase-buffer)
  10920. (setq-local org-done-keywords done-keywords)
  10921. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10922. (org-fast-tag-insert "Current" current c-face "\n\n")
  10923. (org-fast-tag-show-exit exit-after-next)
  10924. (org-set-current-tags-overlay current ov-prefix)
  10925. (setq tbl fulltable char ?a cnt 0)
  10926. (while (setq e (pop tbl))
  10927. (cond
  10928. ((eq (car e) :startgroup)
  10929. (push '() groups) (setq ingroup t)
  10930. (unless (zerop cnt)
  10931. (setq cnt 0)
  10932. (insert "\n"))
  10933. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10934. ((eq (car e) :endgroup)
  10935. (setq ingroup nil cnt 0)
  10936. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10937. ((eq (car e) :startgrouptag)
  10938. (setq intaggroup t)
  10939. (unless (zerop cnt)
  10940. (setq cnt 0)
  10941. (insert "\n"))
  10942. (insert "[ "))
  10943. ((eq (car e) :endgrouptag)
  10944. (setq intaggroup nil cnt 0)
  10945. (insert "]\n"))
  10946. ((equal e '(:newline))
  10947. (unless (zerop cnt)
  10948. (setq cnt 0)
  10949. (insert "\n")
  10950. (setq e (car tbl))
  10951. (while (equal (car tbl) '(:newline))
  10952. (insert "\n")
  10953. (setq tbl (cdr tbl)))))
  10954. ((equal e '(:grouptags)) (insert " : "))
  10955. (t
  10956. (setq tg (copy-sequence (car e)) c2 nil)
  10957. (if (cdr e)
  10958. (setq c (cdr e))
  10959. ;; automatically assign a character.
  10960. (setq c1 (string-to-char
  10961. (downcase (substring
  10962. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10963. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10964. (while (or (rassoc char ntable) (rassoc char table))
  10965. (setq char (1+ char)))
  10966. (setq c2 c1))
  10967. (setq c (or c2 char)))
  10968. (when ingroup (push tg (car groups)))
  10969. (setq tg (org-add-props tg nil 'face
  10970. (cond
  10971. ((not (assoc tg table))
  10972. (org-get-todo-face tg))
  10973. ((member tg current) c-face)
  10974. ((member tg inherited) i-face))))
  10975. (when (equal (caar tbl) :grouptags)
  10976. (org-add-props tg nil 'face 'org-tag-group))
  10977. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10978. (insert "[" c "] " tg (make-string
  10979. (- fwidth 4 (length tg)) ?\ ))
  10980. (push (cons tg c) ntable)
  10981. (when (= (cl-incf cnt) ncol)
  10982. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10983. (insert "\n")
  10984. (when (or ingroup intaggroup) (insert " ")))
  10985. (setq cnt 0)))))
  10986. (setq ntable (nreverse ntable))
  10987. (insert "\n")
  10988. (goto-char (point-min))
  10989. (unless expert (org-fit-window-to-buffer))
  10990. (setq rtn
  10991. (catch 'exit
  10992. (while t
  10993. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10994. (if (not groups) "no " "")
  10995. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10996. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10997. (setq org-last-tag-selection-key c)
  10998. (cond
  10999. ((= c ?\r) (throw 'exit t))
  11000. ((= c ?!)
  11001. (setq groups (not groups))
  11002. (goto-char (point-min))
  11003. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11004. ((= c ?\C-c)
  11005. (if (not expert)
  11006. (org-fast-tag-show-exit
  11007. (setq exit-after-next (not exit-after-next)))
  11008. (setq expert nil)
  11009. (delete-other-windows)
  11010. (set-window-buffer (split-window-vertically) " *Org tags*")
  11011. (org-switch-to-buffer-other-window " *Org tags*")
  11012. (org-fit-window-to-buffer)))
  11013. ((or (= c ?\C-g)
  11014. (and (= c ?q) (not (rassoc c ntable))))
  11015. (delete-overlay org-tags-overlay)
  11016. (setq quit-flag t))
  11017. ((= c ?\ )
  11018. (setq current nil)
  11019. (when exit-after-next (setq exit-after-next 'now)))
  11020. ((= c ?\t)
  11021. (condition-case nil
  11022. (setq tg (completing-read
  11023. "Tag: "
  11024. (or buffer-tags
  11025. (with-current-buffer buf
  11026. (setq buffer-tags
  11027. (org-get-buffer-tags))))))
  11028. (quit (setq tg "")))
  11029. (when (string-match "\\S-" tg)
  11030. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11031. (if (member tg current)
  11032. (setq current (delete tg current))
  11033. (push tg current)))
  11034. (when exit-after-next (setq exit-after-next 'now)))
  11035. ((setq e (rassoc c todo-table) tg (car e))
  11036. (with-current-buffer buf
  11037. (save-excursion (org-todo tg)))
  11038. (when exit-after-next (setq exit-after-next 'now)))
  11039. ((setq e (rassoc c ntable) tg (car e))
  11040. (if (member tg current)
  11041. (setq current (delete tg current))
  11042. (cl-loop for g in groups do
  11043. (when (member tg g)
  11044. (dolist (x g) (setq current (delete x current)))))
  11045. (push tg current))
  11046. (when exit-after-next (setq exit-after-next 'now))))
  11047. ;; Create a sorted list
  11048. (setq current
  11049. (sort current
  11050. (lambda (a b)
  11051. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11052. (when (eq exit-after-next 'now) (throw 'exit t))
  11053. (goto-char (point-min))
  11054. (beginning-of-line 2)
  11055. (delete-region (point) (point-at-eol))
  11056. (org-fast-tag-insert "Current" current c-face)
  11057. (org-set-current-tags-overlay current ov-prefix)
  11058. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11059. (while (re-search-forward tag-re nil t)
  11060. (let ((tag (match-string 1)))
  11061. (add-text-properties
  11062. (match-beginning 1) (match-end 1)
  11063. (list 'face
  11064. (cond
  11065. ((member tag current) c-face)
  11066. ((member tag inherited) i-face)
  11067. (t (get-text-property (match-beginning 1) '
  11068. face))))))))
  11069. (goto-char (point-min)))))
  11070. (delete-overlay org-tags-overlay)
  11071. (if rtn
  11072. (mapconcat 'identity current ":")
  11073. nil)))))
  11074. (defun org-make-tag-string (tags)
  11075. "Return string associated to TAGS.
  11076. TAGS is a list of strings."
  11077. (if (null tags) ""
  11078. (format ":%s:" (mapconcat #'identity tags ":"))))
  11079. (defun org--get-local-tags ()
  11080. "Return list of tags for the current headline.
  11081. Assume point is at the beginning of the headline."
  11082. (and (looking-at org-tag-line-re)
  11083. (split-string (match-string-no-properties 2) ":" t)))
  11084. (defun org-get-tags (&optional pos local)
  11085. "Get the list of tags specified in the current headline.
  11086. When argument POS is non-nil, retrieve tags for headline at POS.
  11087. According to `org-use-tag-inheritance', tags may be inherited
  11088. from parent headlines, and from the whole document, through
  11089. `org-file-tags'. In this case, the returned list of tags
  11090. contains tags in this order: file tags, tags inherited from
  11091. parent headlines, local tags.
  11092. However, when optional argument LOCAL is non-nil, only return
  11093. tags specified at the headline.
  11094. Inherited tags have the `inherited' text property."
  11095. (if (and org-trust-scanner-tags
  11096. (or (not pos) (eq pos (point)))
  11097. (not local))
  11098. org-scanner-tags
  11099. (org-with-point-at (or pos (point))
  11100. (unless (org-before-first-heading-p)
  11101. (org-back-to-heading t)
  11102. (let ((ltags (org--get-local-tags)) itags)
  11103. (if (or local (not org-use-tag-inheritance)) ltags
  11104. (while (org-up-heading-safe)
  11105. (setq itags (append (mapcar #'org-add-prop-inherited
  11106. (org--get-local-tags))
  11107. itags)))
  11108. (setq itags (append org-file-tags itags))
  11109. (delete-dups
  11110. (append (org-remove-uninherited-tags itags) ltags))))))))
  11111. (defun org-get-buffer-tags ()
  11112. "Get a table of all tags used in the buffer, for completion."
  11113. (org-with-point-at 1
  11114. (let (tags)
  11115. (while (re-search-forward org-tag-line-re nil t)
  11116. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11117. tags)))
  11118. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11119. ;;;; The mapping API
  11120. (defvar org-agenda-skip-comment-trees)
  11121. (defvar org-agenda-skip-function)
  11122. (defun org-map-entries (func &optional match scope &rest skip)
  11123. "Call FUNC at each headline selected by MATCH in SCOPE.
  11124. FUNC is a function or a lisp form. The function will be called without
  11125. arguments, with the cursor positioned at the beginning of the headline.
  11126. The return values of all calls to the function will be collected and
  11127. returned as a list.
  11128. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11129. does not need to preserve point. After evaluation, the cursor will be
  11130. moved to the end of the line (presumably of the headline of the
  11131. processed entry) and search continues from there. Under some
  11132. circumstances, this may not produce the wanted results. For example,
  11133. if you have removed (e.g. archived) the current (sub)tree it could
  11134. mean that the next entry will be skipped entirely. In such cases, you
  11135. can specify the position from where search should continue by making
  11136. FUNC set the variable `org-map-continue-from' to the desired buffer
  11137. position.
  11138. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11139. Only headlines that are matched by this query will be considered during
  11140. the iteration. When MATCH is nil or t, all headlines will be
  11141. visited by the iteration.
  11142. SCOPE determines the scope of this command. It can be any of:
  11143. nil The current buffer, respecting the restriction if any
  11144. tree The subtree started with the entry at point
  11145. region The entries within the active region, if any
  11146. region-start-level
  11147. The entries within the active region, but only those at
  11148. the same level than the first one.
  11149. file The current buffer, without restriction
  11150. file-with-archives
  11151. The current buffer, and any archives associated with it
  11152. agenda All agenda files
  11153. agenda-with-archives
  11154. All agenda files with any archive files associated with them
  11155. \(file1 file2 ...)
  11156. If this is a list, all files in the list will be scanned
  11157. The remaining args are treated as settings for the skipping facilities of
  11158. the scanner. The following items can be given here:
  11159. archive skip trees with the archive tag
  11160. comment skip trees with the COMMENT keyword
  11161. function or Emacs Lisp form:
  11162. will be used as value for `org-agenda-skip-function', so
  11163. whenever the function returns a position, FUNC will not be
  11164. called for that entry and search will continue from the
  11165. position returned
  11166. If your function needs to retrieve the tags including inherited tags
  11167. at the *current* entry, you can use the value of the variable
  11168. `org-scanner-tags' which will be much faster than getting the value
  11169. with `org-get-tags'. If your function gets properties with
  11170. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11171. to t around the call to `org-entry-properties' to get the same speedup.
  11172. Note that if your function moves around to retrieve tags and properties at
  11173. a *different* entry, you cannot use these techniques."
  11174. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11175. (not (org-region-active-p)))
  11176. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11177. (org-agenda-skip-archived-trees (memq 'archive skip))
  11178. (org-agenda-skip-comment-trees (memq 'comment skip))
  11179. (org-agenda-skip-function
  11180. (car (org-delete-all '(comment archive) skip)))
  11181. (org-tags-match-list-sublevels t)
  11182. (start-level (eq scope 'region-start-level))
  11183. matcher res
  11184. org-todo-keywords-for-agenda
  11185. org-done-keywords-for-agenda
  11186. org-todo-keyword-alist-for-agenda
  11187. org-tag-alist-for-agenda
  11188. org--matcher-tags-todo-only)
  11189. (cond
  11190. ((eq match t) (setq matcher t))
  11191. ((eq match nil) (setq matcher t))
  11192. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11193. (save-excursion
  11194. (save-restriction
  11195. (cond ((eq scope 'tree)
  11196. (org-back-to-heading t)
  11197. (org-narrow-to-subtree)
  11198. (setq scope nil))
  11199. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11200. (org-region-active-p))
  11201. ;; If needed, set start-level to a string like "2"
  11202. (when start-level
  11203. (save-excursion
  11204. (goto-char (region-beginning))
  11205. (unless (org-at-heading-p) (outline-next-heading))
  11206. (setq start-level (org-current-level))))
  11207. (narrow-to-region (region-beginning)
  11208. (save-excursion
  11209. (goto-char (region-end))
  11210. (unless (and (bolp) (org-at-heading-p))
  11211. (outline-next-heading))
  11212. (point)))
  11213. (setq scope nil)))
  11214. (if (not scope)
  11215. (progn
  11216. (org-agenda-prepare-buffers
  11217. (and buffer-file-name (list buffer-file-name)))
  11218. (setq res
  11219. (org-scan-tags
  11220. func matcher org--matcher-tags-todo-only start-level)))
  11221. ;; Get the right scope
  11222. (cond
  11223. ((and scope (listp scope) (symbolp (car scope)))
  11224. (setq scope (eval scope)))
  11225. ((eq scope 'agenda)
  11226. (setq scope (org-agenda-files t)))
  11227. ((eq scope 'agenda-with-archives)
  11228. (setq scope (org-agenda-files t))
  11229. (setq scope (org-add-archive-files scope)))
  11230. ((eq scope 'file)
  11231. (setq scope (and buffer-file-name (list buffer-file-name))))
  11232. ((eq scope 'file-with-archives)
  11233. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11234. (org-agenda-prepare-buffers scope)
  11235. (dolist (file scope)
  11236. (with-current-buffer (org-find-base-buffer-visiting file)
  11237. (org-with-wide-buffer
  11238. (goto-char (point-min))
  11239. (setq res
  11240. (append
  11241. res
  11242. (org-scan-tags
  11243. func matcher org--matcher-tags-todo-only)))))))))
  11244. res)))
  11245. ;;; Properties API
  11246. (defconst org-special-properties
  11247. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11248. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11249. "The special properties valid in Org mode.
  11250. These are properties that are not defined in the property drawer,
  11251. but in some other way.")
  11252. (defconst org-default-properties
  11253. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11254. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11255. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11256. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11257. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11258. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11259. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11260. "Some properties that are used by Org mode for various purposes.
  11261. Being in this list makes sure that they are offered for completion.")
  11262. (defun org--valid-property-p (property)
  11263. "Non-nil when string PROPERTY is a valid property name."
  11264. (not
  11265. (or (equal property "")
  11266. (string-match-p "\\s-" property))))
  11267. (defun org--update-property-plist (key val props)
  11268. "Associate KEY to VAL in alist PROPS.
  11269. Modifications are made by side-effect. Return new alist."
  11270. (let* ((appending (string= (substring key -1) "+"))
  11271. (key (if appending (substring key 0 -1) key))
  11272. (old (assoc-string key props t)))
  11273. (if (not old) (cons (cons key val) props)
  11274. (setcdr old (if appending (concat (cdr old) " " val) val))
  11275. props)))
  11276. (defun org-get-property-block (&optional beg force)
  11277. "Return the (beg . end) range of the body of the property drawer.
  11278. BEG is the beginning of the current subtree or the beginning of
  11279. the document if before the first headline. If it is not given,
  11280. it will be found. If the drawer does not exist, create it if
  11281. FORCE is non-nil, or return nil."
  11282. (org-with-wide-buffer
  11283. (let ((beg (cond (beg (goto-char beg))
  11284. ((or (not (featurep 'org-inlinetask))
  11285. (org-inlinetask-in-task-p))
  11286. (org-back-to-heading-or-point-min t) (point))
  11287. (t (org-with-limited-levels
  11288. (org-back-to-heading-or-point-min t))
  11289. (point)))))
  11290. ;; Move point to its position according to its positional rules.
  11291. (cond ((org-before-first-heading-p)
  11292. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11293. (t (forward-line)
  11294. (when (looking-at-p org-planning-line-re) (forward-line))))
  11295. (cond ((looking-at org-property-drawer-re)
  11296. (forward-line)
  11297. (cons (point) (progn (goto-char (match-end 0))
  11298. (line-beginning-position))))
  11299. (force
  11300. (goto-char beg)
  11301. (org-insert-property-drawer)
  11302. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11303. (line-beginning-position))))
  11304. (cons pos pos)))))))
  11305. (defun org-at-property-drawer-p ()
  11306. "Non-nil when point is at the first line of a property drawer."
  11307. (org-with-wide-buffer
  11308. (beginning-of-line)
  11309. (and (looking-at org-property-start-re)
  11310. (or (bobp)
  11311. (progn
  11312. (forward-line -1)
  11313. (cond ((org-at-heading-p))
  11314. ((looking-at org-planning-line-re)
  11315. (forward-line -1)
  11316. (org-at-heading-p))
  11317. ((looking-at org-comment-regexp)
  11318. (forward-line -1)
  11319. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11320. (forward-line -1))
  11321. (looking-at org-comment-regexp))
  11322. (t nil)))))))
  11323. (defun org-at-property-p ()
  11324. "Non-nil when point is inside a property drawer.
  11325. See `org-property-re' for match data, if applicable."
  11326. (save-excursion
  11327. (beginning-of-line)
  11328. (and (looking-at org-property-re)
  11329. (let ((property-drawer (save-match-data (org-get-property-block))))
  11330. (and property-drawer
  11331. (>= (point) (car property-drawer))
  11332. (< (point) (cdr property-drawer)))))))
  11333. (defun org-property-action ()
  11334. "Do an action on properties."
  11335. (interactive)
  11336. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11337. (let ((c (read-char-exclusive)))
  11338. (cl-case c
  11339. (?s (call-interactively #'org-set-property))
  11340. (?d (call-interactively #'org-delete-property))
  11341. (?D (call-interactively #'org-delete-property-globally))
  11342. (?c (call-interactively #'org-compute-property-at-point))
  11343. (otherwise (user-error "No such property action %c" c)))))
  11344. (defun org-inc-effort ()
  11345. "Increment the value of the effort property in the current entry."
  11346. (interactive)
  11347. (org-set-effort t))
  11348. (defvar org-clock-effort) ; Defined in org-clock.el.
  11349. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11350. (defun org-set-effort (&optional increment value)
  11351. "Set the effort property of the current entry.
  11352. If INCREMENT is non-nil, set the property to the next allowed
  11353. value. Otherwise, if optional argument VALUE is provided, use
  11354. it. Eventually, prompt for the new value if none of the previous
  11355. variables is set."
  11356. (interactive "P")
  11357. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11358. (current (org-entry-get nil org-effort-property))
  11359. (value
  11360. (cond
  11361. (increment
  11362. (unless allowed (user-error "Allowed effort values are not set"))
  11363. (or (cl-caadr (member (list current) allowed))
  11364. (user-error "Unknown value %S among allowed values" current)))
  11365. (value
  11366. (if (stringp value) value
  11367. (error "Invalid effort value: %S" value)))
  11368. (t
  11369. (let ((must-match
  11370. (and allowed
  11371. (not (get-text-property 0 'org-unrestricted
  11372. (caar allowed))))))
  11373. (completing-read "Effort: " allowed nil must-match))))))
  11374. ;; Test whether the value can be interpreted as a duration before
  11375. ;; inserting it in the buffer:
  11376. (org-duration-to-minutes value)
  11377. ;; Maybe update the effort value:
  11378. (unless (equal current value)
  11379. (org-entry-put nil org-effort-property value))
  11380. (org-refresh-property '((effort . identity)
  11381. (effort-minutes . org-duration-to-minutes))
  11382. value)
  11383. (when (equal (org-get-heading t t t t)
  11384. (bound-and-true-p org-clock-current-task))
  11385. (setq org-clock-effort value)
  11386. (org-clock-update-mode-line))
  11387. (message "%s is now %s" org-effort-property value)))
  11388. (defun org-entry-properties (&optional pom which)
  11389. "Get all properties of the current entry.
  11390. When POM is a buffer position, get all properties from the entry
  11391. there instead.
  11392. This includes the TODO keyword, the tags, time strings for
  11393. deadline, scheduled, and clocking, and any additional properties
  11394. defined in the entry.
  11395. If WHICH is nil or `all', get all properties. If WHICH is
  11396. `special' or `standard', only get that subclass. If WHICH is
  11397. a string, only get that property.
  11398. Return value is an alist. Keys are properties, as upcased
  11399. strings."
  11400. (org-with-point-at pom
  11401. (when (and (derived-mode-p 'org-mode)
  11402. (org-back-to-heading-or-point-min t))
  11403. (catch 'exit
  11404. (let* ((beg (point))
  11405. (specific (and (stringp which) (upcase which)))
  11406. (which (cond ((not specific) which)
  11407. ((member specific org-special-properties) 'special)
  11408. (t 'standard)))
  11409. props)
  11410. ;; Get the special properties, like TODO and TAGS.
  11411. (when (memq which '(nil all special))
  11412. (when (or (not specific) (string= specific "CLOCKSUM"))
  11413. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11414. (when clocksum
  11415. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11416. props)))
  11417. (when specific (throw 'exit props)))
  11418. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11419. (let ((clocksumt (get-text-property (point)
  11420. :org-clock-minutes-today)))
  11421. (when clocksumt
  11422. (push (cons "CLOCKSUM_T"
  11423. (org-duration-from-minutes clocksumt))
  11424. props)))
  11425. (when specific (throw 'exit props)))
  11426. (when (or (not specific) (string= specific "ITEM"))
  11427. (let ((case-fold-search nil))
  11428. (when (looking-at org-complex-heading-regexp)
  11429. (push (cons "ITEM"
  11430. (let ((title (match-string-no-properties 4)))
  11431. (if (org-string-nw-p title)
  11432. (org-remove-tabs title)
  11433. "")))
  11434. props)))
  11435. (when specific (throw 'exit props)))
  11436. (when (or (not specific) (string= specific "TODO"))
  11437. (let ((case-fold-search nil))
  11438. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11439. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11440. (when specific (throw 'exit props)))
  11441. (when (or (not specific) (string= specific "PRIORITY"))
  11442. (push (cons "PRIORITY"
  11443. (if (looking-at org-priority-regexp)
  11444. (match-string-no-properties 2)
  11445. (char-to-string org-priority-default)))
  11446. props)
  11447. (when specific (throw 'exit props)))
  11448. (when (or (not specific) (string= specific "FILE"))
  11449. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11450. props)
  11451. (when specific (throw 'exit props)))
  11452. (when (or (not specific) (string= specific "TAGS"))
  11453. (let ((tags (org-get-tags nil t)))
  11454. (when tags
  11455. (push (cons "TAGS" (org-make-tag-string tags))
  11456. props)))
  11457. (when specific (throw 'exit props)))
  11458. (when (or (not specific) (string= specific "ALLTAGS"))
  11459. (let ((tags (org-get-tags)))
  11460. (when tags
  11461. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11462. props)))
  11463. (when specific (throw 'exit props)))
  11464. (when (or (not specific) (string= specific "BLOCKED"))
  11465. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11466. (when specific (throw 'exit props)))
  11467. (when (or (not specific)
  11468. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11469. (forward-line)
  11470. (when (looking-at-p org-planning-line-re)
  11471. (end-of-line)
  11472. (let ((bol (line-beginning-position))
  11473. ;; Backward compatibility: time keywords used to
  11474. ;; be configurable (before 8.3). Make sure we
  11475. ;; get the correct keyword.
  11476. (key-assoc `(("CLOSED" . ,org-closed-string)
  11477. ("DEADLINE" . ,org-deadline-string)
  11478. ("SCHEDULED" . ,org-scheduled-string))))
  11479. (dolist (pair (if specific (list (assoc specific key-assoc))
  11480. key-assoc))
  11481. (save-excursion
  11482. (when (search-backward (cdr pair) bol t)
  11483. (goto-char (match-end 0))
  11484. (skip-chars-forward " \t")
  11485. (and (looking-at org-ts-regexp-both)
  11486. (push (cons (car pair)
  11487. (match-string-no-properties 0))
  11488. props)))))))
  11489. (when specific (throw 'exit props)))
  11490. (when (or (not specific)
  11491. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11492. (let ((find-ts
  11493. (lambda (end ts)
  11494. ;; Fix next time-stamp before END. TS is the
  11495. ;; list of time-stamps found so far.
  11496. (let ((ts ts)
  11497. (regexp (cond
  11498. ((string= specific "TIMESTAMP")
  11499. org-ts-regexp)
  11500. ((string= specific "TIMESTAMP_IA")
  11501. org-ts-regexp-inactive)
  11502. ((assoc "TIMESTAMP_IA" ts)
  11503. org-ts-regexp)
  11504. ((assoc "TIMESTAMP" ts)
  11505. org-ts-regexp-inactive)
  11506. (t org-ts-regexp-both))))
  11507. (catch 'next
  11508. (while (re-search-forward regexp end t)
  11509. (backward-char)
  11510. (let ((object (org-element-context)))
  11511. ;; Accept to match timestamps in node
  11512. ;; properties, too.
  11513. (when (memq (org-element-type object)
  11514. '(node-property timestamp))
  11515. (let ((type
  11516. (org-element-property :type object)))
  11517. (cond
  11518. ((and (memq type '(active active-range))
  11519. (not (equal specific "TIMESTAMP_IA")))
  11520. (unless (assoc "TIMESTAMP" ts)
  11521. (push (cons "TIMESTAMP"
  11522. (org-element-property
  11523. :raw-value object))
  11524. ts)
  11525. (when specific (throw 'exit ts))))
  11526. ((and (memq type '(inactive inactive-range))
  11527. (not (string= specific "TIMESTAMP")))
  11528. (unless (assoc "TIMESTAMP_IA" ts)
  11529. (push (cons "TIMESTAMP_IA"
  11530. (org-element-property
  11531. :raw-value object))
  11532. ts)
  11533. (when specific (throw 'exit ts))))))
  11534. ;; Both timestamp types are found,
  11535. ;; move to next part.
  11536. (when (= (length ts) 2) (throw 'next ts)))))
  11537. ts)))))
  11538. (goto-char beg)
  11539. ;; First look for timestamps within headline.
  11540. (let ((ts (funcall find-ts (line-end-position) nil)))
  11541. (if (= (length ts) 2) (setq props (nconc ts props))
  11542. ;; Then find timestamps in the section, skipping
  11543. ;; planning line.
  11544. (let ((end (save-excursion (outline-next-heading))))
  11545. (forward-line)
  11546. (when (looking-at-p org-planning-line-re) (forward-line))
  11547. (setq props (nconc (funcall find-ts end ts) props))))))))
  11548. ;; Get the standard properties, like :PROP:.
  11549. (when (memq which '(nil all standard))
  11550. ;; If we are looking after a specific property, delegate
  11551. ;; to `org-entry-get', which is faster. However, make an
  11552. ;; exception for "CATEGORY", since it can be also set
  11553. ;; through keywords (i.e. #+CATEGORY).
  11554. (if (and specific (not (equal specific "CATEGORY")))
  11555. (let ((value (org-entry-get beg specific nil t)))
  11556. (throw 'exit (and value (list (cons specific value)))))
  11557. (let ((range (org-get-property-block beg)))
  11558. (when range
  11559. (let ((end (cdr range)) seen-base)
  11560. (goto-char (car range))
  11561. ;; Unlike to `org--update-property-plist', we
  11562. ;; handle the case where base values is found
  11563. ;; after its extension. We also forbid standard
  11564. ;; properties to be named as special properties.
  11565. (while (re-search-forward org-property-re end t)
  11566. (let* ((key (upcase (match-string-no-properties 2)))
  11567. (extendp (string-match-p "\\+\\'" key))
  11568. (key-base (if extendp (substring key 0 -1) key))
  11569. (value (match-string-no-properties 3)))
  11570. (cond
  11571. ((member-ignore-case key-base org-special-properties))
  11572. (extendp
  11573. (setq props
  11574. (org--update-property-plist key value props)))
  11575. ((member key seen-base))
  11576. (t (push key seen-base)
  11577. (let ((p (assoc-string key props t)))
  11578. (if p (setcdr p (concat value " " (cdr p)))
  11579. (push (cons key value) props))))))))))))
  11580. (unless (assoc "CATEGORY" props)
  11581. (push (cons "CATEGORY" (org-get-category beg)) props)
  11582. (when (string= specific "CATEGORY") (throw 'exit props)))
  11583. ;; Return value.
  11584. props)))))
  11585. (defun org--property-local-values (property literal-nil)
  11586. "Return value for PROPERTY in current entry.
  11587. Value is a list whose car is the base value for PROPERTY and cdr
  11588. a list of accumulated values. Return nil if neither is found in
  11589. the entry. Also return nil when PROPERTY is set to \"nil\",
  11590. unless LITERAL-NIL is non-nil."
  11591. (let ((range (org-get-property-block)))
  11592. (when range
  11593. (goto-char (car range))
  11594. (let* ((case-fold-search t)
  11595. (end (cdr range))
  11596. (value
  11597. ;; Base value.
  11598. (save-excursion
  11599. (let ((v (and (re-search-forward
  11600. (org-re-property property nil t) end t)
  11601. (match-string-no-properties 3))))
  11602. (list (if literal-nil v (org-not-nil v)))))))
  11603. ;; Find additional values.
  11604. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11605. (while (re-search-forward property+ end t)
  11606. (push (match-string-no-properties 3) value)))
  11607. ;; Return final values.
  11608. (and (not (equal value '(nil))) (nreverse value))))))
  11609. (defun org--property-global-or-keyword-value (property literal-nil)
  11610. "Return value for PROPERTY as defined by global properties or by keyword.
  11611. Return value is a string. Return nil if property is not set
  11612. globally or by keyword. Also return nil when PROPERTY is set to
  11613. \"nil\", unless LITERAL-NIL is non-nil."
  11614. (let ((global
  11615. (cdr (or (assoc-string property org-keyword-properties t)
  11616. (assoc-string property org-global-properties t)
  11617. (assoc-string property org-global-properties-fixed t)))))
  11618. (if literal-nil global (org-not-nil global))))
  11619. (defun org-entry-get (pom property &optional inherit literal-nil)
  11620. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11621. If INHERIT is non-nil and the entry does not have the property,
  11622. then also check higher levels of the hierarchy. If INHERIT is
  11623. the symbol `selective', use inheritance only if the setting in
  11624. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11625. If the property is present but empty, the return value is the
  11626. empty string. If the property is not present at all, nil is
  11627. returned. In any other case, return the value as a string.
  11628. Search is case-insensitive.
  11629. If LITERAL-NIL is set, return the string value \"nil\" as
  11630. a string, do not interpret it as the list atom nil. This is used
  11631. for inheritance when a \"nil\" value can supersede a non-nil
  11632. value higher up the hierarchy."
  11633. (org-with-point-at pom
  11634. (cond
  11635. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11636. ;; We need a special property. Use `org-entry-properties' to
  11637. ;; retrieve it, but specify the wanted property.
  11638. (cdr (assoc-string property (org-entry-properties nil property))))
  11639. ((and inherit
  11640. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11641. (org-entry-get-with-inheritance property literal-nil))
  11642. (t
  11643. (let* ((local (org--property-local-values property literal-nil))
  11644. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11645. (if literal-nil value (org-not-nil value)))))))
  11646. (defun org-property-or-variable-value (var &optional inherit)
  11647. "Check if there is a property fixing the value of VAR.
  11648. If yes, return this value. If not, return the current value of the variable."
  11649. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11650. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11651. (read prop)
  11652. (symbol-value var))))
  11653. (defun org-entry-delete (pom property)
  11654. "Delete PROPERTY from entry at point-or-marker POM.
  11655. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11656. non-nil when a property was removed."
  11657. (org-with-point-at pom
  11658. (pcase (org-get-property-block)
  11659. (`(,begin . ,origin)
  11660. (let* ((end (copy-marker origin))
  11661. (re (org-re-property
  11662. (concat (regexp-quote property) "\\+?") t t)))
  11663. (goto-char begin)
  11664. (while (re-search-forward re end t)
  11665. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11666. ;; If drawer is empty, remove it altogether.
  11667. (when (= begin end)
  11668. (delete-region (line-beginning-position 0)
  11669. (line-beginning-position 2)))
  11670. ;; Return non-nil if some property was removed.
  11671. (prog1 (/= end origin) (set-marker end nil))))
  11672. (_ nil))))
  11673. ;; Multi-values properties are properties that contain multiple values
  11674. ;; These values are assumed to be single words, separated by whitespace.
  11675. (defun org-entry-add-to-multivalued-property (pom property value)
  11676. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11677. (let* ((old (org-entry-get pom property))
  11678. (values (and old (split-string old))))
  11679. (setq value (org-entry-protect-space value))
  11680. (unless (member value values)
  11681. (setq values (append values (list value)))
  11682. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11683. (defun org-entry-remove-from-multivalued-property (pom property value)
  11684. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11685. (let* ((old (org-entry-get pom property))
  11686. (values (and old (split-string old))))
  11687. (setq value (org-entry-protect-space value))
  11688. (when (member value values)
  11689. (setq values (delete value values))
  11690. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11691. (defun org-entry-member-in-multivalued-property (pom property value)
  11692. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11693. (let* ((old (org-entry-get pom property))
  11694. (values (and old (split-string old))))
  11695. (setq value (org-entry-protect-space value))
  11696. (member value values)))
  11697. (defun org-entry-get-multivalued-property (pom property)
  11698. "Return a list of values in a multivalued property."
  11699. (let* ((value (org-entry-get pom property))
  11700. (values (and value (split-string value))))
  11701. (mapcar #'org-entry-restore-space values)))
  11702. (defun org-entry-put-multivalued-property (pom property &rest values)
  11703. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11704. VALUES should be a list of strings. Spaces will be protected."
  11705. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11706. (let* ((value (org-entry-get pom property))
  11707. (values (and value (split-string value))))
  11708. (mapcar #'org-entry-restore-space values)))
  11709. (defun org-entry-protect-space (s)
  11710. "Protect spaces and newline in string S."
  11711. (while (string-match " " s)
  11712. (setq s (replace-match "%20" t t s)))
  11713. (while (string-match "\n" s)
  11714. (setq s (replace-match "%0A" t t s)))
  11715. s)
  11716. (defun org-entry-restore-space (s)
  11717. "Restore spaces and newline in string S."
  11718. (while (string-match "%20" s)
  11719. (setq s (replace-match " " t t s)))
  11720. (while (string-match "%0A" s)
  11721. (setq s (replace-match "\n" t t s)))
  11722. s)
  11723. (defvar org-entry-property-inherited-from (make-marker)
  11724. "Marker pointing to the entry from where a property was inherited.
  11725. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11726. location of the entry where the inheritance search matched. If there was
  11727. no match, the marker will point nowhere.
  11728. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11729. is set.")
  11730. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11731. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11732. The search will stop at the first ancestor which has the property defined.
  11733. If the value found is \"nil\", return nil to show that the property
  11734. should be considered as undefined (this is the meaning of nil here).
  11735. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11736. (move-marker org-entry-property-inherited-from nil)
  11737. (org-with-wide-buffer
  11738. (let (value)
  11739. (catch 'exit
  11740. (while t
  11741. (let ((v (org--property-local-values property literal-nil)))
  11742. (when v
  11743. (setq value
  11744. (concat (mapconcat #'identity (delq nil v) " ")
  11745. (and value " ")
  11746. value)))
  11747. (cond
  11748. ((car v)
  11749. (org-back-to-heading-or-point-min t)
  11750. (move-marker org-entry-property-inherited-from (point))
  11751. (throw 'exit nil))
  11752. ((org-up-heading-or-point-min))
  11753. (t
  11754. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11755. (cond ((not global))
  11756. (value (setq value (concat global " " value)))
  11757. (t (setq value global))))
  11758. (throw 'exit nil))))))
  11759. (if literal-nil value (org-not-nil value)))))
  11760. (defvar org-property-changed-functions nil
  11761. "Hook called when the value of a property has changed.
  11762. Each hook function should accept two arguments, the name of the property
  11763. and the new value.")
  11764. (defun org-entry-put (pom property value)
  11765. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11766. If the value is nil, it is converted to the empty string. If it
  11767. is not a string, an error is raised. Also raise an error on
  11768. invalid property names.
  11769. PROPERTY can be any regular property (see
  11770. `org-special-properties'). It can also be \"TODO\",
  11771. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11772. For the last two properties, VALUE may have any of the special
  11773. values \"earlier\" and \"later\". The function then increases or
  11774. decreases scheduled or deadline date by one day."
  11775. (cond ((null value) (setq value ""))
  11776. ((not (stringp value)) (error "Properties values should be strings"))
  11777. ((not (org--valid-property-p property))
  11778. (user-error "Invalid property name: \"%s\"" property)))
  11779. (org-with-point-at pom
  11780. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11781. (org-back-to-heading-or-point-min t)
  11782. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11783. (let ((beg (point)))
  11784. (cond
  11785. ((equal property "TODO")
  11786. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11787. ((not (member value org-todo-keywords-1))
  11788. (user-error "\"%s\" is not a valid TODO state" value)))
  11789. (org-todo value)
  11790. (org-align-tags))
  11791. ((equal property "PRIORITY")
  11792. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11793. (org-align-tags))
  11794. ((equal property "SCHEDULED")
  11795. (forward-line)
  11796. (if (and (looking-at-p org-planning-line-re)
  11797. (re-search-forward
  11798. org-scheduled-time-regexp (line-end-position) t))
  11799. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11800. ((string= value "later") (org-timestamp-change 1 'day))
  11801. ((string= value "") (org-schedule '(4)))
  11802. (t (org-schedule nil value)))
  11803. (if (member value '("earlier" "later" ""))
  11804. (call-interactively #'org-schedule)
  11805. (org-schedule nil value))))
  11806. ((equal property "DEADLINE")
  11807. (forward-line)
  11808. (if (and (looking-at-p org-planning-line-re)
  11809. (re-search-forward
  11810. org-deadline-time-regexp (line-end-position) t))
  11811. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11812. ((string= value "later") (org-timestamp-change 1 'day))
  11813. ((string= value "") (org-deadline '(4)))
  11814. (t (org-deadline nil value)))
  11815. (if (member value '("earlier" "later" ""))
  11816. (call-interactively #'org-deadline)
  11817. (org-deadline nil value))))
  11818. ((member property org-special-properties)
  11819. (error "The %s property cannot be set with `org-entry-put'" property))
  11820. (t
  11821. (let* ((range (org-get-property-block beg 'force))
  11822. (end (cdr range))
  11823. (case-fold-search t))
  11824. (goto-char (car range))
  11825. (if (re-search-forward (org-re-property property nil t) end t)
  11826. (progn (delete-region (match-beginning 0) (match-end 0))
  11827. (goto-char (match-beginning 0)))
  11828. (goto-char end)
  11829. (insert "\n")
  11830. (backward-char))
  11831. (insert ":" property ":")
  11832. (when value (insert " " value))
  11833. (org-indent-line)))))
  11834. (run-hook-with-args 'org-property-changed-functions property value)))
  11835. (defun org-buffer-property-keys (&optional specials defaults columns)
  11836. "Get all property keys in the current buffer.
  11837. When SPECIALS is non-nil, also list the special properties that
  11838. reflect things like tags and TODO state.
  11839. When DEFAULTS is non-nil, also include properties that has
  11840. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11841. DESCRIPTION, LOCATION, and LOGGING and others.
  11842. When COLUMNS in non-nil, also include property names given in
  11843. COLUMN formats in the current buffer."
  11844. (let ((case-fold-search t)
  11845. (props (append
  11846. (and specials org-special-properties)
  11847. (and defaults (cons org-effort-property org-default-properties))
  11848. nil)))
  11849. (org-with-wide-buffer
  11850. (goto-char (point-min))
  11851. (while (re-search-forward org-property-start-re nil t)
  11852. (catch :skip
  11853. (let ((range (org-get-property-block)))
  11854. (unless range (throw :skip nil))
  11855. (goto-char (car range))
  11856. (let ((begin (car range))
  11857. (end (cdr range)))
  11858. ;; Make sure that found property block is not located
  11859. ;; before current point, as it would generate an infloop.
  11860. ;; It can happen, for example, in the following
  11861. ;; situation:
  11862. ;;
  11863. ;; * Headline
  11864. ;; :PROPERTIES:
  11865. ;; ...
  11866. ;; :END:
  11867. ;; *************** Inlinetask
  11868. ;; #+BEGIN_EXAMPLE
  11869. ;; :PROPERTIES:
  11870. ;; #+END_EXAMPLE
  11871. ;;
  11872. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11873. (while (< (point) end)
  11874. (let ((p (progn (looking-at org-property-re)
  11875. (match-string-no-properties 2))))
  11876. ;; Only add true property name, not extension symbol.
  11877. (push (if (not (string-match-p "\\+\\'" p)) p
  11878. (substring p 0 -1))
  11879. props))
  11880. (forward-line))))
  11881. (outline-next-heading)))
  11882. (when columns
  11883. (goto-char (point-min))
  11884. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11885. (let ((element (org-element-at-point)))
  11886. (when (memq (org-element-type element) '(keyword node-property))
  11887. (let ((value (org-element-property :value element))
  11888. (start 0))
  11889. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11890. \\(?:{[^}]+}\\)?"
  11891. value start)
  11892. (setq start (match-end 0))
  11893. (let ((p (match-string-no-properties 1 value)))
  11894. (unless (member-ignore-case p org-special-properties)
  11895. (push p props))))))))))
  11896. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  11897. (defun org-property-values (key)
  11898. "List all non-nil values of property KEY in current buffer."
  11899. (org-with-wide-buffer
  11900. (goto-char (point-min))
  11901. (let ((case-fold-search t)
  11902. (re (org-re-property key))
  11903. values)
  11904. (while (re-search-forward re nil t)
  11905. (push (org-entry-get (point) key) values))
  11906. (delete-dups values))))
  11907. (defun org-insert-property-drawer ()
  11908. "Insert a property drawer into the current entry.
  11909. Do nothing if the drawer already exists. The newly created
  11910. drawer is immediately hidden."
  11911. (org-with-wide-buffer
  11912. ;; Set point to the position where the drawer should be inserted.
  11913. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11914. (org-back-to-heading-or-point-min t)
  11915. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11916. (if (org-before-first-heading-p)
  11917. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11918. (progn
  11919. (forward-line)
  11920. (when (looking-at-p org-planning-line-re) (forward-line))))
  11921. (unless (looking-at-p org-property-drawer-re)
  11922. ;; Make sure we start editing a line from current entry, not from
  11923. ;; next one. It prevents extending text properties or overlays
  11924. ;; belonging to the latter.
  11925. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11926. (let ((begin (if (bobp) (point) (1+ (point))))
  11927. (inhibit-read-only t))
  11928. (unless (bobp) (insert "\n"))
  11929. (insert ":PROPERTIES:\n:END:")
  11930. (org-flag-region (line-end-position 0) (point) t 'org-hide-drawer)
  11931. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11932. (org-indent-region begin (point))))))
  11933. (defun org-insert-drawer (&optional arg drawer)
  11934. "Insert a drawer at point.
  11935. When optional argument ARG is non-nil, insert a property drawer.
  11936. Optional argument DRAWER, when non-nil, is a string representing
  11937. drawer's name. Otherwise, the user is prompted for a name.
  11938. If a region is active, insert the drawer around that region
  11939. instead.
  11940. Point is left between drawer's boundaries."
  11941. (interactive "P")
  11942. (let* ((drawer (if arg "PROPERTIES"
  11943. (or drawer (read-from-minibuffer "Drawer: ")))))
  11944. (cond
  11945. ;; With C-u, fall back on `org-insert-property-drawer'
  11946. (arg (org-insert-property-drawer))
  11947. ;; Check validity of suggested drawer's name.
  11948. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11949. (user-error "Invalid drawer name"))
  11950. ;; With an active region, insert a drawer at point.
  11951. ((not (org-region-active-p))
  11952. (progn
  11953. (unless (bolp) (insert "\n"))
  11954. (insert (format ":%s:\n\n:END:\n" drawer))
  11955. (forward-line -2)))
  11956. ;; Otherwise, insert the drawer at point
  11957. (t
  11958. (let ((rbeg (region-beginning))
  11959. (rend (copy-marker (region-end))))
  11960. (unwind-protect
  11961. (progn
  11962. (goto-char rbeg)
  11963. (beginning-of-line)
  11964. (when (save-excursion
  11965. (re-search-forward org-outline-regexp-bol rend t))
  11966. (user-error "Drawers cannot contain headlines"))
  11967. ;; Position point at the beginning of the first
  11968. ;; non-blank line in region. Insert drawer's opening
  11969. ;; there, then indent it.
  11970. (org-skip-whitespace)
  11971. (beginning-of-line)
  11972. (insert ":" drawer ":\n")
  11973. (forward-line -1)
  11974. (indent-for-tab-command)
  11975. ;; Move point to the beginning of the first blank line
  11976. ;; after the last non-blank line in region. Insert
  11977. ;; drawer's closing, then indent it.
  11978. (goto-char rend)
  11979. (skip-chars-backward " \r\t\n")
  11980. (insert "\n:END:")
  11981. (deactivate-mark t)
  11982. (indent-for-tab-command)
  11983. (unless (eolp) (insert "\n")))
  11984. ;; Clear marker, whatever the outcome of insertion is.
  11985. (set-marker rend nil)))))))
  11986. (defvar org-property-set-functions-alist nil
  11987. "Property set function alist.
  11988. Each entry should have the following format:
  11989. (PROPERTY . READ-FUNCTION)
  11990. The read function will be called with the same argument as
  11991. `org-completing-read'.")
  11992. (defun org-set-property-function (property)
  11993. "Get the function that should be used to set PROPERTY.
  11994. This is computed according to `org-property-set-functions-alist'."
  11995. (or (cdr (assoc property org-property-set-functions-alist))
  11996. 'org-completing-read))
  11997. (defun org-read-property-value (property &optional pom)
  11998. "Read value for PROPERTY, as a string.
  11999. When optional argument POM is non-nil, completion uses additional
  12000. information, i.e., allowed or existing values at point or marker
  12001. POM."
  12002. (let* ((completion-ignore-case t)
  12003. (allowed
  12004. (or (org-property-get-allowed-values nil property 'table)
  12005. (and pom (org-property-get-allowed-values pom property 'table))))
  12006. (current (org-entry-get nil property))
  12007. (prompt (format "%s value%s: "
  12008. property
  12009. (if (org-string-nw-p current)
  12010. (format " [%s]" current)
  12011. "")))
  12012. (set-function (org-set-property-function property)))
  12013. (org-trim
  12014. (if allowed
  12015. (funcall set-function
  12016. prompt allowed nil
  12017. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12018. (let ((all (mapcar #'list
  12019. (append (org-property-values property)
  12020. (and pom
  12021. (org-with-point-at pom
  12022. (org-property-values property)))))))
  12023. (funcall set-function prompt all nil nil "" nil current))))))
  12024. (defvar org-last-set-property nil)
  12025. (defvar org-last-set-property-value nil)
  12026. (defun org-read-property-name ()
  12027. "Read a property name."
  12028. (let ((completion-ignore-case t)
  12029. (default-prop (or (and (org-at-property-p)
  12030. (match-string-no-properties 2))
  12031. org-last-set-property)))
  12032. (org-completing-read
  12033. (concat "Property"
  12034. (if default-prop (concat " [" default-prop "]") "")
  12035. ": ")
  12036. (mapcar #'list (org-buffer-property-keys nil t t))
  12037. nil nil nil nil default-prop)))
  12038. (defun org-set-property-and-value (use-last)
  12039. "Allow to set [PROPERTY]: [value] direction from prompt.
  12040. When use-default, don't even ask, just use the last
  12041. \"[PROPERTY]: [value]\" string from the history."
  12042. (interactive "P")
  12043. (let* ((completion-ignore-case t)
  12044. (pv (or (and use-last org-last-set-property-value)
  12045. (org-completing-read
  12046. "Enter a \"[Property]: [value]\" pair: "
  12047. nil nil nil nil nil
  12048. org-last-set-property-value)))
  12049. prop val)
  12050. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12051. (setq prop (match-string 1 pv)
  12052. val (match-string 2 pv))
  12053. (org-set-property prop val))))
  12054. (defun org-set-property (property value)
  12055. "In the current entry, set PROPERTY to VALUE.
  12056. When called interactively, this will prompt for a property name, offering
  12057. completion on existing and default properties. And then it will prompt
  12058. for a value, offering completion either on allowed values (via an inherited
  12059. xxx_ALL property) or on existing values in other instances of this property
  12060. in the current file.
  12061. Throw an error when trying to set a property with an invalid name."
  12062. (interactive (list nil nil))
  12063. (let ((property (or property (org-read-property-name))))
  12064. ;; `org-entry-put' also makes the following check, but this one
  12065. ;; avoids polluting `org-last-set-property' and
  12066. ;; `org-last-set-property-value' needlessly.
  12067. (unless (org--valid-property-p property)
  12068. (user-error "Invalid property name: \"%s\"" property))
  12069. (let ((value (or value (org-read-property-value property)))
  12070. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12071. (setq org-last-set-property property)
  12072. (setq org-last-set-property-value (concat property ": " value))
  12073. ;; Possibly postprocess the inserted value:
  12074. (when fn (setq value (funcall fn value)))
  12075. (unless (equal (org-entry-get nil property) value)
  12076. (org-entry-put nil property value)))))
  12077. (defun org-find-property (property &optional value)
  12078. "Find first entry in buffer that sets PROPERTY.
  12079. When optional argument VALUE is non-nil, only consider an entry
  12080. if it contains PROPERTY set to this value. If PROPERTY should be
  12081. explicitly set to nil, use string \"nil\" for VALUE.
  12082. Return position where the entry begins, or nil if there is no
  12083. such entry. If narrowing is in effect, only search the visible
  12084. part of the buffer."
  12085. (save-excursion
  12086. (goto-char (point-min))
  12087. (let ((case-fold-search t)
  12088. (re (org-re-property property nil (not value) value)))
  12089. (catch 'exit
  12090. (while (re-search-forward re nil t)
  12091. (when (if value (org-at-property-p)
  12092. (org-entry-get (point) property nil t))
  12093. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12094. (point)))))))))
  12095. (defun org-delete-property (property)
  12096. "In the current entry, delete PROPERTY."
  12097. (interactive
  12098. (let* ((completion-ignore-case t)
  12099. (cat (org-entry-get (point) "CATEGORY"))
  12100. (props0 (org-entry-properties nil 'standard))
  12101. (props (if cat props0
  12102. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12103. (prop (if (< 1 (length props))
  12104. (completing-read "Property: " props nil t)
  12105. (caar props))))
  12106. (list prop)))
  12107. (if (not property)
  12108. (message "No property to delete in this entry")
  12109. (org-entry-delete nil property)
  12110. (message "Property \"%s\" deleted" property)))
  12111. (defun org-delete-property-globally (property)
  12112. "Remove PROPERTY globally, from all entries.
  12113. This function ignores narrowing, if any."
  12114. (interactive
  12115. (let* ((completion-ignore-case t)
  12116. (prop (completing-read
  12117. "Globally remove property: "
  12118. (mapcar #'list (org-buffer-property-keys)))))
  12119. (list prop)))
  12120. (org-with-wide-buffer
  12121. (goto-char (point-min))
  12122. (let ((count 0)
  12123. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12124. (while (re-search-forward re nil t)
  12125. (when (org-entry-delete (point) property) (cl-incf count)))
  12126. (message "Property \"%s\" removed from %d entries" property count))))
  12127. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12128. (defun org-compute-property-at-point ()
  12129. "Compute the property at point.
  12130. This looks for an enclosing column format, extracts the operator and
  12131. then applies it to the property in the column format's scope."
  12132. (interactive)
  12133. (unless (org-at-property-p)
  12134. (user-error "Not at a property"))
  12135. (let ((prop (match-string-no-properties 2)))
  12136. (org-columns-get-format-and-top-level)
  12137. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12138. (user-error "No operator defined for property %s" prop))
  12139. (org-columns-compute prop)))
  12140. (defvar org-property-allowed-value-functions nil
  12141. "Hook for functions supplying allowed values for a specific property.
  12142. The functions must take a single argument, the name of the property, and
  12143. return a flat list of allowed values. If \":ETC\" is one of
  12144. the values, this means that these values are intended as defaults for
  12145. completion, but that other values should be allowed too.
  12146. The functions must return nil if they are not responsible for this
  12147. property.")
  12148. (defun org-property-get-allowed-values (pom property &optional table)
  12149. "Get allowed values for the property PROPERTY.
  12150. When TABLE is non-nil, return an alist that can directly be used for
  12151. completion."
  12152. (let (vals)
  12153. (cond
  12154. ((equal property "TODO")
  12155. (setq vals (org-with-point-at pom
  12156. (append org-todo-keywords-1 '("")))))
  12157. ((equal property "PRIORITY")
  12158. (let ((n org-priority-lowest))
  12159. (while (>= n org-priority-highest)
  12160. (push (char-to-string n) vals)
  12161. (setq n (1- n)))))
  12162. ((equal property "CATEGORY"))
  12163. ((member property org-special-properties))
  12164. ((setq vals (run-hook-with-args-until-success
  12165. 'org-property-allowed-value-functions property)))
  12166. (t
  12167. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12168. (when (and vals (string-match "\\S-" vals))
  12169. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12170. (setq vals (mapcar (lambda (x)
  12171. (cond ((stringp x) x)
  12172. ((numberp x) (number-to-string x))
  12173. ((symbolp x) (symbol-name x))
  12174. (t "???")))
  12175. vals)))))
  12176. (when (member ":ETC" vals)
  12177. (setq vals (remove ":ETC" vals))
  12178. (org-add-props (car vals) '(org-unrestricted t)))
  12179. (if table (mapcar 'list vals) vals)))
  12180. (defun org-property-previous-allowed-value (&optional _previous)
  12181. "Switch to the next allowed value for this property."
  12182. (interactive)
  12183. (org-property-next-allowed-value t))
  12184. (defun org-property-next-allowed-value (&optional previous)
  12185. "Switch to the next allowed value for this property."
  12186. (interactive)
  12187. (unless (org-at-property-p)
  12188. (user-error "Not at a property"))
  12189. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12190. (key (match-string 2))
  12191. (value (match-string 3))
  12192. (allowed (or (org-property-get-allowed-values (point) key)
  12193. (and (member value '("[ ]" "[-]" "[X]"))
  12194. '("[ ]" "[X]"))))
  12195. (heading (save-match-data (nth 4 (org-heading-components))))
  12196. nval)
  12197. (unless allowed
  12198. (user-error "Allowed values for this property have not been defined"))
  12199. (when previous (setq allowed (reverse allowed)))
  12200. (when (member value allowed)
  12201. (setq nval (car (cdr (member value allowed)))))
  12202. (setq nval (or nval (car allowed)))
  12203. (when (equal nval value)
  12204. (user-error "Only one allowed value for this property"))
  12205. (org-at-property-p)
  12206. (replace-match (concat " :" key ": " nval) t t)
  12207. (org-indent-line)
  12208. (beginning-of-line 1)
  12209. (skip-chars-forward " \t")
  12210. (when (equal prop org-effort-property)
  12211. (org-refresh-property
  12212. '((effort . identity)
  12213. (effort-minutes . org-duration-to-minutes))
  12214. nval)
  12215. (when (string= org-clock-current-task heading)
  12216. (setq org-clock-effort nval)
  12217. (org-clock-update-mode-line)))
  12218. (run-hook-with-args 'org-property-changed-functions key nval)))
  12219. (defun org-find-olp (path &optional this-buffer)
  12220. "Return a marker pointing to the entry at outline path OLP.
  12221. If anything goes wrong, throw an error.
  12222. You can wrap this call to catch the error like this:
  12223. (condition-case msg
  12224. (org-mobile-locate-entry (match-string 4))
  12225. (error (nth 1 msg)))
  12226. The return value will then be either a string with the error message,
  12227. or a marker if everything is OK.
  12228. If THIS-BUFFER is set, the outline path does not contain a file,
  12229. only headings."
  12230. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12231. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12232. (level 1)
  12233. (lmin 1)
  12234. (lmax 1)
  12235. end found flevel)
  12236. (unless buffer (error "File not found :%s" file))
  12237. (with-current-buffer buffer
  12238. (unless (derived-mode-p 'org-mode)
  12239. (error "Buffer %s needs to be in Org mode" buffer))
  12240. (org-with-wide-buffer
  12241. (goto-char (point-min))
  12242. (dolist (heading path)
  12243. (let ((re (format org-complex-heading-regexp-format
  12244. (regexp-quote heading)))
  12245. (cnt 0))
  12246. (while (re-search-forward re end t)
  12247. (setq level (- (match-end 1) (match-beginning 1)))
  12248. (when (and (>= level lmin) (<= level lmax))
  12249. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12250. (when (= cnt 0)
  12251. (error "Heading not found on level %d: %s" lmax heading))
  12252. (when (> cnt 1)
  12253. (error "Heading not unique on level %d: %s" lmax heading))
  12254. (goto-char found)
  12255. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12256. (setq end (save-excursion (org-end-of-subtree t t)))))
  12257. (when (org-at-heading-p)
  12258. (point-marker))))))
  12259. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12260. "Find node HEADING in BUFFER.
  12261. Return a marker to the heading if it was found, or nil if not.
  12262. If POS-ONLY is set, return just the position instead of a marker.
  12263. The heading text must match exact, but it may have a TODO keyword,
  12264. a priority cookie and tags in the standard locations."
  12265. (with-current-buffer (or buffer (current-buffer))
  12266. (org-with-wide-buffer
  12267. (goto-char (point-min))
  12268. (let (case-fold-search)
  12269. (when (re-search-forward
  12270. (format org-complex-heading-regexp-format
  12271. (regexp-quote heading)) nil t)
  12272. (if pos-only
  12273. (match-beginning 0)
  12274. (move-marker (make-marker) (match-beginning 0))))))))
  12275. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12276. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12277. When the target headline is found, return a marker to this location."
  12278. (let ((files (directory-files (or dir default-directory)
  12279. t "\\`[^.#].*\\.org\\'"))
  12280. visiting m buffer)
  12281. (catch 'found
  12282. (dolist (file files)
  12283. (message "trying %s" file)
  12284. (setq visiting (org-find-base-buffer-visiting file))
  12285. (setq buffer (or visiting (find-file-noselect file)))
  12286. (setq m (org-find-exact-headline-in-buffer
  12287. heading buffer))
  12288. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12289. (and m (throw 'found m))))))
  12290. (defun org-find-entry-with-id (ident)
  12291. "Locate the entry that contains the ID property with exact value IDENT.
  12292. IDENT can be a string, a symbol or a number, this function will search for
  12293. the string representation of it.
  12294. Return the position where this entry starts, or nil if there is no such entry."
  12295. (interactive "sID: ")
  12296. (let ((id (cond
  12297. ((stringp ident) ident)
  12298. ((symbolp ident) (symbol-name ident))
  12299. ((numberp ident) (number-to-string ident))
  12300. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12301. (org-with-wide-buffer (org-find-property "ID" id))))
  12302. ;;;; Timestamps
  12303. (defvar org-last-changed-timestamp nil)
  12304. (defvar org-last-inserted-timestamp nil
  12305. "The last time stamp inserted with `org-insert-time-stamp'.")
  12306. (defun org-time-stamp (arg &optional inactive)
  12307. "Prompt for a date/time and insert a time stamp.
  12308. If the user specifies a time like HH:MM or if this command is
  12309. called with at least one prefix argument, the time stamp contains
  12310. the date and the time. Otherwise, only the date is included.
  12311. All parts of a date not specified by the user are filled in from
  12312. the timestamp at point, if any, or the current date/time
  12313. otherwise.
  12314. If there is already a timestamp at the cursor, it is replaced.
  12315. With two universal prefix arguments, insert an active timestamp
  12316. with the current time without prompting the user.
  12317. When called from lisp, the timestamp is inactive if INACTIVE is
  12318. non-nil."
  12319. (interactive "P")
  12320. (let* ((ts (cond
  12321. ((org-at-date-range-p t)
  12322. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12323. ((org-at-timestamp-p 'lax) (match-string 0))))
  12324. ;; Default time is either the timestamp at point or today.
  12325. ;; When entering a range, only the range start is considered.
  12326. (default-time (and ts (org-time-string-to-time ts)))
  12327. (default-input (and ts (org-get-compact-tod ts)))
  12328. (repeater (and ts
  12329. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12330. (match-string 0 ts)))
  12331. org-time-was-given
  12332. org-end-time-was-given
  12333. (time
  12334. (if (equal arg '(16)) (current-time)
  12335. ;; Preserve `this-command' and `last-command'.
  12336. (let ((this-command this-command)
  12337. (last-command last-command))
  12338. (org-read-date
  12339. arg 'totime nil nil default-time default-input
  12340. inactive)))))
  12341. (cond
  12342. ((and ts
  12343. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12344. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12345. (insert "--")
  12346. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12347. (ts
  12348. ;; Make sure we're on a timestamp. When in the middle of a date
  12349. ;; range, move arbitrarily to range end.
  12350. (unless (org-at-timestamp-p 'lax)
  12351. (skip-chars-forward "-")
  12352. (org-at-timestamp-p 'lax))
  12353. (replace-match "")
  12354. (setq org-last-changed-timestamp
  12355. (org-insert-time-stamp
  12356. time (or org-time-was-given arg)
  12357. inactive nil nil (list org-end-time-was-given)))
  12358. (when repeater
  12359. (backward-char)
  12360. (insert " " repeater)
  12361. (setq org-last-changed-timestamp
  12362. (concat (substring org-last-inserted-timestamp 0 -1)
  12363. " " repeater ">")))
  12364. (message "Timestamp updated"))
  12365. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12366. (t (org-insert-time-stamp
  12367. time (or org-time-was-given arg) inactive nil nil
  12368. (list org-end-time-was-given))))))
  12369. ;; FIXME: can we use this for something else, like computing time differences?
  12370. (defun org-get-compact-tod (s)
  12371. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12372. (let* ((t1 (match-string 1 s))
  12373. (h1 (string-to-number (match-string 2 s)))
  12374. (m1 (string-to-number (match-string 3 s)))
  12375. (t2 (and (match-end 4) (match-string 5 s)))
  12376. (h2 (and t2 (string-to-number (match-string 6 s))))
  12377. (m2 (and t2 (string-to-number (match-string 7 s))))
  12378. dh dm)
  12379. (if (not t2)
  12380. t1
  12381. (setq dh (- h2 h1) dm (- m2 m1))
  12382. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12383. (concat t1 "+" (number-to-string dh)
  12384. (and (/= 0 dm) (format ":%02d" dm)))))))
  12385. (defun org-time-stamp-inactive (&optional arg)
  12386. "Insert an inactive time stamp.
  12387. An inactive time stamp is enclosed in square brackets instead of
  12388. angle brackets. It is inactive in the sense that it does not
  12389. trigger agenda entries. So these are more for recording a
  12390. certain time/date.
  12391. If the user specifies a time like HH:MM or if this command is called with
  12392. at least one prefix argument, the time stamp contains the date and the time.
  12393. Otherwise, only the date is included.
  12394. When called with two universal prefix arguments, insert an inactive time stamp
  12395. with the current time without prompting the user."
  12396. (interactive "P")
  12397. (org-time-stamp arg 'inactive))
  12398. (defvar org-date-ovl (make-overlay 1 1))
  12399. (overlay-put org-date-ovl 'face 'org-date-selected)
  12400. (delete-overlay org-date-ovl)
  12401. (defvar org-ans1) ; dynamically scoped parameter
  12402. (defvar org-ans2) ; dynamically scoped parameter
  12403. (defvar org-plain-time-of-day-regexp) ; defined below
  12404. (defvar org-overriding-default-time nil) ; dynamically scoped
  12405. (defvar org-read-date-overlay nil)
  12406. (defvar org-read-date-history nil)
  12407. (defvar org-read-date-final-answer nil)
  12408. (defvar org-read-date-analyze-futurep nil)
  12409. (defvar org-read-date-analyze-forced-year nil)
  12410. (defvar org-read-date-inactive)
  12411. (defvar org-def)
  12412. (defvar org-defdecode)
  12413. (defvar org-with-time)
  12414. (defvar calendar-setup) ; Dynamically scoped.
  12415. (defun org-read-date (&optional with-time to-time from-string prompt
  12416. default-time default-input inactive)
  12417. "Read a date, possibly a time, and make things smooth for the user.
  12418. The prompt will suggest to enter an ISO date, but you can also enter anything
  12419. which will at least partially be understood by `parse-time-string'.
  12420. Unrecognized parts of the date will default to the current day, month, year,
  12421. hour and minute. If this command is called to replace a timestamp at point,
  12422. or to enter the second timestamp of a range, the default time is taken
  12423. from the existing stamp. Furthermore, the command prefers the future,
  12424. so if you are giving a date where the year is not given, and the day-month
  12425. combination is already past in the current year, it will assume you
  12426. mean next year. For details, see the manual. A few examples:
  12427. 3-2-5 --> 2003-02-05
  12428. feb 15 --> currentyear-02-15
  12429. 2/15 --> currentyear-02-15
  12430. sep 12 9 --> 2009-09-12
  12431. 12:45 --> today 12:45
  12432. 22 sept 0:34 --> currentyear-09-22 0:34
  12433. 12 --> currentyear-currentmonth-12
  12434. Fri --> nearest Friday after today
  12435. -Tue --> last Tuesday
  12436. etc.
  12437. Furthermore you can specify a relative date by giving, as the *first* thing
  12438. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12439. change in days weeks, months, years.
  12440. With a single plus or minus, the date is relative to today. With a double
  12441. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12442. +4d --> four days from today
  12443. +4 --> same as above
  12444. +2w --> two weeks from today
  12445. ++5 --> five days from default date
  12446. The function understands only English month and weekday abbreviations.
  12447. While prompting, a calendar is popped up - you can also select the
  12448. date with the mouse (button 1). The calendar shows a period of three
  12449. months. To scroll it to other months, use the keys `>' and `<'.
  12450. If you don't like the calendar, turn it off with
  12451. (setq org-read-date-popup-calendar nil)
  12452. With optional argument TO-TIME, the date will immediately be converted
  12453. to an internal time.
  12454. With an optional argument WITH-TIME, the prompt will suggest to
  12455. also insert a time. Note that when WITH-TIME is not set, you can
  12456. still enter a time, and this function will inform the calling routine
  12457. about this change. The calling routine may then choose to change the
  12458. format used to insert the time stamp into the buffer to include the time.
  12459. With optional argument FROM-STRING, read from this string instead from
  12460. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12461. the time/date that is used for everything that is not specified by the
  12462. user."
  12463. (require 'parse-time)
  12464. (let* ((org-with-time with-time)
  12465. (org-time-stamp-rounding-minutes
  12466. (if (equal org-with-time '(16))
  12467. '(0 0)
  12468. org-time-stamp-rounding-minutes))
  12469. (ct (org-current-time))
  12470. (org-def (or org-overriding-default-time default-time ct))
  12471. (org-defdecode (decode-time org-def))
  12472. (cur-frame (selected-frame))
  12473. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12474. (calendar-setup
  12475. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12476. (calendar-move-hook nil)
  12477. (calendar-view-diary-initially-flag nil)
  12478. (calendar-view-holidays-initially-flag nil)
  12479. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12480. ;; Rationalize `org-def' and `org-defdecode', if required.
  12481. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12482. (setf (nth 2 org-defdecode) -1)
  12483. (setf (nth 1 org-defdecode) 59)
  12484. (setq org-def (apply #'encode-time org-defdecode))
  12485. (setq org-defdecode (decode-time org-def)))
  12486. (let* ((timestr (format-time-string
  12487. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12488. org-def))
  12489. (prompt (concat (if prompt (concat prompt " ") "")
  12490. (format "Date+time [%s]: " timestr))))
  12491. (cond
  12492. (from-string (setq ans from-string))
  12493. (org-read-date-popup-calendar
  12494. (save-excursion
  12495. (save-window-excursion
  12496. (calendar)
  12497. (when (eq calendar-setup 'calendar-only)
  12498. (setq cal-frame
  12499. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12500. (select-frame cal-frame))
  12501. (org-eval-in-calendar '(setq cursor-type nil) t)
  12502. (unwind-protect
  12503. (progn
  12504. (calendar-forward-day (- (time-to-days org-def)
  12505. (calendar-absolute-from-gregorian
  12506. (calendar-current-date))))
  12507. (org-eval-in-calendar nil t)
  12508. (let* ((old-map (current-local-map))
  12509. (map (copy-keymap calendar-mode-map))
  12510. (minibuffer-local-map
  12511. (copy-keymap org-read-date-minibuffer-local-map)))
  12512. (org-defkey map (kbd "RET") 'org-calendar-select)
  12513. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12514. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12515. (unwind-protect
  12516. (progn
  12517. (use-local-map map)
  12518. (setq org-read-date-inactive inactive)
  12519. (add-hook 'post-command-hook 'org-read-date-display)
  12520. (setq org-ans0
  12521. (read-string prompt
  12522. default-input
  12523. 'org-read-date-history
  12524. nil))
  12525. ;; org-ans0: from prompt
  12526. ;; org-ans1: from mouse click
  12527. ;; org-ans2: from calendar motion
  12528. (setq ans
  12529. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12530. (remove-hook 'post-command-hook 'org-read-date-display)
  12531. (use-local-map old-map)
  12532. (when org-read-date-overlay
  12533. (delete-overlay org-read-date-overlay)
  12534. (setq org-read-date-overlay nil)))))
  12535. (bury-buffer "*Calendar*")
  12536. (when cal-frame
  12537. (delete-frame cal-frame)
  12538. (select-frame-set-input-focus cur-frame))))))
  12539. (t ; Naked prompt only
  12540. (unwind-protect
  12541. (setq ans (read-string prompt default-input
  12542. 'org-read-date-history timestr))
  12543. (when org-read-date-overlay
  12544. (delete-overlay org-read-date-overlay)
  12545. (setq org-read-date-overlay nil))))))
  12546. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12547. (when org-read-date-analyze-forced-year
  12548. (message "Year was forced into %s"
  12549. (if org-read-date-force-compatible-dates
  12550. "compatible range (1970-2037)"
  12551. "range representable on this machine"))
  12552. (ding))
  12553. (setq final (apply #'encode-time final))
  12554. (setq org-read-date-final-answer ans)
  12555. (if to-time
  12556. final
  12557. ;; This round-trip gets rid of 34th of August and stuff like that....
  12558. (setq final (decode-time final))
  12559. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12560. (format "%04d-%02d-%02d %02d:%02d"
  12561. (nth 5 final) (nth 4 final) (nth 3 final)
  12562. (nth 2 final) (nth 1 final))
  12563. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12564. (defun org-read-date-display ()
  12565. "Display the current date prompt interpretation in the minibuffer."
  12566. (when org-read-date-display-live
  12567. (when org-read-date-overlay
  12568. (delete-overlay org-read-date-overlay))
  12569. (when (minibufferp (current-buffer))
  12570. (save-excursion
  12571. (end-of-line 1)
  12572. (while (not (equal (buffer-substring
  12573. (max (point-min) (- (point) 4)) (point))
  12574. " "))
  12575. (insert " ")))
  12576. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12577. " " (or org-ans1 org-ans2)))
  12578. (org-end-time-was-given nil)
  12579. (f (org-read-date-analyze ans org-def org-defdecode))
  12580. (fmts (if org-display-custom-times
  12581. org-time-stamp-custom-formats
  12582. org-time-stamp-formats))
  12583. (fmt (if (or org-with-time
  12584. (and (boundp 'org-time-was-given) org-time-was-given))
  12585. (cdr fmts)
  12586. (car fmts)))
  12587. (txt (format-time-string fmt (apply #'encode-time f)))
  12588. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12589. (txt (concat "=> " txt)))
  12590. (when (and org-end-time-was-given
  12591. (string-match org-plain-time-of-day-regexp txt))
  12592. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12593. org-end-time-was-given
  12594. (substring txt (match-end 0)))))
  12595. (when org-read-date-analyze-futurep
  12596. (setq txt (concat txt " (=>F)")))
  12597. (setq org-read-date-overlay
  12598. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12599. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12600. (defun org-read-date-analyze (ans def defdecode)
  12601. "Analyze the combined answer of the date prompt."
  12602. ;; FIXME: cleanup and comment
  12603. (let ((org-def def)
  12604. (org-defdecode defdecode)
  12605. (nowdecode (decode-time))
  12606. delta deltan deltaw deltadef year month day
  12607. hour minute second wday pm h2 m2 tl wday1
  12608. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12609. (setq org-read-date-analyze-futurep nil
  12610. org-read-date-analyze-forced-year nil)
  12611. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12612. (setq ans "+0"))
  12613. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12614. (setq ans (replace-match "" t t ans)
  12615. deltan (car delta)
  12616. deltaw (nth 1 delta)
  12617. deltadef (nth 2 delta)))
  12618. ;; Check if there is an iso week date in there. If yes, store the
  12619. ;; info and postpone interpreting it until the rest of the parsing
  12620. ;; is done.
  12621. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12622. (setq iso-year (when (match-end 1)
  12623. (org-small-year-to-year
  12624. (string-to-number (match-string 1 ans))))
  12625. iso-weekday (when (match-end 3)
  12626. (string-to-number (match-string 3 ans)))
  12627. iso-week (string-to-number (match-string 2 ans)))
  12628. (setq ans (replace-match "" t t ans)))
  12629. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12630. (when (string-match
  12631. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12632. (setq year (if (match-end 2)
  12633. (string-to-number (match-string 2 ans))
  12634. (progn (setq kill-year t)
  12635. (string-to-number (format-time-string "%Y"))))
  12636. month (string-to-number (match-string 3 ans))
  12637. day (string-to-number (match-string 4 ans)))
  12638. (setq year (org-small-year-to-year year))
  12639. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12640. t nil ans)))
  12641. ;; Help matching dotted european dates
  12642. (when (string-match
  12643. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12644. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12645. (setq kill-year t)
  12646. (string-to-number (format-time-string "%Y")))
  12647. day (string-to-number (match-string 1 ans))
  12648. month (string-to-number (match-string 2 ans))
  12649. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12650. t nil ans)))
  12651. ;; Help matching american dates, like 5/30 or 5/30/7
  12652. (when (string-match
  12653. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12654. (setq year (if (match-end 4)
  12655. (string-to-number (match-string 4 ans))
  12656. (progn (setq kill-year t)
  12657. (string-to-number (format-time-string "%Y"))))
  12658. month (string-to-number (match-string 1 ans))
  12659. day (string-to-number (match-string 2 ans)))
  12660. (setq year (org-small-year-to-year year))
  12661. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12662. t nil ans)))
  12663. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12664. ;; If there is a time with am/pm, and *no* time without it, we convert
  12665. ;; so that matching will be successful.
  12666. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12667. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12668. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12669. (setq hour (string-to-number (match-string 1 ans))
  12670. minute (if (match-end 3)
  12671. (string-to-number (match-string 3 ans))
  12672. 0)
  12673. pm (equal ?p
  12674. (string-to-char (downcase (match-string 4 ans)))))
  12675. (if (and (= hour 12) (not pm))
  12676. (setq hour 0)
  12677. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12678. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12679. t t ans))))
  12680. ;; Check if a time range is given as a duration
  12681. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12682. (setq hour (string-to-number (match-string 1 ans))
  12683. h2 (+ hour (string-to-number (match-string 3 ans)))
  12684. minute (string-to-number (match-string 2 ans))
  12685. m2 (+ minute (if (match-end 5) (string-to-number
  12686. (match-string 5 ans))0)))
  12687. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12688. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12689. t t ans)))
  12690. ;; Check if there is a time range
  12691. (when (boundp 'org-end-time-was-given)
  12692. (setq org-time-was-given nil)
  12693. (when (and (string-match org-plain-time-of-day-regexp ans)
  12694. (match-end 8))
  12695. (setq org-end-time-was-given (match-string 8 ans))
  12696. (setq ans (concat (substring ans 0 (match-beginning 7))
  12697. (substring ans (match-end 7))))))
  12698. (setq tl (parse-time-string ans)
  12699. day (or (nth 3 tl) (nth 3 org-defdecode))
  12700. month
  12701. (cond ((nth 4 tl))
  12702. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12703. ;; Day was specified. Make sure DAY+MONTH
  12704. ;; combination happens in the future.
  12705. ((nth 3 tl)
  12706. (setq futurep t)
  12707. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12708. (nth 4 nowdecode)))
  12709. (t (nth 4 org-defdecode)))
  12710. year
  12711. (cond ((and (not kill-year) (nth 5 tl)))
  12712. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12713. ;; Month was guessed in the future and is at least
  12714. ;; equal to NOWDECODE's. Fix year accordingly.
  12715. (futurep
  12716. (if (or (> month (nth 4 nowdecode))
  12717. (>= day (nth 3 nowdecode)))
  12718. (nth 5 nowdecode)
  12719. (1+ (nth 5 nowdecode))))
  12720. ;; Month was specified. Make sure MONTH+YEAR
  12721. ;; combination happens in the future.
  12722. ((nth 4 tl)
  12723. (setq futurep t)
  12724. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12725. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12726. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12727. (t (nth 5 nowdecode))))
  12728. (t (nth 5 org-defdecode)))
  12729. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12730. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12731. second (or (nth 0 tl) 0)
  12732. wday (nth 6 tl))
  12733. (when (and (eq org-read-date-prefer-future 'time)
  12734. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12735. (equal day (nth 3 nowdecode))
  12736. (equal month (nth 4 nowdecode))
  12737. (equal year (nth 5 nowdecode))
  12738. (nth 2 tl)
  12739. (or (< (nth 2 tl) (nth 2 nowdecode))
  12740. (and (= (nth 2 tl) (nth 2 nowdecode))
  12741. (nth 1 tl)
  12742. (< (nth 1 tl) (nth 1 nowdecode)))))
  12743. (setq day (1+ day)
  12744. futurep t))
  12745. ;; Special date definitions below
  12746. (cond
  12747. (iso-week
  12748. ;; There was an iso week
  12749. (require 'cal-iso)
  12750. (setq futurep nil)
  12751. (setq year (or iso-year year)
  12752. day (or iso-weekday wday 1)
  12753. wday nil ; to make sure that the trigger below does not match
  12754. iso-date (calendar-gregorian-from-absolute
  12755. (calendar-iso-to-absolute
  12756. (list iso-week day year))))
  12757. ; FIXME: Should we also push ISO weeks into the future?
  12758. ; (when (and org-read-date-prefer-future
  12759. ; (not iso-year)
  12760. ; (< (calendar-absolute-from-gregorian iso-date)
  12761. ; (time-to-days nil)))
  12762. ; (setq year (1+ year)
  12763. ; iso-date (calendar-gregorian-from-absolute
  12764. ; (calendar-iso-to-absolute
  12765. ; (list iso-week day year)))))
  12766. (setq month (car iso-date)
  12767. year (nth 2 iso-date)
  12768. day (nth 1 iso-date)))
  12769. (deltan
  12770. (setq futurep nil)
  12771. (unless deltadef
  12772. (let ((now (decode-time)))
  12773. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12774. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12775. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12776. ((equal deltaw "m") (setq month (+ month deltan)))
  12777. ((equal deltaw "y") (setq year (+ year deltan)))))
  12778. ((and wday (not (nth 3 tl)))
  12779. ;; Weekday was given, but no day, so pick that day in the week
  12780. ;; on or after the derived date.
  12781. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12782. (unless (equal wday wday1)
  12783. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12784. (when (and (boundp 'org-time-was-given)
  12785. (nth 2 tl))
  12786. (setq org-time-was-given t))
  12787. (when (< year 100) (setq year (+ 2000 year)))
  12788. ;; Check of the date is representable
  12789. (if org-read-date-force-compatible-dates
  12790. (progn
  12791. (when (< year 1970)
  12792. (setq year 1970 org-read-date-analyze-forced-year t))
  12793. (when (> year 2037)
  12794. (setq year 2037 org-read-date-analyze-forced-year t)))
  12795. (condition-case nil
  12796. (ignore (encode-time second minute hour day month year))
  12797. (error
  12798. (setq year (nth 5 org-defdecode))
  12799. (setq org-read-date-analyze-forced-year t))))
  12800. (setq org-read-date-analyze-futurep futurep)
  12801. (list second minute hour day month year)))
  12802. (defvar parse-time-weekdays)
  12803. (defun org-read-date-get-relative (s today default)
  12804. "Check string S for special relative date string.
  12805. TODAY and DEFAULT are internal times, for today and for a default.
  12806. Return shift list (N what def-flag)
  12807. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12808. N is the number of WHATs to shift.
  12809. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12810. the DEFAULT date rather than TODAY."
  12811. (require 'parse-time)
  12812. (when (and
  12813. (string-match
  12814. (concat
  12815. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12816. "\\([0-9]+\\)?"
  12817. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12818. "\\([ \t]\\|$\\)") s)
  12819. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12820. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12821. (string-to-char (substring (match-string 1 s) -1))
  12822. ?+))
  12823. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12824. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12825. (what (if (match-end 3) (match-string 3 s) "d"))
  12826. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12827. (date (if rel default today))
  12828. (wday (nth 6 (decode-time date)))
  12829. delta)
  12830. (if wday1
  12831. (progn
  12832. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12833. (when (= delta 0) (setq delta 7))
  12834. (when (= dir ?-)
  12835. (setq delta (- delta 7))
  12836. (when (= delta 0) (setq delta -7)))
  12837. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12838. (list delta "d" rel))
  12839. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12840. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12841. "Turn a user-specified date into the internal representation.
  12842. The internal representation needed by the calendar is (month day year).
  12843. This is a wrapper to handle the brain-dead convention in calendar that
  12844. user function argument order change dependent on argument order."
  12845. (pcase calendar-date-style
  12846. (`american (list arg1 arg2 arg3))
  12847. (`european (list arg2 arg1 arg3))
  12848. (`iso (list arg2 arg3 arg1))))
  12849. (defun org-eval-in-calendar (form &optional keepdate)
  12850. "Eval FORM in the calendar window and return to current window.
  12851. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12852. (let ((sf (selected-frame))
  12853. (sw (selected-window)))
  12854. (select-window (get-buffer-window "*Calendar*" t))
  12855. (eval form)
  12856. (when (and (not keepdate) (calendar-cursor-to-date))
  12857. (let* ((date (calendar-cursor-to-date))
  12858. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12859. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12860. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12861. (select-window sw)
  12862. (select-frame-set-input-focus sf)))
  12863. (defun org-calendar-select ()
  12864. "Return to `org-read-date' with the date currently selected.
  12865. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12866. (interactive)
  12867. (when (calendar-cursor-to-date)
  12868. (let* ((date (calendar-cursor-to-date))
  12869. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12870. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12871. (when (active-minibuffer-window) (exit-minibuffer))))
  12872. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12873. "Insert a date stamp for the date given by the internal TIME.
  12874. See `format-time-string' for the format of TIME.
  12875. WITH-HM means use the stamp format that includes the time of the day.
  12876. INACTIVE means use square brackets instead of angular ones, so that the
  12877. stamp will not contribute to the agenda.
  12878. PRE and POST are optional strings to be inserted before and after the
  12879. stamp.
  12880. The command returns the inserted time stamp."
  12881. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12882. stamp)
  12883. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12884. (insert-before-markers (or pre ""))
  12885. (when (listp extra)
  12886. (setq extra (car extra))
  12887. (if (and (stringp extra)
  12888. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12889. (setq extra (format "-%02d:%02d"
  12890. (string-to-number (match-string 1 extra))
  12891. (string-to-number (match-string 2 extra))))
  12892. (setq extra nil)))
  12893. (when extra
  12894. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12895. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12896. (insert-before-markers (or post ""))
  12897. (setq org-last-inserted-timestamp stamp)))
  12898. (defun org-toggle-time-stamp-overlays ()
  12899. "Toggle the use of custom time stamp formats."
  12900. (interactive)
  12901. (setq org-display-custom-times (not org-display-custom-times))
  12902. (unless org-display-custom-times
  12903. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12904. (while (setq p (next-single-property-change p 'display))
  12905. (when (and (get-text-property p 'display)
  12906. (eq (get-text-property p 'face) 'org-date))
  12907. (remove-text-properties
  12908. p (setq p (next-single-property-change p 'display))
  12909. '(display t))))
  12910. (set-buffer-modified-p bmp)))
  12911. (org-restart-font-lock)
  12912. (setq org-table-may-need-update t)
  12913. (if org-display-custom-times
  12914. (message "Time stamps are overlaid with custom format")
  12915. (message "Time stamp overlays removed")))
  12916. (defun org-display-custom-time (beg end)
  12917. "Overlay modified time stamp format over timestamp between BEG and END."
  12918. (let* ((ts (buffer-substring beg end))
  12919. t1 with-hm tf time str (off 0))
  12920. (save-match-data
  12921. (setq t1 (org-parse-time-string ts t))
  12922. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12923. (setq off (- (match-end 0) (match-beginning 0)))))
  12924. (setq end (- end off))
  12925. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12926. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12927. time (org-fix-decoded-time t1)
  12928. str (org-add-props
  12929. (format-time-string
  12930. (substring tf 1 -1) (apply 'encode-time time))
  12931. nil 'mouse-face 'highlight))
  12932. (put-text-property beg end 'display str)))
  12933. (defun org-fix-decoded-time (time)
  12934. "Set 0 instead of nil for the first 6 elements of time.
  12935. Don't touch the rest."
  12936. (let ((n 0))
  12937. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12938. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12939. "Difference between TIMESTAMP-STRING and now in days.
  12940. If SECONDS is non-nil, return the difference in seconds."
  12941. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12942. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12943. (funcall fdiff nil))))
  12944. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12945. "Is the time in TIMESTAMP-STRING close to the current date?"
  12946. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12947. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12948. (not (org-entry-is-done-p))))
  12949. (defun org-get-wdays (ts &optional delay zero-delay)
  12950. "Get the deadline lead time appropriate for timestring TS.
  12951. When DELAY is non-nil, get the delay time for scheduled items
  12952. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12953. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12954. don't try to find the delay cookie in the scheduled timestamp."
  12955. (let ((tv (if delay org-scheduled-delay-days
  12956. org-deadline-warning-days)))
  12957. (cond
  12958. ((or (and delay (< tv 0))
  12959. (and delay zero-delay (<= tv 0))
  12960. (and (not delay) (<= tv 0)))
  12961. ;; Enforce this value no matter what
  12962. (- tv))
  12963. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12964. ;; lead time is specified.
  12965. (floor (* (string-to-number (match-string 1 ts))
  12966. (cdr (assoc (match-string 2 ts)
  12967. '(("d" . 1) ("w" . 7)
  12968. ("m" . 30.4) ("y" . 365.25)
  12969. ("h" . 0.041667)))))))
  12970. ;; go for the default.
  12971. (t tv))))
  12972. (defun org-calendar-select-mouse (ev)
  12973. "Return to `org-read-date' with the date currently selected.
  12974. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12975. (interactive "e")
  12976. (mouse-set-point ev)
  12977. (when (calendar-cursor-to-date)
  12978. (let* ((date (calendar-cursor-to-date))
  12979. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12980. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12981. (when (active-minibuffer-window) (exit-minibuffer))))
  12982. (defun org-check-deadlines (ndays)
  12983. "Check if there are any deadlines due or past due.
  12984. A deadline is considered due if it happens within `org-deadline-warning-days'
  12985. days from today's date. If the deadline appears in an entry marked DONE,
  12986. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12987. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12988. are shown."
  12989. (interactive "P")
  12990. (let* ((org-warn-days
  12991. (cond
  12992. ((equal ndays '(4)) 100000)
  12993. (ndays (prefix-numeric-value ndays))
  12994. (t (abs org-deadline-warning-days))))
  12995. (case-fold-search nil)
  12996. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12997. (callback
  12998. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12999. (message "%d deadlines past-due or due within %d days"
  13000. (org-occur regexp nil callback)
  13001. org-warn-days)))
  13002. (defsubst org-re-timestamp (type)
  13003. "Return a regexp for timestamp TYPE.
  13004. Allowed values for TYPE are:
  13005. all: all timestamps
  13006. active: only active timestamps (<...>)
  13007. inactive: only inactive timestamps ([...])
  13008. scheduled: only scheduled timestamps
  13009. deadline: only deadline timestamps
  13010. closed: only closed time-stamps
  13011. When TYPE is nil, fall back on returning a regexp that matches
  13012. both scheduled and deadline timestamps."
  13013. (cl-case type
  13014. (all org-ts-regexp-both)
  13015. (active org-ts-regexp)
  13016. (inactive org-ts-regexp-inactive)
  13017. (scheduled org-scheduled-time-regexp)
  13018. (deadline org-deadline-time-regexp)
  13019. (closed org-closed-time-regexp)
  13020. (otherwise
  13021. (concat "\\<"
  13022. (regexp-opt (list org-deadline-string org-scheduled-string))
  13023. " *<\\([^>]+\\)>"))))
  13024. (defun org-check-before-date (d)
  13025. "Check if there are deadlines or scheduled entries before date D."
  13026. (interactive (list (org-read-date)))
  13027. (let* ((case-fold-search nil)
  13028. (regexp (org-re-timestamp org-ts-type))
  13029. (ts-type org-ts-type)
  13030. (callback
  13031. (lambda ()
  13032. (let ((match (match-string 1)))
  13033. (and (if (memq ts-type '(active inactive all))
  13034. (eq (org-element-type (save-excursion
  13035. (backward-char)
  13036. (org-element-context)))
  13037. 'timestamp)
  13038. (org-at-planning-p))
  13039. (time-less-p
  13040. (org-time-string-to-time match)
  13041. (org-time-string-to-time d)))))))
  13042. (message "%d entries before %s"
  13043. (org-occur regexp nil callback)
  13044. d)))
  13045. (defun org-check-after-date (d)
  13046. "Check if there are deadlines or scheduled entries after date D."
  13047. (interactive (list (org-read-date)))
  13048. (let* ((case-fold-search nil)
  13049. (regexp (org-re-timestamp org-ts-type))
  13050. (ts-type org-ts-type)
  13051. (callback
  13052. (lambda ()
  13053. (let ((match (match-string 1)))
  13054. (and (if (memq ts-type '(active inactive all))
  13055. (eq (org-element-type (save-excursion
  13056. (backward-char)
  13057. (org-element-context)))
  13058. 'timestamp)
  13059. (org-at-planning-p))
  13060. (not (time-less-p
  13061. (org-time-string-to-time match)
  13062. (org-time-string-to-time d))))))))
  13063. (message "%d entries after %s"
  13064. (org-occur regexp nil callback)
  13065. d)))
  13066. (defun org-check-dates-range (start-date end-date)
  13067. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13068. (interactive (list (org-read-date nil nil nil "Range starts")
  13069. (org-read-date nil nil nil "Range end")))
  13070. (let ((case-fold-search nil)
  13071. (regexp (org-re-timestamp org-ts-type))
  13072. (callback
  13073. (let ((type org-ts-type))
  13074. (lambda ()
  13075. (let ((match (match-string 1)))
  13076. (and
  13077. (if (memq type '(active inactive all))
  13078. (eq (org-element-type (save-excursion
  13079. (backward-char)
  13080. (org-element-context)))
  13081. 'timestamp)
  13082. (org-at-planning-p))
  13083. (not (time-less-p
  13084. (org-time-string-to-time match)
  13085. (org-time-string-to-time start-date)))
  13086. (time-less-p
  13087. (org-time-string-to-time match)
  13088. (org-time-string-to-time end-date))))))))
  13089. (message "%d entries between %s and %s"
  13090. (org-occur regexp nil callback) start-date end-date)))
  13091. (defun org-evaluate-time-range (&optional to-buffer)
  13092. "Evaluate a time range by computing the difference between start and end.
  13093. Normally the result is just printed in the echo area, but with prefix arg
  13094. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13095. If the time range is actually in a table, the result is inserted into the
  13096. next column.
  13097. For time difference computation, a year is assumed to be exactly 365
  13098. days in order to avoid rounding problems."
  13099. (interactive "P")
  13100. (or
  13101. (org-clock-update-time-maybe)
  13102. (save-excursion
  13103. (unless (org-at-date-range-p t)
  13104. (goto-char (point-at-bol))
  13105. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13106. (unless (org-at-date-range-p t)
  13107. (user-error "Not at a time-stamp range, and none found in current line")))
  13108. (let* ((ts1 (match-string 1))
  13109. (ts2 (match-string 2))
  13110. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13111. (match-end (match-end 0))
  13112. (time1 (org-time-string-to-time ts1))
  13113. (time2 (org-time-string-to-time ts2))
  13114. (diff (abs (float-time (time-subtract time2 time1))))
  13115. (negative (time-less-p time2 time1))
  13116. ;; (ys (floor (* 365 24 60 60)))
  13117. (ds (* 24 60 60))
  13118. (hs (* 60 60))
  13119. (fy "%dy %dd %02d:%02d")
  13120. (fy1 "%dy %dd")
  13121. (fd "%dd %02d:%02d")
  13122. (fd1 "%dd")
  13123. (fh "%02d:%02d")
  13124. y d h m align)
  13125. (if havetime
  13126. (setq ; y (floor diff ys) diff (mod diff ys)
  13127. y 0
  13128. d (floor diff ds) diff (mod diff ds)
  13129. h (floor diff hs) diff (mod diff hs)
  13130. m (floor diff 60))
  13131. (setq ; y (floor diff ys) diff (mod diff ys)
  13132. y 0
  13133. d (round diff ds)
  13134. h 0 m 0))
  13135. (if (not to-buffer)
  13136. (message "%s" (org-make-tdiff-string y d h m))
  13137. (if (org-at-table-p)
  13138. (progn
  13139. (goto-char match-end)
  13140. (setq align t)
  13141. (and (looking-at " *|") (goto-char (match-end 0))))
  13142. (goto-char match-end))
  13143. (when (looking-at
  13144. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13145. (replace-match ""))
  13146. (when negative (insert " -"))
  13147. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13148. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13149. (insert " " (format fh h m))))
  13150. (when align (org-table-align))
  13151. (message "Time difference inserted")))))
  13152. (defun org-make-tdiff-string (y d h m)
  13153. (let ((fmt "")
  13154. (l nil))
  13155. (when (> y 0)
  13156. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13157. (push y l))
  13158. (when (> d 0)
  13159. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13160. (push d l))
  13161. (when (> h 0)
  13162. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13163. (push h l))
  13164. (when (> m 0)
  13165. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13166. (push m l))
  13167. (apply 'format fmt (nreverse l))))
  13168. (defun org-time-string-to-time (s)
  13169. "Convert timestamp string S into internal time."
  13170. (apply #'encode-time (org-parse-time-string s)))
  13171. (defun org-time-string-to-seconds (s)
  13172. "Convert a timestamp string S into a number of seconds."
  13173. (float-time (org-time-string-to-time s)))
  13174. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13175. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13176. "Convert time stamp S to an absolute day number.
  13177. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13178. stamp, get the closest date to DAYNR. If PREFER is
  13179. `past' (respectively `future') return a date past (respectively
  13180. after) or equal to DAYNR.
  13181. POS is the location of time stamp S, as a buffer position in
  13182. BUFFER.
  13183. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13184. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13185. signaled."
  13186. (cond
  13187. ((string-match "\\`%%\\((.*)\\)" s)
  13188. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13189. ;; only able to match individual dates. If it fails, raise an
  13190. ;; error.
  13191. (if (and daynr
  13192. (org-diary-sexp-entry
  13193. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13194. daynr
  13195. (signal 'org-diary-sexp-no-match (list s))))
  13196. (daynr (org-closest-date s daynr prefer))
  13197. (t (time-to-days
  13198. (condition-case errdata
  13199. (org-time-string-to-time s)
  13200. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13201. s
  13202. (if (not (and buffer pos)) ""
  13203. (format-message " at %d in buffer `%s'" pos buffer))
  13204. (cdr errdata))))))))
  13205. (defun org-days-to-iso-week (days)
  13206. "Return the iso week number."
  13207. (require 'cal-iso)
  13208. (car (calendar-iso-from-absolute days)))
  13209. (defun org-small-year-to-year (year)
  13210. "Convert 2-digit years into 4-digit years.
  13211. YEAR is expanded into one of the 30 next years, if possible, or
  13212. into a past one. Any year larger than 99 is returned unchanged."
  13213. (if (>= year 100) year
  13214. (let* ((current (string-to-number (format-time-string "%Y")))
  13215. (century (/ current 100))
  13216. (offset (- year (% current 100))))
  13217. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13218. ((> offset -70) (+ (* century 100) year))
  13219. (t (+ (* (1+ century) 100) year))))))
  13220. (defun org-time-from-absolute (d)
  13221. "Return the time corresponding to date D.
  13222. D may be an absolute day number, or a calendar-type list (month day year)."
  13223. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13224. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13225. (defvar org-agenda-current-date)
  13226. (defun org-calendar-holiday ()
  13227. "List of holidays, for Diary display in Org mode."
  13228. (require 'holidays)
  13229. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13230. (and hl (mapconcat #'identity hl "; "))))
  13231. (defun org-diary-sexp-entry (sexp entry d)
  13232. "Process a SEXP diary ENTRY for date D."
  13233. (require 'diary-lib)
  13234. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13235. ;; dynamically.
  13236. (let* ((sexp `(let ((entry ,entry)
  13237. (date ',d))
  13238. ,(car (read-from-string sexp))))
  13239. (result (if calendar-debug-sexp (eval sexp)
  13240. (condition-case nil
  13241. (eval sexp)
  13242. (error
  13243. (beep)
  13244. (message "Bad sexp at line %d in %s: %s"
  13245. (org-current-line)
  13246. (buffer-file-name) sexp)
  13247. (sleep-for 2))))))
  13248. (cond ((stringp result) (split-string result "; "))
  13249. ((and (consp result)
  13250. (not (consp (cdr result)))
  13251. (stringp (cdr result))) (cdr result))
  13252. ((and (consp result)
  13253. (stringp (car result))) result)
  13254. (result entry))))
  13255. (defun org-diary-to-ical-string (frombuf)
  13256. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13257. This uses the icalendar.el library."
  13258. (let* ((tmpdir temporary-file-directory)
  13259. (tmpfile (make-temp-name
  13260. (expand-file-name "orgics" tmpdir)))
  13261. buf rtn b e)
  13262. (with-current-buffer frombuf
  13263. (icalendar-export-region (point-min) (point-max) tmpfile)
  13264. (setq buf (find-buffer-visiting tmpfile))
  13265. (set-buffer buf)
  13266. (goto-char (point-min))
  13267. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13268. (setq b (match-beginning 0)))
  13269. (goto-char (point-max))
  13270. (when (re-search-backward "^END:VEVENT" nil t)
  13271. (setq e (match-end 0)))
  13272. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13273. (kill-buffer buf)
  13274. (delete-file tmpfile)
  13275. rtn))
  13276. (defun org-closest-date (start current prefer)
  13277. "Return closest date to CURRENT starting from START.
  13278. CURRENT and START are both time stamps.
  13279. When PREFER is `past', return a date that is either CURRENT or
  13280. past. When PREFER is `future', return a date that is either
  13281. CURRENT or future.
  13282. Only time stamps with a repeater are modified. Any other time
  13283. stamp stay unchanged. In any case, return value is an absolute
  13284. day number."
  13285. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13286. ;; No repeater. Do not shift time stamp.
  13287. (time-to-days (org-time-string-to-time start))
  13288. (let ((value (string-to-number (match-string 1 start)))
  13289. (type (match-string 2 start)))
  13290. (if (= 0 value)
  13291. ;; Repeater with a 0-value is considered as void.
  13292. (time-to-days (org-time-string-to-time start))
  13293. (let* ((base (org-date-to-gregorian start))
  13294. (target (org-date-to-gregorian current))
  13295. (sday (calendar-absolute-from-gregorian base))
  13296. (cday (calendar-absolute-from-gregorian target))
  13297. n1 n2)
  13298. ;; If START is already past CURRENT, just return START.
  13299. (if (<= cday sday) sday
  13300. ;; Compute closest date before (N1) and closest date past
  13301. ;; (N2) CURRENT.
  13302. (pcase type
  13303. ("h"
  13304. (let ((missing-hours
  13305. (mod (+ (- (* 24 (- cday sday))
  13306. (nth 2 (org-parse-time-string start)))
  13307. org-extend-today-until)
  13308. value)))
  13309. (setf n1 (if (= missing-hours 0) cday
  13310. (- cday (1+ (/ missing-hours 24)))))
  13311. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13312. ((or "d" "w")
  13313. (let ((value (if (equal type "w") (* 7 value) value)))
  13314. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13315. (setf n2 (+ n1 value))))
  13316. ("m"
  13317. (let* ((add-months
  13318. (lambda (d n)
  13319. ;; Add N months to gregorian date D, i.e.,
  13320. ;; a list (MONTH DAY YEAR). Return a valid
  13321. ;; gregorian date.
  13322. (let ((m (+ (nth 0 d) n)))
  13323. (list (mod m 12)
  13324. (nth 1 d)
  13325. (+ (/ m 12) (nth 2 d))))))
  13326. (months ; Complete months to TARGET.
  13327. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13328. (- (nth 0 target) (nth 0 base))
  13329. ;; If START's day is greater than
  13330. ;; TARGET's, remove incomplete month.
  13331. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13332. value)
  13333. value))
  13334. (before (funcall add-months base months)))
  13335. (setf n1 (calendar-absolute-from-gregorian before))
  13336. (setf n2
  13337. (calendar-absolute-from-gregorian
  13338. (funcall add-months before value)))))
  13339. (_
  13340. (let* ((d (nth 1 base))
  13341. (m (nth 0 base))
  13342. (y (nth 2 base))
  13343. (years ; Complete years to TARGET.
  13344. (* (/ (- (nth 2 target)
  13345. y
  13346. ;; If START's month and day are
  13347. ;; greater than TARGET's, remove
  13348. ;; incomplete year.
  13349. (if (or (> (nth 0 target) m)
  13350. (and (= (nth 0 target) m)
  13351. (> (nth 1 target) d)))
  13352. 0
  13353. 1))
  13354. value)
  13355. value))
  13356. (before (list m d (+ y years))))
  13357. (setf n1 (calendar-absolute-from-gregorian before))
  13358. (setf n2 (calendar-absolute-from-gregorian
  13359. (list m d (+ (nth 2 before) value)))))))
  13360. ;; Handle PREFER parameter, if any.
  13361. (cond
  13362. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13363. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13364. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13365. (defun org-date-to-gregorian (d)
  13366. "Turn any specification of date D into a Gregorian date for the calendar."
  13367. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13368. ((and (listp d) (= (length d) 3)) d)
  13369. ((stringp d)
  13370. (let ((d (org-parse-time-string d)))
  13371. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13372. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13373. (defun org-timestamp-up (&optional arg)
  13374. "Increase the date item at the cursor by one.
  13375. If the cursor is on the year, change the year. If it is on the month,
  13376. the day or the time, change that. If the cursor is on the enclosing
  13377. bracket, change the timestamp type.
  13378. With prefix ARG, change by that many units."
  13379. (interactive "p")
  13380. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13381. (defun org-timestamp-down (&optional arg)
  13382. "Decrease the date item at the cursor by one.
  13383. If the cursor is on the year, change the year. If it is on the month,
  13384. the day or the time, change that. If the cursor is on the enclosing
  13385. bracket, change the timestamp type.
  13386. With prefix ARG, change by that many units."
  13387. (interactive "p")
  13388. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13389. (defun org-timestamp-up-day (&optional arg)
  13390. "Increase the date in the time stamp by one day.
  13391. With prefix ARG, change that many days."
  13392. (interactive "p")
  13393. (if (and (not (org-at-timestamp-p 'lax))
  13394. (org-at-heading-p))
  13395. (org-todo 'up)
  13396. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13397. (defun org-timestamp-down-day (&optional arg)
  13398. "Decrease the date in the time stamp by one day.
  13399. With prefix ARG, change that many days."
  13400. (interactive "p")
  13401. (if (and (not (org-at-timestamp-p 'lax))
  13402. (org-at-heading-p))
  13403. (org-todo 'down)
  13404. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13405. (defun org-at-timestamp-p (&optional extended)
  13406. "Non-nil if point is inside a timestamp.
  13407. By default, the function only consider syntactically valid active
  13408. timestamps. However, the caller may have a broader definition
  13409. for timestamps. As a consequence, optional argument EXTENDED can
  13410. be set to the following values
  13411. `inactive'
  13412. Include also syntactically valid inactive timestamps.
  13413. `agenda'
  13414. Include timestamps allowed in Agenda, i.e., those in
  13415. properties drawers, planning lines and clock lines.
  13416. `lax'
  13417. Ignore context. The function matches any part of the
  13418. document looking like a timestamp. This includes comments,
  13419. example blocks...
  13420. For backward-compatibility with Org 9.0, every other non-nil
  13421. value is equivalent to `inactive'.
  13422. When at a timestamp, return the position of the point as a symbol
  13423. among `bracket', `after', `year', `month', `hour', `minute',
  13424. `day' or a number of character from the last know part of the
  13425. time stamp.
  13426. When matching, the match groups are the following:
  13427. group 1: year
  13428. group 2: month
  13429. group 3: day number
  13430. group 4: day name
  13431. group 5: hours, if any
  13432. group 6: minutes, if any"
  13433. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13434. (pos (point))
  13435. (match?
  13436. (let ((boundaries (org-in-regexp regexp)))
  13437. (save-match-data
  13438. (cond ((null boundaries) nil)
  13439. ((eq extended 'lax) t)
  13440. (t
  13441. (or (and (eq extended 'agenda)
  13442. (or (org-at-planning-p)
  13443. (org-at-property-p)
  13444. (and (bound-and-true-p
  13445. org-agenda-include-inactive-timestamps)
  13446. (org-at-clock-log-p))))
  13447. (eq 'timestamp
  13448. (save-excursion
  13449. (when (= pos (cdr boundaries)) (forward-char -1))
  13450. (org-element-type (org-element-context)))))))))))
  13451. (cond
  13452. ((not match?) nil)
  13453. ((= pos (match-beginning 0)) 'bracket)
  13454. ;; Distinguish location right before the closing bracket from
  13455. ;; right after it.
  13456. ((= pos (1- (match-end 0))) 'bracket)
  13457. ((= pos (match-end 0)) 'after)
  13458. ((org-pos-in-match-range pos 2) 'year)
  13459. ((org-pos-in-match-range pos 3) 'month)
  13460. ((org-pos-in-match-range pos 7) 'hour)
  13461. ((org-pos-in-match-range pos 8) 'minute)
  13462. ((or (org-pos-in-match-range pos 4)
  13463. (org-pos-in-match-range pos 5)) 'day)
  13464. ((and (> pos (or (match-end 8) (match-end 5)))
  13465. (< pos (match-end 0)))
  13466. (- pos (or (match-end 8) (match-end 5))))
  13467. (t 'day))))
  13468. (defun org-toggle-timestamp-type ()
  13469. "Toggle the type (<active> or [inactive]) of a time stamp."
  13470. (interactive)
  13471. (when (org-at-timestamp-p 'lax)
  13472. (let ((beg (match-beginning 0)) (end (match-end 0))
  13473. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13474. (save-excursion
  13475. (goto-char beg)
  13476. (while (re-search-forward "[][<>]" end t)
  13477. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13478. t t)))
  13479. (message "Timestamp is now %sactive"
  13480. (if (equal (char-after beg) ?<) "" "in")))))
  13481. (defun org-at-clock-log-p ()
  13482. "Non-nil if point is on a clock log line."
  13483. (and (org-match-line org-clock-line-re)
  13484. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13485. (defvar org-clock-history) ; defined in org-clock.el
  13486. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13487. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13488. "Change the date in the time stamp at point.
  13489. The date is changed by N times WHAT. WHAT can be `day', `month',
  13490. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13491. position in the timestamp determines what is changed.
  13492. When optional argument UPDOWN is non-nil, minutes are rounded
  13493. according to `org-time-stamp-rounding-minutes'.
  13494. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13495. \"--2d\"."
  13496. (let ((origin (point))
  13497. (timestamp? (org-at-timestamp-p 'lax))
  13498. origin-cat
  13499. with-hm inactive
  13500. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13501. extra rem
  13502. ts time time0 fixnext clrgx)
  13503. (unless timestamp? (user-error "Not at a timestamp"))
  13504. (if (and (not what) (eq timestamp? 'bracket))
  13505. (org-toggle-timestamp-type)
  13506. ;; Point isn't on brackets. Remember the part of the time-stamp
  13507. ;; the point was in. Indeed, size of time-stamps may change,
  13508. ;; but point must be kept in the same category nonetheless.
  13509. (setq origin-cat timestamp?)
  13510. (when (and (not what) (not (eq timestamp? 'day))
  13511. org-display-custom-times
  13512. (get-text-property (point) 'display)
  13513. (not (get-text-property (1- (point)) 'display)))
  13514. (setq timestamp? 'day))
  13515. (setq timestamp? (or what timestamp?)
  13516. inactive (= (char-after (match-beginning 0)) ?\[)
  13517. ts (match-string 0))
  13518. (replace-match "")
  13519. (when (string-match
  13520. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13521. ts)
  13522. (setq extra (match-string 1 ts))
  13523. (when suppress-tmp-delay
  13524. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13525. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13526. (setq with-hm t))
  13527. (setq time0 (org-parse-time-string ts))
  13528. (when (and updown
  13529. (eq timestamp? 'minute)
  13530. (not current-prefix-arg))
  13531. ;; This looks like s-up and s-down. Change by one rounding step.
  13532. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13533. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13534. (setcar (cdr time0) (+ (nth 1 time0)
  13535. (if (> n 0) (- rem) (- dm rem))))))
  13536. (setq time
  13537. (apply #'encode-time
  13538. (or (car time0) 0)
  13539. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13540. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13541. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13542. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13543. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13544. (nthcdr 6 time0)))
  13545. (when (and (memq timestamp? '(hour minute))
  13546. extra
  13547. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13548. (setq extra (org-modify-ts-extra
  13549. extra
  13550. (if (eq timestamp? 'hour) 2 5)
  13551. n dm)))
  13552. (when (integerp timestamp?)
  13553. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13554. (when (eq what 'calendar)
  13555. (let ((cal-date (org-get-date-from-calendar)))
  13556. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13557. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13558. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13559. (setcar time0 (or (car time0) 0))
  13560. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13561. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13562. (setq time (apply 'encode-time time0))))
  13563. ;; Insert the new time-stamp, and ensure point stays in the same
  13564. ;; category as before (i.e. not after the last position in that
  13565. ;; category).
  13566. (let ((pos (point)))
  13567. ;; Stay before inserted string. `save-excursion' is of no use.
  13568. (setq org-last-changed-timestamp
  13569. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13570. (goto-char pos))
  13571. (save-match-data
  13572. (looking-at org-ts-regexp3)
  13573. (goto-char
  13574. (pcase origin-cat
  13575. ;; `day' category ends before `hour' if any, or at the end
  13576. ;; of the day name.
  13577. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13578. (`hour (min (match-end 7) origin))
  13579. (`minute (min (1- (match-end 8)) origin))
  13580. ((pred integerp) (min (1- (match-end 0)) origin))
  13581. ;; Point was right after the time-stamp. However, the
  13582. ;; time-stamp length might have changed, so refer to
  13583. ;; (match-end 0) instead.
  13584. (`after (match-end 0))
  13585. ;; `year' and `month' have both fixed size: point couldn't
  13586. ;; have moved into another part.
  13587. (_ origin))))
  13588. ;; Update clock if on a CLOCK line.
  13589. (org-clock-update-time-maybe)
  13590. ;; Maybe adjust the closest clock in `org-clock-history'
  13591. (when org-clock-adjust-closest
  13592. (if (not (and (org-at-clock-log-p)
  13593. (< 1 (length (delq nil (mapcar 'marker-position
  13594. org-clock-history))))))
  13595. (message "No clock to adjust")
  13596. (cond ((save-excursion ; fix previous clock?
  13597. (re-search-backward org-ts-regexp0 nil t)
  13598. (looking-back (concat org-clock-string " \\[")
  13599. (line-beginning-position)))
  13600. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13601. ((save-excursion ; fix next clock?
  13602. (re-search-backward org-ts-regexp0 nil t)
  13603. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13604. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13605. (save-window-excursion
  13606. ;; Find closest clock to point, adjust the previous/next one in history
  13607. (let* ((p (save-excursion (org-back-to-heading t)))
  13608. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13609. (clfixnth
  13610. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13611. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13612. (if (not clfixpos)
  13613. (message "No clock to adjust")
  13614. (save-excursion
  13615. (org-goto-marker-or-bmk clfixpos)
  13616. (org-show-subtree)
  13617. (when (re-search-forward clrgx nil t)
  13618. (goto-char (match-beginning 1))
  13619. (let (org-clock-adjust-closest)
  13620. (org-timestamp-change n timestamp? updown))
  13621. (message "Clock adjusted in %s for heading: %s"
  13622. (file-name-nondirectory (buffer-file-name))
  13623. (org-get-heading t t)))))))))
  13624. ;; Try to recenter the calendar window, if any.
  13625. (when (and org-calendar-follow-timestamp-change
  13626. (get-buffer-window "*Calendar*" t)
  13627. (memq timestamp? '(day month year)))
  13628. (org-recenter-calendar (time-to-days time))))))
  13629. (defun org-modify-ts-extra (s pos n dm)
  13630. "Change the different parts of the lead-time and repeat fields in timestamp."
  13631. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13632. ng h m new rem)
  13633. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13634. (cond
  13635. ((or (org-pos-in-match-range pos 2)
  13636. (org-pos-in-match-range pos 3))
  13637. (setq m (string-to-number (match-string 3 s))
  13638. h (string-to-number (match-string 2 s)))
  13639. (if (org-pos-in-match-range pos 2)
  13640. (setq h (+ h n))
  13641. (setq n (* dm (with-no-warnings (cl-signum n))))
  13642. (unless (= 0 (setq rem (% m dm)))
  13643. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13644. (setq m (+ m n)))
  13645. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13646. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13647. (setq h (mod h 24))
  13648. (setq ng 1 new (format "-%02d:%02d" h m)))
  13649. ((org-pos-in-match-range pos 6)
  13650. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13651. ((org-pos-in-match-range pos 5)
  13652. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13653. ((org-pos-in-match-range pos 9)
  13654. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13655. ((org-pos-in-match-range pos 8)
  13656. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13657. (when ng
  13658. (setq s (concat
  13659. (substring s 0 (match-beginning ng))
  13660. new
  13661. (substring s (match-end ng))))))
  13662. s))
  13663. (defun org-recenter-calendar (d)
  13664. "If the calendar is visible, recenter it to date D."
  13665. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13666. (when cwin
  13667. (let ((calendar-move-hook nil))
  13668. (with-selected-window cwin
  13669. (calendar-goto-date
  13670. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13671. (defun org-goto-calendar (&optional arg)
  13672. "Go to the Emacs calendar at the current date.
  13673. If there is a time stamp in the current line, go to that date.
  13674. A prefix ARG can be used to force the current date."
  13675. (interactive "P")
  13676. (let ((calendar-move-hook nil)
  13677. (calendar-view-holidays-initially-flag nil)
  13678. (calendar-view-diary-initially-flag nil)
  13679. diff)
  13680. (when (or (org-at-timestamp-p 'lax)
  13681. (org-match-line (concat ".*" org-ts-regexp)))
  13682. (let ((d1 (time-to-days nil))
  13683. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13684. (setq diff (- d2 d1))))
  13685. (calendar)
  13686. (calendar-goto-today)
  13687. (when (and diff (not arg)) (calendar-forward-day diff))))
  13688. (defun org-get-date-from-calendar ()
  13689. "Return a list (month day year) of date at point in calendar."
  13690. (with-current-buffer "*Calendar*"
  13691. (save-match-data
  13692. (calendar-cursor-to-date))))
  13693. (defun org-date-from-calendar ()
  13694. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13695. If there is already a time stamp at the cursor position, update it."
  13696. (interactive)
  13697. (if (org-at-timestamp-p 'lax)
  13698. (org-timestamp-change 0 'calendar)
  13699. (let ((cal-date (org-get-date-from-calendar)))
  13700. (org-insert-time-stamp
  13701. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13702. (defcustom org-image-actual-width t
  13703. "When non-nil, use the actual width of images when inlining them.
  13704. When set to a number, use imagemagick (when available) to set the
  13705. image's width to this value.
  13706. When set to a number in a list, try to get the width from any
  13707. #+ATTR.* keyword if it matches a width specification like
  13708. #+ATTR_HTML: :width 300px
  13709. and fall back on that number if none is found.
  13710. When set to nil, try to get the width from an #+ATTR.* keyword
  13711. and fall back on the original width if none is found.
  13712. When set to any other non-nil value, always use the image width.
  13713. This requires Emacs >= 24.1, built with imagemagick support."
  13714. :group 'org-appearance
  13715. :version "24.4"
  13716. :package-version '(Org . "8.0")
  13717. :type '(choice
  13718. (const :tag "Use the image width" t)
  13719. (integer :tag "Use a number of pixels")
  13720. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13721. (const :tag "Use #+ATTR* or don't resize" nil)))
  13722. (defcustom org-agenda-inhibit-startup nil
  13723. "Inhibit startup when preparing agenda buffers.
  13724. When this variable is t, the initialization of the Org agenda
  13725. buffers is inhibited: e.g. the visibility state is not set, the
  13726. tables are not re-aligned, etc."
  13727. :type 'boolean
  13728. :version "24.3"
  13729. :group 'org-agenda)
  13730. (defcustom org-agenda-ignore-properties nil
  13731. "Avoid updating text properties when building the agenda.
  13732. Properties are used to prepare buffers for effort estimates,
  13733. appointments, statistics and subtree-local categories.
  13734. If you don't use these in the agenda, you can add them to this
  13735. list and agenda building will be a bit faster.
  13736. The value is a list, with zero or more of the symbols `effort', `appt',
  13737. `stats' or `category'."
  13738. :type '(set :greedy t
  13739. (const effort)
  13740. (const appt)
  13741. (const stats)
  13742. (const category))
  13743. :version "26.1"
  13744. :package-version '(Org . "8.3")
  13745. :group 'org-agenda)
  13746. ;;;; Files
  13747. (defun org-save-all-org-buffers ()
  13748. "Save all Org buffers without user confirmation."
  13749. (interactive)
  13750. (message "Saving all Org buffers...")
  13751. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13752. (when (featurep 'org-id) (org-id-locations-save))
  13753. (message "Saving all Org buffers... done"))
  13754. (defun org-revert-all-org-buffers ()
  13755. "Revert all Org buffers.
  13756. Prompt for confirmation when there are unsaved changes.
  13757. Be sure you know what you are doing before letting this function
  13758. overwrite your changes.
  13759. This function is useful in a setup where one tracks Org files
  13760. with a version control system, to revert on one machine after pulling
  13761. changes from another. I believe the procedure must be like this:
  13762. 1. M-x org-save-all-org-buffers
  13763. 2. Pull changes from the other machine, resolve conflicts
  13764. 3. M-x org-revert-all-org-buffers"
  13765. (interactive)
  13766. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13767. (user-error "Abort"))
  13768. (save-excursion
  13769. (save-window-excursion
  13770. (dolist (b (buffer-list))
  13771. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13772. (with-current-buffer b buffer-file-name))
  13773. (pop-to-buffer-same-window b)
  13774. (revert-buffer t 'no-confirm)))
  13775. (when (and (featurep 'org-id) org-id-track-globally)
  13776. (org-id-locations-load)))))
  13777. ;;;; Agenda files
  13778. ;;;###autoload
  13779. (defun org-switchb (&optional arg)
  13780. "Switch between Org buffers.
  13781. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13782. With `\\[universal-argument] \\[universal-argument]' \
  13783. prefix, restrict available buffers to agenda files."
  13784. (interactive "P")
  13785. (let ((blist (org-buffer-list
  13786. (cond ((equal arg '(4)) 'files)
  13787. ((equal arg '(16)) 'agenda)))))
  13788. (pop-to-buffer-same-window
  13789. (completing-read "Org buffer: "
  13790. (mapcar #'list (mapcar #'buffer-name blist))
  13791. nil t))))
  13792. (defun org-buffer-list (&optional predicate exclude-tmp)
  13793. "Return a list of Org buffers.
  13794. PREDICATE can be `export', `files' or `agenda'.
  13795. export restrict the list to Export buffers.
  13796. files restrict the list to buffers visiting Org files.
  13797. agenda restrict the list to buffers visiting agenda files.
  13798. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13799. (let* ((bfn nil)
  13800. (agenda-files (and (eq predicate 'agenda)
  13801. (mapcar 'file-truename (org-agenda-files t))))
  13802. (filter
  13803. (cond
  13804. ((eq predicate 'files)
  13805. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13806. ((eq predicate 'export)
  13807. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13808. ((eq predicate 'agenda)
  13809. (lambda (b)
  13810. (with-current-buffer b
  13811. (and (derived-mode-p 'org-mode)
  13812. (setq bfn (buffer-file-name b))
  13813. (member (file-truename bfn) agenda-files)))))
  13814. (t (lambda (b) (with-current-buffer b
  13815. (or (derived-mode-p 'org-mode)
  13816. (string-match "\\*Org .*Export"
  13817. (buffer-name b)))))))))
  13818. (delq nil
  13819. (mapcar
  13820. (lambda(b)
  13821. (if (and (funcall filter b)
  13822. (or (not exclude-tmp)
  13823. (not (string-match "tmp" (buffer-name b)))))
  13824. b
  13825. nil))
  13826. (buffer-list)))))
  13827. (defun org-agenda-files (&optional unrestricted archives)
  13828. "Get the list of agenda files.
  13829. Optional UNRESTRICTED means return the full list even if a restriction
  13830. is currently in place.
  13831. When ARCHIVES is t, include all archive files that are really being
  13832. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13833. `org-agenda-archives-mode' is t."
  13834. (let ((files
  13835. (cond
  13836. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13837. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13838. ((listp org-agenda-files) org-agenda-files)
  13839. (t (error "Invalid value of `org-agenda-files'")))))
  13840. (setq files (apply 'append
  13841. (mapcar (lambda (f)
  13842. (if (file-directory-p f)
  13843. (directory-files
  13844. f t org-agenda-file-regexp)
  13845. (list f)))
  13846. files)))
  13847. (when org-agenda-skip-unavailable-files
  13848. (setq files (delq nil
  13849. (mapcar (function
  13850. (lambda (file)
  13851. (and (file-readable-p file) file)))
  13852. files))))
  13853. (when (or (eq archives t)
  13854. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13855. (setq files (org-add-archive-files files)))
  13856. files))
  13857. (defun org-agenda-file-p (&optional file)
  13858. "Return non-nil, if FILE is an agenda file.
  13859. If FILE is omitted, use the file associated with the current
  13860. buffer."
  13861. (let ((fname (or file (buffer-file-name))))
  13862. (and fname
  13863. (member (file-truename fname)
  13864. (mapcar #'file-truename (org-agenda-files t))))))
  13865. (defun org-edit-agenda-file-list ()
  13866. "Edit the list of agenda files.
  13867. Depending on setup, this either uses customize to edit the variable
  13868. `org-agenda-files', or it visits the file that is holding the list. In the
  13869. latter case, the buffer is set up in a way that saving it automatically kills
  13870. the buffer and restores the previous window configuration."
  13871. (interactive)
  13872. (if (stringp org-agenda-files)
  13873. (let ((cw (current-window-configuration)))
  13874. (find-file org-agenda-files)
  13875. (setq-local org-window-configuration cw)
  13876. (add-hook 'after-save-hook
  13877. (lambda ()
  13878. (set-window-configuration
  13879. (prog1 org-window-configuration
  13880. (kill-buffer (current-buffer))))
  13881. (org-install-agenda-files-menu)
  13882. (message "New agenda file list installed"))
  13883. nil 'local)
  13884. (message "%s" (substitute-command-keys
  13885. "Edit list and finish with \\[save-buffer]")))
  13886. (customize-variable 'org-agenda-files)))
  13887. (defun org-store-new-agenda-file-list (list)
  13888. "Set new value for the agenda file list and save it correctly."
  13889. (if (stringp org-agenda-files)
  13890. (let ((fe (org-read-agenda-file-list t)) b u)
  13891. (while (setq b (find-buffer-visiting org-agenda-files))
  13892. (kill-buffer b))
  13893. (with-temp-file org-agenda-files
  13894. (insert
  13895. (mapconcat
  13896. (lambda (f) ;; Keep un-expanded entries.
  13897. (if (setq u (assoc f fe))
  13898. (cdr u)
  13899. f))
  13900. list "\n")
  13901. "\n")))
  13902. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13903. (org-insert-mode-line-in-empty-file nil))
  13904. (setq org-agenda-files list)
  13905. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13906. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13907. "Read the list of agenda files from a file.
  13908. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13909. filenames, used by `org-store-new-agenda-file-list' to write back
  13910. un-expanded file names."
  13911. (when (file-directory-p org-agenda-files)
  13912. (error "`org-agenda-files' cannot be a single directory"))
  13913. (when (stringp org-agenda-files)
  13914. (with-temp-buffer
  13915. (insert-file-contents org-agenda-files)
  13916. (mapcar
  13917. (lambda (f)
  13918. (let ((e (expand-file-name (substitute-in-file-name f)
  13919. org-directory)))
  13920. (if pair-with-expansion
  13921. (cons e f)
  13922. e)))
  13923. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13924. ;;;###autoload
  13925. (defun org-cycle-agenda-files ()
  13926. "Cycle through the files in `org-agenda-files'.
  13927. If the current buffer visits an agenda file, find the next one in the list.
  13928. If the current buffer does not, find the first agenda file."
  13929. (interactive)
  13930. (let* ((fs (or (org-agenda-files t)
  13931. (user-error "No agenda files")))
  13932. (files (copy-sequence fs))
  13933. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13934. file)
  13935. (when tcf
  13936. (while (and (setq file (pop files))
  13937. (not (equal (file-truename file) tcf)))))
  13938. (find-file (car (or files fs)))
  13939. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13940. (defun org-agenda-file-to-front (&optional to-end)
  13941. "Move/add the current file to the top of the agenda file list.
  13942. If the file is not present in the list, it is added to the front. If it is
  13943. present, it is moved there. With optional argument TO-END, add/move to the
  13944. end of the list."
  13945. (interactive "P")
  13946. (let ((org-agenda-skip-unavailable-files nil)
  13947. (file-alist (mapcar (lambda (x)
  13948. (cons (file-truename x) x))
  13949. (org-agenda-files t)))
  13950. (ctf (file-truename
  13951. (or buffer-file-name
  13952. (user-error "Please save the current buffer to a file"))))
  13953. x had)
  13954. (setq x (assoc ctf file-alist) had x)
  13955. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13956. (if to-end
  13957. (setq file-alist (append (delq x file-alist) (list x)))
  13958. (setq file-alist (cons x (delq x file-alist))))
  13959. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13960. (org-install-agenda-files-menu)
  13961. (message "File %s to %s of agenda file list"
  13962. (if had "moved" "added") (if to-end "end" "front"))))
  13963. (defun org-remove-file (&optional file)
  13964. "Remove current file from the list of files in variable `org-agenda-files'.
  13965. These are the files which are being checked for agenda entries.
  13966. Optional argument FILE means use this file instead of the current."
  13967. (interactive)
  13968. (let* ((org-agenda-skip-unavailable-files nil)
  13969. (file (or file buffer-file-name
  13970. (user-error "Current buffer does not visit a file")))
  13971. (true-file (file-truename file))
  13972. (afile (abbreviate-file-name file))
  13973. (files (delq nil (mapcar
  13974. (lambda (x)
  13975. (unless (equal true-file
  13976. (file-truename x))
  13977. x))
  13978. (org-agenda-files t)))))
  13979. (if (not (= (length files) (length (org-agenda-files t))))
  13980. (progn
  13981. (org-store-new-agenda-file-list files)
  13982. (org-install-agenda-files-menu)
  13983. (message "Removed from Org Agenda list: %s" afile))
  13984. (message "File was not in list: %s (not removed)" afile))))
  13985. (defun org-file-menu-entry (file)
  13986. (vector file (list 'find-file file) t))
  13987. (defun org-check-agenda-file (file)
  13988. "Make sure FILE exists. If not, ask user what to do."
  13989. (unless (file-exists-p file)
  13990. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13991. (abbreviate-file-name file))
  13992. (let ((r (downcase (read-char-exclusive))))
  13993. (cond
  13994. ((equal r ?r)
  13995. (org-remove-file file)
  13996. (throw 'nextfile t))
  13997. (t (user-error "Abort"))))))
  13998. (defun org-get-agenda-file-buffer (file)
  13999. "Get an agenda buffer visiting FILE.
  14000. If the buffer needs to be created, add it to the list of buffers
  14001. which might be released later."
  14002. (let ((buf (org-find-base-buffer-visiting file)))
  14003. (if buf
  14004. buf ; just return it
  14005. ;; Make a new buffer and remember it
  14006. (setq buf (find-file-noselect file))
  14007. (when buf (push buf org-agenda-new-buffers))
  14008. buf)))
  14009. (defun org-release-buffers (blist)
  14010. "Release all buffers in list, asking the user for confirmation when needed.
  14011. When a buffer is unmodified, it is just killed. When modified, it is saved
  14012. \(if the user agrees) and then killed."
  14013. (let (file)
  14014. (dolist (buf blist)
  14015. (setq file (buffer-file-name buf))
  14016. (when (and (buffer-modified-p buf)
  14017. file
  14018. (y-or-n-p (format "Save file %s? " file)))
  14019. (with-current-buffer buf (save-buffer)))
  14020. (kill-buffer buf))))
  14021. (defun org-agenda-prepare-buffers (files)
  14022. "Create buffers for all agenda files, protect archived trees and comments."
  14023. (interactive)
  14024. (let ((pa '(:org-archived t))
  14025. (pc '(:org-comment t))
  14026. (pall '(:org-archived t :org-comment t))
  14027. (inhibit-read-only t)
  14028. (org-inhibit-startup org-agenda-inhibit-startup)
  14029. (rea (org-make-tag-string (list org-archive-tag)))
  14030. re pos)
  14031. (setq org-tag-alist-for-agenda nil
  14032. org-tag-groups-alist-for-agenda nil)
  14033. (save-excursion
  14034. (save-restriction
  14035. (dolist (file files)
  14036. (catch 'nextfile
  14037. (if (bufferp file)
  14038. (set-buffer file)
  14039. (org-check-agenda-file file)
  14040. (set-buffer (org-get-agenda-file-buffer file)))
  14041. (widen)
  14042. (org-set-regexps-and-options 'tags-only)
  14043. (setq pos (point))
  14044. (or (memq 'category org-agenda-ignore-properties)
  14045. (org-refresh-category-properties))
  14046. (or (memq 'stats org-agenda-ignore-properties)
  14047. (org-refresh-stats-properties))
  14048. (or (memq 'effort org-agenda-ignore-properties)
  14049. (org-refresh-effort-properties))
  14050. (or (memq 'appt org-agenda-ignore-properties)
  14051. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14052. (setq org-todo-keywords-for-agenda
  14053. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14054. (setq org-done-keywords-for-agenda
  14055. (append org-done-keywords-for-agenda org-done-keywords))
  14056. (setq org-todo-keyword-alist-for-agenda
  14057. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14058. (setq org-tag-alist-for-agenda
  14059. (org--tag-add-to-alist
  14060. org-tag-alist-for-agenda
  14061. org-current-tag-alist))
  14062. ;; Merge current file's tag groups into global
  14063. ;; `org-tag-groups-alist-for-agenda'.
  14064. (when org-group-tags
  14065. (dolist (alist org-tag-groups-alist)
  14066. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14067. (if old
  14068. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14069. (push alist org-tag-groups-alist-for-agenda)))))
  14070. (with-silent-modifications
  14071. (save-excursion
  14072. (remove-text-properties (point-min) (point-max) pall)
  14073. (when org-agenda-skip-archived-trees
  14074. (goto-char (point-min))
  14075. (while (re-search-forward rea nil t)
  14076. (when (org-at-heading-p t)
  14077. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14078. (goto-char (point-min))
  14079. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14080. (while (re-search-forward re nil t)
  14081. (when (save-match-data (org-in-commented-heading-p t))
  14082. (add-text-properties
  14083. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14084. (goto-char pos)))))
  14085. (setq org-todo-keywords-for-agenda
  14086. (org-uniquify org-todo-keywords-for-agenda))
  14087. (setq org-todo-keyword-alist-for-agenda
  14088. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14089. ;;;; CDLaTeX minor mode
  14090. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14091. "Keymap for the minor `org-cdlatex-mode'.")
  14092. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14093. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14094. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14095. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14096. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14097. (defvar org-cdlatex-texmathp-advice-is-done nil
  14098. "Flag remembering if we have applied the advice to texmathp already.")
  14099. (define-minor-mode org-cdlatex-mode
  14100. "Toggle the minor `org-cdlatex-mode'.
  14101. This mode supports entering LaTeX environment and math in LaTeX fragments
  14102. in Org mode.
  14103. \\{org-cdlatex-mode-map}"
  14104. nil " OCDL" nil
  14105. (when org-cdlatex-mode
  14106. (require 'cdlatex)
  14107. (run-hooks 'cdlatex-mode-hook)
  14108. (cdlatex-compute-tables))
  14109. (unless org-cdlatex-texmathp-advice-is-done
  14110. (setq org-cdlatex-texmathp-advice-is-done t)
  14111. (defadvice texmathp (around org-math-always-on activate)
  14112. "Always return t in Org buffers.
  14113. This is because we want to insert math symbols without dollars even outside
  14114. the LaTeX math segments. If Org mode thinks that point is actually inside
  14115. an embedded LaTeX fragment, let `texmathp' do its job.
  14116. `\\[org-cdlatex-mode-map]'"
  14117. (interactive)
  14118. (let (p)
  14119. (cond
  14120. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14121. ((eq this-command 'cdlatex-math-symbol)
  14122. (setq ad-return-value t
  14123. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14124. (t
  14125. (let ((p (org-inside-LaTeX-fragment-p)))
  14126. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14127. (setq ad-return-value t
  14128. texmathp-why '("Org mode embedded math" . 0))
  14129. (when p ad-do-it)))))))))
  14130. (defun turn-on-org-cdlatex ()
  14131. "Unconditionally turn on `org-cdlatex-mode'."
  14132. (org-cdlatex-mode 1))
  14133. (defun org-try-cdlatex-tab ()
  14134. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14135. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14136. - inside a LaTeX fragment, or
  14137. - after the first word in a line, where an abbreviation expansion could
  14138. insert a LaTeX environment."
  14139. (when org-cdlatex-mode
  14140. (cond
  14141. ;; Before any word on the line: No expansion possible.
  14142. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14143. ;; Just after first word on the line: Expand it. Make sure it
  14144. ;; cannot happen on headlines, though.
  14145. ((save-excursion
  14146. (skip-chars-backward "a-zA-Z0-9*")
  14147. (skip-chars-backward " \t")
  14148. (and (bolp) (not (org-at-heading-p))))
  14149. (cdlatex-tab) t)
  14150. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14151. (defun org-cdlatex-underscore-caret (&optional _arg)
  14152. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14153. Revert to the normal definition outside of these fragments."
  14154. (interactive "P")
  14155. (if (org-inside-LaTeX-fragment-p)
  14156. (call-interactively 'cdlatex-sub-superscript)
  14157. (let (org-cdlatex-mode)
  14158. (call-interactively (key-binding (vector last-input-event))))))
  14159. (defun org-cdlatex-math-modify (&optional _arg)
  14160. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14161. Revert to the normal definition outside of these fragments."
  14162. (interactive "P")
  14163. (if (org-inside-LaTeX-fragment-p)
  14164. (call-interactively 'cdlatex-math-modify)
  14165. (let (org-cdlatex-mode)
  14166. (call-interactively (key-binding (vector last-input-event))))))
  14167. (defun org-cdlatex-environment-indent (&optional environment item)
  14168. "Execute `cdlatex-environment' and indent the inserted environment.
  14169. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14170. The inserted environment is indented to current indentation
  14171. unless point is at the beginning of the line, in which the
  14172. environment remains unintended."
  14173. (interactive)
  14174. ;; cdlatex-environment always return nil. Therefore, capture output
  14175. ;; first and determine if an environment was selected.
  14176. (let* ((beg (point-marker))
  14177. (end (copy-marker (point) t))
  14178. (inserted (progn
  14179. (ignore-errors (cdlatex-environment environment item))
  14180. (< beg end)))
  14181. ;; Figure out how many lines to move forward after the
  14182. ;; environment has been inserted.
  14183. (lines (when inserted
  14184. (save-excursion
  14185. (- (cl-loop while (< beg (point))
  14186. with x = 0
  14187. do (forward-line -1)
  14188. (cl-incf x)
  14189. finally return x)
  14190. (if (progn (goto-char beg)
  14191. (and (progn (skip-chars-forward " \t") (eolp))
  14192. (progn (skip-chars-backward " \t") (bolp))))
  14193. 1 0)))))
  14194. (env (org-trim (delete-and-extract-region beg end))))
  14195. (when inserted
  14196. ;; Get indentation of next line unless at column 0.
  14197. (let ((ind (if (bolp) 0
  14198. (save-excursion
  14199. (org-return t)
  14200. (prog1 (current-indentation)
  14201. (when (progn (skip-chars-forward " \t") (eolp))
  14202. (delete-region beg (point)))))))
  14203. (bol (progn (skip-chars-backward " \t") (bolp))))
  14204. ;; Insert a newline before environment unless at column zero
  14205. ;; to "escape" the current line. Insert a newline if
  14206. ;; something is one the same line as \end{ENVIRONMENT}.
  14207. (insert
  14208. (concat (unless bol "\n") env
  14209. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14210. (unless (zerop ind)
  14211. (save-excursion
  14212. (goto-char beg)
  14213. (while (< (point) end)
  14214. (unless (eolp) (indent-line-to ind))
  14215. (forward-line))))
  14216. (goto-char beg)
  14217. (forward-line lines)
  14218. (indent-line-to ind)))
  14219. (set-marker beg nil)
  14220. (set-marker end nil)))
  14221. ;;;; LaTeX fragments
  14222. (defun org-inside-LaTeX-fragment-p ()
  14223. "Test if point is inside a LaTeX fragment.
  14224. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14225. sequence appearing also before point.
  14226. Even though the matchers for math are configurable, this function assumes
  14227. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14228. delimiters are skipped when they have been removed by customization.
  14229. The return value is nil, or a cons cell with the delimiter and the
  14230. position of this delimiter.
  14231. This function does a reasonably good job, but can locally be fooled by
  14232. for example currency specifications. For example it will assume being in
  14233. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14234. fragments that are properly closed, but during editing, we have to live
  14235. with the uncertainty caused by missing closing delimiters. This function
  14236. looks only before point, not after."
  14237. (catch 'exit
  14238. (let ((pos (point))
  14239. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14240. (lim (progn
  14241. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14242. 'move)
  14243. (point)))
  14244. dd-on str (start 0) m re)
  14245. (goto-char pos)
  14246. (when dodollar
  14247. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14248. re (nth 1 (assoc "$" org-latex-regexps)))
  14249. (while (string-match re str start)
  14250. (cond
  14251. ((= (match-end 0) (length str))
  14252. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14253. ((= (match-end 0) (- (length str) 5))
  14254. (throw 'exit nil))
  14255. (t (setq start (match-end 0))))))
  14256. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14257. (goto-char pos)
  14258. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14259. (and (match-beginning 2) (throw 'exit nil))
  14260. ;; count $$
  14261. (while (re-search-backward "\\$\\$" lim t)
  14262. (setq dd-on (not dd-on)))
  14263. (goto-char pos)
  14264. (when dd-on (cons "$$" m))))))
  14265. (defun org-inside-latex-macro-p ()
  14266. "Is point inside a LaTeX macro or its arguments?"
  14267. (save-match-data
  14268. (org-in-regexp
  14269. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14270. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14271. "Build an overlay between BEG and END using IMAGE file.
  14272. Argument IMAGETYPE is the extension of the displayed image,
  14273. as a string. It defaults to \"png\"."
  14274. (let ((ov (make-overlay beg end))
  14275. (imagetype (or (intern imagetype) 'png)))
  14276. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14277. (overlay-put ov 'evaporate t)
  14278. (overlay-put ov
  14279. 'modification-hooks
  14280. (list (lambda (o _flag _beg _end &optional _l)
  14281. (delete-overlay o))))
  14282. (overlay-put ov
  14283. 'display
  14284. (list 'image :type imagetype :file image :ascent 'center))))
  14285. (defun org-clear-latex-preview (&optional beg end)
  14286. "Remove all overlays with LaTeX fragment images in current buffer.
  14287. When optional arguments BEG and END are non-nil, remove all
  14288. overlays between them instead. Return a non-nil value when some
  14289. overlays were removed, nil otherwise."
  14290. (let ((overlays
  14291. (cl-remove-if-not
  14292. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14293. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14294. (mapc #'delete-overlay overlays)
  14295. overlays))
  14296. (defun org--latex-preview-region (beg end)
  14297. "Preview LaTeX fragments between BEG and END.
  14298. BEG and END are buffer positions."
  14299. (let ((file (buffer-file-name (buffer-base-buffer))))
  14300. (save-excursion
  14301. (org-format-latex
  14302. (concat org-preview-latex-image-directory "org-ltximg")
  14303. beg end
  14304. ;; Emacs cannot overlay images from remote hosts. Create it in
  14305. ;; `temporary-file-directory' instead.
  14306. (if (or (not file) (file-remote-p file))
  14307. temporary-file-directory
  14308. default-directory)
  14309. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14310. (defun org-latex-preview (&optional arg)
  14311. "Toggle preview of the LaTeX fragment at point.
  14312. If the cursor is on a LaTeX fragment, create the image and
  14313. overlay it over the source code, if there is none. Remove it
  14314. otherwise. If there is no fragment at point, display images for
  14315. all fragments in the current section.
  14316. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14317. for all fragments
  14318. in the current section.
  14319. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14320. argument ARG, display image for all
  14321. fragments in the buffer.
  14322. With a `\\[universal-argument] \\[universal-argument] \
  14323. \\[universal-argument]' prefix argument ARG, clear image for all
  14324. fragments in the buffer."
  14325. (interactive "P")
  14326. (cond
  14327. ((not (display-graphic-p)) nil)
  14328. ;; Clear whole buffer.
  14329. ((equal arg '(64))
  14330. (org-clear-latex-preview (point-min) (point-max))
  14331. (message "LaTeX previews removed from buffer"))
  14332. ;; Preview whole buffer.
  14333. ((equal arg '(16))
  14334. (message "Creating LaTeX previews in buffer...")
  14335. (org--latex-preview-region (point-min) (point-max))
  14336. (message "Creating LaTeX previews in buffer... done."))
  14337. ;; Clear current section.
  14338. ((equal arg '(4))
  14339. (org-clear-latex-preview
  14340. (if (org-before-first-heading-p) (point-min)
  14341. (save-excursion
  14342. (org-with-limited-levels (org-back-to-heading t) (point))))
  14343. (org-with-limited-levels (org-entry-end-position))))
  14344. ;; Toggle preview on LaTeX code at point.
  14345. ((let ((datum (org-element-context)))
  14346. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14347. (let ((beg (org-element-property :begin datum))
  14348. (end (org-element-property :end datum)))
  14349. (if (org-clear-latex-preview beg end)
  14350. (message "LaTeX preview removed")
  14351. (message "Creating LaTeX preview...")
  14352. (org--latex-preview-region beg end)
  14353. (message "Creating LaTeX preview... done."))
  14354. t))))
  14355. ;; Preview current section.
  14356. (t
  14357. (let ((beg (if (org-before-first-heading-p) (point-min)
  14358. (save-excursion
  14359. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14360. (end (org-with-limited-levels (org-entry-end-position))))
  14361. (message "Creating LaTeX previews in section...")
  14362. (org--latex-preview-region beg end)
  14363. (message "Creating LaTeX previews in section... done.")))))
  14364. (defun org-format-latex
  14365. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14366. "Replace LaTeX fragments with links to an image.
  14367. The function takes care of creating the replacement image.
  14368. Only consider fragments between BEG and END when those are
  14369. provided.
  14370. When optional argument OVERLAYS is non-nil, display the image on
  14371. top of the fragment instead of replacing it.
  14372. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14373. Some of the options can be changed using the variable
  14374. `org-format-latex-options', which see."
  14375. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14376. (unless (eq processing-type 'verbatim)
  14377. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14378. (cnt 0)
  14379. checkdir-flag)
  14380. (goto-char (or beg (point-min)))
  14381. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14382. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14383. (overlay-recenter (or end (point-max))))
  14384. (while (re-search-forward math-regexp end t)
  14385. (unless (and overlays
  14386. (eq (get-char-property (point) 'org-overlay-type)
  14387. 'org-latex-overlay))
  14388. (let* ((context (org-element-context))
  14389. (type (org-element-type context)))
  14390. (when (memq type '(latex-environment latex-fragment))
  14391. (let ((block-type (eq type 'latex-environment))
  14392. (value (org-element-property :value context))
  14393. (beg (org-element-property :begin context))
  14394. (end (save-excursion
  14395. (goto-char (org-element-property :end context))
  14396. (skip-chars-backward " \r\t\n")
  14397. (point))))
  14398. (cond
  14399. ((eq processing-type 'mathjax)
  14400. ;; Prepare for MathJax processing.
  14401. (if (not (string-match "\\`\\$\\$?" value))
  14402. (goto-char end)
  14403. (delete-region beg end)
  14404. (if (string= (match-string 0 value) "$$")
  14405. (insert "\\[" (substring value 2 -2) "\\]")
  14406. (insert "\\(" (substring value 1 -1) "\\)"))))
  14407. ((eq processing-type 'html)
  14408. (goto-char beg)
  14409. (delete-region beg end)
  14410. (insert (org-format-latex-as-html value)))
  14411. ((assq processing-type org-preview-latex-process-alist)
  14412. ;; Process to an image.
  14413. (cl-incf cnt)
  14414. (goto-char beg)
  14415. (let* ((processing-info
  14416. (cdr (assq processing-type org-preview-latex-process-alist)))
  14417. (face (face-at-point))
  14418. ;; Get the colors from the face at point.
  14419. (fg
  14420. (let ((color (plist-get org-format-latex-options
  14421. :foreground)))
  14422. (if (and forbuffer (eq color 'auto))
  14423. (face-attribute face :foreground nil 'default)
  14424. color)))
  14425. (bg
  14426. (let ((color (plist-get org-format-latex-options
  14427. :background)))
  14428. (if (and forbuffer (eq color 'auto))
  14429. (face-attribute face :background nil 'default)
  14430. color)))
  14431. (hash (sha1 (prin1-to-string
  14432. (list org-format-latex-header
  14433. org-latex-default-packages-alist
  14434. org-latex-packages-alist
  14435. org-format-latex-options
  14436. forbuffer value fg bg))))
  14437. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14438. (absprefix (expand-file-name prefix dir))
  14439. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14440. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14441. (sep (and block-type "\n\n"))
  14442. (link (concat sep "[[file:" linkfile "]]" sep))
  14443. (options
  14444. (org-combine-plists
  14445. org-format-latex-options
  14446. `(:foreground ,fg :background ,bg))))
  14447. (when msg (message msg cnt))
  14448. (unless checkdir-flag ; Ensure the directory exists.
  14449. (setq checkdir-flag t)
  14450. (let ((todir (file-name-directory absprefix)))
  14451. (unless (file-directory-p todir)
  14452. (make-directory todir t))))
  14453. (unless (file-exists-p movefile)
  14454. (org-create-formula-image
  14455. value movefile options forbuffer processing-type))
  14456. (if overlays
  14457. (progn
  14458. (dolist (o (overlays-in beg end))
  14459. (when (eq (overlay-get o 'org-overlay-type)
  14460. 'org-latex-overlay)
  14461. (delete-overlay o)))
  14462. (org--make-preview-overlay beg end movefile imagetype)
  14463. (goto-char end))
  14464. (delete-region beg end)
  14465. (insert
  14466. (org-add-props link
  14467. (list 'org-latex-src
  14468. (replace-regexp-in-string "\"" "" value)
  14469. 'org-latex-src-embed-type
  14470. (if block-type 'paragraph 'character)))))))
  14471. ((eq processing-type 'mathml)
  14472. ;; Process to MathML.
  14473. (unless (org-format-latex-mathml-available-p)
  14474. (user-error "LaTeX to MathML converter not configured"))
  14475. (cl-incf cnt)
  14476. (when msg (message msg cnt))
  14477. (goto-char beg)
  14478. (delete-region beg end)
  14479. (insert (org-format-latex-as-mathml
  14480. value block-type prefix dir)))
  14481. (t
  14482. (error "Unknown conversion process %s for LaTeX fragments"
  14483. processing-type)))))))))))
  14484. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14485. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14486. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14487. successful, return the portion between \"<math...> </math>\"
  14488. elements otherwise return nil. When MATHML-FILE is specified,
  14489. write the results in to that file. When invoked as an
  14490. interactive command, prompt for LATEX-FRAG, with initial value
  14491. set to the current active region and echo the results for user
  14492. inspection."
  14493. (interactive (list (let ((frag (when (org-region-active-p)
  14494. (buffer-substring-no-properties
  14495. (region-beginning) (region-end)))))
  14496. (read-string "LaTeX Fragment: " frag nil frag))))
  14497. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14498. (let* ((tmp-in-file
  14499. (let ((file (file-relative-name
  14500. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14501. (write-region latex-frag nil file)
  14502. file))
  14503. (tmp-out-file (file-relative-name
  14504. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14505. (cmd (format-spec
  14506. org-latex-to-mathml-convert-command
  14507. `((?j . ,(and org-latex-to-mathml-jar-file
  14508. (shell-quote-argument
  14509. (expand-file-name
  14510. org-latex-to-mathml-jar-file))))
  14511. (?I . ,(shell-quote-argument tmp-in-file))
  14512. (?i . ,latex-frag)
  14513. (?o . ,(shell-quote-argument tmp-out-file)))))
  14514. mathml shell-command-output)
  14515. (when (called-interactively-p 'any)
  14516. (unless (org-format-latex-mathml-available-p)
  14517. (user-error "LaTeX to MathML converter not configured")))
  14518. (message "Running %s" cmd)
  14519. (setq shell-command-output (shell-command-to-string cmd))
  14520. (setq mathml
  14521. (when (file-readable-p tmp-out-file)
  14522. (with-current-buffer (find-file-noselect tmp-out-file t)
  14523. (goto-char (point-min))
  14524. (when (re-search-forward
  14525. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14526. (regexp-quote
  14527. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14528. nil t)
  14529. (prog1 (match-string 0) (kill-buffer))))))
  14530. (cond
  14531. (mathml
  14532. (setq mathml
  14533. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14534. (when mathml-file
  14535. (write-region mathml nil mathml-file))
  14536. (when (called-interactively-p 'any)
  14537. (message mathml)))
  14538. ((warn "LaTeX to MathML conversion failed")
  14539. (message shell-command-output)))
  14540. (delete-file tmp-in-file)
  14541. (when (file-exists-p tmp-out-file)
  14542. (delete-file tmp-out-file))
  14543. mathml))
  14544. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14545. prefix &optional dir)
  14546. "Use `org-create-math-formula' but check local cache first."
  14547. (let* ((absprefix (expand-file-name prefix dir))
  14548. (print-length nil) (print-level nil)
  14549. (formula-id (concat
  14550. "formula-"
  14551. (sha1
  14552. (prin1-to-string
  14553. (list latex-frag
  14554. org-latex-to-mathml-convert-command)))))
  14555. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14556. (formula-cache-dir (file-name-directory formula-cache)))
  14557. (unless (file-directory-p formula-cache-dir)
  14558. (make-directory formula-cache-dir t))
  14559. (unless (file-exists-p formula-cache)
  14560. (org-create-math-formula latex-frag formula-cache))
  14561. (if (file-exists-p formula-cache)
  14562. ;; Successful conversion. Return the link to MathML file.
  14563. (org-add-props
  14564. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14565. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14566. 'org-latex-src-embed-type (if latex-frag-type
  14567. 'paragraph 'character)))
  14568. ;; Failed conversion. Return the LaTeX fragment verbatim
  14569. latex-frag)))
  14570. (defun org-format-latex-as-html (latex-fragment)
  14571. "Convert LATEX-FRAGMENT to HTML.
  14572. This uses `org-latex-to-html-convert-command', which see."
  14573. (let ((cmd (format-spec org-latex-to-html-convert-command
  14574. `((?i . ,latex-fragment)))))
  14575. (message "Running %s" cmd)
  14576. (shell-command-to-string cmd)))
  14577. (defun org--get-display-dpi ()
  14578. "Get the DPI of the display.
  14579. The function assumes that the display has the same pixel width in
  14580. the horizontal and vertical directions."
  14581. (if (display-graphic-p)
  14582. (round (/ (display-pixel-height)
  14583. (/ (display-mm-height) 25.4)))
  14584. (error "Attempt to calculate the dpi of a non-graphic display")))
  14585. (defun org-create-formula-image
  14586. (string tofile options buffer &optional processing-type)
  14587. "Create an image from LaTeX source using external processes.
  14588. The LaTeX STRING is saved to a temporary LaTeX file, then
  14589. converted to an image file by process PROCESSING-TYPE defined in
  14590. `org-preview-latex-process-alist'. A nil value defaults to
  14591. `org-preview-latex-default-process'.
  14592. The generated image file is eventually moved to TOFILE.
  14593. The OPTIONS argument controls the size, foreground color and
  14594. background color of the generated image.
  14595. When BUFFER non-nil, this function is used for LaTeX previewing.
  14596. Otherwise, it is used to deal with LaTeX snippets showed in
  14597. a HTML file."
  14598. (let* ((processing-type (or processing-type
  14599. org-preview-latex-default-process))
  14600. (processing-info
  14601. (cdr (assq processing-type org-preview-latex-process-alist)))
  14602. (programs (plist-get processing-info :programs))
  14603. (error-message (or (plist-get processing-info :message) ""))
  14604. (image-input-type (plist-get processing-info :image-input-type))
  14605. (image-output-type (plist-get processing-info :image-output-type))
  14606. (post-clean (or (plist-get processing-info :post-clean)
  14607. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14608. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14609. (latex-header
  14610. (or (plist-get processing-info :latex-header)
  14611. (org-latex-make-preamble
  14612. (org-export-get-environment (org-export-get-backend 'latex))
  14613. org-format-latex-header
  14614. 'snippet)))
  14615. (latex-compiler (plist-get processing-info :latex-compiler))
  14616. (image-converter (plist-get processing-info :image-converter))
  14617. (tmpdir temporary-file-directory)
  14618. (texfilebase (make-temp-name
  14619. (expand-file-name "orgtex" tmpdir)))
  14620. (texfile (concat texfilebase ".tex"))
  14621. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14622. '(1.0 . 1.0)))
  14623. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14624. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14625. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14626. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14627. "Black"))
  14628. (bg (or (plist-get options (if buffer :background :html-background))
  14629. "Transparent"))
  14630. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14631. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14632. (dolist (program programs)
  14633. (org-check-external-command program error-message))
  14634. (if (eq fg 'default)
  14635. (setq fg (org-latex-color :foreground))
  14636. (setq fg (org-latex-color-format fg)))
  14637. (if (eq bg 'default)
  14638. (setq bg (org-latex-color :background))
  14639. (setq bg (org-latex-color-format
  14640. (if (string= bg "Transparent") "white" bg))))
  14641. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14642. (if (string-suffix-p string "\n")
  14643. (aset string (1- (length string)) ?%)
  14644. (setq string (concat string "%")))
  14645. (with-temp-file texfile
  14646. (insert latex-header)
  14647. (insert "\n\\begin{document}\n"
  14648. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14649. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14650. "\n\\pagecolor{bg}%\n"
  14651. "\n{\\color{fg}\n"
  14652. string
  14653. "\n}\n"
  14654. "\n\\end{document}\n"))
  14655. (let* ((err-msg (format "Please adjust `%s' part of \
  14656. `org-preview-latex-process-alist'."
  14657. processing-type))
  14658. (image-input-file
  14659. (org-compile-file
  14660. texfile latex-compiler image-input-type err-msg log-buf))
  14661. (image-output-file
  14662. (org-compile-file
  14663. image-input-file image-converter image-output-type err-msg log-buf
  14664. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14665. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14666. (copy-file image-output-file tofile 'replace)
  14667. (dolist (e post-clean)
  14668. (when (file-exists-p (concat texfilebase e))
  14669. (delete-file (concat texfilebase e))))
  14670. image-output-file)))
  14671. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14672. "Fill a LaTeX header template TPL.
  14673. In the template, the following place holders will be recognized:
  14674. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14675. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14676. [PACKAGES] \\usepackage statements for PKG
  14677. [NO-PACKAGES] do not include PKG
  14678. [EXTRA] the string EXTRA
  14679. [NO-EXTRA] do not include EXTRA
  14680. For backward compatibility, if both the positive and the negative place
  14681. holder is missing, the positive one (without the \"NO-\") will be
  14682. assumed to be present at the end of the template.
  14683. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14684. EXTRA is a string.
  14685. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14686. (let (rpl (end ""))
  14687. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14688. (setq rpl (if (or (match-end 1) (not def-pkg))
  14689. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14690. tpl (replace-match rpl t t tpl))
  14691. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14692. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14693. (setq rpl (if (or (match-end 1) (not pkg))
  14694. "" (org-latex-packages-to-string pkg snippets-p t))
  14695. tpl (replace-match rpl t t tpl))
  14696. (when pkg (setq end
  14697. (concat end "\n"
  14698. (org-latex-packages-to-string pkg snippets-p)))))
  14699. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14700. (setq rpl (if (or (match-end 1) (not extra))
  14701. "" (concat extra "\n"))
  14702. tpl (replace-match rpl t t tpl))
  14703. (when (and extra (string-match "\\S-" extra))
  14704. (setq end (concat end "\n" extra))))
  14705. (if (string-match "\\S-" end)
  14706. (concat tpl "\n" end)
  14707. tpl)))
  14708. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14709. "Turn an alist of packages into a string with the \\usepackage macros."
  14710. (setq pkg (mapconcat (lambda(p)
  14711. (cond
  14712. ((stringp p) p)
  14713. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14714. (format "%% Package %s omitted" (cadr p)))
  14715. ((equal "" (car p))
  14716. (format "\\usepackage{%s}" (cadr p)))
  14717. (t
  14718. (format "\\usepackage[%s]{%s}"
  14719. (car p) (cadr p)))))
  14720. pkg
  14721. "\n"))
  14722. (if newline (concat pkg "\n") pkg))
  14723. (defun org-dvipng-color (attr)
  14724. "Return a RGB color specification for dvipng."
  14725. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14726. (defun org-dvipng-color-format (color-name)
  14727. "Convert COLOR-NAME to a RGB color value for dvipng."
  14728. (apply #'format "rgb %s %s %s"
  14729. (mapcar 'org-normalize-color
  14730. (color-values color-name))))
  14731. (defun org-latex-color (attr)
  14732. "Return a RGB color for the LaTeX color package."
  14733. (org-latex-color-format (face-attribute 'default attr nil)))
  14734. (defun org-latex-color-format (color-name)
  14735. "Convert COLOR-NAME to a RGB color value."
  14736. (apply #'format "%s,%s,%s"
  14737. (mapcar 'org-normalize-color
  14738. (color-values color-name))))
  14739. (defun org-normalize-color (value)
  14740. "Return string to be used as color value for an RGB component."
  14741. (format "%g" (/ value 65535.0)))
  14742. ;; Image display
  14743. (defvar-local org-inline-image-overlays nil)
  14744. (defun org-toggle-inline-images (&optional include-linked)
  14745. "Toggle the display of inline images.
  14746. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14747. (interactive "P")
  14748. (if org-inline-image-overlays
  14749. (progn
  14750. (org-remove-inline-images)
  14751. (when (called-interactively-p 'interactive)
  14752. (message "Inline image display turned off")))
  14753. (org-display-inline-images include-linked)
  14754. (when (called-interactively-p 'interactive)
  14755. (message (if org-inline-image-overlays
  14756. (format "%d images displayed inline"
  14757. (length org-inline-image-overlays))
  14758. "No images to display inline")))))
  14759. (defun org-redisplay-inline-images ()
  14760. "Assure display of inline images and refresh them."
  14761. (interactive)
  14762. (org-toggle-inline-images)
  14763. (unless org-inline-image-overlays
  14764. (org-toggle-inline-images)))
  14765. ;; For without-x builds.
  14766. (declare-function image-refresh "image" (spec &optional frame))
  14767. (defcustom org-display-remote-inline-images 'skip
  14768. "How to display remote inline images.
  14769. Possible values of this option are:
  14770. skip Don't display remote images.
  14771. download Always download and display remote images.
  14772. cache Display remote images, and open them in separate buffers
  14773. for cacheing. Silently update the image buffer when a file
  14774. change is detected."
  14775. :group 'org-appearance
  14776. :package-version '(Org . "9.4")
  14777. :type '(choice
  14778. (const :tag "Ignore remote images" skip)
  14779. (const :tag "Always display remote images" download)
  14780. (const :tag "Display and silently update remote images" cache))
  14781. :safe #'symbolp)
  14782. (defun org--create-inline-image (file width)
  14783. "Create image located at FILE, or return nil.
  14784. WIDTH is the width of the image. The image may not be created
  14785. according to the value of `org-display-remote-inline-images'."
  14786. (let* ((remote? (file-remote-p file))
  14787. (file-or-data
  14788. (pcase org-display-remote-inline-images
  14789. ((guard (not remote?)) file)
  14790. (`download (with-temp-buffer
  14791. (set-buffer-multibyte nil)
  14792. (insert-file-contents-literally file)
  14793. (buffer-string)))
  14794. (`cache (let ((revert-without-query '(".")))
  14795. (with-current-buffer (find-file-noselect file)
  14796. (buffer-string))))
  14797. (`skip nil)
  14798. (other
  14799. (message "Invalid value of `org-display-remote-inline-images': %S"
  14800. other)
  14801. nil))))
  14802. (when file-or-data
  14803. (create-image file-or-data
  14804. (and (image-type-available-p 'imagemagick)
  14805. width
  14806. 'imagemagick)
  14807. remote?
  14808. :width width))))
  14809. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14810. "Display inline images.
  14811. An inline image is a link which follows either of these
  14812. conventions:
  14813. 1. Its path is a file with an extension matching return value
  14814. from `image-file-name-regexp' and it has no contents.
  14815. 2. Its description consists in a single link of the previous
  14816. type. In this case, that link must be a well-formed plain
  14817. or angle link, i.e., it must have an explicit \"file\" type.
  14818. Equip each image with the key-map `image-map'.
  14819. When optional argument INCLUDE-LINKED is non-nil, also links with
  14820. a text description part will be inlined. This can be nice for
  14821. a quick look at those images, but it does not reflect what
  14822. exported files will look like.
  14823. When optional argument REFRESH is non-nil, refresh existing
  14824. images between BEG and END. This will create new image displays
  14825. only if necessary.
  14826. BEG and END define the considered part. They default to the
  14827. buffer boundaries with possible narrowing."
  14828. (interactive "P")
  14829. (when (display-graphic-p)
  14830. (unless refresh
  14831. (org-remove-inline-images)
  14832. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14833. (let ((end (or end (point-max))))
  14834. (org-with-point-at (or beg (point-min))
  14835. (let* ((case-fold-search t)
  14836. (file-extension-re (image-file-name-regexp))
  14837. (link-abbrevs (mapcar #'car
  14838. (append org-link-abbrev-alist-local
  14839. org-link-abbrev-alist)))
  14840. ;; Check absolute, relative file names and explicit
  14841. ;; "file:" links. Also check link abbreviations since
  14842. ;; some might expand to "file" links.
  14843. (file-types-re
  14844. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14845. (if (not link-abbrevs) ""
  14846. (concat "\\|" (regexp-opt link-abbrevs))))))
  14847. (while (re-search-forward file-types-re end t)
  14848. (let* ((link (org-element-lineage
  14849. (save-match-data (org-element-context))
  14850. '(link) t))
  14851. (linktype (org-element-property :type link))
  14852. (inner-start (match-beginning 1))
  14853. (path
  14854. (cond
  14855. ;; No link at point; no inline image.
  14856. ((not link) nil)
  14857. ;; File link without a description. Also handle
  14858. ;; INCLUDE-LINKED here since it should have
  14859. ;; precedence over the next case. I.e., if link
  14860. ;; contains filenames in both the path and the
  14861. ;; description, prioritize the path only when
  14862. ;; INCLUDE-LINKED is non-nil.
  14863. ((or (not (org-element-property :contents-begin link))
  14864. include-linked)
  14865. (and (or (equal "file" linktype)
  14866. (equal "attachment" linktype))
  14867. (org-element-property :path link)))
  14868. ;; Link with a description. Check if description
  14869. ;; is a filename. Even if Org doesn't have syntax
  14870. ;; for those -- clickable image -- constructs, fake
  14871. ;; them, as in `org-export-insert-image-links'.
  14872. ((not inner-start) nil)
  14873. (t
  14874. (org-with-point-at inner-start
  14875. (and (looking-at
  14876. (if (char-equal ?< (char-after inner-start))
  14877. org-link-angle-re
  14878. org-link-plain-re))
  14879. ;; File name must fill the whole
  14880. ;; description.
  14881. (= (org-element-property :contents-end link)
  14882. (match-end 0))
  14883. (match-string 2)))))))
  14884. (when (and path (string-match-p file-extension-re path))
  14885. (let ((file (if (equal "attachment" linktype)
  14886. (progn
  14887. (require 'org-attach)
  14888. (ignore-errors (org-attach-expand path)))
  14889. (expand-file-name path))))
  14890. (when (and file (file-exists-p file))
  14891. (let ((width
  14892. ;; Apply `org-image-actual-width' specifications.
  14893. (cond
  14894. ((eq org-image-actual-width t) nil)
  14895. ((listp org-image-actual-width)
  14896. (or
  14897. ;; First try to find a width among
  14898. ;; attributes associated to the paragraph
  14899. ;; containing link.
  14900. (pcase (org-element-lineage link '(paragraph))
  14901. (`nil nil)
  14902. (p
  14903. (let* ((case-fold-search t)
  14904. (end (org-element-property :post-affiliated p))
  14905. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14906. (when (org-with-point-at
  14907. (org-element-property :begin p)
  14908. (re-search-forward re end t))
  14909. (string-to-number (match-string 1))))))
  14910. ;; Otherwise, fall-back to provided number.
  14911. (car org-image-actual-width)))
  14912. ((numberp org-image-actual-width)
  14913. org-image-actual-width)
  14914. (t nil)))
  14915. (old (get-char-property-and-overlay
  14916. (org-element-property :begin link)
  14917. 'org-image-overlay)))
  14918. (if (and (car-safe old) refresh)
  14919. (image-refresh (overlay-get (cdr old) 'display))
  14920. (let ((image (org--create-inline-image file width)))
  14921. (when image
  14922. (let ((ov (make-overlay
  14923. (org-element-property :begin link)
  14924. (progn
  14925. (goto-char
  14926. (org-element-property :end link))
  14927. (skip-chars-backward " \t")
  14928. (point)))))
  14929. (overlay-put ov 'display image)
  14930. (overlay-put ov 'face 'default)
  14931. (overlay-put ov 'org-image-overlay t)
  14932. (overlay-put
  14933. ov 'modification-hooks
  14934. (list 'org-display-inline-remove-overlay))
  14935. (when (<= 26 emacs-major-version)
  14936. (cl-assert (boundp 'image-map))
  14937. (overlay-put ov 'keymap image-map))
  14938. (push ov org-inline-image-overlays))))))))))))))))
  14939. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14940. "Remove inline-display overlay if a corresponding region is modified."
  14941. (let ((inhibit-modification-hooks t))
  14942. (when (and ov after)
  14943. (delete ov org-inline-image-overlays)
  14944. (delete-overlay ov))))
  14945. (defun org-remove-inline-images ()
  14946. "Remove inline display of images."
  14947. (interactive)
  14948. (mapc #'delete-overlay org-inline-image-overlays)
  14949. (setq org-inline-image-overlays nil))
  14950. (defvar org-self-insert-command-undo-counter 0)
  14951. (defvar org-speed-command nil)
  14952. (defun org-self-insert-command (N)
  14953. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14954. If the cursor is in a table looking at whitespace, the whitespace is
  14955. overwritten, and the table is not marked as requiring realignment."
  14956. (interactive "p")
  14957. (org-check-before-invisible-edit 'insert)
  14958. (cond
  14959. ((and org-use-speed-commands
  14960. (let ((kv (this-command-keys-vector)))
  14961. (setq org-speed-command
  14962. (run-hook-with-args-until-success
  14963. 'org-speed-command-hook
  14964. (make-string 1 (aref kv (1- (length kv))))))))
  14965. (cond
  14966. ((commandp org-speed-command)
  14967. (setq this-command org-speed-command)
  14968. (call-interactively org-speed-command))
  14969. ((functionp org-speed-command)
  14970. (funcall org-speed-command))
  14971. ((and org-speed-command (listp org-speed-command))
  14972. (eval org-speed-command))
  14973. (t (let (org-use-speed-commands)
  14974. (call-interactively 'org-self-insert-command)))))
  14975. ((and
  14976. (= N 1)
  14977. (not (org-region-active-p))
  14978. (org-at-table-p)
  14979. (progn
  14980. ;; Check if we blank the field, and if that triggers align.
  14981. (and (featurep 'org-table)
  14982. org-table-auto-blank-field
  14983. (memq last-command
  14984. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14985. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14986. ;; Got extra space, this field does not determine
  14987. ;; column width.
  14988. (let (org-table-may-need-update) (org-table-blank-field))
  14989. ;; No extra space, this field may determine column
  14990. ;; width.
  14991. (org-table-blank-field)))
  14992. t)
  14993. (looking-at "[^|\n]* |"))
  14994. ;; There is room for insertion without re-aligning the table.
  14995. (self-insert-command N)
  14996. (org-table-with-shrunk-field
  14997. (save-excursion
  14998. (skip-chars-forward "^|")
  14999. ;; Do not delete last space, which is
  15000. ;; `org-table-separator-space', but the regular space before
  15001. ;; it.
  15002. (delete-region (- (point) 2) (1- (point))))))
  15003. (t
  15004. (setq org-table-may-need-update t)
  15005. (self-insert-command N)
  15006. (org-fix-tags-on-the-fly)
  15007. (when org-self-insert-cluster-for-undo
  15008. (if (not (eq last-command 'org-self-insert-command))
  15009. (setq org-self-insert-command-undo-counter 1)
  15010. (if (>= org-self-insert-command-undo-counter 20)
  15011. (setq org-self-insert-command-undo-counter 1)
  15012. (and (> org-self-insert-command-undo-counter 0)
  15013. buffer-undo-list (listp buffer-undo-list)
  15014. (not (cadr buffer-undo-list)) ; remove nil entry
  15015. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15016. (setq org-self-insert-command-undo-counter
  15017. (1+ org-self-insert-command-undo-counter))))))))
  15018. (defun org-check-before-invisible-edit (kind)
  15019. "Check is editing if kind KIND would be dangerous with invisible text around.
  15020. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15021. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15022. (when (and org-catch-invisible-edits
  15023. (or (not (boundp 'visible-mode)) (not visible-mode))
  15024. (or (get-char-property (point) 'invisible)
  15025. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15026. ;; OK, we need to take a closer look. Do not consider
  15027. ;; invisibility obtained through text properties (e.g., link
  15028. ;; fontification), as it cannot be toggled.
  15029. (let* ((invisible-at-point
  15030. (pcase (get-char-property-and-overlay (point) 'invisible)
  15031. (`(,_ . ,(and (pred overlayp) o)) o)))
  15032. ;; Assume that point cannot land in the middle of an
  15033. ;; overlay, or between two overlays.
  15034. (invisible-before-point
  15035. (and (not invisible-at-point)
  15036. (not (bobp))
  15037. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15038. (`(,_ . ,(and (pred overlayp) o)) o))))
  15039. (border-and-ok-direction
  15040. (or
  15041. ;; Check if we are acting predictably before invisible
  15042. ;; text.
  15043. (and invisible-at-point
  15044. (memq kind '(insert delete-backward)))
  15045. ;; Check if we are acting predictably after invisible text
  15046. ;; This works not well, and I have turned it off. It seems
  15047. ;; better to always show and stop after invisible text.
  15048. ;; (and (not invisible-at-point) invisible-before-point
  15049. ;; (memq kind '(insert delete)))
  15050. )))
  15051. (when (or invisible-at-point invisible-before-point)
  15052. (when (eq org-catch-invisible-edits 'error)
  15053. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15054. (if (and org-custom-properties-overlays
  15055. (y-or-n-p "Display invisible properties in this buffer? "))
  15056. (org-toggle-custom-properties-visibility)
  15057. ;; Make the area visible
  15058. (save-excursion
  15059. (when invisible-before-point
  15060. (goto-char
  15061. (previous-single-char-property-change (point) 'invisible)))
  15062. ;; Remove whatever overlay is currently making yet-to-be
  15063. ;; edited text invisible. Also remove nested invisibility
  15064. ;; related overlays.
  15065. (delete-overlay (or invisible-at-point invisible-before-point))
  15066. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15067. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15068. (`(,_ . ,(and (pred overlayp) o))
  15069. (delete-overlay o)
  15070. t)))))
  15071. (cond
  15072. ((eq org-catch-invisible-edits 'show)
  15073. ;; That's it, we do the edit after showing
  15074. (message
  15075. "Unfolding invisible region around point before editing")
  15076. (sit-for 1))
  15077. ((and (eq org-catch-invisible-edits 'smart)
  15078. border-and-ok-direction)
  15079. (message "Unfolding invisible region around point before editing"))
  15080. (t
  15081. ;; Don't do the edit, make the user repeat it in full visibility
  15082. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15083. (defun org-fix-tags-on-the-fly ()
  15084. "Align tags in headline at point.
  15085. Unlike `org-align-tags', this function does nothing if point is
  15086. either not currently on a tagged headline or on a tag."
  15087. (when (and (org-match-line org-tag-line-re)
  15088. (< (point) (match-beginning 1)))
  15089. (org-align-tags)))
  15090. (defun org-delete-backward-char (N)
  15091. "Like `delete-backward-char', insert whitespace at field end in tables.
  15092. When deleting backwards, in tables this function will insert whitespace in
  15093. front of the next \"|\" separator, to keep the table aligned. The table will
  15094. still be marked for re-alignment if the field did fill the entire column,
  15095. because, in this case the deletion might narrow the column."
  15096. (interactive "p")
  15097. (save-match-data
  15098. (org-check-before-invisible-edit 'delete-backward)
  15099. (if (and (= N 1)
  15100. (not overwrite-mode)
  15101. (not (org-region-active-p))
  15102. (not (eq (char-before) ?|))
  15103. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15104. (looking-at-p ".*?|")
  15105. (org-at-table-p))
  15106. (progn (forward-char -1) (org-delete-char 1))
  15107. (backward-delete-char N)
  15108. (org-fix-tags-on-the-fly))))
  15109. (defun org-delete-char (N)
  15110. "Like `delete-char', but insert whitespace at field end in tables.
  15111. When deleting characters, in tables this function will insert whitespace in
  15112. front of the next \"|\" separator, to keep the table aligned. The table will
  15113. still be marked for re-alignment if the field did fill the entire column,
  15114. because, in this case the deletion might narrow the column."
  15115. (interactive "p")
  15116. (save-match-data
  15117. (org-check-before-invisible-edit 'delete)
  15118. (cond
  15119. ((or (/= N 1)
  15120. (eq (char-after) ?|)
  15121. (save-excursion (skip-chars-backward " \t") (bolp))
  15122. (not (org-at-table-p)))
  15123. (delete-char N)
  15124. (org-fix-tags-on-the-fly))
  15125. ((looking-at ".\\(.*?\\)|")
  15126. (let* ((update? org-table-may-need-update)
  15127. (noalign (looking-at-p ".*? |")))
  15128. (delete-char 1)
  15129. (org-table-with-shrunk-field
  15130. (save-excursion
  15131. ;; Last space is `org-table-separator-space', so insert
  15132. ;; a regular one before it instead.
  15133. (goto-char (- (match-end 0) 2))
  15134. (insert " ")))
  15135. ;; If there were two spaces at the end, this field does not
  15136. ;; determine the width of the column.
  15137. (when noalign (setq org-table-may-need-update update?))))
  15138. (t
  15139. (delete-char N)))))
  15140. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15141. (put 'org-self-insert-command 'delete-selection
  15142. (lambda ()
  15143. (not (run-hook-with-args-until-success
  15144. 'self-insert-uses-region-functions))))
  15145. (put 'orgtbl-self-insert-command 'delete-selection
  15146. (lambda ()
  15147. (not (run-hook-with-args-until-success
  15148. 'self-insert-uses-region-functions))))
  15149. (put 'org-delete-char 'delete-selection 'supersede)
  15150. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15151. (put 'org-yank 'delete-selection 'yank)
  15152. ;; Make `flyspell-mode' delay after some commands
  15153. (put 'org-self-insert-command 'flyspell-delayed t)
  15154. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15155. (put 'org-delete-char 'flyspell-delayed t)
  15156. (put 'org-delete-backward-char 'flyspell-delayed t)
  15157. ;; Make pabbrev-mode expand after Org mode commands
  15158. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15159. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15160. (defun org-transpose-words ()
  15161. "Transpose words for Org.
  15162. This uses the `org-mode-transpose-word-syntax-table' syntax
  15163. table, which interprets characters in `org-emphasis-alist' as
  15164. word constituents."
  15165. (interactive)
  15166. (with-syntax-table org-mode-transpose-word-syntax-table
  15167. (call-interactively 'transpose-words)))
  15168. (defvar org-ctrl-c-ctrl-c-hook nil
  15169. "Hook for functions attaching themselves to `C-c C-c'.
  15170. This can be used to add additional functionality to the C-c C-c
  15171. key which executes context-dependent commands. This hook is run
  15172. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15173. run after the last test.
  15174. Each function will be called with no arguments. The function
  15175. must check if the context is appropriate for it to act. If yes,
  15176. it should do its thing and then return a non-nil value. If the
  15177. context is wrong, just do nothing and return nil.")
  15178. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15179. "Hook for functions attaching themselves to `C-c C-c'.
  15180. This can be used to add additional functionality to the C-c C-c
  15181. key which executes context-dependent commands. This hook is run
  15182. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15183. before the first test.
  15184. Each function will be called with no arguments. The function
  15185. must check if the context is appropriate for it to act. If yes,
  15186. it should do its thing and then return a non-nil value. If the
  15187. context is wrong, just do nothing and return nil.")
  15188. (defvar org-tab-first-hook nil
  15189. "Hook for functions to attach themselves to TAB.
  15190. See `org-ctrl-c-ctrl-c-hook' for more information.
  15191. This hook runs as the first action when TAB is pressed, even before
  15192. `org-cycle' messes around with the `outline-regexp' to cater for
  15193. inline tasks and plain list item folding.
  15194. If any function in this hook returns t, any other actions that
  15195. would have been caused by TAB (such as table field motion or visibility
  15196. cycling) will not occur.")
  15197. (defvar org-tab-after-check-for-table-hook nil
  15198. "Hook for functions to attach themselves to TAB.
  15199. See `org-ctrl-c-ctrl-c-hook' for more information.
  15200. This hook runs after it has been established that the cursor is not in a
  15201. table, but before checking if the cursor is in a headline or if global cycling
  15202. should be done.
  15203. If any function in this hook returns t, not other actions like visibility
  15204. cycling will be done.")
  15205. (defvar org-tab-after-check-for-cycling-hook nil
  15206. "Hook for functions to attach themselves to TAB.
  15207. See `org-ctrl-c-ctrl-c-hook' for more information.
  15208. This hook runs after it has been established that not table field motion and
  15209. not visibility should be done because of current context. This is probably
  15210. the place where a package like yasnippets can hook in.")
  15211. (defvar org-tab-before-tab-emulation-hook nil
  15212. "Hook for functions to attach themselves to TAB.
  15213. See `org-ctrl-c-ctrl-c-hook' for more information.
  15214. This hook runs after every other options for TAB have been exhausted, but
  15215. before indentation and \t insertion takes place.")
  15216. (defvar org-metaleft-hook nil
  15217. "Hook for functions attaching themselves to `M-left'.
  15218. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15219. (defvar org-metaright-hook nil
  15220. "Hook for functions attaching themselves to `M-right'.
  15221. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15222. (defvar org-metaup-hook nil
  15223. "Hook for functions attaching themselves to `M-up'.
  15224. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15225. (defvar org-metadown-hook nil
  15226. "Hook for functions attaching themselves to `M-down'.
  15227. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15228. (defvar org-shiftmetaleft-hook nil
  15229. "Hook for functions attaching themselves to `M-S-left'.
  15230. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15231. (defvar org-shiftmetaright-hook nil
  15232. "Hook for functions attaching themselves to `M-S-right'.
  15233. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15234. (defvar org-shiftmetaup-hook nil
  15235. "Hook for functions attaching themselves to `M-S-up'.
  15236. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15237. (defvar org-shiftmetadown-hook nil
  15238. "Hook for functions attaching themselves to `M-S-down'.
  15239. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15240. (defvar org-metareturn-hook nil
  15241. "Hook for functions attaching themselves to `M-RET'.
  15242. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15243. (defvar org-shiftup-hook nil
  15244. "Hook for functions attaching themselves to `S-up'.
  15245. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15246. (defvar org-shiftup-final-hook nil
  15247. "Hook for functions attaching themselves to `S-up'.
  15248. This one runs after all other options except shift-select have been excluded.
  15249. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15250. (defvar org-shiftdown-hook nil
  15251. "Hook for functions attaching themselves to `S-down'.
  15252. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15253. (defvar org-shiftdown-final-hook nil
  15254. "Hook for functions attaching themselves to `S-down'.
  15255. This one runs after all other options except shift-select have been excluded.
  15256. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15257. (defvar org-shiftleft-hook nil
  15258. "Hook for functions attaching themselves to `S-left'.
  15259. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15260. (defvar org-shiftleft-final-hook nil
  15261. "Hook for functions attaching themselves to `S-left'.
  15262. This one runs after all other options except shift-select have been excluded.
  15263. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15264. (defvar org-shiftright-hook nil
  15265. "Hook for functions attaching themselves to `S-right'.
  15266. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15267. (defvar org-shiftright-final-hook nil
  15268. "Hook for functions attaching themselves to `S-right'.
  15269. This one runs after all other options except shift-select have been excluded.
  15270. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15271. (defun org-modifier-cursor-error ()
  15272. "Throw an error, a modified cursor command was applied in wrong context."
  15273. (user-error "This command is active in special context like tables, headlines or items"))
  15274. (defun org-shiftselect-error ()
  15275. "Throw an error because Shift-Cursor command was applied in wrong context."
  15276. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15277. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15278. (user-error "This command works only in special context like headlines or timestamps")))
  15279. (defun org-call-for-shift-select (cmd)
  15280. (let ((this-command-keys-shift-translated t))
  15281. (call-interactively cmd)))
  15282. (defun org-shifttab (&optional arg)
  15283. "Global visibility cycling or move to previous table field.
  15284. Call `org-table-previous-field' within a table.
  15285. When ARG is nil, cycle globally through visibility states.
  15286. When ARG is a numeric prefix, show contents of this level."
  15287. (interactive "P")
  15288. (cond
  15289. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15290. ((integerp arg)
  15291. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15292. (message "Content view to level: %d" arg)
  15293. (org-content (prefix-numeric-value arg2))
  15294. (org-cycle-show-empty-lines t)
  15295. (setq org-cycle-global-status 'overview)))
  15296. (t (call-interactively 'org-global-cycle))))
  15297. (defun org-shiftmetaleft ()
  15298. "Promote subtree or delete table column.
  15299. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15300. `org-table-delete-column', depending on context. See the
  15301. individual commands for more information."
  15302. (interactive)
  15303. (cond
  15304. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15305. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15306. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15307. ((if (not (org-region-active-p)) (org-at-item-p)
  15308. (save-excursion (goto-char (region-beginning))
  15309. (org-at-item-p)))
  15310. (call-interactively 'org-outdent-item-tree))
  15311. (t (org-modifier-cursor-error))))
  15312. (defun org-shiftmetaright ()
  15313. "Demote subtree or insert table column.
  15314. Calls `org-demote-subtree', `org-indent-item-tree', or
  15315. `org-table-insert-column', depending on context. See the
  15316. individual commands for more information."
  15317. (interactive)
  15318. (cond
  15319. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15320. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15321. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15322. ((if (not (org-region-active-p)) (org-at-item-p)
  15323. (save-excursion (goto-char (region-beginning))
  15324. (org-at-item-p)))
  15325. (call-interactively 'org-indent-item-tree))
  15326. (t (org-modifier-cursor-error))))
  15327. (defun org-shiftmetaup (&optional _arg)
  15328. "Drag the line at point up.
  15329. In a table, kill the current row.
  15330. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15331. but also adjust the previous clocked item in the clock history.
  15332. Everywhere else, drag the line at point up."
  15333. (interactive "P")
  15334. (cond
  15335. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15336. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15337. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15338. (call-interactively 'org-timestamp-up)))
  15339. (t (call-interactively 'org-drag-line-backward))))
  15340. (defun org-shiftmetadown (&optional _arg)
  15341. "Drag the line at point down.
  15342. In a table, insert an empty row at the current line.
  15343. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15344. but also adjust the previous clocked item in the clock history.
  15345. Everywhere else, drag the line at point down."
  15346. (interactive "P")
  15347. (cond
  15348. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15349. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15350. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15351. (call-interactively 'org-timestamp-down)))
  15352. (t (call-interactively 'org-drag-line-forward))))
  15353. (defsubst org-hidden-tree-error ()
  15354. (user-error
  15355. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15356. (defun org-metaleft (&optional _arg)
  15357. "Promote heading, list item at point or move table column left.
  15358. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15359. depending on context. With no specific context, calls the Emacs
  15360. default `backward-word'. See the individual commands for more
  15361. information.
  15362. This function runs the hook `org-metaleft-hook' as a first step,
  15363. and returns at first non-nil value."
  15364. (interactive "P")
  15365. (cond
  15366. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15367. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15368. ((org-with-limited-levels
  15369. (or (org-at-heading-p)
  15370. (and (org-region-active-p)
  15371. (save-excursion
  15372. (goto-char (region-beginning))
  15373. (org-at-heading-p)))))
  15374. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15375. (call-interactively 'org-do-promote))
  15376. ;; At an inline task.
  15377. ((org-at-heading-p)
  15378. (call-interactively 'org-inlinetask-promote))
  15379. ((or (org-at-item-p)
  15380. (and (org-region-active-p)
  15381. (save-excursion
  15382. (goto-char (region-beginning))
  15383. (org-at-item-p))))
  15384. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15385. (call-interactively 'org-outdent-item))
  15386. (t (call-interactively 'backward-word))))
  15387. (defun org-metaright (&optional _arg)
  15388. "Demote heading, list item at point or move table column right.
  15389. In front of a drawer or a block keyword, indent it correctly.
  15390. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15391. `org-indent-drawer' or `org-indent-block' depending on context.
  15392. With no specific context, calls the Emacs default `forward-word'.
  15393. See the individual commands for more information.
  15394. This function runs the hook `org-metaright-hook' as a first step,
  15395. and returns at first non-nil value."
  15396. (interactive "P")
  15397. (cond
  15398. ((run-hook-with-args-until-success 'org-metaright-hook))
  15399. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15400. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15401. ((org-at-block-p) (call-interactively 'org-indent-block))
  15402. ((org-with-limited-levels
  15403. (or (org-at-heading-p)
  15404. (and (org-region-active-p)
  15405. (save-excursion
  15406. (goto-char (region-beginning))
  15407. (org-at-heading-p)))))
  15408. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15409. (call-interactively 'org-do-demote))
  15410. ;; At an inline task.
  15411. ((org-at-heading-p)
  15412. (call-interactively 'org-inlinetask-demote))
  15413. ((or (org-at-item-p)
  15414. (and (org-region-active-p)
  15415. (save-excursion
  15416. (goto-char (region-beginning))
  15417. (org-at-item-p))))
  15418. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15419. (call-interactively 'org-indent-item))
  15420. (t (call-interactively 'forward-word))))
  15421. (defun org-check-for-hidden (what)
  15422. "Check if there are hidden headlines/items in the current visual line.
  15423. WHAT can be either `headlines' or `items'. If the current line is
  15424. an outline or item heading and it has a folded subtree below it,
  15425. this function returns t, nil otherwise."
  15426. (let ((re (cond
  15427. ((eq what 'headlines) org-outline-regexp-bol)
  15428. ((eq what 'items) (org-item-beginning-re))
  15429. (t (error "This should not happen"))))
  15430. beg end)
  15431. (save-excursion
  15432. (catch 'exit
  15433. (unless (org-region-active-p)
  15434. (setq beg (point-at-bol))
  15435. (beginning-of-line 2)
  15436. (while (and (not (eobp)) ;; this is like `next-line'
  15437. (get-char-property (1- (point)) 'invisible))
  15438. (beginning-of-line 2))
  15439. (setq end (point))
  15440. (goto-char beg)
  15441. (goto-char (point-at-eol))
  15442. (setq end (max end (point)))
  15443. (while (re-search-forward re end t)
  15444. (when (get-char-property (match-beginning 0) 'invisible)
  15445. (throw 'exit t))))
  15446. nil))))
  15447. (defun org-metaup (&optional _arg)
  15448. "Move subtree up or move table row up.
  15449. Calls `org-move-subtree-up' or `org-table-move-row' or
  15450. `org-move-item-up', depending on context. See the individual commands
  15451. for more information."
  15452. (interactive "P")
  15453. (cond
  15454. ((run-hook-with-args-until-success 'org-metaup-hook))
  15455. ((org-region-active-p)
  15456. (let* ((a (save-excursion
  15457. (goto-char (min (region-beginning) (region-end)))
  15458. (line-beginning-position)))
  15459. (b (save-excursion
  15460. (goto-char (max (region-beginning) (region-end)))
  15461. (if (bolp) (1- (point)) (line-end-position))))
  15462. (c (save-excursion
  15463. (goto-char a)
  15464. (move-beginning-of-line 0)
  15465. (point)))
  15466. (d (save-excursion
  15467. (goto-char a)
  15468. (move-end-of-line 0)
  15469. (point))))
  15470. (transpose-regions a b c d)
  15471. (goto-char c)))
  15472. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15473. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15474. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15475. (t (org-drag-element-backward))))
  15476. (defun org-metadown (&optional _arg)
  15477. "Move subtree down or move table row down.
  15478. Calls `org-move-subtree-down' or `org-table-move-row' or
  15479. `org-move-item-down', depending on context. See the individual
  15480. commands for more information."
  15481. (interactive "P")
  15482. (cond
  15483. ((run-hook-with-args-until-success 'org-metadown-hook))
  15484. ((org-region-active-p)
  15485. (let* ((a (save-excursion
  15486. (goto-char (min (region-beginning) (region-end)))
  15487. (line-beginning-position)))
  15488. (b (save-excursion
  15489. (goto-char (max (region-beginning) (region-end)))
  15490. (if (bolp) (1- (point)) (line-end-position))))
  15491. (c (save-excursion
  15492. (goto-char b)
  15493. (move-beginning-of-line (if (bolp) 1 2))
  15494. (point)))
  15495. (d (save-excursion
  15496. (goto-char b)
  15497. (move-end-of-line (if (bolp) 1 2))
  15498. (point))))
  15499. (transpose-regions a b c d)
  15500. (goto-char d)))
  15501. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15502. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15503. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15504. (t (org-drag-element-forward))))
  15505. (defun org-shiftup (&optional arg)
  15506. "Act on current element according to context.
  15507. Call `org-timestamp-up' or `org-priority-up', or
  15508. `org-previous-item', or `org-table-move-cell-up'. See the
  15509. individual commands for more information."
  15510. (interactive "P")
  15511. (cond
  15512. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15513. ((and org-support-shift-select (org-region-active-p))
  15514. (org-call-for-shift-select 'previous-line))
  15515. ((org-at-timestamp-p 'lax)
  15516. (call-interactively (if org-edit-timestamp-down-means-later
  15517. 'org-timestamp-down 'org-timestamp-up)))
  15518. ((and (not (eq org-support-shift-select 'always))
  15519. org-priority-enable-commands
  15520. (org-at-heading-p))
  15521. (call-interactively 'org-priority-up))
  15522. ((and (not org-support-shift-select) (org-at-item-p))
  15523. (call-interactively 'org-previous-item))
  15524. ((org-clocktable-try-shift 'up arg))
  15525. ((and (not (eq org-support-shift-select 'always))
  15526. (org-at-table-p))
  15527. (org-table-move-cell-up))
  15528. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15529. (org-support-shift-select
  15530. (org-call-for-shift-select 'previous-line))
  15531. (t (org-shiftselect-error))))
  15532. (defun org-shiftdown (&optional arg)
  15533. "Act on current element according to context.
  15534. Call `org-timestamp-down' or `org-priority-down', or
  15535. `org-next-item', or `org-table-move-cell-down'. See the
  15536. individual commands for more information."
  15537. (interactive "P")
  15538. (cond
  15539. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15540. ((and org-support-shift-select (org-region-active-p))
  15541. (org-call-for-shift-select 'next-line))
  15542. ((org-at-timestamp-p 'lax)
  15543. (call-interactively (if org-edit-timestamp-down-means-later
  15544. 'org-timestamp-up 'org-timestamp-down)))
  15545. ((and (not (eq org-support-shift-select 'always))
  15546. org-priority-enable-commands
  15547. (org-at-heading-p))
  15548. (call-interactively 'org-priority-down))
  15549. ((and (not org-support-shift-select) (org-at-item-p))
  15550. (call-interactively 'org-next-item))
  15551. ((org-clocktable-try-shift 'down arg))
  15552. ((and (not (eq org-support-shift-select 'always))
  15553. (org-at-table-p))
  15554. (org-table-move-cell-down))
  15555. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15556. (org-support-shift-select
  15557. (org-call-for-shift-select 'next-line))
  15558. (t (org-shiftselect-error))))
  15559. (defun org-shiftright (&optional arg)
  15560. "Act on the current element according to context.
  15561. This does one of the following:
  15562. - switch a timestamp at point one day into the future
  15563. - on a headline, switch to the next TODO keyword
  15564. - on an item, switch entire list to the next bullet type
  15565. - on a property line, switch to the next allowed value
  15566. - on a clocktable definition line, move time block into the future
  15567. - in a table, move a single cell right"
  15568. (interactive "P")
  15569. (cond
  15570. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15571. ((and org-support-shift-select (org-region-active-p))
  15572. (org-call-for-shift-select 'forward-char))
  15573. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15574. ((and (not (eq org-support-shift-select 'always))
  15575. (org-at-heading-p))
  15576. (let ((org-inhibit-logging
  15577. (not org-treat-S-cursor-todo-selection-as-state-change))
  15578. (org-inhibit-blocking
  15579. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15580. (org-call-with-arg 'org-todo 'right)))
  15581. ((or (and org-support-shift-select
  15582. (not (eq org-support-shift-select 'always))
  15583. (org-at-item-bullet-p))
  15584. (and (not org-support-shift-select) (org-at-item-p)))
  15585. (org-call-with-arg 'org-cycle-list-bullet nil))
  15586. ((and (not (eq org-support-shift-select 'always))
  15587. (org-at-property-p))
  15588. (call-interactively 'org-property-next-allowed-value))
  15589. ((org-clocktable-try-shift 'right arg))
  15590. ((and (not (eq org-support-shift-select 'always))
  15591. (org-at-table-p))
  15592. (org-table-move-cell-right))
  15593. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15594. (org-support-shift-select
  15595. (org-call-for-shift-select 'forward-char))
  15596. (t (org-shiftselect-error))))
  15597. (defun org-shiftleft (&optional arg)
  15598. "Act on current element according to context.
  15599. This does one of the following:
  15600. - switch a timestamp at point one day into the past
  15601. - on a headline, switch to the previous TODO keyword.
  15602. - on an item, switch entire list to the previous bullet type
  15603. - on a property line, switch to the previous allowed value
  15604. - on a clocktable definition line, move time block into the past
  15605. - in a table, move a single cell left"
  15606. (interactive "P")
  15607. (cond
  15608. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15609. ((and org-support-shift-select (org-region-active-p))
  15610. (org-call-for-shift-select 'backward-char))
  15611. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15612. ((and (not (eq org-support-shift-select 'always))
  15613. (org-at-heading-p))
  15614. (let ((org-inhibit-logging
  15615. (not org-treat-S-cursor-todo-selection-as-state-change))
  15616. (org-inhibit-blocking
  15617. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15618. (org-call-with-arg 'org-todo 'left)))
  15619. ((or (and org-support-shift-select
  15620. (not (eq org-support-shift-select 'always))
  15621. (org-at-item-bullet-p))
  15622. (and (not org-support-shift-select) (org-at-item-p)))
  15623. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15624. ((and (not (eq org-support-shift-select 'always))
  15625. (org-at-property-p))
  15626. (call-interactively 'org-property-previous-allowed-value))
  15627. ((org-clocktable-try-shift 'left arg))
  15628. ((and (not (eq org-support-shift-select 'always))
  15629. (org-at-table-p))
  15630. (org-table-move-cell-left))
  15631. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15632. (org-support-shift-select
  15633. (org-call-for-shift-select 'backward-char))
  15634. (t (org-shiftselect-error))))
  15635. (defun org-shiftcontrolright ()
  15636. "Switch to next TODO set."
  15637. (interactive)
  15638. (cond
  15639. ((and org-support-shift-select (org-region-active-p))
  15640. (org-call-for-shift-select 'forward-word))
  15641. ((and (not (eq org-support-shift-select 'always))
  15642. (org-at-heading-p))
  15643. (org-call-with-arg 'org-todo 'nextset))
  15644. (org-support-shift-select
  15645. (org-call-for-shift-select 'forward-word))
  15646. (t (org-shiftselect-error))))
  15647. (defun org-shiftcontrolleft ()
  15648. "Switch to previous TODO set."
  15649. (interactive)
  15650. (cond
  15651. ((and org-support-shift-select (org-region-active-p))
  15652. (org-call-for-shift-select 'backward-word))
  15653. ((and (not (eq org-support-shift-select 'always))
  15654. (org-at-heading-p))
  15655. (org-call-with-arg 'org-todo 'previousset))
  15656. (org-support-shift-select
  15657. (org-call-for-shift-select 'backward-word))
  15658. (t (org-shiftselect-error))))
  15659. (defun org-shiftcontrolup (&optional n)
  15660. "Change timestamps synchronously up in CLOCK log lines.
  15661. Optional argument N tells to change by that many units."
  15662. (interactive "P")
  15663. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15664. (let (org-support-shift-select)
  15665. (org-clock-timestamps-up n))
  15666. (user-error "Not at a clock log")))
  15667. (defun org-shiftcontroldown (&optional n)
  15668. "Change timestamps synchronously down in CLOCK log lines.
  15669. Optional argument N tells to change by that many units."
  15670. (interactive "P")
  15671. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15672. (let (org-support-shift-select)
  15673. (org-clock-timestamps-down n))
  15674. (user-error "Not at a clock log")))
  15675. (defun org-increase-number-at-point (&optional inc)
  15676. "Increment the number at point.
  15677. With an optional prefix numeric argument INC, increment using
  15678. this numeric value."
  15679. (interactive "p")
  15680. (if (not (number-at-point))
  15681. (user-error "Not on a number")
  15682. (unless inc (setq inc 1))
  15683. (let ((pos (point))
  15684. (beg (skip-chars-backward "-+^/*0-9eE."))
  15685. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15686. (setq nap (buffer-substring-no-properties
  15687. (+ pos beg) (+ pos beg end)))
  15688. (delete-region (+ pos beg) (+ pos beg end))
  15689. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15690. (when (org-at-table-p)
  15691. (org-table-align)
  15692. (org-table-end-of-field 1))))
  15693. (defun org-decrease-number-at-point (&optional inc)
  15694. "Decrement the number at point.
  15695. With an optional prefix numeric argument INC, decrement using
  15696. this numeric value."
  15697. (interactive "p")
  15698. (org-increase-number-at-point (- (or inc 1))))
  15699. (defun org-ctrl-c-ret ()
  15700. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  15701. (interactive)
  15702. (cond
  15703. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15704. (t (call-interactively 'org-insert-heading))))
  15705. (defun org-copy-visible (beg end)
  15706. "Copy the visible parts of the region."
  15707. (interactive "r")
  15708. (let ((result ""))
  15709. (while (/= beg end)
  15710. (when (get-char-property beg 'invisible)
  15711. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15712. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15713. (setq result (concat result (buffer-substring beg next)))
  15714. (setq beg next)))
  15715. (setq deactivate-mark t)
  15716. (kill-new result)
  15717. (message "Visible strings have been copied to the kill ring.")))
  15718. (defun org-copy-special ()
  15719. "Copy region in table or copy current subtree.
  15720. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15721. context. See the individual commands for more information."
  15722. (interactive)
  15723. (call-interactively
  15724. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15725. (defun org-cut-special ()
  15726. "Cut region in table or cut current subtree.
  15727. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15728. context. See the individual commands for more information."
  15729. (interactive)
  15730. (call-interactively
  15731. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15732. (defun org-paste-special (arg)
  15733. "Paste rectangular region into table, or past subtree relative to level.
  15734. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15735. See the individual commands for more information."
  15736. (interactive "P")
  15737. (if (org-at-table-p)
  15738. (org-table-paste-rectangle)
  15739. (org-paste-subtree arg)))
  15740. (defun org-edit-special (&optional arg)
  15741. "Call a special editor for the element at point.
  15742. When at a table, call the formula editor with `org-table-edit-formulas'.
  15743. When in a source code block, call `org-edit-src-code'.
  15744. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15745. When in an export block, call `org-edit-export-block'.
  15746. When in a LaTeX environment, call `org-edit-latex-environment'.
  15747. When at an #+INCLUDE keyword, visit the included file.
  15748. When at a footnote reference, call `org-edit-footnote-reference'.
  15749. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15750. When at an active timestamp, call `org-time-stamp'.
  15751. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15752. On a link, call `ffap' to visit the link at point.
  15753. Otherwise, return a user error."
  15754. (interactive "P")
  15755. (let ((element (org-element-at-point)))
  15756. (barf-if-buffer-read-only)
  15757. (pcase (org-element-type element)
  15758. (`src-block
  15759. (if (not arg) (org-edit-src-code)
  15760. (let* ((info (org-babel-get-src-block-info))
  15761. (lang (nth 0 info))
  15762. (params (nth 2 info))
  15763. (session (cdr (assq :session params))))
  15764. (if (not session) (org-edit-src-code)
  15765. ;; At a source block with a session and function called
  15766. ;; with an ARG: switch to the buffer related to the
  15767. ;; inferior process.
  15768. (switch-to-buffer
  15769. (funcall (intern (concat "org-babel-prep-session:" lang))
  15770. session params))))))
  15771. (`keyword
  15772. (unless (member (org-element-property :key element)
  15773. '("INCLUDE" "SETUPFILE"))
  15774. (user-error "No special environment to edit here"))
  15775. (let ((value (org-element-property :value element)))
  15776. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15777. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15778. (or (match-string 1 value)
  15779. (match-string 0 value)))))
  15780. (when (org-file-url-p file)
  15781. (user-error "Files located with a URL cannot be edited"))
  15782. (org-link-open-from-string
  15783. (format "[[%s]]" (expand-file-name file))))))
  15784. (`table
  15785. (if (eq (org-element-property :type element) 'table.el)
  15786. (org-edit-table.el)
  15787. (call-interactively 'org-table-edit-formulas)))
  15788. ;; Only Org tables contain `table-row' type elements.
  15789. (`table-row (call-interactively 'org-table-edit-formulas))
  15790. (`example-block (org-edit-src-code))
  15791. (`export-block (org-edit-export-block))
  15792. (`fixed-width (org-edit-fixed-width-region))
  15793. (`latex-environment (org-edit-latex-environment))
  15794. (`planning
  15795. (let ((proplist (cadr element)))
  15796. (mapc #'call-interactively
  15797. (remq nil
  15798. (list
  15799. (when (plist-get proplist :deadline) #'org-deadline)
  15800. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15801. (_
  15802. ;; No notable element at point. Though, we may be at a link or
  15803. ;; a footnote reference, which are objects. Thus, scan deeper.
  15804. (let ((context (org-element-context element)))
  15805. (pcase (org-element-type context)
  15806. (`footnote-reference (org-edit-footnote-reference))
  15807. (`inline-src-block (org-edit-inline-src-code))
  15808. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15809. (call-interactively #'org-time-stamp-inactive)
  15810. (call-interactively #'org-time-stamp)))
  15811. (`link (call-interactively #'ffap))
  15812. (_ (user-error "No special environment to edit here"))))))))
  15813. (defun org-ctrl-c-ctrl-c (&optional arg)
  15814. "Set tags in headline, or update according to changed information at point.
  15815. This command does many different things, depending on context:
  15816. - If column view is active, in agenda or org buffers, quit it.
  15817. - If there are highlights, remove them.
  15818. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15819. this is what we do.
  15820. - If the cursor is on a statistics cookie, update it.
  15821. - If the cursor is in a headline, in an agenda or an org buffer,
  15822. prompt for tags and insert them into the current line, aligned
  15823. to `org-tags-column'. When called with prefix arg, realign all
  15824. tags in the current buffer.
  15825. - If the cursor is in one of the special #+KEYWORD lines, this
  15826. triggers scanning the buffer for these lines and updating the
  15827. information.
  15828. - If the cursor is inside a table, realign the table. This command
  15829. works even if the automatic table editor has been turned off.
  15830. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15831. the entire table.
  15832. - If the cursor is at a footnote reference or definition, jump to
  15833. the corresponding definition or references, respectively.
  15834. - If the cursor is a the beginning of a dynamic block, update it.
  15835. - If the current buffer is a capture buffer, close note and file it.
  15836. - If the cursor is on a <<<target>>>, update radio targets and
  15837. corresponding links in this buffer.
  15838. - If the cursor is on a numbered item in a plain list, renumber the
  15839. ordered list.
  15840. - If the cursor is on a checkbox, toggle it.
  15841. - If the cursor is on a code block, evaluate it. The variable
  15842. `org-confirm-babel-evaluate' can be used to control prompting
  15843. before code block evaluation, by default every code block
  15844. evaluation requires confirmation. Code block evaluation can be
  15845. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15846. (interactive "P")
  15847. (cond
  15848. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15849. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15850. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15851. (org-remove-occur-highlights)
  15852. (message "Temporary highlights/overlays removed from current buffer"))
  15853. ((and (local-variable-p 'org-finish-function)
  15854. (fboundp org-finish-function))
  15855. (funcall org-finish-function))
  15856. ((org-babel-hash-at-point))
  15857. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15858. (t
  15859. (let* ((context
  15860. (org-element-lineage
  15861. (org-element-context)
  15862. ;; Limit to supported contexts.
  15863. '(babel-call clock dynamic-block footnote-definition
  15864. footnote-reference inline-babel-call inline-src-block
  15865. inlinetask item keyword node-property paragraph
  15866. plain-list planning property-drawer radio-target
  15867. src-block statistics-cookie table table-cell table-row
  15868. timestamp)
  15869. t))
  15870. (radio-list-p (org-at-radio-list-p))
  15871. (type (org-element-type context)))
  15872. ;; For convenience: at the first line of a paragraph on the same
  15873. ;; line as an item, apply function on that item instead.
  15874. (when (eq type 'paragraph)
  15875. (let ((parent (org-element-property :parent context)))
  15876. (when (and (eq (org-element-type parent) 'item)
  15877. (= (line-beginning-position)
  15878. (org-element-property :begin parent)))
  15879. (setq context parent)
  15880. (setq type 'item))))
  15881. ;; Act according to type of element or object at point.
  15882. ;;
  15883. ;; Do nothing on a blank line, except if it is contained in
  15884. ;; a source block. Hence, we first check if point is in such
  15885. ;; a block and then if it is at a blank line.
  15886. (pcase type
  15887. ((or `inline-src-block `src-block)
  15888. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15889. (org-babel-eval-wipe-error-buffer)
  15890. (org-babel-execute-src-block
  15891. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15892. ((guard (org-match-line "[ \t]*$"))
  15893. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15894. (user-error
  15895. (substitute-command-keys
  15896. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15897. ((or `babel-call `inline-babel-call)
  15898. (let ((info (org-babel-lob-get-info context)))
  15899. (when info (org-babel-execute-src-block nil info))))
  15900. (`clock (org-clock-update-time-maybe))
  15901. (`dynamic-block
  15902. (save-excursion
  15903. (goto-char (org-element-property :post-affiliated context))
  15904. (org-update-dblock)))
  15905. (`footnote-definition
  15906. (goto-char (org-element-property :post-affiliated context))
  15907. (call-interactively 'org-footnote-action))
  15908. (`footnote-reference (call-interactively #'org-footnote-action))
  15909. ((or `headline `inlinetask)
  15910. (save-excursion (goto-char (org-element-property :begin context))
  15911. (call-interactively #'org-set-tags-command)))
  15912. (`item
  15913. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15914. ;; unconditionally, whereas `C-u' will toggle its presence.
  15915. ;; Without a universal argument, if the item has a checkbox,
  15916. ;; toggle it. Otherwise repair the list.
  15917. (if (or radio-list-p
  15918. (and (boundp org-list-checkbox-radio-mode)
  15919. org-list-checkbox-radio-mode))
  15920. (org-toggle-radio-button arg)
  15921. (let* ((box (org-element-property :checkbox context))
  15922. (struct (org-element-property :structure context))
  15923. (old-struct (copy-tree struct))
  15924. (parents (org-list-parents-alist struct))
  15925. (prevs (org-list-prevs-alist struct))
  15926. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15927. (org-list-set-checkbox
  15928. (org-element-property :begin context) struct
  15929. (cond ((equal arg '(16)) "[-]")
  15930. ((and (not box) (equal arg '(4))) "[ ]")
  15931. ((or (not box) (equal arg '(4))) nil)
  15932. ((eq box 'on) "[ ]")
  15933. (t "[X]")))
  15934. ;; Mimic `org-list-write-struct' but with grabbing a return
  15935. ;; value from `org-list-struct-fix-box'.
  15936. (org-list-struct-fix-ind struct parents 2)
  15937. (org-list-struct-fix-item-end struct)
  15938. (org-list-struct-fix-bul struct prevs)
  15939. (org-list-struct-fix-ind struct parents)
  15940. (let ((block-item
  15941. (org-list-struct-fix-box struct parents prevs orderedp)))
  15942. (if (and box (equal struct old-struct))
  15943. (if (equal arg '(16))
  15944. (message "Checkboxes already reset")
  15945. (user-error "Cannot toggle this checkbox: %s"
  15946. (if (eq box 'on)
  15947. "all subitems checked"
  15948. "unchecked subitems")))
  15949. (org-list-struct-apply-struct struct old-struct)
  15950. (org-update-checkbox-count-maybe))
  15951. (when block-item
  15952. (message "Checkboxes were removed due to empty box at line %d"
  15953. (org-current-line block-item)))))))
  15954. (`plain-list
  15955. ;; At a plain list, with a double C-u argument, set
  15956. ;; checkboxes of each item to "[-]", whereas a single one
  15957. ;; will toggle their presence according to the state of the
  15958. ;; first item in the list. Without an argument, repair the
  15959. ;; list.
  15960. (if (or radio-list-p
  15961. (and (boundp org-list-checkbox-radio-mode)
  15962. org-list-checkbox-radio-mode))
  15963. (org-toggle-radio-button arg)
  15964. (let* ((begin (org-element-property :contents-begin context))
  15965. (struct (org-element-property :structure context))
  15966. (old-struct (copy-tree struct))
  15967. (first-box (save-excursion
  15968. (goto-char begin)
  15969. (looking-at org-list-full-item-re)
  15970. (match-string-no-properties 3)))
  15971. (new-box (cond ((equal arg '(16)) "[-]")
  15972. ((equal arg '(4)) (unless first-box "[ ]"))
  15973. ((equal first-box "[X]") "[ ]")
  15974. (t "[X]"))))
  15975. (cond
  15976. (arg
  15977. (dolist (pos
  15978. (org-list-get-all-items
  15979. begin struct (org-list-prevs-alist struct)))
  15980. (org-list-set-checkbox pos struct new-box)))
  15981. ((and first-box (eq (point) begin))
  15982. ;; For convenience, when point is at bol on the first
  15983. ;; item of the list and no argument is provided, simply
  15984. ;; toggle checkbox of that item, if any.
  15985. (org-list-set-checkbox begin struct new-box)))
  15986. (when (equal
  15987. (org-list-write-struct
  15988. struct (org-list-parents-alist struct) old-struct)
  15989. old-struct)
  15990. (message "Cannot update this checkbox"))
  15991. (org-update-checkbox-count-maybe))))
  15992. (`keyword
  15993. (let ((org-inhibit-startup-visibility-stuff t)
  15994. (org-startup-align-all-tables nil))
  15995. (when (boundp 'org-table-coordinate-overlays)
  15996. (mapc #'delete-overlay org-table-coordinate-overlays)
  15997. (setq org-table-coordinate-overlays nil))
  15998. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15999. (message "Local setup has been refreshed"))
  16000. ((or `property-drawer `node-property)
  16001. (call-interactively #'org-property-action))
  16002. (`radio-target
  16003. (call-interactively #'org-update-radio-target-regexp))
  16004. (`statistics-cookie
  16005. (call-interactively #'org-update-statistics-cookies))
  16006. ((or `table `table-cell `table-row)
  16007. ;; At a table, recalculate every field and align it. Also
  16008. ;; send the table if necessary. If the table has
  16009. ;; a `table.el' type, just give up. At a table row or cell,
  16010. ;; maybe recalculate line but always align table.
  16011. (if (eq (org-element-property :type context) 'table.el)
  16012. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16013. Use `\\[org-edit-special]' to edit table.el tables"))
  16014. (if (or (eq type 'table)
  16015. ;; Check if point is at a TBLFM line.
  16016. (and (eq type 'table-row)
  16017. (= (point) (org-element-property :end context))))
  16018. (save-excursion
  16019. (if (org-at-TBLFM-p)
  16020. (progn (require 'org-table)
  16021. (org-table-calc-current-TBLFM))
  16022. (goto-char (org-element-property :contents-begin context))
  16023. (org-call-with-arg 'org-table-recalculate (or arg t))
  16024. (orgtbl-send-table 'maybe)))
  16025. (org-table-maybe-eval-formula)
  16026. (cond (arg (call-interactively #'org-table-recalculate))
  16027. ((org-table-maybe-recalculate-line))
  16028. (t (org-table-align))))))
  16029. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16030. (org-timestamp-change 0 'day))
  16031. ((and `nil (guard (org-at-heading-p)))
  16032. ;; When point is on an unsupported object type, we can miss
  16033. ;; the fact that it also is at a heading. Handle it here.
  16034. (call-interactively #'org-set-tags-command))
  16035. ((guard
  16036. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16037. (_
  16038. (user-error
  16039. (substitute-command-keys
  16040. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16041. (defun org-mode-restart ()
  16042. (interactive)
  16043. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16044. (funcall major-mode)
  16045. (hack-local-variables)
  16046. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16047. (org-indent-mode -1))
  16048. (org-reset-file-cache))
  16049. (message "%s restarted" major-mode))
  16050. (defun org-flag-above-first-heading (&optional arg)
  16051. "Hide from bob up to the first heading.
  16052. Move point to the beginning of first heading or end of buffer."
  16053. (goto-char (point-min))
  16054. (unless (org-at-heading-p)
  16055. (outline-next-heading))
  16056. (unless (bobp)
  16057. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16058. (defun org-show-branches-buffer ()
  16059. "Show all branches in the buffer."
  16060. (org-flag-above-first-heading)
  16061. (outline-hide-sublevels 1)
  16062. (unless (eobp)
  16063. (outline-show-branches)
  16064. (while (outline-get-next-sibling)
  16065. (outline-show-branches)))
  16066. (goto-char (point-min)))
  16067. (defun org-kill-note-or-show-branches ()
  16068. "Abort storing current note, or show just branches."
  16069. (interactive)
  16070. (cond (org-finish-function
  16071. (let ((org-note-abort t)) (funcall org-finish-function)))
  16072. ((org-before-first-heading-p)
  16073. (org-show-branches-buffer)
  16074. (org-hide-archived-subtrees (point-min) (point-max)))
  16075. (t
  16076. (let ((beg (progn (org-back-to-heading) (point)))
  16077. (end (save-excursion (org-end-of-subtree t t) (point))))
  16078. (outline-hide-subtree)
  16079. (outline-show-branches)
  16080. (org-hide-archived-subtrees beg end)))))
  16081. (defun org-delete-indentation (&optional arg)
  16082. "Join current line to previous and fix whitespace at join.
  16083. If previous line is a headline add to headline title. Otherwise
  16084. the function calls `delete-indentation'.
  16085. With a non-nil optional argument, join it to the following one."
  16086. (interactive "*P")
  16087. (if (save-excursion
  16088. (beginning-of-line (if arg 1 0))
  16089. (let ((case-fold-search nil))
  16090. (looking-at org-complex-heading-regexp)))
  16091. ;; At headline.
  16092. (let ((tags-column (when (match-beginning 5)
  16093. (save-excursion (goto-char (match-beginning 5))
  16094. (current-column))))
  16095. (string (concat " " (progn (when arg (forward-line 1))
  16096. (org-trim (delete-and-extract-region
  16097. (line-beginning-position)
  16098. (line-end-position)))))))
  16099. (unless (bobp) (delete-region (point) (1- (point))))
  16100. (goto-char (or (match-end 4)
  16101. (match-beginning 5)
  16102. (match-end 0)))
  16103. (skip-chars-backward " \t")
  16104. (save-excursion (insert string))
  16105. ;; Adjust alignment of tags.
  16106. (cond
  16107. ((not tags-column)) ;no tags
  16108. (org-auto-align-tags (org-align-tags))
  16109. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16110. (delete-indentation arg)))
  16111. (defun org-open-line (n)
  16112. "Insert a new row in tables, call `open-line' elsewhere.
  16113. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16114. As a special case, when a document starts with a table, allow to
  16115. call `open-line' on the very first character."
  16116. (interactive "*p")
  16117. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16118. (org-table-insert-row)
  16119. (open-line n)))
  16120. (defun org--newline (indent arg interactive)
  16121. "Call `newline-and-indent' or just `newline'.
  16122. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16123. indent unconditionally; otherwise, call `newline' with ARG and
  16124. INTERACTIVE, which can trigger indentation if
  16125. `electric-indent-mode' is enabled."
  16126. (if indent
  16127. (org-newline-and-indent arg)
  16128. (newline arg interactive)))
  16129. (defun org-return (&optional indent arg interactive)
  16130. "Goto next table row or insert a newline.
  16131. Calls `org-table-next-row' or `newline', depending on context.
  16132. When optional INDENT argument is non-nil, call
  16133. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16134. and INTERACTIVE.
  16135. When `org-return-follows-link' is non-nil and point is on
  16136. a timestamp or a link, call `org-open-at-point'. However, it
  16137. will not happen if point is in a table or on a \"dead\"
  16138. object (e.g., within a comment). In these case, you need to use
  16139. `org-open-at-point' directly."
  16140. (interactive "*i\nP\np")
  16141. (let ((context (if org-return-follows-link (org-element-context)
  16142. (org-element-at-point))))
  16143. (cond
  16144. ;; In a table, call `org-table-next-row'. However, before first
  16145. ;; column or after last one, split the table.
  16146. ((or (and (eq 'table (org-element-type context))
  16147. (not (eq 'table.el (org-element-property :type context)))
  16148. (>= (point) (org-element-property :contents-begin context))
  16149. (< (point) (org-element-property :contents-end context)))
  16150. (org-element-lineage context '(table-row table-cell) t))
  16151. (if (or (looking-at-p "[ \t]*$")
  16152. (save-excursion (skip-chars-backward " \t") (bolp)))
  16153. (insert "\n")
  16154. (org-table-justify-field-maybe)
  16155. (call-interactively #'org-table-next-row)))
  16156. ;; On a link or a timestamp, call `org-open-at-point' if
  16157. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16158. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16159. ((and org-return-follows-link
  16160. (or (and (eq 'link (org-element-type context))
  16161. ;; Ensure point is not on the white spaces after
  16162. ;; the link.
  16163. (let ((origin (point)))
  16164. (org-with-point-at (org-element-property :end context)
  16165. (skip-chars-backward " \t")
  16166. (> (point) origin))))
  16167. (org-in-regexp org-ts-regexp-both nil t)
  16168. (org-in-regexp org-tsr-regexp-both nil t)
  16169. (org-in-regexp org-link-any-re nil t)))
  16170. (call-interactively #'org-open-at-point))
  16171. ;; Insert newline in heading, but preserve tags.
  16172. ((and (not (bolp))
  16173. (let ((case-fold-search nil))
  16174. (org-match-line org-complex-heading-regexp)))
  16175. ;; At headline. Split line. However, if point is on keyword,
  16176. ;; priority cookie or tags, do not break any of them: add
  16177. ;; a newline after the headline instead.
  16178. (let ((tags-column (and (match-beginning 5)
  16179. (save-excursion (goto-char (match-beginning 5))
  16180. (current-column))))
  16181. (string
  16182. (when (and (match-end 4) (org-point-in-group (point) 4))
  16183. (delete-and-extract-region (point) (match-end 4)))))
  16184. ;; Adjust tag alignment.
  16185. (cond
  16186. ((not (and tags-column string)))
  16187. (org-auto-align-tags (org-align-tags))
  16188. (t (org--align-tags-here tags-column))) ;preserve tags column
  16189. (end-of-line)
  16190. (org-show-entry)
  16191. (org--newline indent arg interactive)
  16192. (when string (save-excursion (insert (org-trim string))))))
  16193. ;; In a list, make sure indenting keeps trailing text within.
  16194. ((and (not (eolp))
  16195. (org-element-lineage context '(item)))
  16196. (let ((trailing-data
  16197. (delete-and-extract-region (point) (line-end-position))))
  16198. (org--newline indent arg interactive)
  16199. (save-excursion (insert trailing-data))))
  16200. (t
  16201. ;; Do not auto-fill when point is in an Org property drawer.
  16202. (let ((auto-fill-function (and (not (org-at-property-p))
  16203. auto-fill-function)))
  16204. (org--newline indent arg interactive))))))
  16205. (defun org-return-and-maybe-indent ()
  16206. "Goto next table row, or insert a newline.
  16207. Call `org-table-next-row' or `org-return', depending on context.
  16208. See the individual commands for more information.
  16209. When inserting a newline, indent the new line if
  16210. `electric-indent-mode' is disabled."
  16211. (interactive)
  16212. (org-return (not electric-indent-mode)))
  16213. (defun org-ctrl-c-tab (&optional arg)
  16214. "Toggle columns width in a table, or show children.
  16215. Call `org-table-toggle-column-width' if point is in a table.
  16216. Otherwise, call `org-show-children'. ARG is the level to hide."
  16217. (interactive "p")
  16218. (if (org-at-table-p)
  16219. (call-interactively #'org-table-toggle-column-width)
  16220. (if (org-before-first-heading-p)
  16221. (progn
  16222. (org-flag-above-first-heading)
  16223. (outline-hide-sublevels (or arg 1))
  16224. (goto-char (point-min)))
  16225. (outline-hide-subtree)
  16226. (org-show-children arg))))
  16227. (defun org-ctrl-c-star ()
  16228. "Compute table, or change heading status of lines.
  16229. Calls `org-table-recalculate' or `org-toggle-heading',
  16230. depending on context."
  16231. (interactive)
  16232. (cond
  16233. ((org-at-table-p)
  16234. (call-interactively 'org-table-recalculate))
  16235. (t
  16236. ;; Convert all lines in region to list items
  16237. (call-interactively 'org-toggle-heading))))
  16238. (defun org-ctrl-c-minus ()
  16239. "Insert separator line in table or modify bullet status of line.
  16240. Also turns a plain line or a region of lines into list items.
  16241. Calls `org-table-insert-hline', `org-toggle-item', or
  16242. `org-cycle-list-bullet', depending on context."
  16243. (interactive)
  16244. (cond
  16245. ((org-at-table-p)
  16246. (call-interactively 'org-table-insert-hline))
  16247. ((org-region-active-p)
  16248. (call-interactively 'org-toggle-item))
  16249. ((org-in-item-p)
  16250. (call-interactively 'org-cycle-list-bullet))
  16251. (t
  16252. (call-interactively 'org-toggle-item))))
  16253. (defun org-toggle-heading (&optional nstars)
  16254. "Convert headings to normal text, or items or text to headings.
  16255. If there is no active region, only convert the current line.
  16256. With a `\\[universal-argument]' prefix, convert the whole list at
  16257. point into heading.
  16258. In a region:
  16259. - If the first non blank line is a headline, remove the stars
  16260. from all headlines in the region.
  16261. - If it is a normal line, turn each and every normal line (i.e.,
  16262. not an heading or an item) in the region into headings. If you
  16263. want to convert only the first line of this region, use one
  16264. universal prefix argument.
  16265. - If it is a plain list item, turn all plain list items into headings.
  16266. When converting a line into a heading, the number of stars is chosen
  16267. such that the lines become children of the current entry. However,
  16268. when a numeric prefix argument is given, its value determines the
  16269. number of stars to add."
  16270. (interactive "P")
  16271. (let ((skip-blanks
  16272. (function
  16273. ;; Return beginning of first non-blank line, starting from
  16274. ;; line at POS.
  16275. (lambda (pos)
  16276. (save-excursion
  16277. (goto-char pos)
  16278. (while (org-at-comment-p) (forward-line))
  16279. (skip-chars-forward " \r\t\n")
  16280. (point-at-bol)))))
  16281. beg end toggled)
  16282. ;; Determine boundaries of changes. If a universal prefix has
  16283. ;; been given, put the list in a region. If region ends at a bol,
  16284. ;; do not consider the last line to be in the region.
  16285. (when (and current-prefix-arg (org-at-item-p))
  16286. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16287. (org-mark-element))
  16288. (if (org-region-active-p)
  16289. (setq beg (funcall skip-blanks (region-beginning))
  16290. end (copy-marker (save-excursion
  16291. (goto-char (region-end))
  16292. (if (bolp) (point) (point-at-eol)))))
  16293. (setq beg (funcall skip-blanks (point-at-bol))
  16294. end (copy-marker (point-at-eol))))
  16295. ;; Ensure inline tasks don't count as headings.
  16296. (org-with-limited-levels
  16297. (save-excursion
  16298. (goto-char beg)
  16299. (cond
  16300. ;; Case 1. Started at an heading: de-star headings.
  16301. ((org-at-heading-p)
  16302. (while (< (point) end)
  16303. (when (org-at-heading-p t)
  16304. (looking-at org-outline-regexp) (replace-match "")
  16305. (setq toggled t))
  16306. (forward-line)))
  16307. ;; Case 2. Started at an item: change items into headlines.
  16308. ;; One star will be added by `org-list-to-subtree'.
  16309. ((org-at-item-p)
  16310. (while (< (point) end)
  16311. (when (org-at-item-p)
  16312. ;; Pay attention to cases when region ends before list.
  16313. (let* ((struct (org-list-struct))
  16314. (list-end
  16315. (min (org-list-get-bottom-point struct) (1+ end))))
  16316. (save-restriction
  16317. (narrow-to-region (point) list-end)
  16318. (insert (org-list-to-subtree
  16319. (org-list-to-lisp t)
  16320. (pcase (org-current-level)
  16321. (`nil 1)
  16322. (l (1+ (org-reduced-level l)))))
  16323. "\n")))
  16324. (setq toggled t))
  16325. (forward-line)))
  16326. ;; Case 3. Started at normal text: make every line an heading,
  16327. ;; skipping headlines and items.
  16328. (t (let* ((stars
  16329. (make-string
  16330. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16331. (add-stars
  16332. (cond (nstars "") ; stars from prefix only
  16333. ((equal stars "") "*") ; before first heading
  16334. (org-odd-levels-only "**") ; inside heading, odd
  16335. (t "*"))) ; inside heading, oddeven
  16336. (rpl (concat stars add-stars " "))
  16337. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16338. (while (< (point) (if (equal nstars '(4)) lend end))
  16339. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16340. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16341. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16342. (forward-line)))))))
  16343. (unless toggled (message "Cannot toggle heading from here"))))
  16344. (defun org-meta-return (&optional arg)
  16345. "Insert a new heading or wrap a region in a table.
  16346. Calls `org-insert-heading', `org-insert-item' or
  16347. `org-table-wrap-region', depending on context. When called with
  16348. an argument, unconditionally call `org-insert-heading'."
  16349. (interactive "P")
  16350. (org-check-before-invisible-edit 'insert)
  16351. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16352. (call-interactively (cond (arg #'org-insert-heading)
  16353. ((org-at-table-p) #'org-table-wrap-region)
  16354. ((org-in-item-p) #'org-insert-item)
  16355. (t #'org-insert-heading)))))
  16356. ;;; Menu entries
  16357. (defsubst org-in-subtree-not-table-p ()
  16358. "Are we in a subtree and not in a table?"
  16359. (and (not (org-before-first-heading-p))
  16360. (not (org-at-table-p))))
  16361. ;; Define the Org mode menus
  16362. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16363. `("Org"
  16364. ("Show/Hide"
  16365. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16366. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16367. ["Sparse Tree..." org-sparse-tree t]
  16368. ["Reveal Context" org-reveal t]
  16369. ["Show All" org-show-all t]
  16370. "--"
  16371. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16372. "--"
  16373. ["New Heading" org-insert-heading t]
  16374. ("Navigate Headings"
  16375. ["Up" outline-up-heading t]
  16376. ["Next" outline-next-visible-heading t]
  16377. ["Previous" outline-previous-visible-heading t]
  16378. ["Next Same Level" outline-forward-same-level t]
  16379. ["Previous Same Level" outline-backward-same-level t]
  16380. "--"
  16381. ["Jump" org-goto t])
  16382. ("Edit Structure"
  16383. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16384. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16385. "--"
  16386. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16387. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16388. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16389. "--"
  16390. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16391. "--"
  16392. ["Copy visible text" org-copy-visible t]
  16393. "--"
  16394. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16395. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16396. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16397. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16398. "--"
  16399. ["Sort Region/Children" org-sort t]
  16400. "--"
  16401. ["Convert to odd levels" org-convert-to-odd-levels t]
  16402. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16403. ("Editing"
  16404. ["Emphasis..." org-emphasize t]
  16405. ["Add block structure" org-insert-structure-template t]
  16406. ["Edit Source Example" org-edit-special t]
  16407. "--"
  16408. ["Footnote new/jump" org-footnote-action t]
  16409. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16410. ("Archive"
  16411. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16412. "--"
  16413. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16414. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16415. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16416. "--"
  16417. ("Hyperlinks"
  16418. ["Store Link (Global)" org-store-link t]
  16419. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16420. ["Insert Link" org-insert-link t]
  16421. ["Follow Link" org-open-at-point t]
  16422. "--"
  16423. ["Next link" org-next-link t]
  16424. ["Previous link" org-previous-link t]
  16425. "--"
  16426. ["Descriptive Links"
  16427. org-toggle-link-display
  16428. :style radio
  16429. :selected org-descriptive-links
  16430. ]
  16431. ["Literal Links"
  16432. org-toggle-link-display
  16433. :style radio
  16434. :selected (not org-descriptive-links)])
  16435. "--"
  16436. ("TODO Lists"
  16437. ["TODO/DONE/-" org-todo t]
  16438. ("Select keyword"
  16439. ["Next keyword" org-shiftright (org-at-heading-p)]
  16440. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16441. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16442. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16443. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16444. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16445. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16446. "--"
  16447. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16448. :selected org-enforce-todo-dependencies :style toggle :active t]
  16449. "Settings for tree at point"
  16450. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16451. :selected (org-entry-get nil "ORDERED")
  16452. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16453. ["Do Children parallel" org-toggle-ordered-property :style radio
  16454. :selected (not (org-entry-get nil "ORDERED"))
  16455. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16456. "--"
  16457. ["Set Priority" org-priority t]
  16458. ["Priority Up" org-shiftup t]
  16459. ["Priority Down" org-shiftdown t]
  16460. "--"
  16461. ["Get news from all feeds" org-feed-update-all t]
  16462. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16463. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16464. ("TAGS and Properties"
  16465. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16466. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16467. "--"
  16468. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16469. ["Column view of properties" org-columns t]
  16470. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16471. ("Dates and Scheduling"
  16472. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16473. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16474. ("Change Date"
  16475. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16476. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16477. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16478. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16479. ["Compute Time Range" org-evaluate-time-range t]
  16480. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16481. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16482. "--"
  16483. ["Custom time format" org-toggle-time-stamp-overlays
  16484. :style radio :selected org-display-custom-times]
  16485. "--"
  16486. ["Goto Calendar" org-goto-calendar t]
  16487. ["Date from Calendar" org-date-from-calendar t]
  16488. "--"
  16489. ["Start/Restart Timer" org-timer-start t]
  16490. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16491. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16492. ["Insert Timer String" org-timer t]
  16493. ["Insert Timer Item" org-timer-item t])
  16494. ("Logging work"
  16495. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16496. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16497. ["Clock out" org-clock-out t]
  16498. ["Clock cancel" org-clock-cancel t]
  16499. "--"
  16500. ["Mark as default task" org-clock-mark-default-task t]
  16501. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16502. ["Goto running clock" org-clock-goto t]
  16503. "--"
  16504. ["Display times" org-clock-display t]
  16505. ["Create clock table" org-clock-report t]
  16506. "--"
  16507. ["Record DONE time"
  16508. (progn (setq org-log-done (not org-log-done))
  16509. (message "Switching to %s will %s record a timestamp"
  16510. (car org-done-keywords)
  16511. (if org-log-done "automatically" "not")))
  16512. :style toggle :selected org-log-done])
  16513. "--"
  16514. ["Agenda Command..." org-agenda t]
  16515. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16516. ("File List for Agenda")
  16517. ("Special views current file"
  16518. ["TODO Tree" org-show-todo-tree t]
  16519. ["Check Deadlines" org-check-deadlines t]
  16520. ["Tags/Property tree" org-match-sparse-tree t])
  16521. "--"
  16522. ["Export/Publish..." org-export-dispatch t]
  16523. ("LaTeX"
  16524. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16525. :style toggle :selected org-cdlatex-mode]
  16526. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16527. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16528. ["Modify math symbol" org-cdlatex-math-modify
  16529. (org-inside-LaTeX-fragment-p)]
  16530. ["Insert citation" org-reftex-citation t])
  16531. "--"
  16532. ("Documentation"
  16533. ["Show Version" org-version t]
  16534. ["Info Documentation" org-info t]
  16535. ["Browse Org News" org-browse-news t])
  16536. ("Customize"
  16537. ["Browse Org Group" org-customize t]
  16538. "--"
  16539. ["Expand This Menu" org-create-customize-menu
  16540. (fboundp 'customize-menu-create)])
  16541. ["Send bug report" org-submit-bug-report t]
  16542. "--"
  16543. ("Refresh/Reload"
  16544. ["Refresh setup current buffer" org-mode-restart t]
  16545. ["Reload Org (after update)" org-reload t]
  16546. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16547. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16548. '("Table"
  16549. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16550. ["Next Field" org-cycle (org-at-table-p)]
  16551. ["Previous Field" org-shifttab (org-at-table-p)]
  16552. ["Next Row" org-return (org-at-table-p)]
  16553. "--"
  16554. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16555. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16556. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16557. "--"
  16558. ("Column"
  16559. ["Move Column Left" org-metaleft (org-at-table-p)]
  16560. ["Move Column Right" org-metaright (org-at-table-p)]
  16561. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16562. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16563. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16564. ("Row"
  16565. ["Move Row Up" org-metaup (org-at-table-p)]
  16566. ["Move Row Down" org-metadown (org-at-table-p)]
  16567. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16568. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16569. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16570. "--"
  16571. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16572. ("Rectangle"
  16573. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16574. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16575. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16576. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16577. "--"
  16578. ("Calculate"
  16579. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16580. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16581. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16582. "--"
  16583. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16584. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16585. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16586. "--"
  16587. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16588. "--"
  16589. ["Sum Column/Rectangle" org-table-sum
  16590. (or (org-at-table-p) (org-region-active-p))]
  16591. ["Which Column?" org-table-current-column (org-at-table-p)])
  16592. ["Debug Formulas"
  16593. org-table-toggle-formula-debugger
  16594. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16595. ["Show Col/Row Numbers"
  16596. org-table-toggle-coordinate-overlays
  16597. :style toggle
  16598. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16599. "--"
  16600. ["Create" org-table-create (not (org-at-table-p))]
  16601. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16602. ["Import from File" org-table-import (not (org-at-table-p))]
  16603. ["Export to File" org-table-export (org-at-table-p)]
  16604. "--"
  16605. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16606. "--"
  16607. ("Plot"
  16608. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16609. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16610. (defun org-info (&optional node)
  16611. "Read documentation for Org in the info system.
  16612. With optional NODE, go directly to that node."
  16613. (interactive)
  16614. (info (format "(org)%s" (or node ""))))
  16615. (defun org-browse-news ()
  16616. "Browse the news for the latest major release."
  16617. (interactive)
  16618. (browse-url "https://orgmode.org/Changes.html"))
  16619. ;;;###autoload
  16620. (defun org-submit-bug-report ()
  16621. "Submit a bug report on Org via mail.
  16622. Don't hesitate to report any problems or inaccurate documentation.
  16623. If you don't have setup sending mail from (X)Emacs, please copy the
  16624. output buffer into your mail program, as it gives us important
  16625. information about your Org version and configuration."
  16626. (interactive)
  16627. (require 'reporter)
  16628. (defvar reporter-prompt-for-summary-p)
  16629. (org-load-modules-maybe)
  16630. (org-require-autoloaded-modules)
  16631. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16632. (reporter-submit-bug-report
  16633. "emacs-orgmode@gnu.org"
  16634. (org-version nil 'full)
  16635. (let (list)
  16636. (save-window-excursion
  16637. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16638. (delete-other-windows)
  16639. (erase-buffer)
  16640. (insert "You are about to submit a bug report to the Org mailing list.
  16641. If your report is about Org installation, please read this section:
  16642. https://orgmode.org/org.html#Installation
  16643. Please read https://orgmode.org/org.html#Feedback on how to make
  16644. a good report, it will help Org contributors fixing your problem.
  16645. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16646. if the issue you are about to raise has already been dealt with.
  16647. We also would like to add your full Org and Outline configuration
  16648. to the bug report. It will help us debugging the issue.
  16649. *HOWEVER*, some variables you have customized may contain private
  16650. information. The names of customers, colleagues, or friends, might
  16651. appear in the form of file names, tags, todo states or search strings.
  16652. If you answer \"yes\" to the prompt, you might want to check and remove
  16653. such private information before sending the email.")
  16654. (add-text-properties (point-min) (point-max) '(face org-warning))
  16655. (when (yes-or-no-p "Include your Org configuration ")
  16656. (mapatoms
  16657. (lambda (v)
  16658. (and (boundp v)
  16659. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16660. (or (and (symbol-value v)
  16661. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16662. (and
  16663. (get v 'custom-type) (get v 'standard-value)
  16664. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16665. (push v list)))))
  16666. (kill-buffer (get-buffer "*Warn about privacy*"))
  16667. list))
  16668. nil nil
  16669. "Remember to cover the basics, that is, what you expected to happen and
  16670. what in fact did happen. You don't know how to make a good report? See
  16671. https://orgmode.org/manual/Feedback.html#Feedback
  16672. Your bug report will be posted to the Org mailing list.
  16673. ------------------------------------------------------------------------")
  16674. (save-excursion
  16675. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16676. (replace-match "\\1Bug: \\3 [\\2]")))))
  16677. (defun org-install-agenda-files-menu ()
  16678. (let ((bl (buffer-list)))
  16679. (save-excursion
  16680. (while bl
  16681. (set-buffer (pop bl))
  16682. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16683. (when (derived-mode-p 'org-mode)
  16684. (easy-menu-change
  16685. '("Org") "File List for Agenda"
  16686. (append
  16687. (list
  16688. ["Edit File List" (org-edit-agenda-file-list) t]
  16689. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16690. ["Remove Current File from List" org-remove-file t]
  16691. ["Cycle through agenda files" org-cycle-agenda-files t]
  16692. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16693. "--")
  16694. (mapcar 'org-file-menu-entry
  16695. ;; Prevent initialization from failing.
  16696. (ignore-errors (org-agenda-files t)))))))))
  16697. ;;;; Documentation
  16698. (defun org-require-autoloaded-modules ()
  16699. (interactive)
  16700. (mapc #'require
  16701. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16702. org-table org-timer)))
  16703. ;;;###autoload
  16704. (defun org-reload (&optional uncompiled)
  16705. "Reload all Org Lisp files.
  16706. With prefix arg UNCOMPILED, load the uncompiled versions."
  16707. (interactive "P")
  16708. (require 'loadhist)
  16709. (let* ((org-dir (org-find-library-dir "org"))
  16710. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16711. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16712. (remove-re (format "\\`%s\\'"
  16713. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16714. (feats (delete-dups
  16715. (mapcar 'file-name-sans-extension
  16716. (mapcar 'file-name-nondirectory
  16717. (delq nil
  16718. (mapcar 'feature-file
  16719. features))))))
  16720. (lfeat (append
  16721. (sort
  16722. (setq feats
  16723. (delq nil (mapcar
  16724. (lambda (f)
  16725. (if (and (string-match feature-re f)
  16726. (not (string-match remove-re f)))
  16727. f nil))
  16728. feats)))
  16729. 'string-lessp)
  16730. (list "org-version" "org")))
  16731. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16732. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16733. load-uncore load-misses)
  16734. (setq load-misses
  16735. (delq 't
  16736. (mapcar (lambda (f)
  16737. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16738. (and (string= org-dir contrib-dir)
  16739. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16740. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16741. (push f load-uncore)
  16742. 't)
  16743. f))
  16744. lfeat)))
  16745. (when load-uncore
  16746. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16747. (if (> (length load-uncore) 1) "s were" " was")
  16748. (reverse load-uncore)))
  16749. (if load-misses
  16750. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16751. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16752. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16753. ;;;###autoload
  16754. (defun org-customize ()
  16755. "Call the customize function with org as argument."
  16756. (interactive)
  16757. (org-load-modules-maybe)
  16758. (org-require-autoloaded-modules)
  16759. (customize-browse 'org))
  16760. (defun org-create-customize-menu ()
  16761. "Create a full customization menu for Org mode, insert it into the menu."
  16762. (interactive)
  16763. (org-load-modules-maybe)
  16764. (org-require-autoloaded-modules)
  16765. (if (fboundp 'customize-menu-create)
  16766. (progn
  16767. (easy-menu-change
  16768. '("Org") "Customize"
  16769. `(["Browse Org group" org-customize t]
  16770. "--"
  16771. ,(customize-menu-create 'org)
  16772. ["Set" Custom-set t]
  16773. ["Save" Custom-save t]
  16774. ["Reset to Current" Custom-reset-current t]
  16775. ["Reset to Saved" Custom-reset-saved t]
  16776. ["Reset to Standard Settings" Custom-reset-standard t]))
  16777. (message "\"Org\"-menu now contains full customization menu"))
  16778. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  16779. ;;;; Miscellaneous stuff
  16780. ;;; Generally useful functions
  16781. (defun org-in-clocktable-p ()
  16782. "Check if the cursor is in a clocktable."
  16783. (let ((pos (point)) start)
  16784. (save-excursion
  16785. (end-of-line 1)
  16786. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16787. (setq start (match-beginning 0))
  16788. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16789. (>= (match-end 0) pos)
  16790. start))))
  16791. (defun org-in-verbatim-emphasis ()
  16792. (save-match-data
  16793. (and (org-in-regexp org-verbatim-re 2)
  16794. (>= (point) (match-beginning 3))
  16795. (<= (point) (match-end 4)))))
  16796. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16797. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16798. (if (and marker (marker-buffer marker)
  16799. (buffer-live-p (marker-buffer marker)))
  16800. (progn
  16801. (pop-to-buffer-same-window (marker-buffer marker))
  16802. (when (or (> marker (point-max)) (< marker (point-min)))
  16803. (widen))
  16804. (goto-char marker)
  16805. (org-show-context 'org-goto))
  16806. (if bookmark
  16807. (bookmark-jump bookmark)
  16808. (error "Cannot find location"))))
  16809. (defun org-quote-csv-field (s)
  16810. "Quote field for inclusion in CSV material."
  16811. (if (string-match "[\",]" s)
  16812. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16813. s))
  16814. (defun org-force-self-insert (N)
  16815. "Needed to enforce self-insert under remapping."
  16816. (interactive "p")
  16817. (self-insert-command N))
  16818. (defun org-quote-vert (s)
  16819. "Replace \"|\" with \"\\vert\"."
  16820. (while (string-match "|" s)
  16821. (setq s (replace-match "\\vert" t t s)))
  16822. s)
  16823. (defun org-uuidgen-p (s)
  16824. "Is S an ID created by UUIDGEN?"
  16825. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16826. (defun org-in-src-block-p (&optional inside)
  16827. "Whether point is in a code source block.
  16828. When INSIDE is non-nil, don't consider we are within a source
  16829. block when point is at #+BEGIN_SRC or #+END_SRC."
  16830. (let ((case-fold-search t))
  16831. (or (and (eq (get-char-property (point) 'src-block) t))
  16832. (and (not inside)
  16833. (save-match-data
  16834. (save-excursion
  16835. (beginning-of-line)
  16836. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16837. (defun org-context ()
  16838. "Return a list of contexts of the current cursor position.
  16839. If several contexts apply, all are returned.
  16840. Each context entry is a list with a symbol naming the context, and
  16841. two positions indicating start and end of the context. Possible
  16842. contexts are:
  16843. :headline anywhere in a headline
  16844. :headline-stars on the leading stars in a headline
  16845. :todo-keyword on a TODO keyword (including DONE) in a headline
  16846. :tags on the TAGS in a headline
  16847. :priority on the priority cookie in a headline
  16848. :item on the first line of a plain list item
  16849. :item-bullet on the bullet/number of a plain list item
  16850. :checkbox on the checkbox in a plain list item
  16851. :table in an Org table
  16852. :table-special on a special filed in a table
  16853. :table-table in a table.el table
  16854. :clocktable in a clocktable
  16855. :src-block in a source block
  16856. :link on a hyperlink
  16857. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16858. :latex-fragment on a LaTeX fragment
  16859. :latex-preview on a LaTeX fragment with overlaid preview image
  16860. This function expects the position to be visible because it uses font-lock
  16861. faces as a help to recognize the following contexts: :table-special, :link,
  16862. and :keyword."
  16863. (let* ((f (get-text-property (point) 'face))
  16864. (faces (if (listp f) f (list f)))
  16865. (case-fold-search t)
  16866. (p (point)) clist o)
  16867. ;; First the large context
  16868. (cond
  16869. ((org-at-heading-p t)
  16870. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16871. (when (progn
  16872. (beginning-of-line 1)
  16873. (looking-at org-todo-line-tags-regexp))
  16874. (push (org-point-in-group p 1 :headline-stars) clist)
  16875. (push (org-point-in-group p 2 :todo-keyword) clist)
  16876. (push (org-point-in-group p 4 :tags) clist))
  16877. (goto-char p)
  16878. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16879. (when (looking-at "\\[#[A-Z0-9]\\]")
  16880. (push (org-point-in-group p 0 :priority) clist)))
  16881. ((org-at-item-p)
  16882. (push (org-point-in-group p 2 :item-bullet) clist)
  16883. (push (list :item (point-at-bol)
  16884. (save-excursion (org-end-of-item) (point)))
  16885. clist)
  16886. (and (org-at-item-checkbox-p)
  16887. (push (org-point-in-group p 0 :checkbox) clist)))
  16888. ((org-at-table-p)
  16889. (push (list :table (org-table-begin) (org-table-end)) clist)
  16890. (when (memq 'org-formula faces)
  16891. (push (list :table-special
  16892. (previous-single-property-change p 'face)
  16893. (next-single-property-change p 'face))
  16894. clist)))
  16895. ((org-at-table-p 'any)
  16896. (push (list :table-table) clist)))
  16897. (goto-char p)
  16898. (let ((case-fold-search t))
  16899. ;; New the "medium" contexts: clocktables, source blocks
  16900. (cond ((org-in-clocktable-p)
  16901. (push (list :clocktable
  16902. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16903. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16904. (match-beginning 1))
  16905. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16906. (match-end 0)))
  16907. clist))
  16908. ((org-in-src-block-p)
  16909. (push (list :src-block
  16910. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16911. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16912. (match-beginning 1))
  16913. (and (search-forward "#+END_SRC" nil t)
  16914. (match-beginning 0)))
  16915. clist))))
  16916. (goto-char p)
  16917. ;; Now the small context
  16918. (cond
  16919. ((org-at-timestamp-p)
  16920. (push (org-point-in-group p 0 :timestamp) clist))
  16921. ((memq 'org-link faces)
  16922. (push (list :link
  16923. (previous-single-property-change p 'face)
  16924. (next-single-property-change p 'face))
  16925. clist))
  16926. ((memq 'org-special-keyword faces)
  16927. (push (list :keyword
  16928. (previous-single-property-change p 'face)
  16929. (next-single-property-change p 'face))
  16930. clist))
  16931. ((setq o (cl-some
  16932. (lambda (o)
  16933. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16934. o))
  16935. (overlays-at (point))))
  16936. (push (list :latex-fragment
  16937. (overlay-start o) (overlay-end o))
  16938. clist)
  16939. (push (list :latex-preview
  16940. (overlay-start o) (overlay-end o))
  16941. clist))
  16942. ((org-inside-LaTeX-fragment-p)
  16943. ;; FIXME: positions wrong.
  16944. (push (list :latex-fragment (point) (point)) clist)))
  16945. (setq clist (nreverse (delq nil clist)))
  16946. clist))
  16947. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16948. "Non-nil when point is between matches of START-RE and END-RE.
  16949. Also return a non-nil value when point is on one of the matches.
  16950. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16951. buffer positions. Default values are the positions of headlines
  16952. surrounding the point.
  16953. The functions returns a cons cell whose car (resp. cdr) is the
  16954. position before START-RE (resp. after END-RE)."
  16955. (save-match-data
  16956. (let ((pos (point))
  16957. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16958. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16959. beg end)
  16960. (save-excursion
  16961. ;; Point is on a block when on START-RE or if START-RE can be
  16962. ;; found before it...
  16963. (and (or (org-in-regexp start-re)
  16964. (re-search-backward start-re limit-up t))
  16965. (setq beg (match-beginning 0))
  16966. ;; ... and END-RE after it...
  16967. (goto-char (match-end 0))
  16968. (re-search-forward end-re limit-down t)
  16969. (> (setq end (match-end 0)) pos)
  16970. ;; ... without another START-RE in-between.
  16971. (goto-char (match-beginning 0))
  16972. (not (re-search-backward start-re (1+ beg) t))
  16973. ;; Return value.
  16974. (cons beg end))))))
  16975. (defun org-in-block-p (names)
  16976. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16977. NAMES is a list of strings containing names of blocks.
  16978. Return first block name matched, or nil. Beware that in case of
  16979. nested blocks, the returned name may not belong to the closest
  16980. block from point."
  16981. (save-match-data
  16982. (catch 'exit
  16983. (let ((case-fold-search t)
  16984. (lim-up (save-excursion (outline-previous-heading)))
  16985. (lim-down (save-excursion (outline-next-heading))))
  16986. (dolist (name names)
  16987. (let ((n (regexp-quote name)))
  16988. (when (org-between-regexps-p
  16989. (concat "^[ \t]*#\\+begin_" n)
  16990. (concat "^[ \t]*#\\+end_" n)
  16991. lim-up lim-down)
  16992. (throw 'exit n)))))
  16993. nil)))
  16994. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16995. "Call `multi-occur' with buffers for all agenda files."
  16996. (interactive "sOrg-files matching: ")
  16997. (let* ((files (org-agenda-files))
  16998. (tnames (mapcar #'file-truename files))
  16999. (extra org-agenda-text-search-extra-files))
  17000. (when (eq (car extra) 'agenda-archives)
  17001. (setq extra (cdr extra))
  17002. (setq files (org-add-archive-files files)))
  17003. (dolist (f extra)
  17004. (unless (member (file-truename f) tnames)
  17005. (unless (member f files) (setq files (append files (list f))))
  17006. (setq tnames (append tnames (list (file-truename f))))))
  17007. (multi-occur
  17008. (mapcar (lambda (x)
  17009. (with-current-buffer
  17010. ;; FIXME: Why not just (find-file-noselect x)?
  17011. ;; Is it to avoid the "revert buffer" prompt?
  17012. (or (get-file-buffer x) (find-file-noselect x))
  17013. (widen)
  17014. (current-buffer)))
  17015. files)
  17016. regexp)))
  17017. (add-hook 'occur-mode-find-occurrence-hook
  17018. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17019. (defun org-occur-link-in-agenda-files ()
  17020. "Create a link and search for it in the agendas.
  17021. The link is not stored in `org-stored-links', it is just created
  17022. for the search purpose."
  17023. (interactive)
  17024. (let ((link (condition-case nil
  17025. (org-store-link nil)
  17026. (error "Unable to create a link to here"))))
  17027. (org-occur-in-agenda-files (regexp-quote link))))
  17028. (defun org-back-over-empty-lines ()
  17029. "Move backwards over whitespace, to the beginning of the first empty line.
  17030. Returns the number of empty lines passed."
  17031. (let ((pos (point)))
  17032. (if (cdr (assq 'heading org-blank-before-new-entry))
  17033. (skip-chars-backward " \t\n\r")
  17034. (unless (eobp)
  17035. (forward-line -1)))
  17036. (beginning-of-line 2)
  17037. (goto-char (min (point) pos))
  17038. (count-lines (point) pos)))
  17039. ;;; TODO: Only called once, from ox-odt which should probably use
  17040. ;;; org-export-inline-image-p or something.
  17041. (defun org-file-image-p (file)
  17042. "Return non-nil if FILE is an image."
  17043. (save-match-data
  17044. (string-match (image-file-name-regexp) file)))
  17045. (defun org-get-cursor-date (&optional with-time)
  17046. "Return the date at cursor in as a time.
  17047. This works in the calendar and in the agenda, anywhere else it just
  17048. returns the current time.
  17049. If WITH-TIME is non-nil, returns the time of the event at point (in
  17050. the agenda) or the current time of the day; otherwise returns the
  17051. earliest time on the cursor date that Org treats as that date
  17052. (bearing in mind `org-extend-today-until')."
  17053. (let (date day defd tp hod mod)
  17054. (when with-time
  17055. (setq tp (get-text-property (point) 'time))
  17056. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17057. (setq hod (string-to-number (match-string 1 tp))
  17058. mod (string-to-number (match-string 2 tp))))
  17059. (or tp (let ((now (decode-time)))
  17060. (setq hod (nth 2 now)
  17061. mod (nth 1 now)))))
  17062. (cond
  17063. ((eq major-mode 'calendar-mode)
  17064. (setq date (calendar-cursor-to-date)
  17065. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17066. (nth 1 date) (nth 0 date) (nth 2 date))))
  17067. ((eq major-mode 'org-agenda-mode)
  17068. (setq day (get-text-property (point) 'day))
  17069. (when day
  17070. (setq date (calendar-gregorian-from-absolute day)
  17071. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17072. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17073. (or defd (current-time))))
  17074. (defun org-mark-subtree (&optional up)
  17075. "Mark the current subtree.
  17076. This puts point at the start of the current subtree, and mark at
  17077. the end. If a numeric prefix UP is given, move up into the
  17078. hierarchy of headlines by UP levels before marking the subtree."
  17079. (interactive "P")
  17080. (org-with-limited-levels
  17081. (cond ((org-at-heading-p) (beginning-of-line))
  17082. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17083. (t (outline-previous-visible-heading 1))))
  17084. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17085. (if (called-interactively-p 'any)
  17086. (call-interactively 'org-mark-element)
  17087. (org-mark-element)))
  17088. ;;; Indentation
  17089. (defvar org-element-greater-elements)
  17090. (defun org--get-expected-indentation (element contentsp)
  17091. "Expected indentation column for current line, according to ELEMENT.
  17092. ELEMENT is an element containing point. CONTENTSP is non-nil
  17093. when indentation is to be computed according to contents of
  17094. ELEMENT."
  17095. (let ((type (org-element-type element))
  17096. (start (org-element-property :begin element))
  17097. (post-affiliated (org-element-property :post-affiliated element)))
  17098. (org-with-wide-buffer
  17099. (cond
  17100. (contentsp
  17101. (cl-case type
  17102. ((diary-sexp footnote-definition) 0)
  17103. ((headline inlinetask nil)
  17104. (if (not org-adapt-indentation) 0
  17105. (let ((level (org-current-level)))
  17106. (if level (1+ level) 0))))
  17107. ((item plain-list) (org-list-item-body-column post-affiliated))
  17108. (t
  17109. (goto-char start)
  17110. (current-indentation))))
  17111. ((and
  17112. (eq org-adapt-indentation 'headline-data)
  17113. (memq type '(planning clock node-property property-drawer drawer)))
  17114. (org--get-expected-indentation
  17115. (org-element-property :parent element) t))
  17116. ((memq type '(headline inlinetask nil))
  17117. (if (org-match-line "[ \t]*$")
  17118. (org--get-expected-indentation element t)
  17119. 0))
  17120. ((memq type '(diary-sexp footnote-definition)) 0)
  17121. ;; First paragraph of a footnote definition or an item.
  17122. ;; Indent like parent.
  17123. ((< (line-beginning-position) start)
  17124. (org--get-expected-indentation
  17125. (org-element-property :parent element) t))
  17126. ;; At first line: indent according to previous sibling, if any,
  17127. ;; ignoring footnote definitions and inline tasks, or parent's
  17128. ;; contents.
  17129. ((and ( = (line-beginning-position) start)
  17130. (eq org-adapt-indentation t))
  17131. (catch 'exit
  17132. (while t
  17133. (if (= (point-min) start) (throw 'exit 0)
  17134. (goto-char (1- start))
  17135. (let* ((previous (org-element-at-point))
  17136. (parent previous))
  17137. (while (and parent (<= (org-element-property :end parent) start))
  17138. (setq previous parent
  17139. parent (org-element-property :parent parent)))
  17140. (cond
  17141. ((not previous) (throw 'exit 0))
  17142. ((> (org-element-property :end previous) start)
  17143. (throw 'exit (org--get-expected-indentation previous t)))
  17144. ((memq (org-element-type previous)
  17145. '(footnote-definition inlinetask))
  17146. (setq start (org-element-property :begin previous)))
  17147. (t (goto-char (org-element-property :begin previous))
  17148. (throw 'exit
  17149. (if (bolp) (current-indentation)
  17150. ;; At first paragraph in an item or
  17151. ;; a footnote definition.
  17152. (org--get-expected-indentation
  17153. (org-element-property :parent previous) t))))))))))
  17154. ;; Otherwise, move to the first non-blank line above.
  17155. ((not (eq org-adapt-indentation 'headline-data))
  17156. (beginning-of-line)
  17157. (let ((pos (point)))
  17158. (skip-chars-backward " \r\t\n")
  17159. (cond
  17160. ;; Two blank lines end a footnote definition or a plain
  17161. ;; list. When we indent an empty line after them, the
  17162. ;; containing list or footnote definition is over, so it
  17163. ;; qualifies as a previous sibling. Therefore, we indent
  17164. ;; like its first line.
  17165. ((and (memq type '(footnote-definition plain-list))
  17166. (> (count-lines (point) pos) 2))
  17167. (goto-char start)
  17168. (current-indentation))
  17169. ;; Line above is the first one of a paragraph at the
  17170. ;; beginning of an item or a footnote definition. Indent
  17171. ;; like parent.
  17172. ((< (line-beginning-position) start)
  17173. (org--get-expected-indentation
  17174. (org-element-property :parent element) t))
  17175. ;; Line above is the beginning of an element, i.e., point
  17176. ;; was originally on the blank lines between element's start
  17177. ;; and contents.
  17178. ((= (line-beginning-position) post-affiliated)
  17179. (org--get-expected-indentation element t))
  17180. ;; POS is after contents in a greater element. Indent like
  17181. ;; the beginning of the element.
  17182. ((and (memq type org-element-greater-elements)
  17183. (let ((cend (org-element-property :contents-end element)))
  17184. (and cend (<= cend pos))))
  17185. ;; As a special case, if point is at the end of a footnote
  17186. ;; definition or an item, indent like the very last element
  17187. ;; within. If that last element is an item, indent like
  17188. ;; its contents.
  17189. (if (memq type '(footnote-definition item plain-list))
  17190. (let ((last (org-element-at-point)))
  17191. (goto-char pos)
  17192. (org--get-expected-indentation
  17193. last (eq (org-element-type last) 'item)))
  17194. (goto-char start)
  17195. (current-indentation)))
  17196. ;; In any other case, indent like the current line.
  17197. (t (current-indentation)))))
  17198. ;; Finally, no indentation is needed, fall back to 0.
  17199. (t (current-indentation))))))
  17200. (defun org--align-node-property ()
  17201. "Align node property at point.
  17202. Alignment is done according to `org-property-format', which see."
  17203. (when (save-excursion
  17204. (beginning-of-line)
  17205. (looking-at org-property-re))
  17206. (replace-match
  17207. (concat (match-string 4)
  17208. (org-trim
  17209. (format org-property-format (match-string 1) (match-string 3))))
  17210. t t)))
  17211. (defun org-indent-line ()
  17212. "Indent line depending on context.
  17213. Indentation is done according to the following rules:
  17214. - Footnote definitions, diary sexps, headlines and inline tasks
  17215. have to start at column 0.
  17216. - On the very first line of an element, consider, in order, the
  17217. next rules until one matches:
  17218. 1. If there's a sibling element before, ignoring footnote
  17219. definitions and inline tasks, indent like its first line.
  17220. 2. If element has a parent, indent like its contents. More
  17221. precisely, if parent is an item, indent after the bullet.
  17222. Else, indent like parent's first line.
  17223. 3. Otherwise, indent relatively to current level, if
  17224. `org-adapt-indentation' is non-nil, or to left margin.
  17225. - On a blank line at the end of an element, indent according to
  17226. the type of the element. More precisely
  17227. 1. If element is a plain list, an item, or a footnote
  17228. definition, indent like the very last element within.
  17229. 2. If element is a paragraph, indent like its last non blank
  17230. line.
  17231. 3. Otherwise, indent like its very first line.
  17232. - In the code part of a source block, use language major mode
  17233. to indent current line if `org-src-tab-acts-natively' is
  17234. non-nil. If it is nil, do nothing.
  17235. - Otherwise, indent like the first non-blank line above.
  17236. The function doesn't indent an item as it could break the whole
  17237. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17238. `\\[org-shiftmetaright]'.
  17239. Also align node properties according to `org-property-format'."
  17240. (interactive)
  17241. (if (org-at-heading-p) 'noindent
  17242. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17243. (type (org-element-type element)))
  17244. (cond ((and (memq type '(plain-list item))
  17245. (= (line-beginning-position)
  17246. (org-element-property :post-affiliated element)))
  17247. 'noindent)
  17248. ((and (eq type 'latex-environment)
  17249. (>= (point) (org-element-property :post-affiliated element))
  17250. (< (point) (org-with-wide-buffer
  17251. (goto-char (org-element-property :end element))
  17252. (skip-chars-backward " \r\t\n")
  17253. (line-beginning-position 2))))
  17254. 'noindent)
  17255. ((and (eq type 'src-block)
  17256. org-src-tab-acts-natively
  17257. (> (line-beginning-position)
  17258. (org-element-property :post-affiliated element))
  17259. (< (line-beginning-position)
  17260. (org-with-wide-buffer
  17261. (goto-char (org-element-property :end element))
  17262. (skip-chars-backward " \r\t\n")
  17263. (line-beginning-position))))
  17264. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17265. (t
  17266. (let ((column (org--get-expected-indentation element nil)))
  17267. ;; Preserve current column.
  17268. (if (<= (current-column) (current-indentation))
  17269. (indent-line-to column)
  17270. (save-excursion (indent-line-to column))))
  17271. ;; Align node property. Also preserve current column.
  17272. (when (eq type 'node-property)
  17273. (let ((column (current-column)))
  17274. (org--align-node-property)
  17275. (org-move-to-column column))))))))
  17276. (defun org-indent-region (start end)
  17277. "Indent each non-blank line in the region.
  17278. Called from a program, START and END specify the region to
  17279. indent. The function will not indent contents of example blocks,
  17280. verse blocks and export blocks as leading white spaces are
  17281. assumed to be significant there."
  17282. (interactive "r")
  17283. (save-excursion
  17284. (goto-char start)
  17285. (skip-chars-forward " \r\t\n")
  17286. (unless (eobp) (beginning-of-line))
  17287. (let ((indent-to
  17288. (lambda (ind pos)
  17289. ;; Set IND as indentation for all lines between point and
  17290. ;; POS. Blank lines are ignored. Leave point after POS
  17291. ;; once done.
  17292. (let ((limit (copy-marker pos)))
  17293. (while (< (point) limit)
  17294. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17295. (forward-line))
  17296. (set-marker limit nil))))
  17297. (end (copy-marker end)))
  17298. (while (< (point) end)
  17299. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17300. (let* ((element (org-element-at-point))
  17301. (type (org-element-type element))
  17302. (element-end (copy-marker (org-element-property :end element)))
  17303. (ind (org--get-expected-indentation element nil)))
  17304. (cond
  17305. ;; Element indented as a single block. Example blocks
  17306. ;; preserving indentation are a special case since the
  17307. ;; "contents" must not be indented whereas the block
  17308. ;; boundaries can.
  17309. ((or (memq type '(export-block latex-environment))
  17310. (and (eq type 'example-block)
  17311. (not
  17312. (or org-src-preserve-indentation
  17313. (org-element-property :preserve-indent element)))))
  17314. (let ((offset (- ind (current-indentation))))
  17315. (unless (zerop offset)
  17316. (indent-rigidly (org-element-property :begin element)
  17317. (org-element-property :end element)
  17318. offset)))
  17319. (goto-char element-end))
  17320. ;; Elements indented line wise. Be sure to exclude
  17321. ;; example blocks (preserving indentation) and source
  17322. ;; blocks from this category as they are treated
  17323. ;; specially later.
  17324. ((or (memq type '(paragraph table table-row))
  17325. (not (or (org-element-property :contents-begin element)
  17326. (memq type '(example-block src-block)))))
  17327. (when (eq type 'node-property)
  17328. (org--align-node-property)
  17329. (beginning-of-line))
  17330. (funcall indent-to ind (min element-end end)))
  17331. ;; Elements consisting of three parts: before the
  17332. ;; contents, the contents, and after the contents. The
  17333. ;; contents are treated specially, according to the
  17334. ;; element type, or not indented at all. Other parts are
  17335. ;; indented as a single block.
  17336. (t
  17337. (let* ((post (copy-marker
  17338. (org-element-property :post-affiliated element)))
  17339. (cbeg
  17340. (copy-marker
  17341. (cond
  17342. ((not (org-element-property :contents-begin element))
  17343. ;; Fake contents for source blocks.
  17344. (org-with-wide-buffer
  17345. (goto-char post)
  17346. (line-beginning-position 2)))
  17347. ((memq type '(footnote-definition item plain-list))
  17348. ;; Contents in these elements could start on
  17349. ;; the same line as the beginning of the
  17350. ;; element. Make sure we start indenting
  17351. ;; from the second line.
  17352. (org-with-wide-buffer
  17353. (goto-char post)
  17354. (end-of-line)
  17355. (skip-chars-forward " \r\t\n")
  17356. (if (eobp) (point) (line-beginning-position))))
  17357. (t (org-element-property :contents-begin element)))))
  17358. (cend (copy-marker
  17359. (or (org-element-property :contents-end element)
  17360. ;; Fake contents for source blocks.
  17361. (org-with-wide-buffer
  17362. (goto-char element-end)
  17363. (skip-chars-backward " \r\t\n")
  17364. (line-beginning-position)))
  17365. t)))
  17366. ;; Do not change items indentation individually as it
  17367. ;; might break the list as a whole. On the other
  17368. ;; hand, when at a plain list, indent it as a whole.
  17369. (cond ((eq type 'plain-list)
  17370. (let ((offset (- ind (current-indentation))))
  17371. (unless (zerop offset)
  17372. (indent-rigidly (org-element-property :begin element)
  17373. (org-element-property :end element)
  17374. offset))
  17375. (goto-char cbeg)))
  17376. ((eq type 'item) (goto-char cbeg))
  17377. (t (funcall indent-to ind (min cbeg end))))
  17378. (when (< (point) end)
  17379. (cl-case type
  17380. ((example-block verse-block))
  17381. (src-block
  17382. ;; In a source block, indent source code
  17383. ;; according to language major mode, but only if
  17384. ;; `org-src-tab-acts-natively' is non-nil.
  17385. (when (and (< (point) end) org-src-tab-acts-natively)
  17386. (ignore-errors
  17387. (org-babel-do-in-edit-buffer
  17388. (indent-region (point-min) (point-max))))))
  17389. (t (org-indent-region (point) (min cend end))))
  17390. (goto-char (min cend end))
  17391. (when (< (point) end)
  17392. (funcall indent-to ind (min element-end end))))
  17393. (set-marker post nil)
  17394. (set-marker cbeg nil)
  17395. (set-marker cend nil))))
  17396. (set-marker element-end nil))))
  17397. (set-marker end nil))))
  17398. (defun org-indent-drawer ()
  17399. "Indent the drawer at point."
  17400. (interactive)
  17401. (unless (save-excursion
  17402. (beginning-of-line)
  17403. (looking-at-p org-drawer-regexp))
  17404. (user-error "Not at a drawer"))
  17405. (let ((element (org-element-at-point)))
  17406. (unless (memq (org-element-type element) '(drawer property-drawer))
  17407. (user-error "Not at a drawer"))
  17408. (org-with-wide-buffer
  17409. (org-indent-region (org-element-property :begin element)
  17410. (org-element-property :end element))))
  17411. (message "Drawer at point indented"))
  17412. (defun org-indent-block ()
  17413. "Indent the block at point."
  17414. (interactive)
  17415. (unless (save-excursion
  17416. (beginning-of-line)
  17417. (let ((case-fold-search t))
  17418. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17419. (user-error "Not at a block"))
  17420. (let ((element (org-element-at-point)))
  17421. (unless (memq (org-element-type element)
  17422. '(comment-block center-block dynamic-block example-block
  17423. export-block quote-block special-block
  17424. src-block verse-block))
  17425. (user-error "Not at a block"))
  17426. (org-with-wide-buffer
  17427. (org-indent-region (org-element-property :begin element)
  17428. (org-element-property :end element))))
  17429. (message "Block at point indented"))
  17430. ;;; Filling
  17431. ;; We use our own fill-paragraph and auto-fill functions.
  17432. ;; `org-fill-paragraph' relies on adaptive filling and context
  17433. ;; checking. Appropriate `fill-prefix' is computed with
  17434. ;; `org-adaptive-fill-function'.
  17435. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17436. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17437. ;; `org-adaptive-fill-function' value. Internally,
  17438. ;; `org-comment-line-break-function' breaks the line.
  17439. ;; `org-setup-filling' installs filling and auto-filling related
  17440. ;; variables during `org-mode' initialization.
  17441. (defun org-setup-filling ()
  17442. (require 'org-element)
  17443. ;; Prevent auto-fill from inserting unwanted new items.
  17444. (when (boundp 'fill-nobreak-predicate)
  17445. (setq-local
  17446. fill-nobreak-predicate
  17447. (org-uniquify
  17448. (append fill-nobreak-predicate
  17449. '(org-fill-line-break-nobreak-p
  17450. org-fill-n-macro-as-item-nobreak-p
  17451. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17452. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17453. (setq-local paragraph-start paragraph-ending)
  17454. (setq-local paragraph-separate paragraph-ending))
  17455. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17456. (setq-local auto-fill-inhibit-regexp nil)
  17457. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17458. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17459. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17460. (defun org-fill-line-break-nobreak-p ()
  17461. "Non-nil when a new line at point would create an Org line break."
  17462. (save-excursion
  17463. (skip-chars-backward " \t")
  17464. (skip-chars-backward "\\\\")
  17465. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17466. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17467. "Non-nil when a new line at point would split a timestamp."
  17468. (and (org-at-timestamp-p 'lax)
  17469. (not (looking-at org-ts-regexp-both))))
  17470. (defun org-fill-n-macro-as-item-nobreak-p ()
  17471. "Non-nil when a new line at point would create a new list."
  17472. ;; During export, a "n" macro followed by a dot or a closing
  17473. ;; parenthesis can end up being parsed as a new list item.
  17474. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17475. (defun org-adaptive-fill-function ()
  17476. "Compute a fill prefix for the current line.
  17477. Return fill prefix, as a string, or nil if current line isn't
  17478. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17479. matches in paragraphs or comments, use it."
  17480. (org-with-wide-buffer
  17481. (unless (org-at-heading-p)
  17482. (let* ((p (line-beginning-position))
  17483. (element (save-excursion
  17484. (beginning-of-line)
  17485. (org-element-at-point)))
  17486. (type (org-element-type element))
  17487. (post-affiliated (org-element-property :post-affiliated element)))
  17488. (unless (< p post-affiliated)
  17489. (cl-case type
  17490. (comment
  17491. (save-excursion
  17492. (beginning-of-line)
  17493. (looking-at "[ \t]*")
  17494. (concat (match-string 0) "# ")))
  17495. (footnote-definition "")
  17496. ((item plain-list)
  17497. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17498. (paragraph
  17499. ;; Fill prefix is usually the same as the current line,
  17500. ;; unless the paragraph is at the beginning of an item.
  17501. (let ((parent (org-element-property :parent element)))
  17502. (save-excursion
  17503. (beginning-of-line)
  17504. (cond ((eq (org-element-type parent) 'item)
  17505. (make-string (org-list-item-body-column
  17506. (org-element-property :begin parent))
  17507. ?\s))
  17508. ((and adaptive-fill-regexp
  17509. ;; Locally disable
  17510. ;; `adaptive-fill-function' to let
  17511. ;; `fill-context-prefix' handle
  17512. ;; `adaptive-fill-regexp' variable.
  17513. (let (adaptive-fill-function)
  17514. (fill-context-prefix
  17515. post-affiliated
  17516. (org-element-property :end element)))))
  17517. ((looking-at "[ \t]+") (match-string 0))
  17518. (t "")))))
  17519. (comment-block
  17520. ;; Only fill contents if P is within block boundaries.
  17521. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17522. (forward-line)
  17523. (point)))
  17524. (cend (save-excursion
  17525. (goto-char (org-element-property :end element))
  17526. (skip-chars-backward " \r\t\n")
  17527. (line-beginning-position))))
  17528. (when (and (>= p cbeg) (< p cend))
  17529. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17530. (match-string 0)
  17531. ""))))))))))
  17532. (defun org-fill-element (&optional justify)
  17533. "Fill element at point, when applicable.
  17534. This function only applies to comment blocks, comments, example
  17535. blocks and paragraphs. Also, as a special case, re-align table
  17536. when point is at one.
  17537. If JUSTIFY is non-nil (interactively, with prefix argument),
  17538. justify as well. If `sentence-end-double-space' is non-nil, then
  17539. period followed by one space does not end a sentence, so don't
  17540. break a line there. The variable `fill-column' controls the
  17541. width for filling.
  17542. For convenience, when point is at a plain list, an item or
  17543. a footnote definition, try to fill the first paragraph within."
  17544. (with-syntax-table org-mode-transpose-word-syntax-table
  17545. ;; Move to end of line in order to get the first paragraph within
  17546. ;; a plain list or a footnote definition.
  17547. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17548. ;; First check if point is in a blank line at the beginning of
  17549. ;; the buffer. In that case, ignore filling.
  17550. (cl-case (org-element-type element)
  17551. ;; Use major mode filling function is source blocks.
  17552. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17553. ;; Align Org tables, leave table.el tables as-is.
  17554. (table-row (org-table-align) t)
  17555. (table
  17556. (when (eq (org-element-property :type element) 'org)
  17557. (save-excursion
  17558. (goto-char (org-element-property :post-affiliated element))
  17559. (org-table-align)))
  17560. t)
  17561. (paragraph
  17562. ;; Paragraphs may contain `line-break' type objects.
  17563. (let ((beg (max (point-min)
  17564. (org-element-property :contents-begin element)))
  17565. (end (min (point-max)
  17566. (org-element-property :contents-end element))))
  17567. ;; Do nothing if point is at an affiliated keyword.
  17568. (if (< (line-end-position) beg) t
  17569. ;; Fill paragraph, taking line breaks into account.
  17570. (save-excursion
  17571. (goto-char beg)
  17572. (let ((cuts (list beg)))
  17573. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17574. (when (eq 'line-break
  17575. (org-element-type
  17576. (save-excursion (backward-char)
  17577. (org-element-context))))
  17578. (push (point) cuts)))
  17579. (dolist (c (delq end cuts))
  17580. (fill-region-as-paragraph c end justify)
  17581. (setq end c))))
  17582. t)))
  17583. ;; Contents of `comment-block' type elements should be
  17584. ;; filled as plain text, but only if point is within block
  17585. ;; markers.
  17586. (comment-block
  17587. (let* ((case-fold-search t)
  17588. (beg (save-excursion
  17589. (goto-char (org-element-property :begin element))
  17590. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17591. (forward-line)
  17592. (point)))
  17593. (end (save-excursion
  17594. (goto-char (org-element-property :end element))
  17595. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17596. (line-beginning-position))))
  17597. (if (or (< (point) beg) (> (point) end)) t
  17598. (fill-region-as-paragraph
  17599. (save-excursion (end-of-line)
  17600. (re-search-backward "^[ \t]*$" beg 'move)
  17601. (line-beginning-position))
  17602. (save-excursion (beginning-of-line)
  17603. (re-search-forward "^[ \t]*$" end 'move)
  17604. (line-beginning-position))
  17605. justify))))
  17606. ;; Fill comments.
  17607. (comment
  17608. (let ((begin (org-element-property :post-affiliated element))
  17609. (end (org-element-property :end element)))
  17610. (when (and (>= (point) begin) (<= (point) end))
  17611. (let ((begin (save-excursion
  17612. (end-of-line)
  17613. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17614. (progn (forward-line) (point))
  17615. begin)))
  17616. (end (save-excursion
  17617. (end-of-line)
  17618. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17619. (1- (line-beginning-position))
  17620. (skip-chars-backward " \r\t\n")
  17621. (line-end-position)))))
  17622. ;; Do not fill comments when at a blank line.
  17623. (when (> end begin)
  17624. (let ((fill-prefix
  17625. (save-excursion
  17626. (beginning-of-line)
  17627. (looking-at "[ \t]*#")
  17628. (let ((comment-prefix (match-string 0)))
  17629. (goto-char (match-end 0))
  17630. (if (looking-at adaptive-fill-regexp)
  17631. (concat comment-prefix (match-string 0))
  17632. (concat comment-prefix " "))))))
  17633. (save-excursion
  17634. (fill-region-as-paragraph begin end justify))))))
  17635. t))
  17636. ;; Ignore every other element.
  17637. (otherwise t)))))
  17638. (defun org-fill-paragraph (&optional justify region)
  17639. "Fill element at point, when applicable.
  17640. This function only applies to comment blocks, comments, example
  17641. blocks and paragraphs. Also, as a special case, re-align table
  17642. when point is at one.
  17643. For convenience, when point is at a plain list, an item or
  17644. a footnote definition, try to fill the first paragraph within.
  17645. If JUSTIFY is non-nil (interactively, with prefix argument),
  17646. justify as well. If `sentence-end-double-space' is non-nil, then
  17647. period followed by one space does not end a sentence, so don't
  17648. break a line there. The variable `fill-column' controls the
  17649. width for filling.
  17650. The REGION argument is non-nil if called interactively; in that
  17651. case, if Transient Mark mode is enabled and the mark is active,
  17652. fill each of the elements in the active region, instead of just
  17653. filling the current element."
  17654. (interactive (progn
  17655. (barf-if-buffer-read-only)
  17656. (list (when current-prefix-arg 'full) t)))
  17657. (let ((hash (and (not (buffer-modified-p))
  17658. (org-buffer-hash))))
  17659. (cond
  17660. ((and region transient-mark-mode mark-active
  17661. (not (eq (region-beginning) (region-end))))
  17662. (let ((origin (point-marker))
  17663. (start (region-beginning)))
  17664. (unwind-protect
  17665. (progn
  17666. (goto-char (region-end))
  17667. (while (> (point) start)
  17668. (org-backward-paragraph)
  17669. (org-fill-element justify)))
  17670. (goto-char origin)
  17671. (set-marker origin nil))))
  17672. (t (org-fill-element justify)))
  17673. ;; If we didn't change anything in the buffer (and the buffer was
  17674. ;; previously unmodified), then flip the modification status back
  17675. ;; to "unchanged".
  17676. (when (and hash (equal hash (org-buffer-hash)))
  17677. (set-buffer-modified-p nil))))
  17678. (defun org-auto-fill-function ()
  17679. "Auto-fill function."
  17680. ;; Check if auto-filling is meaningful.
  17681. (let ((fc (current-fill-column)))
  17682. (when (and fc (> (current-column) fc))
  17683. (let* ((fill-prefix (org-adaptive-fill-function))
  17684. ;; Enforce empty fill prefix, if required. Otherwise, it
  17685. ;; will be computed again.
  17686. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17687. (when fill-prefix (do-auto-fill))))))
  17688. (defun org-comment-line-break-function (&optional soft)
  17689. "Break line at point and indent, continuing comment if within one.
  17690. The inserted newline is marked hard if variable
  17691. `use-hard-newlines' is true, unless optional argument SOFT is
  17692. non-nil."
  17693. (if soft (insert-and-inherit ?\n) (newline 1))
  17694. (save-excursion (forward-char -1) (delete-horizontal-space))
  17695. (delete-horizontal-space)
  17696. (indent-to-left-margin)
  17697. (insert-before-markers-and-inherit fill-prefix))
  17698. ;;; Fixed Width Areas
  17699. (defun org-toggle-fixed-width ()
  17700. "Toggle fixed-width markup.
  17701. Add or remove fixed-width markup on current line, whenever it
  17702. makes sense. Return an error otherwise.
  17703. If a region is active and if it contains only fixed-width areas
  17704. or blank lines, remove all fixed-width markup in it. If the
  17705. region contains anything else, convert all non-fixed-width lines
  17706. to fixed-width ones.
  17707. Blank lines at the end of the region are ignored unless the
  17708. region only contains such lines."
  17709. (interactive)
  17710. (if (not (org-region-active-p))
  17711. ;; No region:
  17712. ;;
  17713. ;; Remove fixed width marker only in a fixed-with element.
  17714. ;;
  17715. ;; Add fixed width maker in paragraphs, in blank lines after
  17716. ;; elements or at the beginning of a headline or an inlinetask,
  17717. ;; and before any one-line elements (e.g., a clock).
  17718. (progn
  17719. (beginning-of-line)
  17720. (let* ((element (org-element-at-point))
  17721. (type (org-element-type element)))
  17722. (cond
  17723. ((and (eq type 'fixed-width)
  17724. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17725. (replace-match
  17726. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17727. ((and (memq type '(babel-call clock comment diary-sexp headline
  17728. horizontal-rule keyword paragraph
  17729. planning))
  17730. (<= (org-element-property :post-affiliated element) (point)))
  17731. (skip-chars-forward " \t")
  17732. (insert ": "))
  17733. ((and (looking-at-p "[ \t]*$")
  17734. (or (eq type 'inlinetask)
  17735. (save-excursion
  17736. (skip-chars-forward " \r\t\n")
  17737. (<= (org-element-property :end element) (point)))))
  17738. (delete-region (point) (line-end-position))
  17739. (org-indent-line)
  17740. (insert ": "))
  17741. (t (user-error "Cannot insert a fixed-width line here")))))
  17742. ;; Region active.
  17743. (let* ((begin (save-excursion
  17744. (goto-char (region-beginning))
  17745. (line-beginning-position)))
  17746. (end (copy-marker
  17747. (save-excursion
  17748. (goto-char (region-end))
  17749. (unless (eolp) (beginning-of-line))
  17750. (if (save-excursion (re-search-backward "\\S-" begin t))
  17751. (progn (skip-chars-backward " \r\t\n") (point))
  17752. (point)))))
  17753. (all-fixed-width-p
  17754. (catch 'not-all-p
  17755. (save-excursion
  17756. (goto-char begin)
  17757. (skip-chars-forward " \r\t\n")
  17758. (when (eobp) (throw 'not-all-p nil))
  17759. (while (< (point) end)
  17760. (let ((element (org-element-at-point)))
  17761. (if (eq (org-element-type element) 'fixed-width)
  17762. (goto-char (org-element-property :end element))
  17763. (throw 'not-all-p nil))))
  17764. t))))
  17765. (if all-fixed-width-p
  17766. (save-excursion
  17767. (goto-char begin)
  17768. (while (< (point) end)
  17769. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17770. (replace-match
  17771. "" nil nil nil
  17772. (if (= (line-end-position) (match-end 0)) 0 1)))
  17773. (forward-line)))
  17774. (let ((min-ind (point-max)))
  17775. ;; Find minimum indentation across all lines.
  17776. (save-excursion
  17777. (goto-char begin)
  17778. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17779. (setq min-ind 0)
  17780. (catch 'zerop
  17781. (while (< (point) end)
  17782. (unless (looking-at-p "[ \t]*$")
  17783. (let ((ind (current-indentation)))
  17784. (setq min-ind (min min-ind ind))
  17785. (when (zerop ind) (throw 'zerop t))))
  17786. (forward-line)))))
  17787. ;; Loop over all lines and add fixed-width markup everywhere
  17788. ;; but in fixed-width lines.
  17789. (save-excursion
  17790. (goto-char begin)
  17791. (while (< (point) end)
  17792. (cond
  17793. ((org-at-heading-p)
  17794. (insert ": ")
  17795. (forward-line)
  17796. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17797. (insert ":")
  17798. (forward-line)))
  17799. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17800. (let* ((element (org-element-at-point))
  17801. (element-end (org-element-property :end element)))
  17802. (if (eq (org-element-type element) 'fixed-width)
  17803. (progn (goto-char element-end)
  17804. (skip-chars-backward " \r\t\n")
  17805. (forward-line))
  17806. (let ((limit (min end element-end)))
  17807. (while (< (point) limit)
  17808. (org-move-to-column min-ind t)
  17809. (insert ": ")
  17810. (forward-line))))))
  17811. (t
  17812. (org-move-to-column min-ind t)
  17813. (insert ": ")
  17814. (forward-line)))))))
  17815. (set-marker end nil))))
  17816. ;;; Blocks
  17817. (defun org-block-map (function &optional start end)
  17818. "Call FUNCTION at the head of all source blocks in the current buffer.
  17819. Optional arguments START and END can be used to limit the range."
  17820. (let ((start (or start (point-min)))
  17821. (end (or end (point-max))))
  17822. (save-excursion
  17823. (goto-char start)
  17824. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17825. (save-excursion
  17826. (save-match-data
  17827. (goto-char (match-beginning 0))
  17828. (funcall function)))))))
  17829. (defun org-next-block (arg &optional backward block-regexp)
  17830. "Jump to the next block.
  17831. With a prefix argument ARG, jump forward ARG many blocks.
  17832. When BACKWARD is non-nil, jump to the previous block.
  17833. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17834. Match data is set according to this regexp when the function
  17835. returns.
  17836. Return point at beginning of the opening line of found block.
  17837. Throw an error if no block is found."
  17838. (interactive "p")
  17839. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17840. (case-fold-search t)
  17841. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17842. (count (or arg 1))
  17843. (origin (point))
  17844. last-element)
  17845. (if backward (beginning-of-line) (end-of-line))
  17846. (while (and (> count 0) (funcall search-fn re nil t))
  17847. (let ((element (save-excursion
  17848. (goto-char (match-beginning 0))
  17849. (save-match-data (org-element-at-point)))))
  17850. (when (and (memq (org-element-type element)
  17851. '(center-block comment-block dynamic-block
  17852. example-block export-block quote-block
  17853. special-block src-block verse-block))
  17854. (<= (match-beginning 0)
  17855. (org-element-property :post-affiliated element)))
  17856. (setq last-element element)
  17857. (cl-decf count))))
  17858. (if (= count 0)
  17859. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17860. (save-match-data (org-show-context)))
  17861. (goto-char origin)
  17862. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17863. (defun org-previous-block (arg &optional block-regexp)
  17864. "Jump to the previous block.
  17865. With a prefix argument ARG, jump backward ARG many source blocks.
  17866. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17867. (interactive "p")
  17868. (org-next-block arg t block-regexp))
  17869. ;;; Comments
  17870. ;; Org comments syntax is quite complex. It requires the entire line
  17871. ;; to be just a comment. Also, even with the right syntax at the
  17872. ;; beginning of line, some elements (e.g., verse-block or
  17873. ;; example-block) don't accept comments. Usual Emacs comment commands
  17874. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17875. ;; Org still relies on `comment-dwim', but cannot trust
  17876. ;; `comment-only-p'. So, `comment-region-function' and
  17877. ;; `uncomment-region-function' both point
  17878. ;; to`org-comment-or-uncomment-region'. Eventually,
  17879. ;; `org-insert-comment' takes care of insertion of comments at the
  17880. ;; beginning of line.
  17881. ;; `org-setup-comments-handling' install comments related variables
  17882. ;; during `org-mode' initialization.
  17883. (defun org-setup-comments-handling ()
  17884. (interactive)
  17885. (setq-local comment-use-syntax nil)
  17886. (setq-local comment-start "# ")
  17887. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17888. (setq-local comment-insert-comment-function 'org-insert-comment)
  17889. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17890. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17891. (defun org-insert-comment ()
  17892. "Insert an empty comment above current line.
  17893. If the line is empty, insert comment at its beginning. When
  17894. point is within a source block, comment according to the related
  17895. major mode."
  17896. (if (let ((element (org-element-at-point)))
  17897. (and (eq (org-element-type element) 'src-block)
  17898. (< (save-excursion
  17899. (goto-char (org-element-property :post-affiliated element))
  17900. (line-end-position))
  17901. (point))
  17902. (> (save-excursion
  17903. (goto-char (org-element-property :end element))
  17904. (skip-chars-backward " \r\t\n")
  17905. (line-beginning-position))
  17906. (point))))
  17907. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17908. (beginning-of-line)
  17909. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17910. (open-line 1))
  17911. (org-indent-line)
  17912. (insert "# ")))
  17913. (defvar comment-empty-lines) ; From newcomment.el.
  17914. (defun org-comment-or-uncomment-region (beg end &rest _)
  17915. "Comment or uncomment each non-blank line in the region.
  17916. Uncomment each non-blank line between BEG and END if it only
  17917. contains commented lines. Otherwise, comment them. If region is
  17918. strictly within a source block, use appropriate comment syntax."
  17919. (if (let ((element (org-element-at-point)))
  17920. (and (eq (org-element-type element) 'src-block)
  17921. (< (save-excursion
  17922. (goto-char (org-element-property :post-affiliated element))
  17923. (line-end-position))
  17924. beg)
  17925. (>= (save-excursion
  17926. (goto-char (org-element-property :end element))
  17927. (skip-chars-backward " \r\t\n")
  17928. (line-beginning-position))
  17929. end)))
  17930. ;; Translate region boundaries for the Org buffer to the source
  17931. ;; buffer.
  17932. (let ((offset (- end beg)))
  17933. (save-excursion
  17934. (goto-char beg)
  17935. (org-babel-do-in-edit-buffer
  17936. (comment-or-uncomment-region (point) (+ offset (point))))))
  17937. (save-restriction
  17938. ;; Restrict region
  17939. (narrow-to-region (save-excursion (goto-char beg)
  17940. (skip-chars-forward " \r\t\n" end)
  17941. (line-beginning-position))
  17942. (save-excursion (goto-char end)
  17943. (skip-chars-backward " \r\t\n" beg)
  17944. (line-end-position)))
  17945. (let ((uncommentp
  17946. ;; UNCOMMENTP is non-nil when every non blank line between
  17947. ;; BEG and END is a comment.
  17948. (save-excursion
  17949. (goto-char (point-min))
  17950. (while (and (not (eobp))
  17951. (let ((element (org-element-at-point)))
  17952. (and (eq (org-element-type element) 'comment)
  17953. (goto-char (min (point-max)
  17954. (org-element-property
  17955. :end element)))))))
  17956. (eobp))))
  17957. (if uncommentp
  17958. ;; Only blank lines and comments in region: uncomment it.
  17959. (save-excursion
  17960. (goto-char (point-min))
  17961. (while (not (eobp))
  17962. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17963. (replace-match "" nil nil nil 1))
  17964. (forward-line)))
  17965. ;; Comment each line in region.
  17966. (let ((min-indent (point-max)))
  17967. ;; First find the minimum indentation across all lines.
  17968. (save-excursion
  17969. (goto-char (point-min))
  17970. (while (and (not (eobp)) (not (zerop min-indent)))
  17971. (unless (looking-at "[ \t]*$")
  17972. (setq min-indent (min min-indent (current-indentation))))
  17973. (forward-line)))
  17974. ;; Then loop over all lines.
  17975. (save-excursion
  17976. (goto-char (point-min))
  17977. (while (not (eobp))
  17978. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17979. ;; Don't get fooled by invisible text (e.g. link path)
  17980. ;; when moving to column MIN-INDENT.
  17981. (let ((buffer-invisibility-spec nil))
  17982. (org-move-to-column min-indent t))
  17983. (insert comment-start))
  17984. (forward-line)))))))))
  17985. (defun org-comment-dwim (_arg)
  17986. "Call the comment command you mean.
  17987. Call `org-toggle-comment' if on a heading, otherwise call
  17988. `comment-dwim', within a source edit buffer if needed."
  17989. (interactive "*P")
  17990. (cond ((org-at-heading-p)
  17991. (call-interactively #'org-toggle-comment))
  17992. ((org-in-src-block-p)
  17993. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17994. (t (call-interactively #'comment-dwim))))
  17995. ;;; Timestamps API
  17996. ;; This section contains tools to operate on, or create, timestamp
  17997. ;; objects, as returned by, e.g. `org-element-context'.
  17998. (defun org-timestamp-from-string (s)
  17999. "Convert Org timestamp S, as a string, into a timestamp object.
  18000. Return nil if S is not a valid timestamp string."
  18001. (when (org-string-nw-p s)
  18002. (with-temp-buffer
  18003. (save-excursion (insert s))
  18004. (org-element-timestamp-parser))))
  18005. (defun org-timestamp-from-time (time &optional with-time inactive)
  18006. "Convert a time value into a timestamp object.
  18007. TIME is an Emacs internal time representation, as returned, e.g.,
  18008. by `current-time'.
  18009. When optional argument WITH-TIME is non-nil, return a timestamp
  18010. object with a time part, i.e., with hours and minutes.
  18011. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18012. return an active timestamp."
  18013. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18014. (org-element-create 'timestamp
  18015. (list :type (if inactive 'inactive 'active)
  18016. :year-start year
  18017. :month-start month
  18018. :day-start day
  18019. :hour-start (and with-time hour)
  18020. :minute-start (and with-time minute)))))
  18021. (defun org-timestamp-to-time (timestamp &optional end)
  18022. "Convert TIMESTAMP object into an Emacs internal time value.
  18023. Use end of date range or time range when END is non-nil.
  18024. Otherwise, use its start."
  18025. (apply #'encode-time 0
  18026. (mapcar
  18027. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18028. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18029. '(:minute-start :hour-start :day-start :month-start
  18030. :year-start)))))
  18031. (defun org-timestamp-has-time-p (timestamp)
  18032. "Non-nil when TIMESTAMP has a time specified."
  18033. (org-element-property :hour-start timestamp))
  18034. (defun org-timestamp-format (timestamp format &optional end utc)
  18035. "Format a TIMESTAMP object into a string.
  18036. FORMAT is a format specifier to be passed to
  18037. `format-time-string'.
  18038. When optional argument END is non-nil, use end of date-range or
  18039. time-range, if possible.
  18040. When optional argument UTC is non-nil, time is be expressed as
  18041. Universal Time."
  18042. (format-time-string format (org-timestamp-to-time timestamp end)
  18043. (and utc t)))
  18044. (defun org-timestamp-split-range (timestamp &optional end)
  18045. "Extract a TIMESTAMP object from a date or time range.
  18046. END, when non-nil, means extract the end of the range.
  18047. Otherwise, extract its start.
  18048. Return a new timestamp object."
  18049. (let ((type (org-element-property :type timestamp)))
  18050. (if (memq type '(active inactive diary)) timestamp
  18051. (let ((split-ts (org-element-copy timestamp)))
  18052. ;; Set new type.
  18053. (org-element-put-property
  18054. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18055. ;; Copy start properties over end properties if END is
  18056. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18057. (let ((p-alist '((:minute-start . :minute-end)
  18058. (:hour-start . :hour-end)
  18059. (:day-start . :day-end)
  18060. (:month-start . :month-end)
  18061. (:year-start . :year-end))))
  18062. (dolist (p-cell p-alist)
  18063. (org-element-put-property
  18064. split-ts
  18065. (funcall (if end #'car #'cdr) p-cell)
  18066. (org-element-property
  18067. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18068. ;; Eventually refresh `:raw-value'.
  18069. (org-element-put-property split-ts :raw-value nil)
  18070. (org-element-put-property
  18071. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18072. (defun org-timestamp-translate (timestamp &optional boundary)
  18073. "Translate TIMESTAMP object to custom format.
  18074. Format string is defined in `org-time-stamp-custom-formats',
  18075. which see.
  18076. When optional argument BOUNDARY is non-nil, it is either the
  18077. symbol `start' or `end'. In this case, only translate the
  18078. starting or ending part of TIMESTAMP if it is a date or time
  18079. range. Otherwise, translate both parts.
  18080. Return timestamp as-is if `org-display-custom-times' is nil or if
  18081. it has a `diary' type."
  18082. (let ((type (org-element-property :type timestamp)))
  18083. (if (or (not org-display-custom-times) (eq type 'diary))
  18084. (org-element-interpret-data timestamp)
  18085. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18086. org-time-stamp-custom-formats)))
  18087. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18088. (concat (org-timestamp-format timestamp fmt)
  18089. "--"
  18090. (org-timestamp-format timestamp fmt t))
  18091. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18092. ;;; Other stuff
  18093. (defvar reftex-docstruct-symbol)
  18094. (defvar org--rds)
  18095. (defun org-reftex-citation ()
  18096. "Use reftex-citation to insert a citation into the buffer.
  18097. This looks for a line like
  18098. #+BIBLIOGRAPHY: foo plain option:-d
  18099. and derives from it that foo.bib is the bibliography file relevant
  18100. for this document. It then installs the necessary environment for RefTeX
  18101. to work in this buffer and calls `reftex-citation' to insert a citation
  18102. into the buffer.
  18103. Export of such citations to both LaTeX and HTML is handled by the contributed
  18104. package ox-bibtex by Taru Karttunen."
  18105. (interactive)
  18106. (let ((reftex-docstruct-symbol 'org--rds)
  18107. org--rds bib)
  18108. (org-with-wide-buffer
  18109. (let ((case-fold-search t)
  18110. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18111. (if (not (save-excursion
  18112. (or (re-search-forward re nil t)
  18113. (re-search-backward re nil t))))
  18114. (user-error "No bibliography defined in file")
  18115. (setq bib (concat (match-string 1) ".bib")
  18116. org--rds (list (list 'bib bib))))))
  18117. (call-interactively 'reftex-citation)))
  18118. ;;;; Functions extending outline functionality
  18119. (defun org-beginning-of-line (&optional n)
  18120. "Go to the beginning of the current visible line.
  18121. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18122. symbol `reversed', on the first attempt move to where the
  18123. headline text starts, and only move to beginning of line when the
  18124. cursor is already before the start of the text of the headline.
  18125. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18126. start of the text on the second attempt.
  18127. With argument N not nil or 1, move forward N - 1 lines first."
  18128. (interactive "^p")
  18129. (let ((origin (point))
  18130. (special (pcase org-special-ctrl-a/e
  18131. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18132. deactivate-mark)
  18133. ;; First move to a visible line.
  18134. (if (bound-and-true-p visual-line-mode)
  18135. (beginning-of-visual-line n)
  18136. (move-beginning-of-line n)
  18137. ;; `move-beginning-of-line' may leave point after invisible
  18138. ;; characters if line starts with such of these (e.g., with
  18139. ;; a link at column 0). Really move to the beginning of the
  18140. ;; current visible line.
  18141. (beginning-of-line))
  18142. (cond
  18143. ;; No special behavior. Point is already at the beginning of
  18144. ;; a line, logical or visual.
  18145. ((not special))
  18146. ;; `beginning-of-visual-line' left point before logical beginning
  18147. ;; of line: point is at the beginning of a visual line. Bail
  18148. ;; out.
  18149. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18150. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18151. ;; At a headline, special position is before the title, but
  18152. ;; after any TODO keyword or priority cookie.
  18153. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18154. (line-end-position)))
  18155. (bol (point)))
  18156. (if (eq special 'reversed)
  18157. (when (and (= origin bol) (eq last-command this-command))
  18158. (goto-char refpos))
  18159. (when (or (> origin refpos) (= origin bol))
  18160. (goto-char refpos)))))
  18161. ((and (looking-at org-list-full-item-re)
  18162. (memq (org-element-type (save-match-data (org-element-at-point)))
  18163. '(item plain-list)))
  18164. ;; Set special position at first white space character after
  18165. ;; bullet, and check-box, if any.
  18166. (let ((after-bullet
  18167. (let ((box (match-end 3)))
  18168. (cond ((not box) (match-end 1))
  18169. ((eq (char-after box) ?\s) (1+ box))
  18170. (t box)))))
  18171. (if (eq special 'reversed)
  18172. (when (and (= (point) origin) (eq last-command this-command))
  18173. (goto-char after-bullet))
  18174. (when (or (> origin after-bullet) (= (point) origin))
  18175. (goto-char after-bullet)))))
  18176. ;; No special context. Point is already at beginning of line.
  18177. (t nil))))
  18178. (defun org-end-of-line (&optional n)
  18179. "Go to the end of the line, but before ellipsis, if any.
  18180. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18181. symbol `reversed', ignore tags on the first attempt, and only
  18182. move to after the tags when the cursor is already beyond the end
  18183. of the headline.
  18184. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18185. on the second attempt.
  18186. With argument N not nil or 1, move forward N - 1 lines first."
  18187. (interactive "^p")
  18188. (let ((origin (point))
  18189. (special (pcase org-special-ctrl-a/e
  18190. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18191. deactivate-mark)
  18192. ;; First move to a visible line.
  18193. (if (bound-and-true-p visual-line-mode)
  18194. (beginning-of-visual-line n)
  18195. (move-beginning-of-line n))
  18196. (cond
  18197. ;; At a headline, with tags.
  18198. ((and special
  18199. (save-excursion
  18200. (beginning-of-line)
  18201. (let ((case-fold-search nil))
  18202. (looking-at org-complex-heading-regexp)))
  18203. (match-end 5))
  18204. (let ((tags (save-excursion
  18205. (goto-char (match-beginning 5))
  18206. (skip-chars-backward " \t")
  18207. (point)))
  18208. (visual-end (and (bound-and-true-p visual-line-mode)
  18209. (save-excursion
  18210. (end-of-visual-line)
  18211. (point)))))
  18212. ;; If `end-of-visual-line' brings us before end of line or
  18213. ;; even tags, i.e., the headline spans over multiple visual
  18214. ;; lines, move there.
  18215. (cond ((and visual-end
  18216. (< visual-end tags)
  18217. (<= origin visual-end))
  18218. (goto-char visual-end))
  18219. ((eq special 'reversed)
  18220. (if (and (= origin (line-end-position))
  18221. (eq this-command last-command))
  18222. (goto-char tags)
  18223. (end-of-line)))
  18224. (t
  18225. (if (or (< origin tags) (= origin (line-end-position)))
  18226. (goto-char tags)
  18227. (end-of-line))))))
  18228. ((bound-and-true-p visual-line-mode)
  18229. (let ((bol (line-beginning-position)))
  18230. (end-of-visual-line)
  18231. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18232. ;; end of a line, backtrack and use `end-of-line' instead.
  18233. (when (/= bol (line-beginning-position))
  18234. (goto-char bol)
  18235. (end-of-line))))
  18236. (t (end-of-line)))))
  18237. (defun org-backward-sentence (&optional _arg)
  18238. "Go to beginning of sentence, or beginning of table field.
  18239. This will call `backward-sentence' or `org-table-beginning-of-field',
  18240. depending on context."
  18241. (interactive)
  18242. (let* ((element (org-element-at-point))
  18243. (contents-begin (org-element-property :contents-begin element))
  18244. (table (org-element-lineage element '(table) t)))
  18245. (if (and table
  18246. (> (point) contents-begin)
  18247. (<= (point) (org-element-property :contents-end table)))
  18248. (call-interactively #'org-table-beginning-of-field)
  18249. (save-restriction
  18250. (when (and contents-begin
  18251. (< (point-min) contents-begin)
  18252. (> (point) contents-begin))
  18253. (narrow-to-region contents-begin
  18254. (org-element-property :contents-end element)))
  18255. (call-interactively #'backward-sentence)))))
  18256. (defun org-forward-sentence (&optional _arg)
  18257. "Go to end of sentence, or end of table field.
  18258. This will call `forward-sentence' or `org-table-end-of-field',
  18259. depending on context."
  18260. (interactive)
  18261. (if (and (org-at-heading-p)
  18262. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18263. (save-restriction
  18264. (narrow-to-region (line-beginning-position) (line-end-position))
  18265. (call-interactively #'forward-sentence))
  18266. (let* ((element (org-element-at-point))
  18267. (contents-end (org-element-property :contents-end element))
  18268. (table (org-element-lineage element '(table) t)))
  18269. (if (and table
  18270. (>= (point) (org-element-property :contents-begin table))
  18271. (< (point) contents-end))
  18272. (call-interactively #'org-table-end-of-field)
  18273. (save-restriction
  18274. (when (and contents-end
  18275. (> (point-max) contents-end)
  18276. ;; Skip blank lines between elements.
  18277. (< (org-element-property :end element)
  18278. (save-excursion (goto-char contents-end)
  18279. (skip-chars-forward " \r\t\n"))))
  18280. (narrow-to-region (org-element-property :contents-begin element)
  18281. contents-end))
  18282. ;; End of heading is considered as the end of a sentence.
  18283. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18284. (call-interactively #'forward-sentence)))))))
  18285. (defun org-kill-line (&optional _arg)
  18286. "Kill line, to tags or end of line."
  18287. (interactive)
  18288. (cond
  18289. ((or (not org-special-ctrl-k)
  18290. (bolp)
  18291. (not (org-at-heading-p)))
  18292. (when (and (get-char-property (line-end-position) 'invisible)
  18293. org-ctrl-k-protect-subtree
  18294. (or (eq org-ctrl-k-protect-subtree 'error)
  18295. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18296. (user-error
  18297. (substitute-command-keys
  18298. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18299. (call-interactively
  18300. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18301. ((org-match-line org-tag-line-re)
  18302. (let ((end (save-excursion
  18303. (goto-char (match-beginning 1))
  18304. (skip-chars-backward " \t")
  18305. (point))))
  18306. (if (<= end (point)) ;on tags part
  18307. (kill-region (point) (line-end-position))
  18308. (kill-region (point) end)))
  18309. ;; Only align tags when we are still on a heading:
  18310. (if (org-at-heading-p) (org-align-tags)))
  18311. (t (kill-region (point) (line-end-position)))))
  18312. (defun org-yank (&optional arg)
  18313. "Yank. If the kill is a subtree, treat it specially.
  18314. This command will look at the current kill and check if is a single
  18315. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18316. cursor is at the beginning of a line or after the stars of a currently
  18317. empty headline, then the yank is handled specially. How exactly depends
  18318. on the value of the following variables.
  18319. `org-yank-folded-subtrees'
  18320. By default, this variable is non-nil, which results in
  18321. subtree(s) being folded after insertion, except if doing so
  18322. would swallow text after the yanked text.
  18323. `org-yank-adjusted-subtrees'
  18324. When non-nil (the default value is nil), the subtree will be
  18325. promoted or demoted in order to fit into the local outline tree
  18326. structure, which means that the level will be adjusted so that it
  18327. becomes the smaller one of the two *visible* surrounding headings.
  18328. Any prefix to this command will cause `yank' to be called directly with
  18329. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18330. will just
  18331. plainly yank the text as it is.
  18332. \[1] The test checks if the first non-white line is a heading
  18333. and if there are no other headings with fewer stars."
  18334. (interactive "P")
  18335. (org-yank-generic 'yank arg))
  18336. (defun org-yank-generic (command arg)
  18337. "Perform some yank-like command.
  18338. This function implements the behavior described in the `org-yank'
  18339. documentation. However, it has been generalized to work for any
  18340. interactive command with similar behavior."
  18341. ;; pretend to be command COMMAND
  18342. (setq this-command command)
  18343. (if arg
  18344. (call-interactively command)
  18345. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18346. (and (org-kill-is-subtree-p)
  18347. (or (bolp)
  18348. (and (looking-at "[ \t]*$")
  18349. (string-match
  18350. "\\`\\*+\\'"
  18351. (buffer-substring (point-at-bol) (point)))))))
  18352. swallowp)
  18353. (cond
  18354. ((and subtreep org-yank-folded-subtrees)
  18355. (let ((beg (point))
  18356. end)
  18357. (if (and subtreep org-yank-adjusted-subtrees)
  18358. (org-paste-subtree nil nil 'for-yank)
  18359. (call-interactively command))
  18360. (setq end (point))
  18361. (goto-char beg)
  18362. (when (and (bolp) subtreep
  18363. (not (setq swallowp
  18364. (org-yank-folding-would-swallow-text beg end))))
  18365. (org-with-limited-levels
  18366. (or (looking-at org-outline-regexp)
  18367. (re-search-forward org-outline-regexp-bol end t))
  18368. (while (and (< (point) end) (looking-at org-outline-regexp))
  18369. (org-flag-subtree t)
  18370. (org-cycle-show-empty-lines 'folded)
  18371. (condition-case nil
  18372. (outline-forward-same-level 1)
  18373. (error (goto-char end))))))
  18374. (when swallowp
  18375. (message
  18376. "Inserted text not folded because that would swallow text"))
  18377. (goto-char end)
  18378. (skip-chars-forward " \t\n\r")
  18379. (beginning-of-line 1)
  18380. (push-mark beg 'nomsg)))
  18381. ((and subtreep org-yank-adjusted-subtrees)
  18382. (let ((beg (point-at-bol)))
  18383. (org-paste-subtree nil nil 'for-yank)
  18384. (push-mark beg 'nomsg)))
  18385. (t
  18386. (call-interactively command))))))
  18387. (defun org-yank-folding-would-swallow-text (beg end)
  18388. "Would hide-subtree at BEG swallow any text after END?"
  18389. (let (level)
  18390. (org-with-limited-levels
  18391. (save-excursion
  18392. (goto-char beg)
  18393. (when (or (looking-at org-outline-regexp)
  18394. (re-search-forward org-outline-regexp-bol end t))
  18395. (setq level (org-outline-level)))
  18396. (goto-char end)
  18397. (skip-chars-forward " \t\r\n\v\f")
  18398. (not (or (eobp)
  18399. (and (bolp) (looking-at-p org-outline-regexp)
  18400. (<= (org-outline-level) level))))))))
  18401. (defun org-back-to-heading (&optional invisible-ok)
  18402. "Call `outline-back-to-heading', but provide a better error message."
  18403. (condition-case nil
  18404. (outline-back-to-heading invisible-ok)
  18405. (error
  18406. (user-error "Before first headline at position %d in buffer %s"
  18407. (point) (current-buffer)))))
  18408. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18409. "Go back to heading or first point in buffer.
  18410. If point is before first heading go to first point in buffer
  18411. instead of back to heading."
  18412. (condition-case nil
  18413. (outline-back-to-heading invisible-ok)
  18414. (error
  18415. (goto-char (point-min)))))
  18416. (defun org-before-first-heading-p ()
  18417. "Before first heading?"
  18418. (org-with-limited-levels
  18419. (save-excursion
  18420. (end-of-line)
  18421. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18422. (defun org-at-heading-p (&optional _)
  18423. "Non-nil when on a headline."
  18424. (outline-on-heading-p t))
  18425. (defun org-in-commented-heading-p (&optional no-inheritance)
  18426. "Non-nil if point is under a commented heading.
  18427. This function also checks ancestors of the current headline,
  18428. unless optional argument NO-INHERITANCE is non-nil."
  18429. (cond
  18430. ((org-before-first-heading-p) nil)
  18431. ((let ((headline (nth 4 (org-heading-components))))
  18432. (and headline
  18433. (let ((case-fold-search nil))
  18434. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18435. headline)))))
  18436. (no-inheritance nil)
  18437. (t
  18438. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18439. (defun org-at-comment-p nil
  18440. "Return t if cursor is in a commented line."
  18441. (save-excursion
  18442. (save-match-data
  18443. (beginning-of-line)
  18444. (looking-at org-comment-regexp))))
  18445. (defun org-at-keyword-p nil
  18446. "Return t if cursor is at a keyword-line."
  18447. (save-excursion
  18448. (move-beginning-of-line 1)
  18449. (looking-at org-keyword-regexp)))
  18450. (defun org-at-drawer-p nil
  18451. "Return t if cursor is at a drawer keyword."
  18452. (save-excursion
  18453. (move-beginning-of-line 1)
  18454. (looking-at org-drawer-regexp)))
  18455. (defun org-at-block-p nil
  18456. "Return t if cursor is at a block keyword."
  18457. (save-excursion
  18458. (move-beginning-of-line 1)
  18459. (looking-at org-block-regexp)))
  18460. (defun org-point-at-end-of-empty-headline ()
  18461. "If point is at the end of an empty headline, return t, else nil.
  18462. If the heading only contains a TODO keyword, it is still still considered
  18463. empty."
  18464. (let ((case-fold-search nil))
  18465. (and (looking-at "[ \t]*$")
  18466. org-todo-line-regexp
  18467. (save-excursion
  18468. (beginning-of-line)
  18469. (looking-at org-todo-line-regexp)
  18470. (string= (match-string 3) "")))))
  18471. (defun org-at-heading-or-item-p ()
  18472. (or (org-at-heading-p) (org-at-item-p)))
  18473. (defun org-up-heading-all (arg)
  18474. "Move to the heading line of which the present line is a subheading.
  18475. This function considers both visible and invisible heading lines.
  18476. With argument, move up ARG levels."
  18477. (outline-up-heading arg t))
  18478. (defun org-up-heading-safe ()
  18479. "Move to the heading line of which the present line is a subheading.
  18480. This version will not throw an error. It will return the level of the
  18481. headline found, or nil if no higher level is found.
  18482. Also, this function will be a lot faster than `outline-up-heading',
  18483. because it relies on stars being the outline starters. This can really
  18484. make a significant difference in outlines with very many siblings."
  18485. (when (ignore-errors (org-back-to-heading t))
  18486. (let ((level-up (1- (funcall outline-level))))
  18487. (and (> level-up 0)
  18488. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18489. (funcall outline-level)))))
  18490. (defun org-up-heading-or-point-min ()
  18491. "Move to the heading line of which the present is a subheading, or point-min.
  18492. This version is needed to make point-min behave like a virtual
  18493. heading of level 0 for property-inheritance. It will return the
  18494. level of the headline found (down to 0) or nil if already at a
  18495. point before the first headline or at point-min."
  18496. (when (ignore-errors (org-back-to-heading t))
  18497. (if (< 1 (funcall outline-level))
  18498. (org-up-heading-safe)
  18499. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18500. (defun org-first-sibling-p ()
  18501. "Is this heading the first child of its parents?"
  18502. (interactive)
  18503. (let ((re org-outline-regexp-bol)
  18504. level l)
  18505. (unless (org-at-heading-p t)
  18506. (user-error "Not at a heading"))
  18507. (setq level (funcall outline-level))
  18508. (save-excursion
  18509. (if (not (re-search-backward re nil t))
  18510. t
  18511. (setq l (funcall outline-level))
  18512. (< l level)))))
  18513. (defun org-goto-sibling (&optional previous)
  18514. "Goto the next sibling, even if it is invisible.
  18515. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18516. when a sibling was found. When none is found, return nil and don't
  18517. move point."
  18518. (let ((fun (if previous 're-search-backward 're-search-forward))
  18519. (pos (point))
  18520. (re org-outline-regexp-bol)
  18521. level l)
  18522. (when (ignore-errors (org-back-to-heading t))
  18523. (setq level (funcall outline-level))
  18524. (catch 'exit
  18525. (or previous (forward-char 1))
  18526. (while (funcall fun re nil t)
  18527. (setq l (funcall outline-level))
  18528. (when (< l level) (goto-char pos) (throw 'exit nil))
  18529. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18530. (goto-char pos)
  18531. nil))))
  18532. (defun org-show-siblings ()
  18533. "Show all siblings of the current headline."
  18534. (save-excursion
  18535. (while (org-goto-sibling) (org-flag-heading nil)))
  18536. (save-excursion
  18537. (while (org-goto-sibling 'previous)
  18538. (org-flag-heading nil))))
  18539. (defun org-goto-first-child ()
  18540. "Goto the first child, even if it is invisible.
  18541. Return t when a child was found. Otherwise don't move point and
  18542. return nil."
  18543. (let (level (pos (point)) (re org-outline-regexp-bol))
  18544. (when (ignore-errors (org-back-to-heading t))
  18545. (setq level (outline-level))
  18546. (forward-char 1)
  18547. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18548. (progn (goto-char (match-beginning 0)) t)
  18549. (goto-char pos) nil))))
  18550. (defun org-show-hidden-entry ()
  18551. "Show an entry where even the heading is hidden."
  18552. (save-excursion
  18553. (org-show-entry)))
  18554. (defun org-flag-heading (flag &optional entry)
  18555. "Flag the current heading. FLAG non-nil means make invisible.
  18556. When ENTRY is non-nil, show the entire entry."
  18557. (save-excursion
  18558. (org-back-to-heading t)
  18559. ;; Check if we should show the entire entry
  18560. (if (not entry)
  18561. (org-flag-region
  18562. (line-end-position 0) (line-end-position) flag 'outline)
  18563. (org-show-entry)
  18564. (save-excursion
  18565. (and (outline-next-heading)
  18566. (org-flag-heading nil))))))
  18567. (defun org-get-next-sibling ()
  18568. "Move to next heading of the same level, and return point.
  18569. If there is no such heading, return nil.
  18570. This is like outline-next-sibling, but invisible headings are ok."
  18571. (let ((level (funcall outline-level)))
  18572. (outline-next-heading)
  18573. (while (and (not (eobp)) (> (funcall outline-level) level))
  18574. (outline-next-heading))
  18575. (unless (or (eobp) (< (funcall outline-level) level))
  18576. (point))))
  18577. (defun org-get-last-sibling ()
  18578. "Move to previous heading of the same level, and return point.
  18579. If there is no such heading, return nil."
  18580. (let ((opoint (point))
  18581. (level (funcall outline-level)))
  18582. (outline-previous-heading)
  18583. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18584. (while (and (> (funcall outline-level) level)
  18585. (not (bobp)))
  18586. (outline-previous-heading))
  18587. (unless (< (funcall outline-level) level)
  18588. (point)))))
  18589. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18590. "Goto to the end of a subtree."
  18591. ;; This contains an exact copy of the original function, but it uses
  18592. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18593. ;; trees and before first headline. And is uses an invisible-ok argument.
  18594. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18595. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18596. ;; with many children and grandchildren etc, this can be much faster
  18597. ;; than the outline version.
  18598. (org-back-to-heading-or-point-min invisible-ok)
  18599. (let ((first t)
  18600. (level (funcall outline-level)))
  18601. (cond ((= level 0)
  18602. (goto-char (point-max)))
  18603. ((and (derived-mode-p 'org-mode) (< level 1000))
  18604. ;; A true heading (not a plain list item), in Org
  18605. ;; This means we can easily find the end by looking
  18606. ;; only for the right number of stars. Using a regexp to do
  18607. ;; this is so much faster than using a Lisp loop.
  18608. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18609. (forward-char 1)
  18610. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18611. (t
  18612. ;; something else, do it the slow way
  18613. (while (and (not (eobp))
  18614. (or first (> (funcall outline-level) level)))
  18615. (setq first nil)
  18616. (outline-next-heading))))
  18617. (unless to-heading
  18618. (when (memq (preceding-char) '(?\n ?\^M))
  18619. ;; Go to end of line before heading
  18620. (forward-char -1)
  18621. (when (memq (preceding-char) '(?\n ?\^M))
  18622. ;; leave blank line before heading
  18623. (forward-char -1)))))
  18624. (point))
  18625. (defun org-end-of-meta-data (&optional full)
  18626. "Skip planning line and properties drawer in current entry.
  18627. When optional argument FULL is non-nil, also skip empty lines,
  18628. clocking lines and regular drawers at the beginning of the
  18629. entry."
  18630. (org-back-to-heading t)
  18631. (forward-line)
  18632. (when (looking-at-p org-planning-line-re) (forward-line))
  18633. (when (looking-at org-property-drawer-re)
  18634. (goto-char (match-end 0))
  18635. (forward-line))
  18636. (when (and full (not (org-at-heading-p)))
  18637. (catch 'exit
  18638. (let ((end (save-excursion (outline-next-heading) (point)))
  18639. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18640. (while (not (eobp))
  18641. (cond ((looking-at-p org-drawer-regexp)
  18642. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18643. (forward-line)
  18644. (throw 'exit t)))
  18645. ((looking-at-p re) (forward-line))
  18646. (t (throw 'exit t))))))))
  18647. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18648. "Move forward to the ARG'th subheading at same level as this one.
  18649. Stop at the first and last subheadings of a superior heading.
  18650. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18651. non-nil it will also look at invisible ones."
  18652. (interactive "p")
  18653. (let ((backward? (and arg (< arg 0))))
  18654. (if (org-before-first-heading-p)
  18655. (if backward? (goto-char (point-min)) (outline-next-heading))
  18656. (org-back-to-heading invisible-ok)
  18657. (unless backward? (end-of-line)) ;do not match current headline
  18658. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18659. (f (if backward? #'re-search-backward #'re-search-forward))
  18660. (count (if arg (abs arg) 1))
  18661. (result (point)))
  18662. (while (and (> count 0)
  18663. (funcall f org-outline-regexp-bol nil 'move))
  18664. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18665. (cond ((< l level) (setq count 0))
  18666. ((and (= l level)
  18667. (or invisible-ok
  18668. (not (org-invisible-p
  18669. (line-beginning-position)))))
  18670. (cl-decf count)
  18671. (when (= l level) (setq result (point)))))))
  18672. (goto-char result))
  18673. (beginning-of-line))))
  18674. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18675. "Move backward to the ARG'th subheading at same level as this one.
  18676. Stop at the first and last subheadings of a superior heading."
  18677. (interactive "p")
  18678. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18679. (defun org-next-visible-heading (arg)
  18680. "Move to the next visible heading.
  18681. This function wraps `outline-next-visible-heading' with
  18682. `org-with-limited-levels' in order to skip over inline tasks and
  18683. respect customization of `org-odd-levels-only'."
  18684. (interactive "p")
  18685. (org-with-limited-levels
  18686. (outline-next-visible-heading arg)))
  18687. (defun org-previous-visible-heading (arg)
  18688. "Move to the previous visible heading.
  18689. This function wraps `outline-previous-visible-heading' with
  18690. `org-with-limited-levels' in order to skip over inline tasks and
  18691. respect customization of `org-odd-levels-only'."
  18692. (interactive "p")
  18693. (org-with-limited-levels
  18694. (outline-previous-visible-heading arg)))
  18695. (defun org-forward-paragraph ()
  18696. "Move forward to beginning of next paragraph or equivalent.
  18697. The function moves point to the beginning of the next visible
  18698. structural element, which can be a paragraph, a table, a list
  18699. item, etc. It also provides some special moves for convenience:
  18700. - On an affiliated keyword, jump to the beginning of the
  18701. relative element.
  18702. - On an item or a footnote definition, move to the second
  18703. element inside, if any.
  18704. - On a table or a property drawer, jump after it.
  18705. - On a verse or source block, stop after blank lines."
  18706. (interactive)
  18707. (unless (eobp)
  18708. (let* ((deactivate-mark nil)
  18709. (element (org-element-at-point))
  18710. (type (org-element-type element))
  18711. (post-affiliated (org-element-property :post-affiliated element))
  18712. (contents-begin (org-element-property :contents-begin element))
  18713. (contents-end (org-element-property :contents-end element))
  18714. (end (let ((end (org-element-property :end element)) (parent element))
  18715. (while (and (setq parent (org-element-property :parent parent))
  18716. (= (org-element-property :contents-end parent) end))
  18717. (setq end (org-element-property :end parent)))
  18718. end)))
  18719. (cond ((not element)
  18720. (skip-chars-forward " \r\t\n")
  18721. (or (eobp) (beginning-of-line)))
  18722. ;; On affiliated keywords, move to element's beginning.
  18723. ((< (point) post-affiliated)
  18724. (goto-char post-affiliated))
  18725. ;; At a table row, move to the end of the table. Similarly,
  18726. ;; at a node property, move to the end of the property
  18727. ;; drawer.
  18728. ((memq type '(node-property table-row))
  18729. (goto-char (org-element-property
  18730. :end (org-element-property :parent element))))
  18731. ((memq type '(property-drawer table)) (goto-char end))
  18732. ;; Consider blank lines as separators in verse and source
  18733. ;; blocks to ease editing.
  18734. ((memq type '(src-block verse-block))
  18735. (when (eq type 'src-block)
  18736. (setq contents-end
  18737. (save-excursion (goto-char end)
  18738. (skip-chars-backward " \r\t\n")
  18739. (line-beginning-position))))
  18740. (beginning-of-line)
  18741. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  18742. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  18743. (goto-char end)
  18744. (skip-chars-forward " \r\t\n")
  18745. (if (= (point) contents-end) (goto-char end)
  18746. (beginning-of-line))))
  18747. ;; With no contents, just skip element.
  18748. ((not contents-begin) (goto-char end))
  18749. ;; If contents are invisible, skip the element altogether.
  18750. ((org-invisible-p (line-end-position))
  18751. (cl-case type
  18752. (headline
  18753. (org-with-limited-levels (outline-next-visible-heading 1)))
  18754. ;; At a plain list, make sure we move to the next item
  18755. ;; instead of skipping the whole list.
  18756. (plain-list (forward-char)
  18757. (org-forward-paragraph))
  18758. (otherwise (goto-char end))))
  18759. ((>= (point) contents-end) (goto-char end))
  18760. ((>= (point) contents-begin)
  18761. ;; This can only happen on paragraphs and plain lists.
  18762. (cl-case type
  18763. (paragraph (goto-char end))
  18764. ;; At a plain list, try to move to second element in
  18765. ;; first item, if possible.
  18766. (plain-list (end-of-line)
  18767. (org-forward-paragraph))))
  18768. ;; When contents start on the middle of a line (e.g. in
  18769. ;; items and footnote definitions), try to reach first
  18770. ;; element starting after current line.
  18771. ((> (line-end-position) contents-begin)
  18772. (end-of-line)
  18773. (org-forward-paragraph))
  18774. (t (goto-char contents-begin))))))
  18775. (defun org-backward-paragraph ()
  18776. "Move backward to start of previous paragraph or equivalent.
  18777. The function moves point to the beginning of the current
  18778. structural element, which can be a paragraph, a table, a list
  18779. item, etc., or to the beginning of the previous visible one if
  18780. point is already there. It also provides some special moves for
  18781. convenience:
  18782. - On an affiliated keyword, jump to the first one.
  18783. - On a table or a property drawer, move to its beginning.
  18784. - On comment, example, export, src and verse blocks, stop
  18785. before blank lines."
  18786. (interactive)
  18787. (unless (bobp)
  18788. (let* ((deactivate-mark nil)
  18789. (element (org-element-at-point))
  18790. (type (org-element-type element))
  18791. (contents-end (org-element-property :contents-end element))
  18792. (post-affiliated (org-element-property :post-affiliated element))
  18793. (begin (org-element-property :begin element))
  18794. (special? ;blocks handled specially
  18795. (memq type '(comment-block example-block export-block src-block
  18796. verse-block)))
  18797. (contents-begin
  18798. (if special?
  18799. ;; These types have no proper contents. Fake line
  18800. ;; below the block opening line as contents beginning.
  18801. (save-excursion (goto-char begin) (line-beginning-position 2))
  18802. (org-element-property :contents-begin element))))
  18803. (cond
  18804. ((not element) (goto-char (point-min)))
  18805. ((= (point) begin)
  18806. (backward-char)
  18807. (org-backward-paragraph))
  18808. ((<= (point) post-affiliated) (goto-char begin))
  18809. ;; Special behavior: on a table or a property drawer, move to
  18810. ;; its beginning.
  18811. ((memq type '(node-property table-row))
  18812. (goto-char (org-element-property
  18813. :post-affiliated (org-element-property :parent element))))
  18814. (special?
  18815. (if (<= (point) contents-begin) (goto-char post-affiliated)
  18816. ;; Inside a verse block, see blank lines as paragraph
  18817. ;; separators.
  18818. (let ((origin (point)))
  18819. (skip-chars-backward " \r\t\n" contents-begin)
  18820. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  18821. (skip-chars-forward " \r\t\n" origin)
  18822. (if (= (point) origin) (goto-char contents-begin)
  18823. (beginning-of-line))))))
  18824. ((eq type 'paragraph) (goto-char contents-begin)
  18825. ;; When at first paragraph in an item or a footnote definition,
  18826. ;; move directly to beginning of line.
  18827. (let ((parent-contents
  18828. (org-element-property
  18829. :contents-begin (org-element-property :parent element))))
  18830. (when (and parent-contents (= parent-contents contents-begin))
  18831. (beginning-of-line))))
  18832. ;; At the end of a greater element, move to the beginning of
  18833. ;; the last element within.
  18834. ((and contents-end (>= (point) contents-end))
  18835. (goto-char (1- contents-end))
  18836. (org-backward-paragraph))
  18837. (t (goto-char (or post-affiliated begin))))
  18838. ;; Ensure we never leave point invisible.
  18839. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  18840. (defun org-forward-element ()
  18841. "Move forward by one element.
  18842. Move to the next element at the same level, when possible."
  18843. (interactive)
  18844. (cond ((eobp) (user-error "Cannot move further down"))
  18845. ((org-with-limited-levels (org-at-heading-p))
  18846. (let ((origin (point)))
  18847. (goto-char (org-end-of-subtree nil t))
  18848. (unless (org-with-limited-levels (org-at-heading-p))
  18849. (goto-char origin)
  18850. (user-error "Cannot move further down"))))
  18851. (t
  18852. (let* ((elem (org-element-at-point))
  18853. (end (org-element-property :end elem))
  18854. (parent (org-element-property :parent elem)))
  18855. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18856. (goto-char (org-element-property :end parent)))
  18857. ((integer-or-marker-p end) (goto-char end))
  18858. (t (message "No element at point")))))))
  18859. (defun org-backward-element ()
  18860. "Move backward by one element.
  18861. Move to the previous element at the same level, when possible."
  18862. (interactive)
  18863. (cond ((bobp) (user-error "Cannot move further up"))
  18864. ((org-with-limited-levels (org-at-heading-p))
  18865. ;; At a headline, move to the previous one, if any, or stay
  18866. ;; here.
  18867. (let ((origin (point)))
  18868. (org-with-limited-levels (org-backward-heading-same-level 1))
  18869. ;; When current headline has no sibling above, move to its
  18870. ;; parent.
  18871. (when (= (point) origin)
  18872. (or (org-with-limited-levels (org-up-heading-safe))
  18873. (progn (goto-char origin)
  18874. (user-error "Cannot move further up"))))))
  18875. (t
  18876. (let* ((elem (org-element-at-point))
  18877. (beg (org-element-property :begin elem)))
  18878. (cond
  18879. ;; Move to beginning of current element if point isn't
  18880. ;; there already.
  18881. ((null beg) (message "No element at point"))
  18882. ((/= (point) beg) (goto-char beg))
  18883. (t (goto-char beg)
  18884. (skip-chars-backward " \r\t\n")
  18885. (unless (bobp)
  18886. (let ((prev (org-element-at-point)))
  18887. (goto-char (org-element-property :begin prev))
  18888. (while (and (setq prev (org-element-property :parent prev))
  18889. (<= (org-element-property :end prev) beg))
  18890. (goto-char (org-element-property :begin prev)))))))))))
  18891. (defun org-up-element ()
  18892. "Move to upper element."
  18893. (interactive)
  18894. (if (org-with-limited-levels (org-at-heading-p))
  18895. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  18896. (let* ((elem (org-element-at-point))
  18897. (parent (org-element-property :parent elem)))
  18898. (if parent (goto-char (org-element-property :begin parent))
  18899. (if (org-with-limited-levels (org-before-first-heading-p))
  18900. (user-error "No surrounding element")
  18901. (org-with-limited-levels (org-back-to-heading)))))))
  18902. (defun org-down-element ()
  18903. "Move to inner element."
  18904. (interactive)
  18905. (let ((element (org-element-at-point)))
  18906. (cond
  18907. ((memq (org-element-type element) '(plain-list table))
  18908. (goto-char (org-element-property :contents-begin element))
  18909. (forward-char))
  18910. ((memq (org-element-type element) org-element-greater-elements)
  18911. ;; If contents are hidden, first disclose them.
  18912. (when (org-invisible-p (line-end-position)) (org-cycle))
  18913. (goto-char (or (org-element-property :contents-begin element)
  18914. (user-error "No content for this element"))))
  18915. (t (user-error "No inner element")))))
  18916. (defun org-drag-element-backward ()
  18917. "Move backward element at point."
  18918. (interactive)
  18919. (let ((elem (or (org-element-at-point)
  18920. (user-error "No element at point"))))
  18921. (if (eq (org-element-type elem) 'headline)
  18922. ;; Preserve point when moving a whole tree, even if point was
  18923. ;; on blank lines below the headline.
  18924. (let ((offset (skip-chars-backward " \t\n")))
  18925. (unwind-protect (org-move-subtree-up)
  18926. (forward-char (- offset))))
  18927. (let ((prev-elem
  18928. (save-excursion
  18929. (goto-char (org-element-property :begin elem))
  18930. (skip-chars-backward " \r\t\n")
  18931. (unless (bobp)
  18932. (let* ((beg (org-element-property :begin elem))
  18933. (prev (org-element-at-point))
  18934. (up prev))
  18935. (while (and (setq up (org-element-property :parent up))
  18936. (<= (org-element-property :end up) beg))
  18937. (setq prev up))
  18938. prev)))))
  18939. ;; Error out if no previous element or previous element is
  18940. ;; a parent of the current one.
  18941. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  18942. (user-error "Cannot drag element backward")
  18943. (let ((pos (point)))
  18944. (org-element-swap-A-B prev-elem elem)
  18945. (goto-char (+ (org-element-property :begin prev-elem)
  18946. (- pos (org-element-property :begin elem))))))))))
  18947. (defun org-drag-element-forward ()
  18948. "Move forward element at point."
  18949. (interactive)
  18950. (let* ((pos (point))
  18951. (elem (or (org-element-at-point)
  18952. (user-error "No element at point"))))
  18953. (when (= (point-max) (org-element-property :end elem))
  18954. (user-error "Cannot drag element forward"))
  18955. (goto-char (org-element-property :end elem))
  18956. (let ((next-elem (org-element-at-point)))
  18957. (when (or (org-element-nested-p elem next-elem)
  18958. (and (eq (org-element-type next-elem) 'headline)
  18959. (not (eq (org-element-type elem) 'headline))))
  18960. (goto-char pos)
  18961. (user-error "Cannot drag element forward"))
  18962. ;; Compute new position of point: it's shifted by NEXT-ELEM
  18963. ;; body's length (without final blanks) and by the length of
  18964. ;; blanks between ELEM and NEXT-ELEM.
  18965. (let ((size-next (- (save-excursion
  18966. (goto-char (org-element-property :end next-elem))
  18967. (skip-chars-backward " \r\t\n")
  18968. (forward-line)
  18969. ;; Small correction if buffer doesn't end
  18970. ;; with a newline character.
  18971. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  18972. (org-element-property :begin next-elem)))
  18973. (size-blank (- (org-element-property :end elem)
  18974. (save-excursion
  18975. (goto-char (org-element-property :end elem))
  18976. (skip-chars-backward " \r\t\n")
  18977. (forward-line)
  18978. (point)))))
  18979. (org-element-swap-A-B elem next-elem)
  18980. (goto-char (+ pos size-next size-blank))))))
  18981. (defun org-drag-line-forward (arg)
  18982. "Drag the line at point ARG lines forward."
  18983. (interactive "p")
  18984. (dotimes (_ (abs arg))
  18985. (let ((c (current-column)))
  18986. (if (< 0 arg)
  18987. (progn
  18988. (beginning-of-line 2)
  18989. (transpose-lines 1)
  18990. (beginning-of-line 0))
  18991. (transpose-lines 1)
  18992. (beginning-of-line -1))
  18993. (org-move-to-column c))))
  18994. (defun org-drag-line-backward (arg)
  18995. "Drag the line at point ARG lines backward."
  18996. (interactive "p")
  18997. (org-drag-line-forward (- arg)))
  18998. (defun org-mark-element ()
  18999. "Put point at beginning of this element, mark at end.
  19000. Interactively, if this command is repeated or (in Transient Mark
  19001. mode) if the mark is active, it marks the next element after the
  19002. ones already marked."
  19003. (interactive)
  19004. (let (deactivate-mark)
  19005. (if (and (called-interactively-p 'any)
  19006. (or (and (eq last-command this-command) (mark t))
  19007. (and transient-mark-mode mark-active)))
  19008. (set-mark
  19009. (save-excursion
  19010. (goto-char (mark))
  19011. (goto-char (org-element-property :end (org-element-at-point)))))
  19012. (let ((element (org-element-at-point)))
  19013. (end-of-line)
  19014. (push-mark (org-element-property :end element) t t)
  19015. (goto-char (org-element-property :begin element))))))
  19016. (defun org-narrow-to-element ()
  19017. "Narrow buffer to current element."
  19018. (interactive)
  19019. (let ((elem (org-element-at-point)))
  19020. (cond
  19021. ((eq (car elem) 'headline)
  19022. (narrow-to-region
  19023. (org-element-property :begin elem)
  19024. (org-element-property :end elem)))
  19025. ((memq (car elem) org-element-greater-elements)
  19026. (narrow-to-region
  19027. (org-element-property :contents-begin elem)
  19028. (org-element-property :contents-end elem)))
  19029. (t
  19030. (narrow-to-region
  19031. (org-element-property :begin elem)
  19032. (org-element-property :end elem))))))
  19033. (defun org-transpose-element ()
  19034. "Transpose current and previous elements, keeping blank lines between.
  19035. Point is moved after both elements."
  19036. (interactive)
  19037. (org-skip-whitespace)
  19038. (let ((end (org-element-property :end (org-element-at-point))))
  19039. (org-drag-element-backward)
  19040. (goto-char end)))
  19041. (defun org-unindent-buffer ()
  19042. "Un-indent the visible part of the buffer.
  19043. Relative indentation (between items, inside blocks, etc.) isn't
  19044. modified."
  19045. (interactive)
  19046. (unless (eq major-mode 'org-mode)
  19047. (user-error "Cannot un-indent a buffer not in Org mode"))
  19048. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19049. (unindent-tree
  19050. (lambda (contents)
  19051. (dolist (element (reverse contents))
  19052. (if (memq (org-element-type element) '(headline section))
  19053. (funcall unindent-tree (org-element-contents element))
  19054. (save-excursion
  19055. (save-restriction
  19056. (narrow-to-region
  19057. (org-element-property :begin element)
  19058. (org-element-property :end element))
  19059. (org-do-remove-indentation))))))))
  19060. (funcall unindent-tree (org-element-contents parse-tree))))
  19061. (defun org-make-options-regexp (kwds &optional extra)
  19062. "Make a regular expression for keyword lines.
  19063. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19064. when non-nil, is a regexp matching keywords names."
  19065. (concat "^[ \t]*#\\+\\("
  19066. (regexp-opt kwds)
  19067. (and extra (concat (and kwds "\\|") extra))
  19068. "\\):[ \t]*\\(.*\\)"))
  19069. ;;; Conveniently switch to Info nodes
  19070. (defun org-info-find-node (&optional nodename)
  19071. "Find Info documentation NODENAME or Org documentation according context.
  19072. Started from `gnus-info-find-node'."
  19073. (interactive)
  19074. (Info-goto-node
  19075. (or nodename
  19076. (let ((default-org-info-node "(org) Top"))
  19077. (cond
  19078. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19079. ((eq 'org-mode major-mode)
  19080. (let* ((context (org-element-at-point))
  19081. (element-info-nodes ; compare to `org-element-all-elements'.
  19082. `((babel-call . "(org) Evaluating Code Blocks")
  19083. (center-block . "(org) Paragraphs")
  19084. (clock . ,default-org-info-node)
  19085. (comment . "(org) Comment Lines")
  19086. (comment-block . "(org) Comment Lines")
  19087. (diary-sexp . ,default-org-info-node)
  19088. (drawer . "(org) Drawers")
  19089. (dynamic-block . "(org) Dynamic Blocks")
  19090. (example-block . "(org) Literal Examples")
  19091. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19092. (fixed-width . ,default-org-info-node)
  19093. (footnote-definition . "(org) Creating Footnotes")
  19094. (headline . "(org) Document Structure")
  19095. (horizontal-rule . "(org) Built-in Table Editor")
  19096. (inlinetask . ,default-org-info-node)
  19097. (item . "(org) Plain Lists")
  19098. (keyword . "(org) Per-file keywords")
  19099. (latex-environment . "(org) LaTeX Export")
  19100. (node-property . "(org) Properties and Columns")
  19101. (paragraph . "(org) Paragraphs")
  19102. (plain-list . "(org) Plain Lists")
  19103. (planning . "(org) Deadlines and Scheduling")
  19104. (property-drawer . "(org) Properties and Columns")
  19105. (quote-block . "(org) Paragraphs")
  19106. (section . ,default-org-info-node)
  19107. (special-block . ,default-org-info-node)
  19108. (src-block . "(org) Working with Source Code")
  19109. (table . "(org) Tables")
  19110. (table-row . "(org) Tables")
  19111. (verse-block . "(org) Paragraphs"))))
  19112. (or (cdr (assoc (car context) element-info-nodes))
  19113. default-org-info-node)))
  19114. (t default-org-info-node))))))
  19115. ;;; Finish up
  19116. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19117. (lambda () (add-hook 'change-major-mode-hook
  19118. 'org-show-all 'append 'local)))
  19119. (provide 'org)
  19120. (run-hooks 'org-load-hook)
  19121. ;; Local variables:
  19122. ;; generated-autoload-file: "org-loaddefs.el"
  19123. ;; End:
  19124. ;;; org.el ends here