org.el 805 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277
  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.3.6
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'org-table)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-attach-dir "org-attach"
  112. (&optional create-if-not-exists-p no-fs-check))
  113. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  114. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  115. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  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-insert-dblock "org-colview" ())
  134. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  135. (declare-function org-element-at-point "org-element" ())
  136. (declare-function org-element-cache-refresh "org-element" (pos))
  137. (declare-function org-element-cache-reset "org-element" (&optional all))
  138. (declare-function org-element-contents "org-element" (element))
  139. (declare-function org-element-context "org-element" (&optional element))
  140. (declare-function org-element-copy "org-element" (datum))
  141. (declare-function org-element-create "org-element" (type &optional props &rest children))
  142. (declare-function org-element-interpret-data "org-element" (data))
  143. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  144. (declare-function org-element-link-parser "org-element" ())
  145. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  146. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  147. (declare-function org-element-property "org-element" (property element))
  148. (declare-function org-element-put-property "org-element" (element property value))
  149. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  150. (declare-function org-element-timestamp-parser "org-element" ())
  151. (declare-function org-element-type "org-element" (element))
  152. (declare-function org-export-dispatch "ox" (&optional arg))
  153. (declare-function org-export-get-backend "ox" (name))
  154. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  155. (declare-function org-feed-goto-inbox "org-feed" (feed))
  156. (declare-function org-feed-update-all "org-feed" ())
  157. (declare-function org-goto "org-goto" (&optional alternative-interface))
  158. (declare-function org-id-find-id-file "org-id" (id))
  159. (declare-function org-id-get-create "org-id" (&optional force))
  160. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  161. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  162. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  163. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  165. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  166. (declare-function org-timer "org-timer" (&optional restart no-insert))
  167. (declare-function org-timer-item "org-timer" (&optional arg))
  168. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  169. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  170. (declare-function org-timer-start "org-timer" (&optional offset))
  171. (declare-function org-timer-stop "org-timer" ())
  172. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  173. (declare-function org-update-radio-target-regexp "ol" ())
  174. (defvar ffap-url-regexp)
  175. (defvar org-element-paragraph-separate)
  176. (defvar org-indent-indentation-per-level)
  177. (defvar org-radio-target-regexp)
  178. (defvar org-target-link-regexp)
  179. (defvar org-target-regexp)
  180. (defvar org-id-overriding-file-name)
  181. ;; load languages based on value of `org-babel-load-languages'
  182. (defvar org-babel-load-languages)
  183. ;;;###autoload
  184. (defun org-babel-do-load-languages (sym value)
  185. "Load the languages defined in `org-babel-load-languages'."
  186. (set-default sym value)
  187. (dolist (pair org-babel-load-languages)
  188. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  189. (if active
  190. (require (intern (concat "ob-" lang)))
  191. (fmakunbound
  192. (intern (concat "org-babel-execute:" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-expand-body:" lang)))))))
  195. ;;;###autoload
  196. (defun org-babel-load-file (file &optional compile)
  197. "Load Emacs Lisp source code blocks in the Org FILE.
  198. This function exports the source code using `org-babel-tangle'
  199. and then loads the resulting file using `load-file'. With
  200. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  201. byte-compiled before it is loaded."
  202. (interactive "fFile to load: \nP")
  203. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  204. ;; Tangle only if the Org file is newer than the Elisp file.
  205. (unless (org-file-newer-than-p
  206. tangled-file
  207. (file-attribute-modification-time
  208. (file-attributes (file-truename file))))
  209. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  210. (if compile
  211. (progn
  212. (byte-compile-file tangled-file 'load)
  213. (message "Compiled and loaded %s" tangled-file))
  214. (load-file tangled-file)
  215. (message "Loaded %s" tangled-file))))
  216. (defcustom org-babel-load-languages '((emacs-lisp . t))
  217. "Languages which can be evaluated in Org buffers.
  218. \\<org-mode-map>
  219. This list can be used to load support for any of the languages
  220. below. Each language will depend on a different set of system
  221. executables and/or Emacs modes.
  222. When a language is \"loaded\", code blocks in that language can
  223. be evaluated with `org-babel-execute-src-block', which is bound
  224. by default to \\[org-ctrl-c-ctrl-c].
  225. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  226. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  227. default, only Emacs Lisp is loaded, since it has no specific
  228. requirement."
  229. :group 'org-babel
  230. :set 'org-babel-do-load-languages
  231. :version "24.1"
  232. :type '(alist :tag "Babel Languages"
  233. :key-type
  234. (choice
  235. (const :tag "Awk" awk)
  236. (const :tag "C" C)
  237. (const :tag "R" R)
  238. (const :tag "Asymptote" asymptote)
  239. (const :tag "Calc" calc)
  240. (const :tag "Clojure" clojure)
  241. (const :tag "CSS" css)
  242. (const :tag "Ditaa" ditaa)
  243. (const :tag "Dot" dot)
  244. (const :tag "Ebnf2ps" ebnf2ps)
  245. (const :tag "Emacs Lisp" emacs-lisp)
  246. (const :tag "Forth" forth)
  247. (const :tag "Fortran" fortran)
  248. (const :tag "Gnuplot" gnuplot)
  249. (const :tag "Haskell" haskell)
  250. (const :tag "hledger" hledger)
  251. (const :tag "IO" io)
  252. (const :tag "J" J)
  253. (const :tag "Java" java)
  254. (const :tag "Javascript" js)
  255. (const :tag "LaTeX" latex)
  256. (const :tag "Ledger" ledger)
  257. (const :tag "Lilypond" lilypond)
  258. (const :tag "Lisp" lisp)
  259. (const :tag "Makefile" makefile)
  260. (const :tag "Maxima" maxima)
  261. (const :tag "Matlab" matlab)
  262. (const :tag "Mscgen" mscgen)
  263. (const :tag "Ocaml" ocaml)
  264. (const :tag "Octave" octave)
  265. (const :tag "Org" org)
  266. (const :tag "Perl" perl)
  267. (const :tag "Pico Lisp" picolisp)
  268. (const :tag "PlantUML" plantuml)
  269. (const :tag "Python" python)
  270. (const :tag "Ruby" ruby)
  271. (const :tag "Sass" sass)
  272. (const :tag "Scala" scala)
  273. (const :tag "Scheme" scheme)
  274. (const :tag "Screen" screen)
  275. (const :tag "Shell Script" shell)
  276. (const :tag "Shen" shen)
  277. (const :tag "Sql" sql)
  278. (const :tag "Sqlite" sqlite)
  279. (const :tag "Stan" stan)
  280. (const :tag "Vala" vala))
  281. :value-type (boolean :tag "Activate" :value t)))
  282. ;;;; Customization variables
  283. (defcustom org-clone-delete-id nil
  284. "Remove ID property of clones of a subtree.
  285. When non-nil, clones of a subtree don't inherit the ID property.
  286. Otherwise they inherit the ID property with a new unique
  287. identifier."
  288. :type 'boolean
  289. :version "24.1"
  290. :group 'org-id)
  291. ;;; Version
  292. (org-check-version)
  293. ;;;###autoload
  294. (defun org-version (&optional here full message)
  295. "Show the Org version.
  296. Interactively, or when MESSAGE is non-nil, show it in echo area.
  297. With prefix argument, or when HERE is non-nil, insert it at point.
  298. In non-interactive uses, a reduced version string is output unless
  299. FULL is given."
  300. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  301. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  302. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  303. (load-suffixes (list ".el"))
  304. (org-install-dir
  305. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  306. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  307. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  308. (let* ((load-suffixes save-load-suffixes)
  309. (release (org-release))
  310. (git-version (org-git-version))
  311. (version (format "Org mode version %s (%s @ %s)"
  312. release
  313. git-version
  314. (if org-install-dir
  315. (if (string= org-dir org-install-dir)
  316. org-install-dir
  317. (concat "mixed installation! "
  318. org-install-dir
  319. " and "
  320. org-dir))
  321. "org-loaddefs.el can not be found!")))
  322. (version1 (if full version release)))
  323. (when here (insert version1))
  324. (when message (message "%s" version1))
  325. version1)))
  326. (defconst org-version (org-version))
  327. ;;; Syntax Constants
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. \\<org-mode-map>
  345. A deadline is this string, followed by a time stamp. It must be
  346. a word, terminated by a colon. You can insert a schedule keyword
  347. and a timestamp with `\\[org-deadline]'.")
  348. (defvar org-scheduled-string "SCHEDULED:"
  349. "String to mark scheduled TODO entries.
  350. \\<org-mode-map>
  351. A schedule is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-schedule]'.")
  354. (defconst org-ds-keyword-length
  355. (+ 2
  356. (apply #'max
  357. (mapcar #'length
  358. (list org-deadline-string org-scheduled-string
  359. org-clock-string org-closed-string))))
  360. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  361. (defconst org-planning-line-re
  362. (concat "^[ \t]*"
  363. (regexp-opt
  364. (list org-closed-string org-deadline-string org-scheduled-string)
  365. t))
  366. "Matches a line with planning info.
  367. Matched keyword is in group 1.")
  368. (defconst org-clock-line-re
  369. (concat "^[ \t]*" org-clock-string)
  370. "Matches a line with clock info.")
  371. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  372. "Matches the DEADLINE keyword.")
  373. (defconst org-deadline-time-regexp
  374. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  375. "Matches the DEADLINE keyword together with a time stamp.")
  376. (defconst org-deadline-time-hour-regexp
  377. (concat "\\<" org-deadline-string
  378. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  379. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  380. (defconst org-deadline-line-regexp
  381. (concat "\\<\\(" org-deadline-string "\\).*")
  382. "Matches the DEADLINE keyword and the rest of the line.")
  383. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  384. "Matches the SCHEDULED keyword.")
  385. (defconst org-scheduled-time-regexp
  386. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  387. "Matches the SCHEDULED keyword together with a time stamp.")
  388. (defconst org-scheduled-time-hour-regexp
  389. (concat "\\<" org-scheduled-string
  390. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  391. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  392. (defconst org-closed-time-regexp
  393. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  394. "Matches the CLOSED keyword together with a time stamp.")
  395. (defconst org-keyword-time-regexp
  396. (concat "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string
  399. org-clock-string)
  400. t)
  401. " *[[<]\\([^]>]+\\)[]>]")
  402. "Matches any of the 4 keywords, together with the time stamp.")
  403. (defconst org-keyword-time-not-clock-regexp
  404. (concat
  405. "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string) t)
  408. " *[[<]\\([^]>]+\\)[]>]")
  409. "Matches any of the 3 keywords, together with the time stamp.")
  410. (defconst org-maybe-keyword-time-regexp
  411. (concat "\\(\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string
  414. org-clock-string)
  415. t)
  416. "\\)?"
  417. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  418. "\\|"
  419. "<%%([^\r\n>]*>\\)")
  420. "Matches a timestamp, possibly preceded by a keyword.")
  421. (defconst org-all-time-keywords
  422. (mapcar (lambda (w) (substring w 0 -1))
  423. (list org-scheduled-string org-deadline-string
  424. org-clock-string org-closed-string))
  425. "List of time keywords.")
  426. ;;;; Drawer
  427. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  428. "Matches first or last line of a hidden block.
  429. Group 1 contains drawer's name or \"END\".")
  430. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  431. "Regular expression matching the first line of a property drawer.")
  432. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  433. "Regular expression matching the last line of a property drawer.")
  434. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  435. "Regular expression matching the first line of a clock drawer.")
  436. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a clock drawer.")
  438. (defconst org-property-drawer-re
  439. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  440. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  441. "[ \t]*:END:[ \t]*$")
  442. "Matches an entire property drawer.")
  443. (defconst org-clock-drawer-re
  444. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  445. org-clock-drawer-end-re "\\)\n?")
  446. "Matches an entire clock drawer.")
  447. ;;;; Headline
  448. (defconst org-heading-keyword-regexp-format
  449. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  450. "Printf format for a regexp matching a headline with some keyword.
  451. This regexp will match the headline of any node which has the
  452. exact keyword that is put into the format. The keyword isn't in
  453. any group by default, but the stars and the body are.")
  454. (defconst org-heading-keyword-maybe-regexp-format
  455. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  456. "Printf format for a regexp matching a headline, possibly with some keyword.
  457. This regexp can match any headline with the specified keyword, or
  458. without a keyword. The keyword isn't in any group by default,
  459. but the stars and the body are.")
  460. (defconst org-archive-tag "ARCHIVE"
  461. "The tag that marks a subtree as archived.
  462. An archived subtree does not open during visibility cycling, and does
  463. not contribute to the agenda listings.")
  464. (defconst org-tag-re "[[:alnum:]_@#%]+"
  465. "Regexp matching a single tag.")
  466. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  467. "Regexp matching the tag group at the end of a line, with leading spaces.
  468. Tags are stored in match group 1. Match group 2 stores the tags
  469. without the enclosing colons.")
  470. (defconst org-tag-line-re
  471. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  472. "Regexp matching tags in a headline.
  473. Tags are stored in match group 1. Match group 2 stores the tags
  474. without the enclosing colons.")
  475. (eval-and-compile
  476. (defconst org-comment-string "COMMENT"
  477. "Entries starting with this keyword will never be exported.
  478. \\<org-mode-map>
  479. An entry can be toggled between COMMENT and normal with
  480. `\\[org-toggle-comment]'."))
  481. ;;;; LaTeX Environments and Fragments
  482. (defconst org-latex-regexps
  483. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  484. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  485. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  486. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  487. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  488. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  489. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  490. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  491. "Regular expressions for matching embedded LaTeX.")
  492. ;;;; Node Property
  493. (defconst org-effort-property "Effort"
  494. "The property that is being used to keep track of effort estimates.
  495. Effort estimates given in this property need to have the format H:MM.")
  496. ;;;; Timestamp
  497. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp-inactive
  500. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  501. "Regular expression for fast inactive time stamp matching.")
  502. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp0
  505. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  506. "Regular expression matching time strings for analysis.
  507. This one does not require the space after the date, so it can be used
  508. on a string that terminates immediately after the date.")
  509. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.")
  511. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  512. "Regular expression matching time stamps, with groups.")
  513. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  514. "Regular expression matching time stamps (also [..]), with groups.")
  515. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tr-regexp-both
  518. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  521. org-ts-regexp "\\)?")
  522. "Regular expression matching a time stamp or time stamp range.")
  523. (defconst org-tsr-regexp-both
  524. (concat org-ts-regexp-both "\\(--?-?"
  525. org-ts-regexp-both "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.
  527. The time stamps may be either active or inactive.")
  528. (defconst org-repeat-re
  529. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  530. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "26.1"
  584. :package-version '(Org . "9.2")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to Docview buffers" ol-docview)
  592. (const :tag " eww: Store link to URL of Eww" ol-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" ol-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  603. (const :tag " tempo: Fast completion for structures" org-tempo)
  604. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  605. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  606. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  608. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  609. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  610. (const :tag "C collector: Collect properties into tables" org-collector)
  611. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  612. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  613. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  614. (const :tag "C eval: Include command output as text" org-eval)
  615. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  616. (const :tag "C git-link: Links to specific file version" ol-git-link)
  617. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  618. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  619. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  620. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  621. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  622. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  623. (const :tag "C man: Links to man pages in Org mode" ol-man)
  624. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  625. (const :tag "C notify: Notifications for Org mode" org-notify)
  626. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  627. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  628. (const :tag "C registry: A registry for Org links" org-registry)
  629. (const :tag "C screen: Visit screen sessions through links" org-screen)
  630. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  631. (const :tag "C secretary: Team management with Org" org-secretary)
  632. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  633. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  634. (const :tag "C track: Keep up with Org mode development" org-track)
  635. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  636. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  637. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  638. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  639. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  640. (defvar org-export-registered-backends) ; From ox.el.
  641. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  642. (declare-function org-export-backend-name "ox" (backend) t)
  643. (defcustom org-export-backends '(ascii html icalendar latex odt)
  644. "List of export back-ends that should be always available.
  645. If a description starts with <C>, the file is not part of Emacs
  646. and loading it will require that you have downloaded and properly
  647. installed the Org mode distribution.
  648. Unlike to `org-modules', libraries in this list will not be
  649. loaded along with Org, but only once the export framework is
  650. needed.
  651. This variable needs to be set before org.el is loaded. If you
  652. need to make a change while Emacs is running, use the customize
  653. interface or run the following code, where VAL stands for the new
  654. value of the variable, after updating it:
  655. (progn
  656. (setq org-export-registered-backends
  657. (cl-remove-if-not
  658. (lambda (backend)
  659. (let ((name (org-export-backend-name backend)))
  660. (or (memq name val)
  661. (catch \\='parentp
  662. (dolist (b val)
  663. (and (org-export-derived-backend-p b name)
  664. (throw \\='parentp t)))))))
  665. org-export-registered-backends))
  666. (let ((new-list (mapcar #\\='org-export-backend-name
  667. org-export-registered-backends)))
  668. (dolist (backend val)
  669. (cond
  670. ((not (load (format \"ox-%s\" backend) t t))
  671. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  672. backend))
  673. ((not (memq backend new-list)) (push backend new-list))))
  674. (set-default \\='org-export-backends new-list)))
  675. Adding a back-end to this list will also pull the back-end it
  676. depends on, if any."
  677. :group 'org
  678. :group 'org-export
  679. :version "26.1"
  680. :package-version '(Org . "9.0")
  681. :initialize 'custom-initialize-set
  682. :set (lambda (var val)
  683. (if (not (featurep 'ox)) (set-default var val)
  684. ;; Any back-end not required anymore (not present in VAL and not
  685. ;; a parent of any back-end in the new value) is removed from the
  686. ;; list of registered back-ends.
  687. (setq org-export-registered-backends
  688. (cl-remove-if-not
  689. (lambda (backend)
  690. (let ((name (org-export-backend-name backend)))
  691. (or (memq name val)
  692. (catch 'parentp
  693. (dolist (b val)
  694. (and (org-export-derived-backend-p b name)
  695. (throw 'parentp t)))))))
  696. org-export-registered-backends))
  697. ;; Now build NEW-LIST of both new back-ends and required
  698. ;; parents.
  699. (let ((new-list (mapcar #'org-export-backend-name
  700. org-export-registered-backends)))
  701. (dolist (backend val)
  702. (cond
  703. ((not (load (format "ox-%s" backend) t t))
  704. (message "Problems while trying to load export back-end `%s'"
  705. backend))
  706. ((not (memq backend new-list)) (push backend new-list))))
  707. ;; Set VAR to that list with fixed dependencies.
  708. (set-default var new-list))))
  709. :type '(set :greedy t
  710. (const :tag " ascii Export buffer to ASCII format" ascii)
  711. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  712. (const :tag " html Export buffer to HTML format" html)
  713. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  714. (const :tag " latex Export buffer to LaTeX format" latex)
  715. (const :tag " man Export buffer to MAN format" man)
  716. (const :tag " md Export buffer to Markdown format" md)
  717. (const :tag " odt Export buffer to ODT format" odt)
  718. (const :tag " org Export buffer to Org format" org)
  719. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  720. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  721. (const :tag "C deck Export buffer to deck.js presentations" deck)
  722. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  723. (const :tag "C groff Export buffer to Groff format" groff)
  724. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  725. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  726. (const :tag "C s5 Export buffer to s5 presentations" s5)
  727. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  728. (eval-after-load 'ox
  729. '(dolist (backend org-export-backends)
  730. (condition-case nil (require (intern (format "ox-%s" backend)))
  731. (error (message "Problems while trying to load export back-end `%s'"
  732. backend)))))
  733. (defcustom org-support-shift-select nil
  734. "Non-nil means make shift-cursor commands select text when possible.
  735. \\<org-mode-map>
  736. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  737. start selecting a region, or enlarge regions started in this way.
  738. In Org mode, in special contexts, these same keys are used for
  739. other purposes, important enough to compete with shift selection.
  740. Org tries to balance these needs by supporting `shift-select-mode'
  741. outside these special contexts, under control of this variable.
  742. The default of this variable is nil, to avoid confusing behavior. Shifted
  743. cursor keys will then execute Org commands in the following contexts:
  744. - on a headline, changing TODO state (left/right) and priority (up/down)
  745. - on a time stamp, changing the time
  746. - in a plain list item, changing the bullet type
  747. - in a property definition line, switching between allowed values
  748. - in the BEGIN line of a clock table (changing the time block).
  749. - in a table, moving the cell in the specified direction.
  750. Outside these contexts, the commands will throw an error.
  751. When this variable is t and the cursor is not in a special
  752. context, Org mode will support shift-selection for making and
  753. enlarging regions. To make this more effective, the bullet
  754. cycling will no longer happen anywhere in an item line, but only
  755. if the cursor is exactly on the bullet.
  756. If you set this variable to the symbol `always', then the keys
  757. will not be special in headlines, property lines, item lines, and
  758. table cells, to make shift selection work there as well. If this is
  759. what you want, you can use the following alternative commands:
  760. `\\[org-todo]' and `\\[org-priority]' \
  761. to change TODO state and priority,
  762. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  763. can be used to switch TODO sets,
  764. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  765. and properties can be edited by hand or in column view.
  766. However, when the cursor is on a timestamp, shift-cursor commands
  767. will still edit the time stamp - this is just too good to give up."
  768. :group 'org
  769. :type '(choice
  770. (const :tag "Never" nil)
  771. (const :tag "When outside special context" t)
  772. (const :tag "Everywhere except timestamps" always)))
  773. (defcustom org-loop-over-headlines-in-active-region nil
  774. "Shall some commands act upon headlines in the active region?
  775. When set to t, some commands will be performed in all headlines
  776. within the active region.
  777. When set to `start-level', some commands will be performed in all
  778. headlines within the active region, provided that these headlines
  779. are of the same level than the first one.
  780. When set to a string, those commands will be performed on the
  781. matching headlines within the active region. Such string must be
  782. a tags/property/todo match as it is used in the agenda tags view.
  783. The list of commands is: `org-schedule', `org-deadline',
  784. `org-todo', `org-set-tags-command', `org-archive-subtree',
  785. `org-archive-set-tag', `org-toggle-archive-tag' and
  786. `org-archive-to-archive-sibling'. The archiving commands skip
  787. already archived entries."
  788. :type '(choice (const :tag "Don't loop" nil)
  789. (const :tag "All headlines in active region" t)
  790. (const :tag "In active region, headlines at the same level than the first one" start-level)
  791. (string :tag "Tags/Property/Todo matcher"))
  792. :version "24.1"
  793. :group 'org-todo
  794. :group 'org-archive)
  795. (defcustom org-startup-folded t
  796. "Non-nil means entering Org mode will switch to OVERVIEW.
  797. This can also be configured on a per-file basis by adding one of
  798. the following lines anywhere in the buffer:
  799. #+STARTUP: fold (or `overview', this is equivalent)
  800. #+STARTUP: nofold (or `showall', this is equivalent)
  801. #+STARTUP: content
  802. #+STARTUP: showeverything
  803. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  804. to ignore this option when Org opens agenda files for the first
  805. time."
  806. :group 'org-startup
  807. :type '(choice
  808. (const :tag "nofold: show all" nil)
  809. (const :tag "fold: overview" t)
  810. (const :tag "content: all headlines" content)
  811. (const :tag "show everything, even drawers" showeverything)))
  812. (defcustom org-startup-truncated t
  813. "Non-nil means entering Org mode will set `truncate-lines'.
  814. This is useful since some lines containing links can be very long and
  815. uninteresting. Also tables look terrible when wrapped.
  816. The variable `org-startup-truncated' allows to configure
  817. truncation for Org mode different to the other modes that use the
  818. variable `truncate-lines' and as a shortcut instead of putting
  819. the variable `truncate-lines' into the `org-mode-hook'. If one
  820. wants to configure truncation for Org mode not statically but
  821. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  822. the variable `truncate-lines' has to be used because in such a
  823. case it is too late to set the variable `org-startup-truncated'."
  824. :group 'org-startup
  825. :type 'boolean)
  826. (defcustom org-startup-indented nil
  827. "Non-nil means turn on `org-indent-mode' on startup.
  828. This can also be configured on a per-file basis by adding one of
  829. the following lines anywhere in the buffer:
  830. #+STARTUP: indent
  831. #+STARTUP: noindent"
  832. :group 'org-structure
  833. :type '(choice
  834. (const :tag "Not" nil)
  835. (const :tag "Globally (slow on startup in large files)" t)))
  836. (defcustom org-use-sub-superscripts t
  837. "Non-nil means interpret \"_\" and \"^\" for display.
  838. If you want to control how Org exports those characters, see
  839. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  840. used to be an alias for `org-export-with-sub-superscripts' in
  841. Org <8.0, it is not anymore.
  842. When this option is turned on, you can use TeX-like syntax for
  843. sub- and superscripts within the buffer. Several characters after
  844. \"_\" or \"^\" will be considered as a single item - so grouping
  845. with {} is normally not needed. For example, the following things
  846. will be parsed as single sub- or superscripts:
  847. 10^24 or 10^tau several digits will be considered 1 item.
  848. 10^-12 or 10^-tau a leading sign with digits or a word
  849. x^2-y^3 will be read as x^2 - y^3, because items are
  850. terminated by almost any nonword/nondigit char.
  851. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  852. Still, ambiguity is possible. So when in doubt, use {} to enclose
  853. the sub/superscript. If you set this variable to the symbol `{}',
  854. the braces are *required* in order to trigger interpretations as
  855. sub/superscript. This can be helpful in documents that need \"_\"
  856. frequently in plain text."
  857. :group 'org-startup
  858. :version "24.4"
  859. :package-version '(Org . "8.0")
  860. :type '(choice
  861. (const :tag "Always interpret" t)
  862. (const :tag "Only with braces" {})
  863. (const :tag "Never interpret" nil)))
  864. (defcustom org-startup-with-beamer-mode nil
  865. "Non-nil means turn on `org-beamer-mode' on startup.
  866. This can also be configured on a per-file basis by adding one of
  867. the following lines anywhere in the buffer:
  868. #+STARTUP: beamer"
  869. :group 'org-startup
  870. :version "24.1"
  871. :type 'boolean)
  872. (defcustom org-startup-align-all-tables nil
  873. "Non-nil means align all tables when visiting a file.
  874. This can also be configured on a per-file basis by adding one of
  875. the following lines anywhere in the buffer:
  876. #+STARTUP: align
  877. #+STARTUP: noalign"
  878. :group 'org-startup
  879. :type 'boolean)
  880. (defcustom org-startup-shrink-all-tables nil
  881. "Non-nil means shrink all table columns with a width cookie.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: shrink"
  885. :group 'org-startup
  886. :type 'boolean
  887. :version "27.1"
  888. :package-version '(Org . "9.2")
  889. :safe #'booleanp)
  890. (defcustom org-startup-with-inline-images nil
  891. "Non-nil means show inline images when loading a new Org file.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: inlineimages
  895. #+STARTUP: noinlineimages"
  896. :group 'org-startup
  897. :version "24.1"
  898. :type 'boolean)
  899. (defcustom org-startup-with-latex-preview nil
  900. "Non-nil means preview LaTeX fragments when loading a new Org file.
  901. This can also be configured on a per-file basis by adding one of
  902. the following lines anywhere in the buffer:
  903. #+STARTUP: latexpreview
  904. #+STARTUP: nolatexpreview"
  905. :group 'org-startup
  906. :version "24.4"
  907. :package-version '(Org . "8.0")
  908. :type 'boolean)
  909. (defcustom org-insert-mode-line-in-empty-file nil
  910. "Non-nil means insert the first line setting Org mode in empty files.
  911. When the function `org-mode' is called interactively in an empty file, this
  912. normally means that the file name does not automatically trigger Org mode.
  913. To ensure that the file will always be in Org mode in the future, a
  914. line enforcing Org mode will be inserted into the buffer, if this option
  915. has been set."
  916. :group 'org-startup
  917. :type 'boolean)
  918. (defcustom org-ellipsis nil
  919. "The ellipsis to use in the Org mode outline.
  920. When nil, just use the standard three dots. When a non-empty string,
  921. use that string instead.
  922. The change affects only Org mode (which will then use its own display table).
  923. Changing this requires executing `\\[org-mode]' in a buffer to become
  924. effective."
  925. :group 'org-startup
  926. :type '(choice (const :tag "Default" nil)
  927. (string :tag "String" :value "...#"))
  928. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  929. (defvar org-display-table nil
  930. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  931. (defgroup org-keywords nil
  932. "Keywords in Org mode."
  933. :tag "Org Keywords"
  934. :group 'org)
  935. (defcustom org-closed-keep-when-no-todo nil
  936. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  937. :group 'org-todo
  938. :group 'org-keywords
  939. :version "24.4"
  940. :package-version '(Org . "8.0")
  941. :type 'boolean)
  942. (defgroup org-structure nil
  943. "Options concerning the general structure of Org files."
  944. :tag "Org Structure"
  945. :group 'org)
  946. (defgroup org-reveal-location nil
  947. "Options about how to make context of a location visible."
  948. :tag "Org Reveal Location"
  949. :group 'org-structure)
  950. (defcustom org-show-context-detail '((agenda . local)
  951. (bookmark-jump . lineage)
  952. (isearch . lineage)
  953. (default . ancestors))
  954. "Alist between context and visibility span when revealing a location.
  955. \\<org-mode-map>Some actions may move point into invisible
  956. locations. As a consequence, Org always expose a neighborhood
  957. around point. How much is shown depends on the initial action,
  958. or context. Valid contexts are
  959. agenda when exposing an entry from the agenda
  960. org-goto when using the command `org-goto' (`\\[org-goto]')
  961. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  962. tags-tree when constructing a sparse tree based on tags matches
  963. link-search when exposing search matches associated with a link
  964. mark-goto when exposing the jump goal of a mark
  965. bookmark-jump when exposing a bookmark location
  966. isearch when exiting from an incremental search
  967. default default for all contexts not set explicitly
  968. Allowed visibility spans are
  969. minimal show current headline; if point is not on headline,
  970. also show entry
  971. local show current headline, entry and next headline
  972. ancestors show current headline and its direct ancestors; if
  973. point is not on headline, also show entry
  974. lineage show current headline, its direct ancestors and all
  975. their children; if point is not on headline, also show
  976. entry and first child
  977. tree show current headline, its direct ancestors and all
  978. their children; if point is not on headline, also show
  979. entry and all children
  980. canonical show current headline, its direct ancestors along with
  981. their entries and children; if point is not located on
  982. the headline, also show current entry and all children
  983. As special cases, a nil or t value means show all contexts in
  984. `minimal' or `canonical' view, respectively.
  985. Some views can make displayed information very compact, but also
  986. make it harder to edit the location of the match. In such
  987. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  988. more context."
  989. :group 'org-reveal-location
  990. :version "26.1"
  991. :package-version '(Org . "9.0")
  992. :type '(choice
  993. (const :tag "Canonical" t)
  994. (const :tag "Minimal" nil)
  995. (repeat :greedy t :tag "Individual contexts"
  996. (cons
  997. (choice :tag "Context"
  998. (const agenda)
  999. (const org-goto)
  1000. (const occur-tree)
  1001. (const tags-tree)
  1002. (const link-search)
  1003. (const mark-goto)
  1004. (const bookmark-jump)
  1005. (const isearch)
  1006. (const default))
  1007. (choice :tag "Detail level"
  1008. (const minimal)
  1009. (const local)
  1010. (const ancestors)
  1011. (const lineage)
  1012. (const tree)
  1013. (const canonical))))))
  1014. (defcustom org-indirect-buffer-display 'other-window
  1015. "How should indirect tree buffers be displayed?
  1016. This applies to indirect buffers created with the commands
  1017. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1018. Valid values are:
  1019. current-window Display in the current window
  1020. other-window Just display in another window.
  1021. dedicated-frame Create one new frame, and re-use it each time.
  1022. new-frame Make a new frame each time. Note that in this case
  1023. previously-made indirect buffers are kept, and you need to
  1024. kill these buffers yourself."
  1025. :group 'org-structure
  1026. :group 'org-agenda-windows
  1027. :type '(choice
  1028. (const :tag "In current window" current-window)
  1029. (const :tag "In current frame, other window" other-window)
  1030. (const :tag "Each time a new frame" new-frame)
  1031. (const :tag "One dedicated frame" dedicated-frame)))
  1032. (defconst org-file-apps-gnu
  1033. '((remote . emacs)
  1034. (system . mailcap)
  1035. (t . mailcap))
  1036. "Default file applications on a UNIX or GNU/Linux system.
  1037. See `org-file-apps'.")
  1038. (defconst org-file-apps-macos
  1039. '((remote . emacs)
  1040. (system . "open %s")
  1041. ("ps.gz" . "gv %s")
  1042. ("eps.gz" . "gv %s")
  1043. ("dvi" . "xdvi %s")
  1044. ("fig" . "xfig %s")
  1045. (t . "open %s"))
  1046. "Default file applications on a macOS system.
  1047. The system \"open\" is known as a default, but we use X11 applications
  1048. for some files for which the OS does not have a good default.
  1049. See `org-file-apps'.")
  1050. (defconst org-file-apps-windowsnt
  1051. (list '(remote . emacs)
  1052. (cons 'system (lambda (file _path)
  1053. (with-no-warnings (w32-shell-execute "open" file))))
  1054. (cons t (lambda (file _path)
  1055. (with-no-warnings (w32-shell-execute "open" file)))))
  1056. "Default file applications on a Windows NT system.
  1057. The system \"open\" is used for most files.
  1058. See `org-file-apps'.")
  1059. (defcustom org-file-apps
  1060. '((auto-mode . emacs)
  1061. ("\\.mm\\'" . default)
  1062. ("\\.x?html?\\'" . default)
  1063. ("\\.pdf\\'" . default))
  1064. "External applications for opening `file:path' items in a document.
  1065. \\<org-mode-map>
  1066. Org mode uses system defaults for different file types, but
  1067. you can use this variable to set the application for a given file
  1068. extension. The entries in this list are cons cells where the car identifies
  1069. files and the cdr the corresponding command.
  1070. Possible values for the file identifier are:
  1071. \"string\" A string as a file identifier can be interpreted in different
  1072. ways, depending on its contents:
  1073. - Alphanumeric characters only:
  1074. Match links with this file extension.
  1075. Example: (\"pdf\" . \"evince %s\")
  1076. to open PDFs with evince.
  1077. - Regular expression: Match links where the
  1078. filename matches the regexp. If you want to
  1079. use groups here, use shy groups.
  1080. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1081. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1082. to open *.html and *.xhtml with firefox.
  1083. - Regular expression which contains (non-shy) groups:
  1084. Match links where the whole link, including \"::\", and
  1085. anything after that, matches the regexp.
  1086. In a custom command string, %1, %2, etc. are replaced with
  1087. the parts of the link that were matched by the groups.
  1088. For backwards compatibility, if a command string is given
  1089. that does not use any of the group matches, this case is
  1090. handled identically to the second one (i.e. match against
  1091. file name only).
  1092. In a custom function, you can access the group matches with
  1093. (match-string n link).
  1094. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1095. \"evince -p %1 %s\")
  1096. to open [[file:document.pdf::5]] with evince at page 5.
  1097. `directory' Matches a directory
  1098. `remote' Matches a remote file, accessible through tramp or efs.
  1099. Remote files most likely should be visited through Emacs
  1100. because external applications cannot handle such paths.
  1101. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1102. so all files Emacs knows how to handle. Using this with
  1103. command `emacs' will open most files in Emacs. Beware that this
  1104. will also open html files inside Emacs, unless you add
  1105. (\"html\" . default) to the list as well.
  1106. `system' The system command to open files, like `open' on Windows
  1107. and macOS, and mailcap under GNU/Linux. This is the command
  1108. that will be selected if you call `org-open-at-point' with a
  1109. double prefix argument (`\\[universal-argument] \
  1110. \\[universal-argument] \\[org-open-at-point]').
  1111. t Default for files not matched by any of the other options.
  1112. Possible values for the command are:
  1113. `emacs' The file will be visited by the current Emacs process.
  1114. `default' Use the default application for this file type, which is the
  1115. association for t in the list, most likely in the system-specific
  1116. part. This can be used to overrule an unwanted setting in the
  1117. system-specific variable.
  1118. `system' Use the system command for opening files, like \"open\".
  1119. This command is specified by the entry whose car is `system'.
  1120. Most likely, the system-specific version of this variable
  1121. does define this command, but you can overrule/replace it
  1122. here.
  1123. `mailcap' Use command specified in the mailcaps.
  1124. string A command to be executed by a shell; %s will be replaced
  1125. by the path to the file.
  1126. function A Lisp function, which will be called with two arguments:
  1127. the file path and the original link string, without the
  1128. \"file:\" prefix.
  1129. For more examples, see the system specific constants
  1130. `org-file-apps-macos'
  1131. `org-file-apps-windowsnt'
  1132. `org-file-apps-gnu'."
  1133. :group 'org
  1134. :type '(repeat
  1135. (cons (choice :value ""
  1136. (string :tag "Extension")
  1137. (const :tag "System command to open files" system)
  1138. (const :tag "Default for unrecognized files" t)
  1139. (const :tag "Remote file" remote)
  1140. (const :tag "Links to a directory" directory)
  1141. (const :tag "Any files that have Emacs modes"
  1142. auto-mode))
  1143. (choice :value ""
  1144. (const :tag "Visit with Emacs" emacs)
  1145. (const :tag "Use default" default)
  1146. (const :tag "Use the system command" system)
  1147. (string :tag "Command")
  1148. (function :tag "Function")))))
  1149. (defcustom org-open-non-existing-files nil
  1150. "Non-nil means `org-open-file' opens non-existing files.
  1151. When nil, an error is thrown.
  1152. This variable applies only to external applications because they
  1153. might choke on non-existing files. If the link is to a file that
  1154. will be opened in Emacs, the variable is ignored."
  1155. :group 'org
  1156. :type 'boolean
  1157. :safe #'booleanp)
  1158. (defcustom org-open-directory-means-index-dot-org nil
  1159. "When non-nil a link to a directory really means to \"index.org\".
  1160. When nil, following a directory link runs Dired or opens
  1161. a finder/explorer window on that directory."
  1162. :group 'org
  1163. :type 'boolean
  1164. :safe #'booleanp)
  1165. (defcustom org-bookmark-names-plist
  1166. '(:last-capture "org-capture-last-stored"
  1167. :last-refile "org-refile-last-stored"
  1168. :last-capture-marker "org-capture-last-stored-marker")
  1169. "Names for bookmarks automatically set by some Org commands.
  1170. This can provide strings as names for a number of bookmarks Org sets
  1171. automatically. The following keys are currently implemented:
  1172. :last-capture
  1173. :last-capture-marker
  1174. :last-refile
  1175. When a key does not show up in the property list, the corresponding bookmark
  1176. is not set."
  1177. :group 'org-structure
  1178. :type 'plist)
  1179. (defgroup org-cycle nil
  1180. "Options concerning visibility cycling in Org mode."
  1181. :tag "Org Cycle"
  1182. :group 'org-structure)
  1183. (defcustom org-cycle-skip-children-state-if-no-children t
  1184. "Non-nil means skip CHILDREN state in entries that don't have any."
  1185. :group 'org-cycle
  1186. :type 'boolean)
  1187. (defcustom org-cycle-max-level nil
  1188. "Maximum level which should still be subject to visibility cycling.
  1189. Levels higher than this will, for cycling, be treated as text, not a headline.
  1190. When `org-odd-levels-only' is set, a value of N in this variable actually
  1191. means 2N-1 stars as the limiting headline.
  1192. When nil, cycle all levels.
  1193. Note that the limiting level of cycling is also influenced by
  1194. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1195. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1196. than its value."
  1197. :group 'org-cycle
  1198. :type '(choice
  1199. (const :tag "No limit" nil)
  1200. (integer :tag "Maximum level")))
  1201. (defcustom org-hide-block-startup nil
  1202. "Non-nil means entering Org mode will fold all blocks.
  1203. This can also be set in on a per-file basis with
  1204. #+STARTUP: hideblocks
  1205. #+STARTUP: showblocks"
  1206. :group 'org-startup
  1207. :group 'org-cycle
  1208. :type 'boolean)
  1209. (defcustom org-cycle-global-at-bob nil
  1210. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1211. This makes it possible to do global cycling without having to use `S-TAB'
  1212. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1213. line of the buffer
  1214. must not be a headline -- it may be empty or some other text.
  1215. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1216. sure the cursor stays at the beginning of the buffer.
  1217. When this option is nil, don't do anything special at the beginning of
  1218. the buffer."
  1219. :group 'org-cycle
  1220. :type 'boolean)
  1221. (defcustom org-cycle-level-after-item/entry-creation t
  1222. "Non-nil means cycle entry level or item indentation in new empty entries.
  1223. When the cursor is at the end of an empty headline, i.e., with only stars
  1224. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1225. and then all possible ancestor states, before returning to the original state.
  1226. This makes data entry extremely fast: M-RET to create a new headline,
  1227. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1228. When the cursor is at the end of an empty plain list item, one TAB will
  1229. make it a subitem, two or more tabs will back up to make this an item
  1230. higher up in the item hierarchy."
  1231. :group 'org-cycle
  1232. :type 'boolean)
  1233. (defcustom org-cycle-emulate-tab t
  1234. "Where should `org-cycle' emulate TAB.
  1235. nil Never
  1236. white Only in completely white lines
  1237. whitestart Only at the beginning of lines, before the first non-white char
  1238. t Everywhere except in headlines
  1239. exc-hl-bol Everywhere except at the start of a headline
  1240. If TAB is used in a place where it does not emulate TAB, the current subtree
  1241. visibility is cycled."
  1242. :group 'org-cycle
  1243. :type '(choice (const :tag "Never" nil)
  1244. (const :tag "Only in completely white lines" white)
  1245. (const :tag "Before first char in a line" whitestart)
  1246. (const :tag "Everywhere except in headlines" t)
  1247. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1248. (defcustom org-cycle-separator-lines 2
  1249. "Number of empty lines needed to keep an empty line between collapsed trees.
  1250. If you leave an empty line between the end of a subtree and the following
  1251. headline, this empty line is hidden when the subtree is folded.
  1252. Org mode will leave (exactly) one empty line visible if the number of
  1253. empty lines is equal or larger to the number given in this variable.
  1254. So the default 2 means at least 2 empty lines after the end of a subtree
  1255. are needed to produce free space between a collapsed subtree and the
  1256. following headline.
  1257. If the number is negative, and the number of empty lines is at least -N,
  1258. all empty lines are shown.
  1259. Special case: when 0, never leave empty lines in collapsed view."
  1260. :group 'org-cycle
  1261. :type 'integer)
  1262. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1263. (defcustom org-pre-cycle-hook nil
  1264. "Hook that is run before visibility cycling is happening.
  1265. The function(s) in this hook must accept a single argument which indicates
  1266. the new state that will be set right after running this hook. The
  1267. argument is a symbol. Before a global state change, it can have the values
  1268. `overview', `content', or `all'. Before a local state change, it can have
  1269. the values `folded', `children', or `subtree'."
  1270. :group 'org-cycle
  1271. :type 'hook)
  1272. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1273. org-cycle-show-empty-lines
  1274. org-optimize-window-after-visibility-change)
  1275. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1276. The function(s) in this hook must accept a single argument which indicates
  1277. the new state that was set by the most recent `org-cycle' command. The
  1278. argument is a symbol. After a global state change, it can have the values
  1279. `overview', `contents', or `all'. After a local state change, it can have
  1280. the values `folded', `children', or `subtree'."
  1281. :group 'org-cycle
  1282. :type 'hook
  1283. :version "26.1"
  1284. :package-version '(Org . "8.3"))
  1285. (defgroup org-edit-structure nil
  1286. "Options concerning structure editing in Org mode."
  1287. :tag "Org Edit Structure"
  1288. :group 'org-structure)
  1289. (defcustom org-odd-levels-only nil
  1290. "Non-nil means skip even levels and only use odd levels for the outline.
  1291. This has the effect that two stars are being added/taken away in
  1292. promotion/demotion commands. It also influences how levels are
  1293. handled by the exporters.
  1294. Changing it requires restart of `font-lock-mode' to become effective
  1295. for fontification also in regions already fontified.
  1296. You may also set this on a per-file basis by adding one of the following
  1297. lines to the buffer:
  1298. #+STARTUP: odd
  1299. #+STARTUP: oddeven"
  1300. :group 'org-edit-structure
  1301. :group 'org-appearance
  1302. :type 'boolean)
  1303. (defcustom org-adapt-indentation t
  1304. "Non-nil means adapt indentation to outline node level.
  1305. When this variable is set, Org assumes that you write outlines by
  1306. indenting text in each node to align with the headline (after the
  1307. stars). The following issues are influenced by this variable:
  1308. - The indentation is increased by one space in a demotion
  1309. command, and decreased by one in a promotion command. However,
  1310. in the latter case, if shifting some line in the entry body
  1311. would alter document structure (e.g., insert a new headline),
  1312. indentation is not changed at all.
  1313. - Property drawers and planning information is inserted indented
  1314. when this variable is set. When nil, they will not be indented.
  1315. - TAB indents a line relative to current level. The lines below
  1316. a headline will be indented when this variable is set.
  1317. Note that this is all about true indentation, by adding and
  1318. removing space characters. See also \"org-indent.el\" which does
  1319. level-dependent indentation in a virtual way, i.e. at display
  1320. time in Emacs."
  1321. :group 'org-edit-structure
  1322. :type 'boolean
  1323. :safe #'booleanp)
  1324. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1325. (defcustom org-special-ctrl-a/e nil
  1326. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1327. When t, `C-a' will bring back the cursor to the beginning of the
  1328. headline text, i.e. after the stars and after a possible TODO
  1329. keyword. In an item, this will be the position after bullet and
  1330. check-box, if any. When the cursor is already at that position,
  1331. another `C-a' will bring it to the beginning of the line.
  1332. `C-e' will jump to the end of the headline, ignoring the presence
  1333. of tags in the headline. A second `C-e' will then jump to the
  1334. true end of the line, after any tags. This also means that, when
  1335. this variable is non-nil, `C-e' also will never jump beyond the
  1336. end of the heading of a folded section, i.e. not after the
  1337. ellipses.
  1338. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1339. normally, going to the true line boundary first. Only a directly
  1340. following, identical keypress will bring the cursor to the
  1341. special positions.
  1342. This may also be a cons cell where the behavior for `C-a' and
  1343. `C-e' is set separately."
  1344. :group 'org-edit-structure
  1345. :type '(choice
  1346. (const :tag "off" nil)
  1347. (const :tag "on: after stars/bullet and before tags first" t)
  1348. (const :tag "reversed: true line boundary first" reversed)
  1349. (cons :tag "Set C-a and C-e separately"
  1350. (choice :tag "Special C-a"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: after stars/bullet first" t)
  1353. (const :tag "reversed: before stars/bullet first" reversed))
  1354. (choice :tag "Special C-e"
  1355. (const :tag "off" nil)
  1356. (const :tag "on: before tags first" t)
  1357. (const :tag "reversed: after tags first" reversed)))))
  1358. (defcustom org-special-ctrl-k nil
  1359. "Non-nil means `C-k' will behave specially in headlines.
  1360. When nil, `C-k' will call the default `kill-line' command.
  1361. When t, the following will happen while the cursor is in the headline:
  1362. - When the cursor is at the beginning of a headline, kill the entire
  1363. line and possibly the folded subtree below the line.
  1364. - When in the middle of the headline text, kill the headline up to the tags.
  1365. - When after the headline text, kill the tags."
  1366. :group 'org-edit-structure
  1367. :type 'boolean)
  1368. (defcustom org-ctrl-k-protect-subtree nil
  1369. "Non-nil means, do not delete a hidden subtree with C-k.
  1370. When set to the symbol `error', simply throw an error when C-k is
  1371. used to kill (part-of) a headline that has hidden text behind it.
  1372. Any other non-nil value will result in a query to the user, if it is
  1373. OK to kill that hidden subtree. When nil, kill without remorse."
  1374. :group 'org-edit-structure
  1375. :version "24.1"
  1376. :type '(choice
  1377. (const :tag "Do not protect hidden subtrees" nil)
  1378. (const :tag "Protect hidden subtrees with a security query" t)
  1379. (const :tag "Never kill a hidden subtree with C-k" error)))
  1380. (defcustom org-special-ctrl-o t
  1381. "Non-nil means, make `C-o' insert a row in tables."
  1382. :group 'org-edit-structure
  1383. :type 'boolean)
  1384. (defcustom org-catch-invisible-edits nil
  1385. "Check if in invisible region before inserting or deleting a character.
  1386. Valid values are:
  1387. nil Do not check, so just do invisible edits.
  1388. error Throw an error and do nothing.
  1389. show Make point visible, and do the requested edit.
  1390. show-and-error Make point visible, then throw an error and abort the edit.
  1391. smart Make point visible, and do insertion/deletion if it is
  1392. adjacent to visible text and the change feels predictable.
  1393. Never delete a previously invisible character or add in the
  1394. middle or right after an invisible region. Basically, this
  1395. allows insertion and backward-delete right before ellipses.
  1396. FIXME: maybe in this case we should not even show?"
  1397. :group 'org-edit-structure
  1398. :version "24.1"
  1399. :type '(choice
  1400. (const :tag "Do not check" nil)
  1401. (const :tag "Throw error when trying to edit" error)
  1402. (const :tag "Unhide, but do not do the edit" show-and-error)
  1403. (const :tag "Show invisible part and do the edit" show)
  1404. (const :tag "Be smart and do the right thing" smart)))
  1405. (defcustom org-yank-folded-subtrees t
  1406. "Non-nil means when yanking subtrees, fold them.
  1407. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1408. it starts with a heading and all other headings in it are either children
  1409. or siblings, then fold all the subtrees. However, do this only if no
  1410. text after the yank would be swallowed into a folded tree by this action."
  1411. :group 'org-edit-structure
  1412. :type 'boolean)
  1413. (defcustom org-yank-adjusted-subtrees nil
  1414. "Non-nil means when yanking subtrees, adjust the level.
  1415. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1416. this function for details."
  1417. :group 'org-edit-structure
  1418. :type 'boolean)
  1419. (defcustom org-M-RET-may-split-line '((default . t))
  1420. "Non-nil means M-RET will split the line at the cursor position.
  1421. When nil, it will go to the end of the line before making a
  1422. new line.
  1423. You may also set this option in a different way for different
  1424. contexts. Valid contexts are:
  1425. headline when creating a new headline
  1426. item when creating a new item
  1427. table in a table field
  1428. default the value to be used for all contexts not explicitly
  1429. customized"
  1430. :group 'org-structure
  1431. :group 'org-table
  1432. :type '(choice
  1433. (const :tag "Always" t)
  1434. (const :tag "Never" nil)
  1435. (repeat :greedy t :tag "Individual contexts"
  1436. (cons
  1437. (choice :tag "Context"
  1438. (const headline)
  1439. (const item)
  1440. (const table)
  1441. (const default))
  1442. (boolean)))))
  1443. (defcustom org-insert-heading-respect-content nil
  1444. "Non-nil means insert new headings after the current subtree.
  1445. \\<org-mode-map>
  1446. When nil, the new heading is created directly after the current line.
  1447. The commands `\\[org-insert-heading-respect-content]' and \
  1448. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1449. for the duration of the command."
  1450. :group 'org-structure
  1451. :type 'boolean)
  1452. (defcustom org-blank-before-new-entry '((heading . auto)
  1453. (plain-list-item . auto))
  1454. "Should `org-insert-heading' leave a blank line before new heading/item?
  1455. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1456. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1457. which case Org will look at the surrounding headings/items and try to
  1458. make an intelligent decision whether to insert a blank line or not."
  1459. :group 'org-edit-structure
  1460. :type '(list
  1461. (cons (const heading)
  1462. (choice (const :tag "Never" nil)
  1463. (const :tag "Always" t)
  1464. (const :tag "Auto" auto)))
  1465. (cons (const plain-list-item)
  1466. (choice (const :tag "Never" nil)
  1467. (const :tag "Always" t)
  1468. (const :tag "Auto" auto)))))
  1469. (defcustom org-insert-heading-hook nil
  1470. "Hook being run after inserting a new heading."
  1471. :group 'org-edit-structure
  1472. :type 'hook)
  1473. (defgroup org-sparse-trees nil
  1474. "Options concerning sparse trees in Org mode."
  1475. :tag "Org Sparse Trees"
  1476. :group 'org-structure)
  1477. (defcustom org-highlight-sparse-tree-matches t
  1478. "Non-nil means highlight all matches that define a sparse tree.
  1479. The highlights will automatically disappear the next time the buffer is
  1480. changed by an edit command."
  1481. :group 'org-sparse-trees
  1482. :type 'boolean)
  1483. (defcustom org-remove-highlights-with-change t
  1484. "Non-nil means any change to the buffer will remove temporary highlights.
  1485. \\<org-mode-map>\
  1486. Such highlights are created by `org-occur' and `org-clock-display'.
  1487. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1488. to get rid of the highlights.
  1489. The highlights created by `org-latex-preview' always need
  1490. `\\[org-latex-preview]' to be removed."
  1491. :group 'org-sparse-trees
  1492. :group 'org-time
  1493. :type 'boolean)
  1494. (defcustom org-occur-case-fold-search t
  1495. "Non-nil means `org-occur' should be case-insensitive.
  1496. If set to `smart' the search will be case-insensitive only if it
  1497. doesn't specify any upper case character."
  1498. :group 'org-sparse-trees
  1499. :version "26.1"
  1500. :type '(choice
  1501. (const :tag "Case-sensitive" nil)
  1502. (const :tag "Case-insensitive" t)
  1503. (const :tag "Case-insensitive for lower case searches only" smart)))
  1504. (defcustom org-occur-hook '(org-first-headline-recenter)
  1505. "Hook that is run after `org-occur' has constructed a sparse tree.
  1506. This can be used to recenter the window to show as much of the structure
  1507. as possible."
  1508. :group 'org-sparse-trees
  1509. :type 'hook)
  1510. (defcustom org-self-insert-cluster-for-undo nil
  1511. "Non-nil means cluster self-insert commands for undo when possible.
  1512. If this is set, then, like in the Emacs command loop, 20 consecutive
  1513. characters will be undone together.
  1514. This is configurable, because there is some impact on typing performance."
  1515. :group 'org-table
  1516. :type 'boolean)
  1517. (defvaralias 'org-activate-links 'org-highlight-links)
  1518. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1519. "Types of links that should be highlighted in Org files.
  1520. This is a list of symbols, each one of them leading to the
  1521. highlighting of a certain link type.
  1522. You can still open links that are not highlighted.
  1523. In principle, it does not hurt to turn on highlighting for all
  1524. link types. There may be a small gain when turning off unused
  1525. link types. The types are:
  1526. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1527. angle Links in angular brackets that may contain whitespace like
  1528. <bbdb:Carsten Dominik>.
  1529. plain Plain links in normal text, no whitespace, like http://google.com.
  1530. radio Text that is matched by a radio target, see manual for details.
  1531. tag Tag settings in a headline (link to tag search).
  1532. date Time stamps (link to calendar).
  1533. footnote Footnote labels.
  1534. If you set this variable during an Emacs session, use `org-mode-restart'
  1535. in the Org buffer so that the change takes effect."
  1536. :group 'org-appearance
  1537. :type '(set :greedy t
  1538. (const :tag "Double bracket links" bracket)
  1539. (const :tag "Angular bracket links" angle)
  1540. (const :tag "Plain text links" plain)
  1541. (const :tag "Radio target matches" radio)
  1542. (const :tag "Tags" tag)
  1543. (const :tag "Timestamps" date)
  1544. (const :tag "Footnotes" footnote)))
  1545. (defcustom org-mark-ring-length 4
  1546. "Number of different positions to be recorded in the ring.
  1547. Changing this requires a restart of Emacs to work correctly."
  1548. :group 'org-link-follow
  1549. :type 'integer)
  1550. (defgroup org-refile nil
  1551. "Options concerning refiling entries in Org mode."
  1552. :tag "Org Refile"
  1553. :group 'org)
  1554. (defcustom org-directory "~/org"
  1555. "Directory with Org files.
  1556. This is just a default location to look for Org files. There is no need
  1557. at all to put your files into this directory. It is used in the
  1558. following situations:
  1559. 1. When a capture template specifies a target file that is not an
  1560. absolute path. The path will then be interpreted relative to
  1561. `org-directory'
  1562. 2. When the value of variable `org-agenda-files' is a single file, any
  1563. relative paths in this file will be taken as relative to
  1564. `org-directory'."
  1565. :group 'org-refile
  1566. :group 'org-capture
  1567. :type 'directory)
  1568. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1569. "Default target for storing notes.
  1570. Used as a fall back file for org-capture.el, for templates that
  1571. do not specify a target file."
  1572. :group 'org-refile
  1573. :group 'org-capture
  1574. :type 'file)
  1575. (defcustom org-reverse-note-order nil
  1576. "Non-nil means store new notes at the beginning of a file or entry.
  1577. When nil, new notes will be filed to the end of a file or entry.
  1578. This can also be a list with cons cells of regular expressions that
  1579. are matched against file names, and values."
  1580. :group 'org-capture
  1581. :group 'org-refile
  1582. :type '(choice
  1583. (const :tag "Reverse always" t)
  1584. (const :tag "Reverse never" nil)
  1585. (repeat :tag "By file name regexp"
  1586. (cons regexp boolean))))
  1587. (defcustom org-log-refile nil
  1588. "Information to record when a task is refiled.
  1589. Possible values are:
  1590. nil Don't add anything
  1591. time Add a time stamp to the task
  1592. note Prompt for a note and add it with template `org-log-note-headings'
  1593. This option can also be set with on a per-file-basis with
  1594. #+STARTUP: nologrefile
  1595. #+STARTUP: logrefile
  1596. #+STARTUP: lognoterefile
  1597. You can have local logging settings for a subtree by setting the LOGGING
  1598. property to one or more of these keywords.
  1599. When bulk-refiling, e.g., from the agenda, the value `note' is
  1600. forbidden and will temporarily be changed to `time'."
  1601. :group 'org-refile
  1602. :group 'org-progress
  1603. :version "24.1"
  1604. :type '(choice
  1605. (const :tag "No logging" nil)
  1606. (const :tag "Record timestamp" time)
  1607. (const :tag "Record timestamp with note." note)))
  1608. (defcustom org-refile-targets nil
  1609. "Targets for refiling entries with `\\[org-refile]'.
  1610. This is a list of cons cells. Each cell contains:
  1611. - a specification of the files to be considered, either a list of files,
  1612. or a symbol whose function or variable value will be used to retrieve
  1613. a file name or a list of file names. If you use `org-agenda-files' for
  1614. that, all agenda files will be scanned for targets. Nil means consider
  1615. headings in the current buffer.
  1616. - A specification of how to find candidate refile targets. This may be
  1617. any of:
  1618. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1619. This tag has to be present in all target headlines, inheritance will
  1620. not be considered.
  1621. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1622. todo keyword.
  1623. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1624. headlines that are refiling targets.
  1625. - a cons cell (:level . N). Any headline of level N is considered a target.
  1626. Note that, when `org-odd-levels-only' is set, level corresponds to
  1627. order in hierarchy, not to the number of stars.
  1628. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1629. Note that, when `org-odd-levels-only' is set, level corresponds to
  1630. order in hierarchy, not to the number of stars.
  1631. Each element of this list generates a set of possible targets.
  1632. The union of these sets is presented (with completion) to
  1633. the user by `org-refile'.
  1634. You can set the variable `org-refile-target-verify-function' to a function
  1635. to verify each headline found by the simple criteria above.
  1636. When this variable is nil, all top-level headlines in the current buffer
  1637. are used, equivalent to the value `((nil . (:level . 1))'."
  1638. :group 'org-refile
  1639. :type '(repeat
  1640. (cons
  1641. (choice :value org-agenda-files
  1642. (const :tag "All agenda files" org-agenda-files)
  1643. (const :tag "Current buffer" nil)
  1644. (function) (variable) (file))
  1645. (choice :tag "Identify target headline by"
  1646. (cons :tag "Specific tag" (const :value :tag) (string))
  1647. (cons :tag "TODO keyword" (const :value :todo) (string))
  1648. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1649. (cons :tag "Level number" (const :value :level) (integer))
  1650. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1651. (defcustom org-refile-target-verify-function nil
  1652. "Function to verify if the headline at point should be a refile target.
  1653. The function will be called without arguments, with point at the
  1654. beginning of the headline. It should return t and leave point
  1655. where it is if the headline is a valid target for refiling.
  1656. If the target should not be selected, the function must return nil.
  1657. In addition to this, it may move point to a place from where the search
  1658. should be continued. For example, the function may decide that the entire
  1659. subtree of the current entry should be excluded and move point to the end
  1660. of the subtree."
  1661. :group 'org-refile
  1662. :type '(choice
  1663. (const nil)
  1664. (function)))
  1665. (defcustom org-refile-use-cache nil
  1666. "Non-nil means cache refile targets to speed up the process.
  1667. \\<org-mode-map>\
  1668. The cache for a particular file will be updated automatically when
  1669. the buffer has been killed, or when any of the marker used for flagging
  1670. refile targets no longer points at a live buffer.
  1671. If you have added new entries to a buffer that might themselves be targets,
  1672. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1673. if you find that easier, \
  1674. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1675. \\[org-refile]'."
  1676. :group 'org-refile
  1677. :version "24.1"
  1678. :type 'boolean)
  1679. (defcustom org-refile-use-outline-path nil
  1680. "Non-nil means provide refile targets as paths.
  1681. So a level 3 headline will be available as level1/level2/level3.
  1682. When the value is `file', also include the file name (without directory)
  1683. into the path. In this case, you can also stop the completion after
  1684. the file name, to get entries inserted as top level in the file.
  1685. When `full-file-path', include the full file path.
  1686. When `buffer-name', use the buffer name."
  1687. :group 'org-refile
  1688. :type '(choice
  1689. (const :tag "Not" nil)
  1690. (const :tag "Yes" t)
  1691. (const :tag "Start with file name" file)
  1692. (const :tag "Start with full file path" full-file-path)
  1693. (const :tag "Start with buffer name" buffer-name)))
  1694. (defcustom org-outline-path-complete-in-steps t
  1695. "Non-nil means complete the outline path in hierarchical steps.
  1696. When Org uses the refile interface to select an outline path (see
  1697. `org-refile-use-outline-path'), the completion of the path can be
  1698. done in a single go, or it can be done in steps down the headline
  1699. hierarchy. Going in steps is probably the best if you do not use
  1700. a special completion package like `ido' or `icicles'. However,
  1701. when using these packages, going in one step can be very fast,
  1702. while still showing the whole path to the entry."
  1703. :group 'org-refile
  1704. :type 'boolean)
  1705. (defcustom org-refile-allow-creating-parent-nodes nil
  1706. "Non-nil means allow the creation of new nodes as refile targets.
  1707. New nodes are then created by adding \"/new node name\" to the completion
  1708. of an existing node. When the value of this variable is `confirm',
  1709. new node creation must be confirmed by the user (recommended).
  1710. When nil, the completion must match an existing entry.
  1711. Note that, if the new heading is not seen by the criteria
  1712. listed in `org-refile-targets', multiple instances of the same
  1713. heading would be created by trying again to file under the new
  1714. heading."
  1715. :group 'org-refile
  1716. :type '(choice
  1717. (const :tag "Never" nil)
  1718. (const :tag "Always" t)
  1719. (const :tag "Prompt for confirmation" confirm)))
  1720. (defcustom org-refile-active-region-within-subtree nil
  1721. "Non-nil means also refile active region within a subtree.
  1722. By default `org-refile' doesn't allow refiling regions if they
  1723. don't contain a set of subtrees, but it might be convenient to
  1724. do so sometimes: in that case, the first line of the region is
  1725. converted to a headline before refiling."
  1726. :group 'org-refile
  1727. :version "24.1"
  1728. :type 'boolean)
  1729. (defgroup org-todo nil
  1730. "Options concerning TODO items in Org mode."
  1731. :tag "Org TODO"
  1732. :group 'org)
  1733. (defgroup org-progress nil
  1734. "Options concerning Progress logging in Org mode."
  1735. :tag "Org Progress"
  1736. :group 'org-time)
  1737. (defvar org-todo-interpretation-widgets
  1738. '((:tag "Sequence (cycling hits every state)" sequence)
  1739. (:tag "Type (cycling directly to DONE)" type))
  1740. "The available interpretation symbols for customizing `org-todo-keywords'.
  1741. Interested libraries should add to this list.")
  1742. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1743. "List of TODO entry keyword sequences and their interpretation.
  1744. \\<org-mode-map>This is a list of sequences.
  1745. Each sequence starts with a symbol, either `sequence' or `type',
  1746. indicating if the keywords should be interpreted as a sequence of
  1747. action steps, or as different types of TODO items. The first
  1748. keywords are states requiring action - these states will select a headline
  1749. for inclusion into the global TODO list Org produces. If one of the
  1750. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1751. signify that no further action is necessary. If \"|\" is not found,
  1752. the last keyword is treated as the only DONE state of the sequence.
  1753. The command `\\[org-todo]' cycles an entry through these states, and one
  1754. additional state where no keyword is present. For details about this
  1755. cycling, see the manual.
  1756. TODO keywords and interpretation can also be set on a per-file basis with
  1757. the special #+SEQ_TODO and #+TYP_TODO lines.
  1758. Each keyword can optionally specify a character for fast state selection
  1759. \(in combination with the variable `org-use-fast-todo-selection')
  1760. and specifiers for state change logging, using the same syntax that
  1761. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1762. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1763. indicates to record a time stamp each time this state is selected.
  1764. Each keyword may also specify if a timestamp or a note should be
  1765. recorded when entering or leaving the state, by adding additional
  1766. characters in the parenthesis after the keyword. This looks like this:
  1767. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1768. record only the time of the state change. With X and Y being either
  1769. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1770. Y when leaving the state if and only if the *target* state does not
  1771. define X. You may omit any of the fast-selection key or X or /Y,
  1772. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1773. For backward compatibility, this variable may also be just a list
  1774. of keywords. In this case the interpretation (sequence or type) will be
  1775. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1776. :group 'org-todo
  1777. :group 'org-keywords
  1778. :type '(choice
  1779. (repeat :tag "Old syntax, just keywords"
  1780. (string :tag "Keyword"))
  1781. (repeat :tag "New syntax"
  1782. (cons
  1783. (choice
  1784. :tag "Interpretation"
  1785. ;;Quick and dirty way to see
  1786. ;;`org-todo-interpretations'. This takes the
  1787. ;;place of item arguments
  1788. :convert-widget
  1789. (lambda (widget)
  1790. (widget-put widget
  1791. :args (mapcar
  1792. (lambda (x)
  1793. (widget-convert
  1794. (cons 'const x)))
  1795. org-todo-interpretation-widgets))
  1796. widget))
  1797. (repeat
  1798. (string :tag "Keyword"))))))
  1799. (defvar-local org-todo-keywords-1 nil
  1800. "All TODO and DONE keywords active in a buffer.")
  1801. (defvar org-todo-keywords-for-agenda nil)
  1802. (defvar org-done-keywords-for-agenda nil)
  1803. (defvar org-todo-keyword-alist-for-agenda nil)
  1804. (defvar org-tag-alist-for-agenda nil
  1805. "Alist of all tags from all agenda files.")
  1806. (defvar org-tag-groups-alist-for-agenda nil
  1807. "Alist of all groups tags from all current agenda files.")
  1808. (defvar-local org-tag-groups-alist nil)
  1809. (defvar org-agenda-contributing-files nil)
  1810. (defvar-local org-current-tag-alist nil
  1811. "Alist of all tag groups in current buffer.
  1812. This variable takes into consideration `org-tag-alist',
  1813. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1814. (defvar-local org-not-done-keywords nil)
  1815. (defvar-local org-done-keywords nil)
  1816. (defvar-local org-todo-heads nil)
  1817. (defvar-local org-todo-sets nil)
  1818. (defvar-local org-todo-log-states nil)
  1819. (defvar-local org-todo-kwd-alist nil)
  1820. (defvar-local org-todo-key-alist nil)
  1821. (defvar-local org-todo-key-trigger nil)
  1822. (defcustom org-todo-interpretation 'sequence
  1823. "Controls how TODO keywords are interpreted.
  1824. This variable is in principle obsolete and is only used for
  1825. backward compatibility, if the interpretation of todo keywords is
  1826. not given already in `org-todo-keywords'. See that variable for
  1827. more information."
  1828. :group 'org-todo
  1829. :group 'org-keywords
  1830. :type '(choice (const sequence)
  1831. (const type)))
  1832. (defcustom org-use-fast-todo-selection 'auto
  1833. "\\<org-mode-map>\
  1834. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1835. This variable describes if and under what circumstances the cycling
  1836. mechanism for TODO keywords will be replaced by a single-key, direct
  1837. selection scheme, where the choices are displayed in a little window.
  1838. When nil, fast selection is never used. This means that the command
  1839. will always switch to the next state.
  1840. When it is the symbol `auto', fast selection is whenever selection
  1841. keys have been defined.
  1842. `expert' is like `auto', but no special window with the keyword
  1843. will be shown, choices will only be listed in the prompt.
  1844. In all cases, the special interface is only used if access keys have
  1845. actually been assigned by the user, i.e. if keywords in the configuration
  1846. are followed by a letter in parenthesis, like TODO(t)."
  1847. :group 'org-todo
  1848. :set (lambda (var val)
  1849. (cond
  1850. ((eq var t) (set var 'auto))
  1851. ((eq var 'prefix) (set var nil))
  1852. (t (set var val))))
  1853. :type '(choice
  1854. (const :tag "Never" nil)
  1855. (const :tag "Automatically, when key letter have been defined" auto)
  1856. (const :tag "Automatically, but don't show the selection window" expert)))
  1857. (defcustom org-provide-todo-statistics t
  1858. "Non-nil means update todo statistics after insert and toggle.
  1859. ALL-HEADLINES means update todo statistics by including headlines
  1860. with no TODO keyword as well, counting them as not done.
  1861. A list of TODO keywords means the same, but skip keywords that are
  1862. not in this list.
  1863. When set to a list of two lists, the first list contains keywords
  1864. to consider as TODO keywords, the second list contains keywords
  1865. to consider as DONE keywords.
  1866. When this is set, todo statistics is updated in the parent of the
  1867. current entry each time a todo state is changed."
  1868. :group 'org-todo
  1869. :type '(choice
  1870. (const :tag "Yes, only for TODO entries" t)
  1871. (const :tag "Yes, including all entries" all-headlines)
  1872. (repeat :tag "Yes, for TODOs in this list"
  1873. (string :tag "TODO keyword"))
  1874. (list :tag "Yes, for TODOs and DONEs in these lists"
  1875. (repeat (string :tag "TODO keyword"))
  1876. (repeat (string :tag "DONE keyword")))
  1877. (other :tag "No TODO statistics" nil)))
  1878. (defcustom org-hierarchical-todo-statistics t
  1879. "Non-nil means TODO statistics covers just direct children.
  1880. When nil, all entries in the subtree are considered.
  1881. This has only an effect if `org-provide-todo-statistics' is set.
  1882. To set this to nil for only a single subtree, use a COOKIE_DATA
  1883. property and include the word \"recursive\" into the value."
  1884. :group 'org-todo
  1885. :type 'boolean)
  1886. (defcustom org-after-todo-state-change-hook nil
  1887. "Hook which is run after the state of a TODO item was changed.
  1888. The new state (a string with a TODO keyword, or nil) is available in the
  1889. Lisp variable `org-state'."
  1890. :group 'org-todo
  1891. :type 'hook)
  1892. (defvar org-blocker-hook nil
  1893. "Hook for functions that are allowed to block a state change.
  1894. Functions in this hook should not modify the buffer.
  1895. Each function gets as its single argument a property list,
  1896. see `org-trigger-hook' for more information about this list.
  1897. If any of the functions in this hook returns nil, the state change
  1898. is blocked.")
  1899. (defvar org-trigger-hook nil
  1900. "Hook for functions that are triggered by a state change.
  1901. Each function gets as its single argument a property list with at
  1902. least the following elements:
  1903. (:type type-of-change :position pos-at-entry-start
  1904. :from old-state :to new-state)
  1905. Depending on the type, more properties may be present.
  1906. This mechanism is currently implemented for:
  1907. TODO state changes
  1908. ------------------
  1909. :type todo-state-change
  1910. :from previous state (keyword as a string), or nil, or a symbol
  1911. `todo' or `done', to indicate the general type of state.
  1912. :to new state, like in :from")
  1913. (defcustom org-enforce-todo-dependencies nil
  1914. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1915. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1916. be blocked if any prior sibling is not yet done.
  1917. Finally, if the parent is blocked because of ordered siblings of its own,
  1918. the child will also be blocked."
  1919. :set (lambda (var val)
  1920. (set var val)
  1921. (if val
  1922. (add-hook 'org-blocker-hook
  1923. 'org-block-todo-from-children-or-siblings-or-parent)
  1924. (remove-hook 'org-blocker-hook
  1925. 'org-block-todo-from-children-or-siblings-or-parent)))
  1926. :group 'org-todo
  1927. :type 'boolean)
  1928. (defcustom org-enforce-todo-checkbox-dependencies nil
  1929. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1930. When this is nil, checkboxes have no influence on switching TODO states.
  1931. When non-nil, you first need to check off all check boxes before the TODO
  1932. entry can be switched to DONE.
  1933. This variable needs to be set before org.el is loaded, and you need to
  1934. restart Emacs after a change to make the change effective. The only way
  1935. to change it while Emacs is running is through the customize interface."
  1936. :set (lambda (var val)
  1937. (set var val)
  1938. (if val
  1939. (add-hook 'org-blocker-hook
  1940. 'org-block-todo-from-checkboxes)
  1941. (remove-hook 'org-blocker-hook
  1942. 'org-block-todo-from-checkboxes)))
  1943. :group 'org-todo
  1944. :type 'boolean)
  1945. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1946. "Non-nil means inserting a TODO heading is treated as state change.
  1947. So when the command `\\[org-insert-todo-heading]' is used, state change
  1948. logging will apply if appropriate. When nil, the new TODO item will
  1949. be inserted directly, and no logging will take place."
  1950. :group 'org-todo
  1951. :type 'boolean)
  1952. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1953. "Non-nil means switching TODO states with S-cursor counts as state change.
  1954. This is the default behavior. However, setting this to nil allows a
  1955. convenient way to select a TODO state and bypass any logging associated
  1956. with that."
  1957. :group 'org-todo
  1958. :type 'boolean)
  1959. (defcustom org-todo-state-tags-triggers nil
  1960. "Tag changes that should be triggered by TODO state changes.
  1961. This is a list. Each entry is
  1962. (state-change (tag . flag) .......)
  1963. State-change can be a string with a state, and empty string to indicate the
  1964. state that has no TODO keyword, or it can be one of the symbols `todo'
  1965. or `done', meaning any not-done or done state, respectively."
  1966. :group 'org-todo
  1967. :group 'org-tags
  1968. :type '(repeat
  1969. (cons (choice :tag "When changing to"
  1970. (const :tag "Not-done state" todo)
  1971. (const :tag "Done state" done)
  1972. (string :tag "State"))
  1973. (repeat
  1974. (cons :tag "Tag action"
  1975. (string :tag "Tag")
  1976. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1977. (defcustom org-log-done nil
  1978. "Information to record when a task moves to the DONE state.
  1979. Possible values are:
  1980. nil Don't add anything, just change the keyword
  1981. time Add a time stamp to the task
  1982. note Prompt for a note and add it with template `org-log-note-headings'
  1983. This option can also be set with on a per-file-basis with
  1984. #+STARTUP: nologdone
  1985. #+STARTUP: logdone
  1986. #+STARTUP: lognotedone
  1987. You can have local logging settings for a subtree by setting the LOGGING
  1988. property to one or more of these keywords."
  1989. :group 'org-todo
  1990. :group 'org-progress
  1991. :type '(choice
  1992. (const :tag "No logging" nil)
  1993. (const :tag "Record CLOSED timestamp" time)
  1994. (const :tag "Record CLOSED timestamp with note." note)))
  1995. ;; Normalize old uses of org-log-done.
  1996. (cond
  1997. ((eq org-log-done t) (setq org-log-done 'time))
  1998. ((and (listp org-log-done) (memq 'done org-log-done))
  1999. (setq org-log-done 'note)))
  2000. (defcustom org-log-reschedule nil
  2001. "Information to record when the scheduling date of a task is modified.
  2002. Possible values are:
  2003. nil Don't add anything, just change the date
  2004. time Add a time stamp to the task
  2005. note Prompt for a note and add it with template `org-log-note-headings'
  2006. This option can also be set with on a per-file-basis with
  2007. #+STARTUP: nologreschedule
  2008. #+STARTUP: logreschedule
  2009. #+STARTUP: lognotereschedule
  2010. You can have local logging settings for a subtree by setting the LOGGING
  2011. property to one or more of these keywords.
  2012. This variable has an effect when calling `org-schedule' or
  2013. `org-agenda-schedule' only."
  2014. :group 'org-todo
  2015. :group 'org-progress
  2016. :type '(choice
  2017. (const :tag "No logging" nil)
  2018. (const :tag "Record timestamp" time)
  2019. (const :tag "Record timestamp with note" note)))
  2020. (defcustom org-log-redeadline nil
  2021. "Information to record when the deadline date of a task is modified.
  2022. Possible values are:
  2023. nil Don't add anything, just change the date
  2024. time Add a time stamp to the task
  2025. note Prompt for a note and add it with template `org-log-note-headings'
  2026. This option can also be set with on a per-file-basis with
  2027. #+STARTUP: nologredeadline
  2028. #+STARTUP: logredeadline
  2029. #+STARTUP: lognoteredeadline
  2030. You can have local logging settings for a subtree by setting the LOGGING
  2031. property to one or more of these keywords.
  2032. This variable has an effect when calling `org-deadline' or
  2033. `org-agenda-deadline' only."
  2034. :group 'org-todo
  2035. :group 'org-progress
  2036. :type '(choice
  2037. (const :tag "No logging" nil)
  2038. (const :tag "Record timestamp" time)
  2039. (const :tag "Record timestamp with note." note)))
  2040. (defcustom org-log-note-clock-out nil
  2041. "Non-nil means record a note when clocking out of an item.
  2042. This can also be configured on a per-file basis by adding one of
  2043. the following lines anywhere in the buffer:
  2044. #+STARTUP: lognoteclock-out
  2045. #+STARTUP: nolognoteclock-out"
  2046. :group 'org-todo
  2047. :group 'org-progress
  2048. :type 'boolean)
  2049. (defcustom org-log-done-with-time t
  2050. "Non-nil means the CLOSED time stamp will contain date and time.
  2051. When nil, only the date will be recorded."
  2052. :group 'org-progress
  2053. :type 'boolean)
  2054. (defcustom org-log-note-headings
  2055. '((done . "CLOSING NOTE %t")
  2056. (state . "State %-12s from %-12S %t")
  2057. (note . "Note taken on %t")
  2058. (reschedule . "Rescheduled from %S on %t")
  2059. (delschedule . "Not scheduled, was %S on %t")
  2060. (redeadline . "New deadline from %S on %t")
  2061. (deldeadline . "Removed deadline, was %S on %t")
  2062. (refile . "Refiled on %t")
  2063. (clock-out . ""))
  2064. "Headings for notes added to entries.
  2065. The value is an alist, with the car being a symbol indicating the
  2066. note context, and the cdr is the heading to be used. The heading
  2067. may also be the empty string. The following placeholders can be
  2068. used:
  2069. %t a time stamp.
  2070. %T an active time stamp instead the default inactive one
  2071. %d a short-format time stamp.
  2072. %D an active short-format time stamp.
  2073. %s the new TODO state or time stamp (inactive), in double quotes.
  2074. %S the old TODO state or time stamp (inactive), in double quotes.
  2075. %u the user name.
  2076. %U full user name.
  2077. In fact, it is not a good idea to change the `state' entry,
  2078. because Agenda Log mode depends on the format of these entries."
  2079. :group 'org-todo
  2080. :group 'org-progress
  2081. :type '(list :greedy t
  2082. (cons (const :tag "Heading when closing an item" done) string)
  2083. (cons (const :tag
  2084. "Heading when changing todo state (todo sequence only)"
  2085. state) string)
  2086. (cons (const :tag "Heading when just taking a note" note) string)
  2087. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2088. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2089. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2090. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2091. (cons (const :tag "Heading when refiling" refile) string)
  2092. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2093. (unless (assq 'note org-log-note-headings)
  2094. (push '(note . "%t") org-log-note-headings))
  2095. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2096. (defcustom org-log-into-drawer nil
  2097. "Non-nil means insert state change notes and time stamps into a drawer.
  2098. When nil, state changes notes will be inserted after the headline and
  2099. any scheduling and clock lines, but not inside a drawer.
  2100. The value of this variable should be the name of the drawer to use.
  2101. LOGBOOK is proposed as the default drawer for this purpose, you can
  2102. also set this to a string to define the drawer of your choice.
  2103. A value of t is also allowed, representing \"LOGBOOK\".
  2104. A value of t or nil can also be set with on a per-file-basis with
  2105. #+STARTUP: logdrawer
  2106. #+STARTUP: nologdrawer
  2107. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2108. will be ignored.
  2109. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2110. a subtree.
  2111. Do not check directly this variable in a Lisp program. Call
  2112. function `org-log-into-drawer' instead."
  2113. :group 'org-todo
  2114. :group 'org-progress
  2115. :type '(choice
  2116. (const :tag "Not into a drawer" nil)
  2117. (const :tag "LOGBOOK" t)
  2118. (string :tag "Other")))
  2119. (defun org-log-into-drawer ()
  2120. "Name of the log drawer, as a string, or nil.
  2121. This is the value of `org-log-into-drawer'. However, if the
  2122. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2123. be used instead of the default value."
  2124. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2125. (cond ((equal p "nil") nil)
  2126. ((equal p "t") "LOGBOOK")
  2127. ((stringp p) p)
  2128. (p "LOGBOOK")
  2129. ((stringp org-log-into-drawer) org-log-into-drawer)
  2130. (org-log-into-drawer "LOGBOOK"))))
  2131. (defcustom org-log-state-notes-insert-after-drawers nil
  2132. "Non-nil means insert state change notes after any drawers in entry.
  2133. Only the drawers that *immediately* follow the headline and the
  2134. deadline/scheduled line are skipped.
  2135. When nil, insert notes right after the heading and perhaps the line
  2136. with deadline/scheduling if present.
  2137. This variable will have no effect if `org-log-into-drawer' is
  2138. set."
  2139. :group 'org-todo
  2140. :group 'org-progress
  2141. :type 'boolean)
  2142. (defcustom org-log-states-order-reversed t
  2143. "Non-nil means the latest state note will be directly after heading.
  2144. When nil, the state change notes will be ordered according to time.
  2145. This option can also be set with on a per-file-basis with
  2146. #+STARTUP: logstatesreversed
  2147. #+STARTUP: nologstatesreversed"
  2148. :group 'org-todo
  2149. :group 'org-progress
  2150. :type 'boolean)
  2151. (defcustom org-todo-repeat-to-state nil
  2152. "The TODO state to which a repeater should return the repeating task.
  2153. By default this is the first task of a TODO sequence or the
  2154. previous state of a TYPE_TODO set. But you can specify to use
  2155. the previous state in a TODO sequence or a string.
  2156. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2157. entry, which has precedence over this option."
  2158. :group 'org-todo
  2159. :version "24.1"
  2160. :type '(choice (const :tag "Use the previous TODO state" t)
  2161. (const :tag "Use the head of the TODO sequence" nil)
  2162. (string :tag "Use a specific TODO state")))
  2163. (defcustom org-log-repeat 'time
  2164. "Non-nil means record moving through the DONE state when triggering repeat.
  2165. An auto-repeating task is immediately switched back to TODO when
  2166. marked DONE. If you are not logging state changes (by adding \"@\"
  2167. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2168. record a closing note, there will be no record of the task moving
  2169. through DONE. This variable forces taking a note anyway.
  2170. nil Don't force a record
  2171. time Record a time stamp
  2172. note Prompt for a note and add it with template `org-log-note-headings'
  2173. This option can also be set with on a per-file-basis with
  2174. #+STARTUP: nologrepeat
  2175. #+STARTUP: logrepeat
  2176. #+STARTUP: lognoterepeat
  2177. You can have local logging settings for a subtree by setting the LOGGING
  2178. property to one or more of these keywords."
  2179. :group 'org-todo
  2180. :group 'org-progress
  2181. :type '(choice
  2182. (const :tag "Don't force a record" nil)
  2183. (const :tag "Force recording the DONE state" time)
  2184. (const :tag "Force recording a note with the DONE state" note)))
  2185. (defcustom org-todo-repeat-hook nil
  2186. "Hook that is run after a task has been repeated."
  2187. :package-version '(Org . "9.2")
  2188. :group 'org-todo
  2189. :type 'hook)
  2190. (defgroup org-priorities nil
  2191. "Priorities in Org mode."
  2192. :tag "Org Priorities"
  2193. :group 'org-todo)
  2194. (defcustom org-enable-priority-commands t
  2195. "Non-nil means priority commands are active.
  2196. When nil, these commands will be disabled, so that you never accidentally
  2197. set a priority."
  2198. :group 'org-priorities
  2199. :type 'boolean)
  2200. (defcustom org-highest-priority ?A
  2201. "The highest priority of TODO items. A character like ?A, ?B etc.
  2202. Must have a smaller ASCII number than `org-lowest-priority'."
  2203. :group 'org-priorities
  2204. :type 'character)
  2205. (defcustom org-lowest-priority ?C
  2206. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2207. Must have a larger ASCII number than `org-highest-priority'."
  2208. :group 'org-priorities
  2209. :type 'character)
  2210. (defcustom org-default-priority ?B
  2211. "The default priority of TODO items.
  2212. This is the priority an item gets if no explicit priority is given.
  2213. When starting to cycle on an empty priority the first step in the cycle
  2214. depends on `org-priority-start-cycle-with-default'. The resulting first
  2215. step priority must not exceed the range from `org-highest-priority' to
  2216. `org-lowest-priority' which means that `org-default-priority' has to be
  2217. in this range exclusive or inclusive the range boundaries. Else the
  2218. first step refuses to set the default and the second will fall back
  2219. to (depending on the command used) the highest or lowest priority."
  2220. :group 'org-priorities
  2221. :type 'character)
  2222. (defcustom org-priority-start-cycle-with-default t
  2223. "Non-nil means start with default priority when starting to cycle.
  2224. When this is nil, the first step in the cycle will be (depending on the
  2225. command used) one higher or lower than the default priority.
  2226. See also `org-default-priority'."
  2227. :group 'org-priorities
  2228. :type 'boolean)
  2229. (defcustom org-get-priority-function nil
  2230. "Function to extract the priority from a string.
  2231. The string is normally the headline. If this is nil Org computes the
  2232. priority from the priority cookie like [#A] in the headline. It returns
  2233. an integer, increasing by 1000 for each priority level.
  2234. The user can set a different function here, which should take a string
  2235. as an argument and return the numeric priority."
  2236. :group 'org-priorities
  2237. :version "24.1"
  2238. :type '(choice
  2239. (const nil)
  2240. (function)))
  2241. (defgroup org-time nil
  2242. "Options concerning time stamps and deadlines in Org mode."
  2243. :tag "Org Time"
  2244. :group 'org)
  2245. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2246. "Number of minutes to round time stamps to.
  2247. \\<org-mode-map>\
  2248. These are two values, the first applies when first creating a time stamp.
  2249. The second applies when changing it with the commands `S-up' and `S-down'.
  2250. When changing the time stamp, this means that it will change in steps
  2251. of N minutes, as given by the second value.
  2252. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2253. numbers should be factors of 60, so for example 5, 10, 15.
  2254. When this is larger than 1, you can still force an exact time stamp by using
  2255. a double prefix argument to a time stamp command like \
  2256. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2257. and by using a prefix arg to `S-up/down' to specify the exact number
  2258. of minutes to shift."
  2259. :group 'org-time
  2260. :get (lambda (var) ; Make sure both elements are there
  2261. (if (integerp (default-value var))
  2262. (list (default-value var) 5)
  2263. (default-value var)))
  2264. :type '(list
  2265. (integer :tag "when inserting times")
  2266. (integer :tag "when modifying times")))
  2267. ;; Normalize old customizations of this variable.
  2268. (when (integerp org-time-stamp-rounding-minutes)
  2269. (setq org-time-stamp-rounding-minutes
  2270. (list org-time-stamp-rounding-minutes
  2271. org-time-stamp-rounding-minutes)))
  2272. (defcustom org-display-custom-times nil
  2273. "Non-nil means overlay custom formats over all time stamps.
  2274. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2275. To turn this on on a per-file basis, insert anywhere in the file:
  2276. #+STARTUP: customtime"
  2277. :group 'org-time
  2278. :set 'set-default
  2279. :type 'sexp)
  2280. (make-variable-buffer-local 'org-display-custom-times)
  2281. (defcustom org-time-stamp-custom-formats
  2282. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2283. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2284. These are overlaid over the default ISO format if the variable
  2285. `org-display-custom-times' is set. Time like %H:%M should be at the
  2286. end of the second format. The custom formats are also honored by export
  2287. commands, if custom time display is turned on at the time of export."
  2288. :group 'org-time
  2289. :type 'sexp)
  2290. (defun org-time-stamp-format (&optional long inactive)
  2291. "Get the right format for a time string."
  2292. (let ((f (if long (cdr org-time-stamp-formats)
  2293. (car org-time-stamp-formats))))
  2294. (if inactive
  2295. (concat "[" (substring f 1 -1) "]")
  2296. f)))
  2297. (defcustom org-deadline-warning-days 14
  2298. "Number of days before expiration during which a deadline becomes active.
  2299. This variable governs the display in sparse trees and in the agenda.
  2300. When 0 or negative, it means use this number (the absolute value of it)
  2301. even if a deadline has a different individual lead time specified.
  2302. Custom commands can set this variable in the options section."
  2303. :group 'org-time
  2304. :group 'org-agenda-daily/weekly
  2305. :type 'integer)
  2306. (defcustom org-scheduled-delay-days 0
  2307. "Number of days before a scheduled item becomes active.
  2308. This variable governs the display in sparse trees and in the agenda.
  2309. The default value (i.e. 0) means: don't delay scheduled item.
  2310. When negative, it means use this number (the absolute value of it)
  2311. even if a scheduled item has a different individual delay time
  2312. specified.
  2313. Custom commands can set this variable in the options section."
  2314. :group 'org-time
  2315. :group 'org-agenda-daily/weekly
  2316. :version "24.4"
  2317. :package-version '(Org . "8.0")
  2318. :type 'integer)
  2319. (defcustom org-read-date-prefer-future t
  2320. "Non-nil means assume future for incomplete date input from user.
  2321. This affects the following situations:
  2322. 1. The user gives a month but not a year.
  2323. For example, if it is April and you enter \"feb 2\", this will be read
  2324. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2325. 2. The user gives a day, but no month.
  2326. For example, if today is the 15th, and you enter \"3\", Org will read
  2327. this as the third of *next* month. However, if you enter \"17\",
  2328. it will be considered as *this* month.
  2329. If you set this variable to the symbol `time', then also the following
  2330. will work:
  2331. 3. If the user gives a time.
  2332. If the time is before now, it will be interpreted as tomorrow.
  2333. Currently none of this works for ISO week specifications.
  2334. When this option is nil, the current day, month and year will always be
  2335. used as defaults.
  2336. See also `org-agenda-jump-prefer-future'."
  2337. :group 'org-time
  2338. :type '(choice
  2339. (const :tag "Never" nil)
  2340. (const :tag "Check month and day" t)
  2341. (const :tag "Check month, day, and time" time)))
  2342. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2343. "Should the agenda jump command prefer the future for incomplete dates?
  2344. The default is to do the same as configured in `org-read-date-prefer-future'.
  2345. But you can also set a deviating value here.
  2346. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2347. :group 'org-agenda
  2348. :group 'org-time
  2349. :version "24.1"
  2350. :type '(choice
  2351. (const :tag "Use org-read-date-prefer-future"
  2352. org-read-date-prefer-future)
  2353. (const :tag "Never" nil)
  2354. (const :tag "Always" t)))
  2355. (defcustom org-read-date-force-compatible-dates t
  2356. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2357. Depending on the system Emacs is running on, certain dates cannot
  2358. be represented with the type used internally to represent time.
  2359. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2360. correctly. Some systems allow for earlier dates, some for later,
  2361. some for both. One way to find out is to insert any date into an
  2362. Org buffer, putting the cursor on the year and hitting S-up and
  2363. S-down to test the range.
  2364. When this variable is set to t, the date/time prompt will not let
  2365. you specify dates outside the 1970-2037 range, so it is certain that
  2366. these dates will work in whatever version of Emacs you are
  2367. running, and also that you can move a file from one Emacs implementation
  2368. to another. Whenever Org is forcing the year for you, it will display
  2369. a message and beep.
  2370. When this variable is nil, Org will check if the date is
  2371. representable in the specific Emacs implementation you are using.
  2372. If not, it will force a year, usually the current year, and beep
  2373. to remind you. Currently this setting is not recommended because
  2374. the likelihood that you will open your Org files in an Emacs that
  2375. has limited date range is not negligible.
  2376. A workaround for this problem is to use diary sexp dates for time
  2377. stamps outside of this range."
  2378. :group 'org-time
  2379. :version "24.1"
  2380. :type 'boolean)
  2381. (defcustom org-read-date-display-live t
  2382. "Non-nil means display current interpretation of date prompt live.
  2383. This display will be in an overlay, in the minibuffer."
  2384. :group 'org-time
  2385. :type 'boolean)
  2386. (defvaralias 'org-popup-calendar-for-date-prompt
  2387. 'org-read-date-popup-calendar)
  2388. (defcustom org-read-date-popup-calendar t
  2389. "Non-nil means pop up a calendar when prompting for a date.
  2390. In the calendar, the date can be selected with mouse-1. However, the
  2391. minibuffer will also be active, and you can simply enter the date as well.
  2392. When nil, only the minibuffer will be available."
  2393. :group 'org-time
  2394. :type 'boolean)
  2395. (defcustom org-extend-today-until 0
  2396. "The hour when your day really ends. Must be an integer.
  2397. This has influence for the following applications:
  2398. - When switching the agenda to \"today\". If it is still earlier than
  2399. the time given here, the day recognized as TODAY is actually yesterday.
  2400. - When a date is read from the user and it is still before the time given
  2401. here, the current date and time will be assumed to be yesterday, 23:59.
  2402. Also, timestamps inserted in capture templates follow this rule.
  2403. IMPORTANT: This is a feature whose implementation is and likely will
  2404. remain incomplete. Really, it is only here because past midnight seems to
  2405. be the favorite working time of John Wiegley :-)"
  2406. :group 'org-time
  2407. :type 'integer)
  2408. (defcustom org-use-effective-time nil
  2409. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2410. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2411. \"effective time\" of any timestamps between midnight and 8am will be
  2412. 23:59 of the previous day."
  2413. :group 'org-time
  2414. :version "24.1"
  2415. :type 'boolean)
  2416. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2417. "When non-nil, use the last clock out time for `org-todo'.
  2418. Note that this option has precedence over the combined use of
  2419. `org-use-effective-time' and `org-extend-today-until'."
  2420. :group 'org-time
  2421. :version "24.4"
  2422. :package-version '(Org . "8.0")
  2423. :type 'boolean)
  2424. (defcustom org-edit-timestamp-down-means-later nil
  2425. "Non-nil means S-down will increase the time in a time stamp.
  2426. When nil, S-up will increase."
  2427. :group 'org-time
  2428. :type 'boolean)
  2429. (defcustom org-calendar-follow-timestamp-change t
  2430. "Non-nil means make the calendar window follow timestamp changes.
  2431. When a timestamp is modified and the calendar window is visible, it will be
  2432. moved to the new date."
  2433. :group 'org-time
  2434. :type 'boolean)
  2435. (defgroup org-tags nil
  2436. "Options concerning tags in Org mode."
  2437. :tag "Org Tags"
  2438. :group 'org)
  2439. (defcustom org-tag-alist nil
  2440. "Default tags available in Org files.
  2441. The value of this variable is an alist. Associations either:
  2442. (TAG)
  2443. (TAG . SELECT)
  2444. (SPECIAL)
  2445. where TAG is a tag as a string, SELECT is character, used to
  2446. select that tag through the fast tag selection interface, and
  2447. SPECIAL is one of the following keywords: `:startgroup',
  2448. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2449. `:newline'. These keywords are used to define a hierarchy of
  2450. tags. See manual for details.
  2451. When this variable is nil, Org mode bases tag input on what is
  2452. already in the buffer. The value can be overridden locally by
  2453. using a TAGS keyword, e.g.,
  2454. #+TAGS: tag1 tag2
  2455. See also `org-tag-persistent-alist' to sidestep this behavior."
  2456. :group 'org-tags
  2457. :type '(repeat
  2458. (choice
  2459. (cons :tag "Tag with key"
  2460. (string :tag "Tag name")
  2461. (character :tag "Access char"))
  2462. (list :tag "Tag" (string :tag "Tag name"))
  2463. (const :tag "Start radio group" (:startgroup))
  2464. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2465. (const :tag "Group tags delimiter" (:grouptags))
  2466. (const :tag "End radio group" (:endgroup))
  2467. (const :tag "End tag group, non distinct" (:endgrouptag))
  2468. (const :tag "New line" (:newline)))))
  2469. (defcustom org-tag-persistent-alist nil
  2470. "Tags always available in Org files.
  2471. The value of this variable is an alist. Associations either:
  2472. (TAG)
  2473. (TAG . SELECT)
  2474. (SPECIAL)
  2475. where TAG is a tag as a string, SELECT is a character, used to
  2476. select that tag through the fast tag selection interface, and
  2477. SPECIAL is one of the following keywords: `:startgroup',
  2478. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2479. `:newline'. These keywords are used to define a hierarchy of
  2480. tags. See manual for details.
  2481. Unlike to `org-tag-alist', tags defined in this variable do not
  2482. depend on a local TAGS keyword. Instead, to disable these tags
  2483. on a per-file basis, insert anywhere in the file:
  2484. #+STARTUP: noptag"
  2485. :group 'org-tags
  2486. :type '(repeat
  2487. (choice
  2488. (cons :tag "Tag with key"
  2489. (string :tag "Tag name")
  2490. (character :tag "Access char"))
  2491. (list :tag "Tag" (string :tag "Tag name"))
  2492. (const :tag "Start radio group" (:startgroup))
  2493. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2494. (const :tag "Group tags delimiter" (:grouptags))
  2495. (const :tag "End radio group" (:endgroup))
  2496. (const :tag "End tag group, non distinct" (:endgrouptag))
  2497. (const :tag "New line" (:newline)))))
  2498. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2499. "If non-nil, always offer completion for all tags of all agenda files.
  2500. Setting this variable locally allows for dynamic generation of tag
  2501. completions in capture buffers.
  2502. (add-hook \\='org-capture-mode-hook
  2503. (lambda ()
  2504. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2505. :group 'org-tags
  2506. :version "24.1"
  2507. :type 'boolean)
  2508. (defvar org-file-tags nil
  2509. "List of tags that can be inherited by all entries in the file.
  2510. The tags will be inherited if the variable `org-use-tag-inheritance'
  2511. says they should be.
  2512. This variable is populated from #+FILETAGS lines.")
  2513. (defcustom org-use-fast-tag-selection 'auto
  2514. "Non-nil means use fast tag selection scheme.
  2515. This is a special interface to select and deselect tags with single keys.
  2516. When nil, fast selection is never used.
  2517. When the symbol `auto', fast selection is used if and only if selection
  2518. characters for tags have been configured, either through the variable
  2519. `org-tag-alist' or through a #+TAGS line in the buffer.
  2520. When t, fast selection is always used and selection keys are assigned
  2521. automatically if necessary."
  2522. :group 'org-tags
  2523. :type '(choice
  2524. (const :tag "Always" t)
  2525. (const :tag "Never" nil)
  2526. (const :tag "When selection characters are configured" auto)))
  2527. (defcustom org-fast-tag-selection-single-key nil
  2528. "Non-nil means fast tag selection exits after first change.
  2529. When nil, you have to press RET to exit it.
  2530. During fast tag selection, you can toggle this flag with `C-c'.
  2531. This variable can also have the value `expert'. In this case, the window
  2532. displaying the tags menu is not even shown, until you press C-c again."
  2533. :group 'org-tags
  2534. :type '(choice
  2535. (const :tag "No" nil)
  2536. (const :tag "Yes" t)
  2537. (const :tag "Expert" expert)))
  2538. (defvar org-fast-tag-selection-include-todo nil
  2539. "Non-nil means fast tags selection interface will also offer TODO states.
  2540. This is an undocumented feature, you should not rely on it.")
  2541. (defcustom org-tags-column -77
  2542. "The column to which tags should be indented in a headline.
  2543. If this number is positive, it specifies the column. If it is negative,
  2544. it means that the tags should be flushright to that column. For example,
  2545. -80 works well for a normal 80 character screen.
  2546. When 0, place tags directly after headline text, with only one space in
  2547. between."
  2548. :group 'org-tags
  2549. :type 'integer)
  2550. (defcustom org-auto-align-tags t
  2551. "Non-nil keeps tags aligned when modifying headlines.
  2552. Some operations (i.e. demoting) change the length of a headline and
  2553. therefore shift the tags around. With this option turned on, after
  2554. each such operation the tags are again aligned to `org-tags-column'."
  2555. :group 'org-tags
  2556. :type 'boolean)
  2557. (defcustom org-use-tag-inheritance t
  2558. "Non-nil means tags in levels apply also for sublevels.
  2559. When nil, only the tags directly given in a specific line apply there.
  2560. This may also be a list of tags that should be inherited, or a regexp that
  2561. matches tags that should be inherited. Additional control is possible
  2562. with the variable `org-tags-exclude-from-inheritance' which gives an
  2563. explicit list of tags to be excluded from inheritance, even if the value of
  2564. `org-use-tag-inheritance' would select it for inheritance.
  2565. If this option is t, a match early-on in a tree can lead to a large
  2566. number of matches in the subtree when constructing the agenda or creating
  2567. a sparse tree. If you only want to see the first match in a tree during
  2568. a search, check out the variable `org-tags-match-list-sublevels'."
  2569. :group 'org-tags
  2570. :type '(choice
  2571. (const :tag "Not" nil)
  2572. (const :tag "Always" t)
  2573. (repeat :tag "Specific tags" (string :tag "Tag"))
  2574. (regexp :tag "Tags matched by regexp")))
  2575. (defcustom org-tags-exclude-from-inheritance nil
  2576. "List of tags that should never be inherited.
  2577. This is a way to exclude a few tags from inheritance. For way to do
  2578. the opposite, to actively allow inheritance for selected tags,
  2579. see the variable `org-use-tag-inheritance'."
  2580. :group 'org-tags
  2581. :type '(repeat (string :tag "Tag")))
  2582. (defun org-tag-inherit-p (tag)
  2583. "Check if TAG is one that should be inherited."
  2584. (cond
  2585. ((member tag org-tags-exclude-from-inheritance) nil)
  2586. ((eq org-use-tag-inheritance t) t)
  2587. ((not org-use-tag-inheritance) nil)
  2588. ((stringp org-use-tag-inheritance)
  2589. (string-match org-use-tag-inheritance tag))
  2590. ((listp org-use-tag-inheritance)
  2591. (member tag org-use-tag-inheritance))
  2592. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2593. (defcustom org-tags-match-list-sublevels t
  2594. "Non-nil means list also sublevels of headlines matching a search.
  2595. This variable applies to tags/property searches, and also to stuck
  2596. projects because this search is based on a tags match as well.
  2597. When set to the symbol `indented', sublevels are indented with
  2598. leading dots.
  2599. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2600. the sublevels of a headline matching a tag search often also match
  2601. the same search. Listing all of them can create very long lists.
  2602. Setting this variable to nil causes subtrees of a match to be skipped.
  2603. This variable is semi-obsolete and probably should always be true. It
  2604. is better to limit inheritance to certain tags using the variables
  2605. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2606. :group 'org-tags
  2607. :type '(choice
  2608. (const :tag "No, don't list them" nil)
  2609. (const :tag "Yes, do list them" t)
  2610. (const :tag "List them, indented with leading dots" indented)))
  2611. (defcustom org-tags-sort-function nil
  2612. "When set, tags are sorted using this function as a comparator."
  2613. :group 'org-tags
  2614. :type '(choice
  2615. (const :tag "No sorting" nil)
  2616. (const :tag "Alphabetical" org-string-collate-lessp)
  2617. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2618. (function :tag "Custom function" nil)))
  2619. (defvar org-tags-history nil
  2620. "History of minibuffer reads for tags.")
  2621. (defvar org-last-tags-completion-table nil
  2622. "The last used completion table for tags.")
  2623. (defvar org-after-tags-change-hook nil
  2624. "Hook that is run after the tags in a line have changed.")
  2625. (defgroup org-properties nil
  2626. "Options concerning properties in Org mode."
  2627. :tag "Org Properties"
  2628. :group 'org)
  2629. (defcustom org-property-format "%-10s %s"
  2630. "How property key/value pairs should be formatted by `indent-line'.
  2631. When `indent-line' hits a property definition, it will format the line
  2632. according to this format, mainly to make sure that the values are
  2633. lined-up with respect to each other."
  2634. :group 'org-properties
  2635. :type 'string)
  2636. (defcustom org-properties-postprocess-alist nil
  2637. "Alist of properties and functions to adjust inserted values.
  2638. Elements of this alist must be of the form
  2639. ([string] [function])
  2640. where [string] must be a property name and [function] must be a
  2641. lambda expression: this lambda expression must take one argument,
  2642. the value to adjust, and return the new value as a string.
  2643. For example, this element will allow the property \"Remaining\"
  2644. to be updated wrt the relation between the \"Effort\" property
  2645. and the clock summary:
  2646. ((\"Remaining\" (lambda(value)
  2647. (let ((clocksum (org-clock-sum-current-item))
  2648. (effort (org-duration-to-minutes
  2649. (org-entry-get (point) \"Effort\"))))
  2650. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2651. :group 'org-properties
  2652. :version "24.1"
  2653. :type '(alist :key-type (string :tag "Property")
  2654. :value-type (function :tag "Function")))
  2655. (defcustom org-use-property-inheritance nil
  2656. "Non-nil means properties apply also for sublevels.
  2657. This setting is chiefly used during property searches. Turning it on can
  2658. cause significant overhead when doing a search, which is why it is not
  2659. on by default.
  2660. When nil, only the properties directly given in the current entry count.
  2661. When t, every property is inherited. The value may also be a list of
  2662. properties that should have inheritance, or a regular expression matching
  2663. properties that should be inherited.
  2664. However, note that some special properties use inheritance under special
  2665. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2666. and the properties ending in \"_ALL\" when they are used as descriptor
  2667. for valid values of a property.
  2668. Note for programmers:
  2669. When querying an entry with `org-entry-get', you can control if inheritance
  2670. should be used. By default, `org-entry-get' looks only at the local
  2671. properties. You can request inheritance by setting the inherit argument
  2672. to t (to force inheritance) or to `selective' (to respect the setting
  2673. in this variable)."
  2674. :group 'org-properties
  2675. :type '(choice
  2676. (const :tag "Not" nil)
  2677. (const :tag "Always" t)
  2678. (repeat :tag "Specific properties" (string :tag "Property"))
  2679. (regexp :tag "Properties matched by regexp")))
  2680. (defun org-property-inherit-p (property)
  2681. "Return a non-nil value if PROPERTY should be inherited."
  2682. (cond
  2683. ((eq org-use-property-inheritance t) t)
  2684. ((not org-use-property-inheritance) nil)
  2685. ((stringp org-use-property-inheritance)
  2686. (string-match org-use-property-inheritance property))
  2687. ((listp org-use-property-inheritance)
  2688. (member-ignore-case property org-use-property-inheritance))
  2689. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2690. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2691. "The default column format, if no other format has been defined.
  2692. This variable can be set on the per-file basis by inserting a line
  2693. #+COLUMNS: %25ITEM ....."
  2694. :group 'org-properties
  2695. :type 'string)
  2696. (defcustom org-columns-default-format-for-agenda nil
  2697. "The default column format in an agenda buffer.
  2698. This will be used for column view in the agenda unless a format has
  2699. been set by adding `org-overriding-columns-format' to the local
  2700. settings list of a custom agenda view. When nil, the columns format
  2701. for the first item in the agenda list will be used, or as a fall-back,
  2702. `org-columns-default-format'."
  2703. :group 'org-properties
  2704. :type '(choice
  2705. (const :tag "No default" nil)
  2706. (string :tag "Format string")))
  2707. (defcustom org-columns-ellipses ".."
  2708. "The ellipses to be used when a field in column view is truncated.
  2709. When this is the empty string, as many characters as possible are shown,
  2710. but then there will be no visual indication that the field has been truncated.
  2711. When this is a string of length N, the last N characters of a truncated
  2712. field are replaced by this string. If the column is narrower than the
  2713. ellipses string, only part of the ellipses string will be shown."
  2714. :group 'org-properties
  2715. :type 'string)
  2716. (defconst org-global-properties-fixed
  2717. '(("VISIBILITY_ALL" . "folded children content all")
  2718. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2719. "List of property/value pairs that can be inherited by any entry.
  2720. These are fixed values, for the preset properties. The user variable
  2721. that can be used to add to this list is `org-global-properties'.
  2722. The entries in this list are cons cells where the car is a property
  2723. name and cdr is a string with the value. If the value represents
  2724. multiple items like an \"_ALL\" property, separate the items by
  2725. spaces.")
  2726. (defcustom org-global-properties nil
  2727. "List of property/value pairs that can be inherited by any entry.
  2728. This list will be combined with the constant `org-global-properties-fixed'.
  2729. The entries in this list are cons cells where the car is a property
  2730. name and cdr is a string with the value.
  2731. You can set buffer-local values for the same purpose in the variable
  2732. `org-file-properties' this by adding lines like
  2733. #+PROPERTY: NAME VALUE"
  2734. :group 'org-properties
  2735. :type '(repeat
  2736. (cons (string :tag "Property")
  2737. (string :tag "Value"))))
  2738. (defvar-local org-file-properties nil
  2739. "List of property/value pairs that can be inherited by any entry.
  2740. Valid for the current buffer.
  2741. This variable is populated from #+PROPERTY lines.")
  2742. (defgroup org-agenda nil
  2743. "Options concerning agenda views in Org mode."
  2744. :tag "Org Agenda"
  2745. :group 'org)
  2746. (defvar-local org-category nil
  2747. "Variable used by Org files to set a category for agenda display.
  2748. Such files should use a file variable to set it, for example
  2749. # -*- mode: org; org-category: \"ELisp\"
  2750. or contain a special line
  2751. #+CATEGORY: ELisp
  2752. If the file does not specify a category, then file's base name
  2753. is used instead.")
  2754. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2755. (defcustom org-agenda-files nil
  2756. "The files to be used for agenda display.
  2757. If an entry is a directory, all files in that directory that are matched
  2758. by `org-agenda-file-regexp' will be part of the file list.
  2759. If the value of the variable is not a list but a single file name, then
  2760. the list of agenda files is actually stored and maintained in that file,
  2761. one agenda file per line. In this file paths can be given relative to
  2762. `org-directory'. Tilde expansion and environment variable substitution
  2763. are also made.
  2764. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2765. and removed with `\\[org-remove-file]'."
  2766. :group 'org-agenda
  2767. :type '(choice
  2768. (repeat :tag "List of files and directories" file)
  2769. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2770. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2771. "Regular expression to match files for `org-agenda-files'.
  2772. If any element in the list in that variable contains a directory instead
  2773. of a normal file, all files in that directory that are matched by this
  2774. regular expression will be included."
  2775. :group 'org-agenda
  2776. :type 'regexp)
  2777. (defvaralias 'org-agenda-multi-occur-extra-files
  2778. 'org-agenda-text-search-extra-files)
  2779. (defcustom org-agenda-text-search-extra-files nil
  2780. "List of extra files to be searched by text search commands.
  2781. These files will be searched in addition to the agenda files by the
  2782. commands `org-search-view' (`\\[org-agenda] s') \
  2783. and `org-occur-in-agenda-files'.
  2784. Note that these files will only be searched for text search commands,
  2785. not for the other agenda views like todo lists, tag searches or the weekly
  2786. agenda. This variable is intended to list notes and possibly archive files
  2787. that should also be searched by these two commands.
  2788. In fact, if the first element in the list is the symbol `agenda-archives',
  2789. then all archive files of all agenda files will be added to the search
  2790. scope."
  2791. :group 'org-agenda
  2792. :type '(set :greedy t
  2793. (const :tag "Agenda Archives" agenda-archives)
  2794. (repeat :inline t (file))))
  2795. (defcustom org-agenda-skip-unavailable-files nil
  2796. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2797. A nil value means to remove them, after a query, from the list."
  2798. :group 'org-agenda
  2799. :type 'boolean)
  2800. (defgroup org-latex nil
  2801. "Options for embedding LaTeX code into Org mode."
  2802. :tag "Org LaTeX"
  2803. :group 'org)
  2804. (defcustom org-format-latex-options
  2805. '(:foreground default :background default :scale 1.0
  2806. :html-foreground "Black" :html-background "Transparent"
  2807. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2808. "Options for creating images from LaTeX fragments.
  2809. This is a property list with the following properties:
  2810. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2811. `default' means use the foreground of the default face.
  2812. `auto' means use the foreground from the text face.
  2813. :background the background color, or \"Transparent\".
  2814. `default' means use the background of the default face.
  2815. `auto' means use the background from the text face.
  2816. :scale a scaling factor for the size of the images, to get more pixels
  2817. :html-foreground, :html-background, :html-scale
  2818. the same numbers for HTML export.
  2819. :matchers a list indicating which matchers should be used to
  2820. find LaTeX fragments. Valid members of this list are:
  2821. \"begin\" find environments
  2822. \"$1\" find single characters surrounded by $.$
  2823. \"$\" find math expressions surrounded by $...$
  2824. \"$$\" find math expressions surrounded by $$....$$
  2825. \"\\(\" find math expressions surrounded by \\(...\\)
  2826. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2827. :group 'org-latex
  2828. :type 'plist)
  2829. (defcustom org-format-latex-signal-error t
  2830. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2831. When nil, just push out a message."
  2832. :group 'org-latex
  2833. :version "24.1"
  2834. :type 'boolean)
  2835. (defcustom org-latex-to-mathml-jar-file nil
  2836. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2837. Use this to specify additional executable file say a jar file.
  2838. When using MathToWeb as the converter, specify the full-path to
  2839. your mathtoweb.jar file."
  2840. :group 'org-latex
  2841. :version "24.1"
  2842. :type '(choice
  2843. (const :tag "None" nil)
  2844. (file :tag "JAR file" :must-match t)))
  2845. (defcustom org-latex-to-mathml-convert-command nil
  2846. "Command to convert LaTeX fragments to MathML.
  2847. Replace format-specifiers in the command as noted below and use
  2848. `shell-command' to convert LaTeX to MathML.
  2849. %j: Executable file in fully expanded form as specified by
  2850. `org-latex-to-mathml-jar-file'.
  2851. %I: Input LaTeX file in fully expanded form.
  2852. %i: The latex fragment to be converted.
  2853. %o: Output MathML file.
  2854. This command is used by `org-create-math-formula'.
  2855. When using MathToWeb as the converter, set this option to
  2856. \"java -jar %j -unicode -force -df %o %I\".
  2857. When using LaTeXML set this option to
  2858. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2859. :group 'org-latex
  2860. :version "24.1"
  2861. :type '(choice
  2862. (const :tag "None" nil)
  2863. (string :tag "\nShell command")))
  2864. (defcustom org-preview-latex-default-process 'dvipng
  2865. "The default process to convert LaTeX fragments to image files.
  2866. All available processes and theirs documents can be found in
  2867. `org-preview-latex-process-alist', which see."
  2868. :group 'org-latex
  2869. :version "26.1"
  2870. :package-version '(Org . "9.0")
  2871. :type 'symbol)
  2872. (defcustom org-preview-latex-process-alist
  2873. '((dvipng
  2874. :programs ("latex" "dvipng")
  2875. :description "dvi > png"
  2876. :message "you need to install the programs: latex and dvipng."
  2877. :image-input-type "dvi"
  2878. :image-output-type "png"
  2879. :image-size-adjust (1.0 . 1.0)
  2880. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2881. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2882. (dvisvgm
  2883. :programs ("latex" "dvisvgm")
  2884. :description "dvi > svg"
  2885. :message "you need to install the programs: latex and dvisvgm."
  2886. :image-input-type "dvi"
  2887. :image-output-type "svg"
  2888. :image-size-adjust (1.7 . 1.5)
  2889. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2890. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2891. (imagemagick
  2892. :programs ("latex" "convert")
  2893. :description "pdf > png"
  2894. :message "you need to install the programs: latex and imagemagick."
  2895. :image-input-type "pdf"
  2896. :image-output-type "png"
  2897. :image-size-adjust (1.0 . 1.0)
  2898. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2899. :image-converter
  2900. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2901. "Definitions of external processes for LaTeX previewing.
  2902. Org mode can use some external commands to generate TeX snippet's images for
  2903. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2904. `org-create-formula-image' how to call them.
  2905. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2906. PROPERTIES accepts the following attributes:
  2907. :programs list of strings, required programs.
  2908. :description string, describe the process.
  2909. :message string, message it when required programs cannot be found.
  2910. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2911. :image-output-type string, output file type of image converter (e.g., \"png\").
  2912. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2913. image size showed in buffer and the cdr element is for
  2914. HTML file. This option is only useful for process
  2915. developers, users should use variable
  2916. `org-format-latex-options' instead.
  2917. :post-clean list of strings, files matched are to be cleaned up once
  2918. the image is generated. When nil, the files with \".dvi\",
  2919. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2920. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2921. be cleaned up.
  2922. :latex-header list of strings, the LaTeX header of the snippet file.
  2923. When nil, the fallback value is used instead, which is
  2924. controlled by `org-format-latex-header',
  2925. `org-latex-default-packages-alist' and
  2926. `org-latex-packages-alist', which see.
  2927. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2928. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2929. replaced with values defined below.
  2930. :image-converter list of image converter commands strings. Each of them is
  2931. given to the shell and supports any of the following
  2932. place-holders defined below.
  2933. Place-holders used by `:image-converter' and `:latex-compiler':
  2934. %f input file name
  2935. %b base name of input file
  2936. %o base directory of input file
  2937. %O absolute output file name
  2938. Place-holders only used by `:image-converter':
  2939. %D dpi, which is used to adjust image size by some processing commands.
  2940. %S the image size scale ratio, which is used to adjust image size by some
  2941. processing commands."
  2942. :group 'org-latex
  2943. :version "26.1"
  2944. :package-version '(Org . "9.0")
  2945. :type '(alist :tag "LaTeX to image backends"
  2946. :value-type (plist)))
  2947. (defcustom org-preview-latex-image-directory "ltximg/"
  2948. "Path to store latex preview images.
  2949. A relative path here creates many directories relative to the
  2950. processed Org files paths. An absolute path puts all preview
  2951. images at the same place."
  2952. :group 'org-latex
  2953. :version "26.1"
  2954. :package-version '(Org . "9.0")
  2955. :type 'string)
  2956. (defun org-format-latex-mathml-available-p ()
  2957. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2958. (save-match-data
  2959. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2960. org-latex-to-mathml-convert-command)
  2961. (let ((executable (car (split-string
  2962. org-latex-to-mathml-convert-command))))
  2963. (when (executable-find executable)
  2964. (if (string-match
  2965. "%j" org-latex-to-mathml-convert-command)
  2966. (file-readable-p org-latex-to-mathml-jar-file)
  2967. t))))))
  2968. (defcustom org-format-latex-header "\\documentclass{article}
  2969. \\usepackage[usenames]{color}
  2970. \[PACKAGES]
  2971. \[DEFAULT-PACKAGES]
  2972. \\pagestyle{empty} % do not remove
  2973. % The settings below are copied from fullpage.sty
  2974. \\setlength{\\textwidth}{\\paperwidth}
  2975. \\addtolength{\\textwidth}{-3cm}
  2976. \\setlength{\\oddsidemargin}{1.5cm}
  2977. \\addtolength{\\oddsidemargin}{-2.54cm}
  2978. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2979. \\setlength{\\textheight}{\\paperheight}
  2980. \\addtolength{\\textheight}{-\\headheight}
  2981. \\addtolength{\\textheight}{-\\headsep}
  2982. \\addtolength{\\textheight}{-\\footskip}
  2983. \\addtolength{\\textheight}{-3cm}
  2984. \\setlength{\\topmargin}{1.5cm}
  2985. \\addtolength{\\topmargin}{-2.54cm}"
  2986. "The document header used for processing LaTeX fragments.
  2987. It is imperative that this header make sure that no page number
  2988. appears on the page. The package defined in the variables
  2989. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2990. will either replace the placeholder \"[PACKAGES]\" in this
  2991. header, or they will be appended."
  2992. :group 'org-latex
  2993. :type 'string)
  2994. (defun org-set-packages-alist (var val)
  2995. "Set the packages alist and make sure it has 3 elements per entry."
  2996. (set var (mapcar (lambda (x)
  2997. (if (and (consp x) (= (length x) 2))
  2998. (list (car x) (nth 1 x) t)
  2999. x))
  3000. val)))
  3001. (defun org-get-packages-alist (var)
  3002. "Get the packages alist and make sure it has 3 elements per entry."
  3003. (mapcar (lambda (x)
  3004. (if (and (consp x) (= (length x) 2))
  3005. (list (car x) (nth 1 x) t)
  3006. x))
  3007. (default-value var)))
  3008. (defcustom org-latex-default-packages-alist
  3009. '(("AUTO" "inputenc" t ("pdflatex"))
  3010. ("T1" "fontenc" t ("pdflatex"))
  3011. ("" "graphicx" t)
  3012. ("" "grffile" t)
  3013. ("" "longtable" nil)
  3014. ("" "wrapfig" nil)
  3015. ("" "rotating" nil)
  3016. ("normalem" "ulem" t)
  3017. ("" "amsmath" t)
  3018. ("" "textcomp" t)
  3019. ("" "amssymb" t)
  3020. ("" "capt-of" nil)
  3021. ("" "hyperref" nil))
  3022. "Alist of default packages to be inserted in the header.
  3023. Change this only if one of the packages here causes an
  3024. incompatibility with another package you are using.
  3025. The packages in this list are needed by one part or another of
  3026. Org mode to function properly:
  3027. - inputenc, fontenc: for basic font and character selection
  3028. - graphicx: for including images
  3029. - grffile: allow periods and spaces in graphics file names
  3030. - longtable: For multipage tables
  3031. - wrapfig: for figure placement
  3032. - rotating: for sideways figures and tables
  3033. - ulem: for underline and strike-through
  3034. - amsmath: for subscript and superscript and math environments
  3035. - textcomp, amssymb: for various symbols used
  3036. for interpreting the entities in `org-entities'. You can skip
  3037. some of these packages if you don't use any of their symbols.
  3038. - capt-of: for captions outside of floats
  3039. - hyperref: for cross references
  3040. Therefore you should not modify this variable unless you know
  3041. what you are doing. The one reason to change it anyway is that
  3042. you might be loading some other package that conflicts with one
  3043. of the default packages. Each element is either a cell or
  3044. a string.
  3045. A cell is of the format
  3046. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3047. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3048. when compiling LaTeX snippets into images for inclusion into
  3049. non-LaTeX output.
  3050. COMPILERS is a list of compilers that should include the package,
  3051. see `org-latex-compiler'. If the document compiler is not in the
  3052. list, and the list is non-nil, the package will not be inserted
  3053. in the final document.
  3054. A string will be inserted as-is in the header of the document."
  3055. :group 'org-latex
  3056. :group 'org-export-latex
  3057. :set 'org-set-packages-alist
  3058. :get 'org-get-packages-alist
  3059. :version "26.1"
  3060. :package-version '(Org . "8.3")
  3061. :type '(repeat
  3062. (choice
  3063. (list :tag "options/package pair"
  3064. (string :tag "options")
  3065. (string :tag "package")
  3066. (boolean :tag "Snippet")
  3067. (choice
  3068. (const :tag "For all compilers" nil)
  3069. (repeat :tag "Allowed compiler" string)))
  3070. (string :tag "A line of LaTeX"))))
  3071. (defcustom org-latex-packages-alist nil
  3072. "Alist of packages to be inserted in every LaTeX header.
  3073. These will be inserted after `org-latex-default-packages-alist'.
  3074. Each element is either a cell or a string.
  3075. A cell is of the format:
  3076. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3077. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3078. needed when turning LaTeX snippets into images for inclusion into
  3079. non-LaTeX output.
  3080. COMPILERS is a list of compilers that should include the package,
  3081. see `org-latex-compiler'. If the document compiler is not in the
  3082. list, and the list is non-nil, the package will not be inserted
  3083. in the final document.
  3084. A string will be inserted as-is in the header of the document.
  3085. Make sure that you only list packages here which:
  3086. - you want in every file;
  3087. - do not conflict with the setup in `org-format-latex-header';
  3088. - do not conflict with the default packages in
  3089. `org-latex-default-packages-alist'."
  3090. :group 'org-latex
  3091. :group 'org-export-latex
  3092. :set 'org-set-packages-alist
  3093. :get 'org-get-packages-alist
  3094. :type '(repeat
  3095. (choice
  3096. (list :tag "options/package pair"
  3097. (string :tag "options")
  3098. (string :tag "package")
  3099. (boolean :tag "Snippet"))
  3100. (string :tag "A line of LaTeX"))))
  3101. (defgroup org-appearance nil
  3102. "Settings for Org mode appearance."
  3103. :tag "Org Appearance"
  3104. :group 'org)
  3105. (defcustom org-level-color-stars-only nil
  3106. "Non-nil means fontify only the stars in each headline.
  3107. When nil, the entire headline is fontified.
  3108. Changing it requires restart of `font-lock-mode' to become effective
  3109. also in regions already fontified."
  3110. :group 'org-appearance
  3111. :type 'boolean)
  3112. (defcustom org-hide-leading-stars nil
  3113. "Non-nil means hide the first N-1 stars in a headline.
  3114. This works by using the face `org-hide' for these stars. This
  3115. face is white for a light background, and black for a dark
  3116. background. You may have to customize the face `org-hide' to
  3117. make this work.
  3118. Changing it requires restart of `font-lock-mode' to become effective
  3119. also in regions already fontified.
  3120. You may also set this on a per-file basis by adding one of the following
  3121. lines to the buffer:
  3122. #+STARTUP: hidestars
  3123. #+STARTUP: showstars"
  3124. :group 'org-appearance
  3125. :type 'boolean)
  3126. (defcustom org-hidden-keywords nil
  3127. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3128. For example, a value \\='(title) for this list makes the document's title
  3129. appear in the buffer without the initial \"#+TITLE:\" part."
  3130. :group 'org-appearance
  3131. :version "24.1"
  3132. :type '(set (const :tag "#+AUTHOR" author)
  3133. (const :tag "#+DATE" date)
  3134. (const :tag "#+EMAIL" email)
  3135. (const :tag "#+TITLE" title)))
  3136. (defcustom org-custom-properties nil
  3137. "List of properties (as strings) with a special meaning.
  3138. The default use of these custom properties is to let the user
  3139. hide them with `org-toggle-custom-properties-visibility'."
  3140. :group 'org-properties
  3141. :group 'org-appearance
  3142. :version "24.3"
  3143. :type '(repeat (string :tag "Property Name")))
  3144. (defcustom org-fontify-done-headline nil
  3145. "Non-nil means change the face of a headline if it is marked DONE.
  3146. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3147. When this is non-nil, the headline after the keyword is set to the
  3148. `org-headline-done' as an additional indication."
  3149. :group 'org-appearance
  3150. :type 'boolean)
  3151. (defcustom org-fontify-emphasized-text t
  3152. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3153. Changing this variable requires a restart of Emacs to take effect."
  3154. :group 'org-appearance
  3155. :type 'boolean)
  3156. (defcustom org-fontify-whole-heading-line nil
  3157. "Non-nil means fontify the whole line for headings.
  3158. This is useful when setting a background color for the
  3159. org-level-* faces."
  3160. :group 'org-appearance
  3161. :type 'boolean)
  3162. (defcustom org-fontify-whole-block-delimiter-line t
  3163. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3164. This is useful when setting a background color for the
  3165. org-block-begin-line and org-block-end-line faces."
  3166. :group 'org-appearance
  3167. :type 'boolean)
  3168. (defcustom org-highlight-latex-and-related nil
  3169. "Non-nil means highlight LaTeX related syntax in the buffer.
  3170. When non-nil, the value should be a list containing any of the
  3171. following symbols:
  3172. `native' Highlight LaTeX snippets and environments natively.
  3173. `latex' Highlight LaTeX snippets and environments.
  3174. `script' Highlight subscript and superscript.
  3175. `entities' Highlight entities."
  3176. :group 'org-appearance
  3177. :version "24.4"
  3178. :package-version '(Org . "8.0")
  3179. :type '(choice
  3180. (const :tag "No highlighting" nil)
  3181. (set :greedy t :tag "Highlight"
  3182. (const :tag "LaTeX snippets and environments (native)" native)
  3183. (const :tag "LaTeX snippets and environments" latex)
  3184. (const :tag "Subscript and superscript" script)
  3185. (const :tag "Entities" entities))))
  3186. (defcustom org-hide-emphasis-markers nil
  3187. "Non-nil mean font-lock should hide the emphasis marker characters."
  3188. :group 'org-appearance
  3189. :type 'boolean
  3190. :safe #'booleanp)
  3191. (defcustom org-hide-macro-markers nil
  3192. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3193. :group 'org-appearance
  3194. :type 'boolean)
  3195. (defcustom org-pretty-entities nil
  3196. "Non-nil means show entities as UTF8 characters.
  3197. When nil, the \\name form remains in the buffer."
  3198. :group 'org-appearance
  3199. :version "24.1"
  3200. :type 'boolean)
  3201. (defcustom org-pretty-entities-include-sub-superscripts t
  3202. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3203. :group 'org-appearance
  3204. :version "24.1"
  3205. :type 'boolean)
  3206. (defvar org-emph-re nil
  3207. "Regular expression for matching emphasis.
  3208. After a match, the match groups contain these elements:
  3209. 0 The match of the full regular expression, including the characters
  3210. before and after the proper match
  3211. 1 The character before the proper match, or empty at beginning of line
  3212. 2 The proper match, including the leading and trailing markers
  3213. 3 The leading marker like * or /, indicating the type of highlighting
  3214. 4 The text between the emphasis markers, not including the markers
  3215. 5 The character after the match, empty at the end of a line")
  3216. (defvar org-verbatim-re nil
  3217. "Regular expression for matching verbatim text.")
  3218. (defvar org-emphasis-regexp-components) ; defined just below
  3219. (defvar org-emphasis-alist) ; defined just below
  3220. (defun org-set-emph-re (var val)
  3221. "Set variable and compute the emphasis regular expression."
  3222. (set var val)
  3223. (when (and (boundp 'org-emphasis-alist)
  3224. (boundp 'org-emphasis-regexp-components)
  3225. org-emphasis-alist org-emphasis-regexp-components)
  3226. (pcase-let*
  3227. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3228. (body (if (<= nl 0) body
  3229. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3230. (template
  3231. (format (concat "\\([%s]\\|^\\)" ;before markers
  3232. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3233. "\\([%s]\\|$\\)") ;after markers
  3234. pre border border body border post)))
  3235. (setq org-emph-re (format template "*/_+"))
  3236. (setq org-verbatim-re (format template "=~")))))
  3237. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3238. ;; set this option proved cumbersome. See this message/thread:
  3239. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3240. (defvar org-emphasis-regexp-components
  3241. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3242. "Components used to build the regular expression for emphasis.
  3243. This is a list with five entries. Terminology: In an emphasis string
  3244. like \" *strong word* \", we call the initial space PREMATCH, the final
  3245. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3246. and \"trong wor\" is the body. The different components in this variable
  3247. specify what is allowed/forbidden in each part:
  3248. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3249. post Chars allowed as postmatch. End of line will be allowed too.
  3250. border The chars *forbidden* as border characters.
  3251. body-regexp A regexp like \".\" to match a body character. Don't use
  3252. non-shy groups here, and don't allow newline here.
  3253. newline The maximum number of newlines allowed in an emphasis exp.
  3254. You need to reload Org or to restart Emacs after setting this.")
  3255. (defcustom org-emphasis-alist
  3256. '(("*" bold)
  3257. ("/" italic)
  3258. ("_" underline)
  3259. ("=" org-verbatim verbatim)
  3260. ("~" org-code verbatim)
  3261. ("+" (:strike-through t)))
  3262. "Alist of characters and faces to emphasize text.
  3263. Text starting and ending with a special character will be emphasized,
  3264. for example *bold*, _underlined_ and /italic/. This variable sets the
  3265. marker characters and the face to be used by font-lock for highlighting
  3266. in Org buffers.
  3267. You need to reload Org or to restart Emacs after customizing this."
  3268. :group 'org-appearance
  3269. :set 'org-set-emph-re
  3270. :version "24.4"
  3271. :package-version '(Org . "8.0")
  3272. :type '(repeat
  3273. (list
  3274. (string :tag "Marker character")
  3275. (choice
  3276. (face :tag "Font-lock-face")
  3277. (plist :tag "Face property list"))
  3278. (option (const verbatim)))))
  3279. (defvar org-protecting-blocks '("src" "example" "export")
  3280. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3281. This is needed for font-lock setup.")
  3282. ;;; Functions and variables from their packages
  3283. ;; Declared here to avoid compiler warnings
  3284. (defvar mark-active)
  3285. ;; Various packages
  3286. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3287. (declare-function calendar-forward-day "cal-move" (arg))
  3288. (declare-function calendar-goto-date "cal-move" (date))
  3289. (declare-function calendar-goto-today "cal-move" ())
  3290. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3291. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3292. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3293. (declare-function cdlatex-tab "ext:cdlatex" ())
  3294. (declare-function dired-get-filename
  3295. "dired"
  3296. (&optional localp no-error-if-not-filep))
  3297. (declare-function iswitchb-read-buffer
  3298. "iswitchb"
  3299. (prompt &optional
  3300. default require-match _predicate start matches-set))
  3301. (declare-function org-agenda-change-all-lines
  3302. "org-agenda"
  3303. (newhead hdmarker &optional fixface just-this))
  3304. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3305. "org-agenda"
  3306. (&optional end))
  3307. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3308. (declare-function org-agenda-format-item
  3309. "org-agenda"
  3310. (extra txt &optional level category tags dotime
  3311. remove-re habitp))
  3312. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3313. (declare-function org-agenda-save-markers-for-cut-and-paste
  3314. "org-agenda"
  3315. (beg end))
  3316. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3317. (declare-function org-agenda-skip "org-agenda" ())
  3318. (declare-function org-attach-expand "org-attach" (file))
  3319. (declare-function org-attach-reveal "org-attach" ())
  3320. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3321. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3322. (declare-function org-indent-mode "org-indent" (&optional arg))
  3323. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3324. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3325. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3326. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3327. (declare-function parse-time-string "parse-time" (string))
  3328. (defvar align-mode-rules-list)
  3329. (defvar calc-embedded-close-formula)
  3330. (defvar calc-embedded-open-formula)
  3331. (defvar calc-embedded-open-mode)
  3332. (defvar font-lock-unfontify-region-function)
  3333. (defvar iswitchb-temp-buflist)
  3334. (defvar org-agenda-tags-todo-honor-ignore-options)
  3335. (defvar remember-data-file)
  3336. (defvar texmathp-why)
  3337. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3338. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3339. (declare-function org-resolve-clocks "org-clock"
  3340. (&optional also-non-dangling-p prompt last-valid))
  3341. (defvar org-clock-start-time)
  3342. (defvar org-clock-marker (make-marker)
  3343. "Marker recording the last clock-in.")
  3344. (defvar org-clock-hd-marker (make-marker)
  3345. "Marker recording the last clock-in, but the headline position.")
  3346. (defvar org-clock-heading ""
  3347. "The heading of the current clock entry.")
  3348. (defun org-clock-is-active ()
  3349. "Return the buffer where the clock is currently running.
  3350. Return nil if no clock is running."
  3351. (marker-buffer org-clock-marker))
  3352. (defun org-check-running-clock ()
  3353. "Check if the current buffer contains the running clock.
  3354. If yes, offer to stop it and to save the buffer with the changes."
  3355. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3356. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3357. (buffer-name))))
  3358. (org-clock-out)
  3359. (when (y-or-n-p "Save changed buffer?")
  3360. (save-buffer))))
  3361. (defun org-clocktable-try-shift (dir n)
  3362. "Check if this line starts a clock table, if yes, shift the time block."
  3363. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3364. (org-clocktable-shift dir n)))
  3365. ;;;###autoload
  3366. (defun org-clock-persistence-insinuate ()
  3367. "Set up hooks for clock persistence."
  3368. (require 'org-clock)
  3369. (add-hook 'org-mode-hook 'org-clock-load)
  3370. (add-hook 'kill-emacs-hook 'org-clock-save))
  3371. (defgroup org-archive nil
  3372. "Options concerning archiving in Org mode."
  3373. :tag "Org Archive"
  3374. :group 'org-structure)
  3375. (defcustom org-archive-location "%s_archive::"
  3376. "The location where subtrees should be archived.
  3377. The value of this variable is a string, consisting of two parts,
  3378. separated by a double-colon. The first part is a filename and
  3379. the second part is a headline.
  3380. When the filename is omitted, archiving happens in the same file.
  3381. %s in the filename will be replaced by the current file
  3382. name (without the directory part). Archiving to a different file
  3383. is useful to keep archived entries from contributing to the
  3384. Org Agenda.
  3385. The archived entries will be filed as subtrees of the specified
  3386. headline. When the headline is omitted, the subtrees are simply
  3387. filed away at the end of the file, as top-level entries. Also in
  3388. the heading you can use %s to represent the file name, this can be
  3389. useful when using the same archive for a number of different files.
  3390. Here are a few examples:
  3391. \"%s_archive::\"
  3392. If the current file is Projects.org, archive in file
  3393. Projects.org_archive, as top-level trees. This is the default.
  3394. \"::* Archived Tasks\"
  3395. Archive in the current file, under the top-level headline
  3396. \"* Archived Tasks\".
  3397. \"~/org/archive.org::\"
  3398. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3399. \"~/org/archive.org::* From %s\"
  3400. Archive in file ~/org/archive.org (absolute path), under headlines
  3401. \"From FILENAME\" where file name is the current file name.
  3402. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3403. The \"datetree/\" string is special, signifying to archive
  3404. items to the datetree. Items are placed in either the CLOSED
  3405. date of the item, or the current date if there is no CLOSED date.
  3406. The heading will be a subentry to the current date. There doesn't
  3407. need to be a heading, but there always needs to be a slash after
  3408. datetree. For example, to store archived items directly in the
  3409. datetree, use \"~/org/datetree.org::datetree/\".
  3410. \"basement::** Finished Tasks\"
  3411. Archive in file ./basement (relative path), as level 3 trees
  3412. below the level 2 heading \"** Finished Tasks\".
  3413. You may set this option on a per-file basis by adding to the buffer a
  3414. line like
  3415. #+ARCHIVE: basement::** Finished Tasks
  3416. You may also define it locally for a subtree by setting an ARCHIVE property
  3417. in the entry. If such a property is found in an entry, or anywhere up
  3418. the hierarchy, it will be used."
  3419. :group 'org-archive
  3420. :type 'string)
  3421. (defcustom org-agenda-skip-archived-trees t
  3422. "Non-nil means the agenda will skip any items located in archived trees.
  3423. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3424. variable is no longer recommended, you should leave it at the value t.
  3425. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3426. :group 'org-archive
  3427. :group 'org-agenda-skip
  3428. :type 'boolean)
  3429. (defcustom org-columns-skip-archived-trees t
  3430. "Non-nil means ignore archived trees when creating column view."
  3431. :group 'org-archive
  3432. :group 'org-properties
  3433. :type 'boolean)
  3434. (defcustom org-cycle-open-archived-trees nil
  3435. "Non-nil means `org-cycle' will open archived trees.
  3436. An archived tree is a tree marked with the tag ARCHIVE.
  3437. When nil, archived trees will stay folded. You can still open them with
  3438. normal outline commands like `show-all', but not with the cycling commands."
  3439. :group 'org-archive
  3440. :group 'org-cycle
  3441. :type 'boolean)
  3442. (defcustom org-sparse-tree-open-archived-trees nil
  3443. "Non-nil means sparse tree construction shows matches in archived trees.
  3444. When nil, matches in these trees are highlighted, but the trees are kept in
  3445. collapsed state."
  3446. :group 'org-archive
  3447. :group 'org-sparse-trees
  3448. :type 'boolean)
  3449. (defcustom org-sparse-tree-default-date-type nil
  3450. "The default date type when building a sparse tree.
  3451. When this is nil, a date is a scheduled or a deadline timestamp.
  3452. Otherwise, these types are allowed:
  3453. all: all timestamps
  3454. active: only active timestamps (<...>)
  3455. inactive: only inactive timestamps ([...])
  3456. scheduled: only scheduled timestamps
  3457. deadline: only deadline timestamps"
  3458. :type '(choice (const :tag "Scheduled or deadline" nil)
  3459. (const :tag "All timestamps" all)
  3460. (const :tag "Only active timestamps" active)
  3461. (const :tag "Only inactive timestamps" inactive)
  3462. (const :tag "Only scheduled timestamps" scheduled)
  3463. (const :tag "Only deadline timestamps" deadline)
  3464. (const :tag "Only closed timestamps" closed))
  3465. :version "26.1"
  3466. :package-version '(Org . "8.3")
  3467. :group 'org-sparse-trees)
  3468. (defun org-cycle-hide-archived-subtrees (state)
  3469. "Re-hide all archived subtrees after a visibility state change.
  3470. STATE should be one of the symbols listed in the docstring of
  3471. `org-cycle-hook'."
  3472. (when (and (not org-cycle-open-archived-trees)
  3473. (not (memq state '(overview folded))))
  3474. (save-excursion
  3475. (let* ((globalp (memq state '(contents all)))
  3476. (beg (if globalp (point-min) (point)))
  3477. (end (if globalp (point-max) (org-end-of-subtree t))))
  3478. (org-hide-archived-subtrees beg end)
  3479. (goto-char beg)
  3480. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3481. (message "%s" (substitute-command-keys
  3482. "Subtree is archived and stays closed. Use \
  3483. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3484. (defun org-force-cycle-archived ()
  3485. "Cycle subtree even if it is archived."
  3486. (interactive)
  3487. (setq this-command 'org-cycle)
  3488. (let ((org-cycle-open-archived-trees t))
  3489. (call-interactively 'org-cycle)))
  3490. (defun org-hide-archived-subtrees (beg end)
  3491. "Re-hide all archived subtrees after a visibility state change."
  3492. (org-with-wide-buffer
  3493. (let ((case-fold-search nil)
  3494. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3495. (goto-char beg)
  3496. ;; Include headline point is currently on.
  3497. (beginning-of-line)
  3498. (while (and (< (point) end) (re-search-forward re end t))
  3499. (when (member org-archive-tag (org-get-tags nil t))
  3500. (org-flag-subtree t)
  3501. (org-end-of-subtree t))))))
  3502. (defun org-flag-subtree (flag)
  3503. (save-excursion
  3504. (org-back-to-heading t)
  3505. (org-flag-region (line-end-position)
  3506. (progn (org-end-of-subtree t) (point))
  3507. flag
  3508. 'outline)))
  3509. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3510. ;; Declare Column View Code
  3511. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3512. (declare-function org-columns-compute "org-colview" (property))
  3513. ;; Declare ID code
  3514. (declare-function org-id-store-link "org-id")
  3515. (declare-function org-id-locations-load "org-id")
  3516. (declare-function org-id-locations-save "org-id")
  3517. (defvar org-id-track-globally)
  3518. ;;; Variables for pre-computed regular expressions, all buffer local
  3519. (defvar-local org-todo-regexp nil
  3520. "Matches any of the TODO state keywords.
  3521. Since TODO keywords are case-sensitive, `case-fold-search' is
  3522. expected to be bound to nil when matching against this regexp.")
  3523. (defvar-local org-not-done-regexp nil
  3524. "Matches any of the TODO state keywords except the last one.
  3525. Since TODO keywords are case-sensitive, `case-fold-search' is
  3526. expected to be bound to nil when matching against this regexp.")
  3527. (defvar-local org-not-done-heading-regexp nil
  3528. "Matches a TODO headline that is not done.
  3529. Since TODO keywords are case-sensitive, `case-fold-search' is
  3530. expected to be bound to nil when matching against this regexp.")
  3531. (defvar-local org-todo-line-regexp nil
  3532. "Matches a headline and puts TODO state into group 2 if present.
  3533. Since TODO keywords are case-sensitive, `case-fold-search' is
  3534. expected to be bound to nil when matching against this regexp.")
  3535. (defvar-local org-complex-heading-regexp nil
  3536. "Matches a headline and puts everything into groups:
  3537. group 1: Stars
  3538. group 2: The TODO keyword, maybe
  3539. group 3: Priority cookie
  3540. group 4: True headline
  3541. group 5: Tags
  3542. Since TODO keywords are case-sensitive, `case-fold-search' is
  3543. expected to be bound to nil when matching against this regexp.")
  3544. (defvar-local org-complex-heading-regexp-format nil
  3545. "Printf format to make regexp to match an exact headline.
  3546. This regexp will match the headline of any node which has the
  3547. exact headline text that is put into the format, but may have any
  3548. TODO state, priority and tags.")
  3549. (defvar-local org-todo-line-tags-regexp nil
  3550. "Matches a headline and puts TODO state into group 2 if present.
  3551. Also put tags into group 4 if tags are present.")
  3552. (defconst org-plain-time-of-day-regexp
  3553. (concat
  3554. "\\(\\<[012]?[0-9]"
  3555. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3556. "\\(--?"
  3557. "\\(\\<[012]?[0-9]"
  3558. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3559. "\\)?")
  3560. "Regular expression to match a plain time or time range.
  3561. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3562. groups carry important information:
  3563. 0 the full match
  3564. 1 the first time, range or not
  3565. 8 the second time, if it is a range.")
  3566. (defconst org-plain-time-extension-regexp
  3567. (concat
  3568. "\\(\\<[012]?[0-9]"
  3569. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3570. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3571. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3572. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3573. groups carry important information:
  3574. 0 the full match
  3575. 7 hours of duration
  3576. 9 minutes of duration")
  3577. (defconst org-stamp-time-of-day-regexp
  3578. (concat
  3579. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3580. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3581. "\\(--?"
  3582. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3583. "Regular expression to match a timestamp time or time range.
  3584. After a match, the following groups carry important information:
  3585. 0 the full match
  3586. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3587. 2 the first time, range or not
  3588. 4 the second time, if it is a range.")
  3589. (defconst org-startup-options
  3590. '(("fold" org-startup-folded t)
  3591. ("overview" org-startup-folded t)
  3592. ("nofold" org-startup-folded nil)
  3593. ("showall" org-startup-folded nil)
  3594. ("showeverything" org-startup-folded showeverything)
  3595. ("content" org-startup-folded content)
  3596. ("indent" org-startup-indented t)
  3597. ("noindent" org-startup-indented nil)
  3598. ("hidestars" org-hide-leading-stars t)
  3599. ("showstars" org-hide-leading-stars nil)
  3600. ("odd" org-odd-levels-only t)
  3601. ("oddeven" org-odd-levels-only nil)
  3602. ("align" org-startup-align-all-tables t)
  3603. ("noalign" org-startup-align-all-tables nil)
  3604. ("shrink" org-startup-shrink-all-tables t)
  3605. ("inlineimages" org-startup-with-inline-images t)
  3606. ("noinlineimages" org-startup-with-inline-images nil)
  3607. ("latexpreview" org-startup-with-latex-preview t)
  3608. ("nolatexpreview" org-startup-with-latex-preview nil)
  3609. ("customtime" org-display-custom-times t)
  3610. ("logdone" org-log-done time)
  3611. ("lognotedone" org-log-done note)
  3612. ("nologdone" org-log-done nil)
  3613. ("lognoteclock-out" org-log-note-clock-out t)
  3614. ("nolognoteclock-out" org-log-note-clock-out nil)
  3615. ("logrepeat" org-log-repeat state)
  3616. ("lognoterepeat" org-log-repeat note)
  3617. ("logdrawer" org-log-into-drawer t)
  3618. ("nologdrawer" org-log-into-drawer nil)
  3619. ("logstatesreversed" org-log-states-order-reversed t)
  3620. ("nologstatesreversed" org-log-states-order-reversed nil)
  3621. ("nologrepeat" org-log-repeat nil)
  3622. ("logreschedule" org-log-reschedule time)
  3623. ("lognotereschedule" org-log-reschedule note)
  3624. ("nologreschedule" org-log-reschedule nil)
  3625. ("logredeadline" org-log-redeadline time)
  3626. ("lognoteredeadline" org-log-redeadline note)
  3627. ("nologredeadline" org-log-redeadline nil)
  3628. ("logrefile" org-log-refile time)
  3629. ("lognoterefile" org-log-refile note)
  3630. ("nologrefile" org-log-refile nil)
  3631. ("fninline" org-footnote-define-inline t)
  3632. ("nofninline" org-footnote-define-inline nil)
  3633. ("fnlocal" org-footnote-section nil)
  3634. ("fnauto" org-footnote-auto-label t)
  3635. ("fnprompt" org-footnote-auto-label nil)
  3636. ("fnconfirm" org-footnote-auto-label confirm)
  3637. ("fnplain" org-footnote-auto-label plain)
  3638. ("fnadjust" org-footnote-auto-adjust t)
  3639. ("nofnadjust" org-footnote-auto-adjust nil)
  3640. ("constcgs" constants-unit-system cgs)
  3641. ("constSI" constants-unit-system SI)
  3642. ("noptag" org-tag-persistent-alist nil)
  3643. ("hideblocks" org-hide-block-startup t)
  3644. ("nohideblocks" org-hide-block-startup nil)
  3645. ("beamer" org-startup-with-beamer-mode t)
  3646. ("entitiespretty" org-pretty-entities t)
  3647. ("entitiesplain" org-pretty-entities nil))
  3648. "Variable associated with STARTUP options for Org.
  3649. Each element is a list of three items: the startup options (as written
  3650. in the #+STARTUP line), the corresponding variable, and the value to set
  3651. this variable to if the option is found. An optional forth element PUSH
  3652. means to push this value onto the list in the variable.")
  3653. (defcustom org-group-tags t
  3654. "When non-nil (the default), use group tags.
  3655. This can be turned on/off through `org-toggle-tags-groups'."
  3656. :group 'org-tags
  3657. :group 'org-startup
  3658. :type 'boolean)
  3659. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3660. (defun org-toggle-tags-groups ()
  3661. "Toggle support for group tags.
  3662. Support for group tags is controlled by the option
  3663. `org-group-tags', which is non-nil by default."
  3664. (interactive)
  3665. (setq org-group-tags (not org-group-tags))
  3666. (cond ((and (derived-mode-p 'org-agenda-mode)
  3667. org-group-tags)
  3668. (org-agenda-redo))
  3669. ((derived-mode-p 'org-mode)
  3670. (let ((org-inhibit-startup t)) (org-mode))))
  3671. (message "Groups tags support has been turned %s"
  3672. (if org-group-tags "on" "off")))
  3673. (defun org--tag-add-to-alist (alist1 alist2)
  3674. "Merge tags from ALIST1 into ALIST2.
  3675. Duplicates tags outside a group are removed. Keywords and order
  3676. are preserved.
  3677. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3678. See `org-tag-alist' for their structure."
  3679. (cond
  3680. ((null alist2) alist1)
  3681. ((null alist1) alist2)
  3682. (t
  3683. (let ((to-add nil)
  3684. (group-flag nil))
  3685. (dolist (tag-pair alist1)
  3686. (pcase tag-pair
  3687. (`(,(or :startgrouptag :startgroup))
  3688. (setq group-flag t)
  3689. (push tag-pair to-add))
  3690. (`(,(or :endgrouptag :endgroup))
  3691. (setq group-flag nil)
  3692. (push tag-pair to-add))
  3693. (`(,(or :grouptags :newline))
  3694. (push tag-pair to-add))
  3695. (`(,tag . ,_)
  3696. ;; Remove duplicates from ALIST1, unless they are in
  3697. ;; a group. Indeed, it makes sense to have a tag appear in
  3698. ;; multiple groups.
  3699. (when (or group-flag (not (assoc tag alist2)))
  3700. (push tag-pair to-add)))
  3701. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3702. ;; Preserve order of ALIST1.
  3703. (append (nreverse to-add) alist2)))))
  3704. (defun org-set-regexps-and-options (&optional tags-only)
  3705. "Precompute regular expressions used in the current buffer.
  3706. When optional argument TAGS-ONLY is non-nil, only compute tags
  3707. related expressions."
  3708. (when (derived-mode-p 'org-mode)
  3709. (let ((alist (org--setup-collect-keywords
  3710. (org-make-options-regexp
  3711. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3712. (and (not tags-only)
  3713. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3714. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3715. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3716. ;; Startup options. Get this early since it does change
  3717. ;; behavior for other options (e.g., tags).
  3718. (let ((startup (cdr (assq 'startup alist))))
  3719. (dolist (option startup)
  3720. (let ((entry (assoc-string option org-startup-options t)))
  3721. (when entry
  3722. (let ((var (nth 1 entry))
  3723. (val (nth 2 entry)))
  3724. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3725. (unless (listp (symbol-value var))
  3726. (set (make-local-variable var) nil))
  3727. (add-to-list var val)))))))
  3728. (setq-local org-file-tags
  3729. (mapcar #'org-add-prop-inherited
  3730. (cdr (assq 'filetags alist))))
  3731. (setq org-current-tag-alist
  3732. (org--tag-add-to-alist
  3733. org-tag-persistent-alist
  3734. (let ((tags (cdr (assq 'tags alist))))
  3735. (if tags (org-tag-string-to-alist tags)
  3736. org-tag-alist))))
  3737. (setq org-tag-groups-alist
  3738. (org-tag-alist-to-groups org-current-tag-alist))
  3739. (unless tags-only
  3740. ;; File properties.
  3741. (setq-local org-file-properties (cdr (assq 'property alist)))
  3742. ;; Archive location.
  3743. (let ((archive (cdr (assq 'archive alist))))
  3744. (when archive (setq-local org-archive-location archive)))
  3745. ;; Category.
  3746. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3747. (when cat
  3748. (setq-local org-category (intern cat))
  3749. (setq-local org-file-properties
  3750. (org--update-property-plist
  3751. "CATEGORY" cat org-file-properties))))
  3752. ;; Columns.
  3753. (let ((column (cdr (assq 'columns alist))))
  3754. (when column (setq-local org-columns-default-format column)))
  3755. ;; Constants.
  3756. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3757. ;; Link abbreviations.
  3758. (let ((links (cdr (assq 'link alist))))
  3759. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3760. ;; Priorities.
  3761. (let ((priorities (cdr (assq 'priorities alist))))
  3762. (when priorities
  3763. (setq-local org-highest-priority (nth 0 priorities))
  3764. (setq-local org-lowest-priority (nth 1 priorities))
  3765. (setq-local org-default-priority (nth 2 priorities))))
  3766. ;; Scripts.
  3767. (let ((scripts (assq 'scripts alist)))
  3768. (when scripts
  3769. (setq-local org-use-sub-superscripts (cdr scripts))))
  3770. ;; TODO keywords.
  3771. (setq-local org-todo-kwd-alist nil)
  3772. (setq-local org-todo-key-alist nil)
  3773. (setq-local org-todo-key-trigger nil)
  3774. (setq-local org-todo-keywords-1 nil)
  3775. (setq-local org-done-keywords nil)
  3776. (setq-local org-todo-heads nil)
  3777. (setq-local org-todo-sets nil)
  3778. (setq-local org-todo-log-states nil)
  3779. (let ((todo-sequences
  3780. (or (nreverse (cdr (assq 'todo alist)))
  3781. (let ((d (default-value 'org-todo-keywords)))
  3782. (if (not (stringp (car d))) d
  3783. ;; XXX: Backward compatibility code.
  3784. (list (cons org-todo-interpretation d)))))))
  3785. (dolist (sequence todo-sequences)
  3786. (let* ((sequence (or (run-hook-with-args-until-success
  3787. 'org-todo-setup-filter-hook sequence)
  3788. sequence))
  3789. (sequence-type (car sequence))
  3790. (keywords (cdr sequence))
  3791. (sep (member "|" keywords))
  3792. names alist)
  3793. (dolist (k (remove "|" keywords))
  3794. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3795. k)
  3796. (error "Invalid TODO keyword %s" k))
  3797. (let ((name (match-string 1 k))
  3798. (key (match-string 2 k))
  3799. (log (org-extract-log-state-settings k)))
  3800. (push name names)
  3801. (push (cons name (and key (string-to-char key))) alist)
  3802. (when log (push log org-todo-log-states))))
  3803. (let* ((names (nreverse names))
  3804. (done (if sep (org-remove-keyword-keys (cdr sep))
  3805. (last names)))
  3806. (head (car names))
  3807. (tail (list sequence-type head (car done) (org-last done))))
  3808. (add-to-list 'org-todo-heads head 'append)
  3809. (push names org-todo-sets)
  3810. (setq org-done-keywords (append org-done-keywords done nil))
  3811. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3812. (setq org-todo-key-alist
  3813. (append org-todo-key-alist
  3814. (and alist
  3815. (append '((:startgroup))
  3816. (nreverse alist)
  3817. '((:endgroup))))))
  3818. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3819. (setq org-todo-sets (nreverse org-todo-sets)
  3820. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3821. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3822. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3823. ;; Compute the regular expressions and other local variables.
  3824. ;; Using `org-outline-regexp-bol' would complicate them much,
  3825. ;; because of the fixed white space at the end of that string.
  3826. (unless org-done-keywords
  3827. (setq org-done-keywords
  3828. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3829. (setq org-not-done-keywords
  3830. (org-delete-all org-done-keywords
  3831. (copy-sequence org-todo-keywords-1))
  3832. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3833. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3834. org-not-done-heading-regexp
  3835. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3836. org-todo-line-regexp
  3837. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3838. org-complex-heading-regexp
  3839. (concat "^\\(\\*+\\)"
  3840. "\\(?: +" org-todo-regexp "\\)?"
  3841. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3842. "\\(?: +\\(.*?\\)\\)??"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3844. "[ \t]*$")
  3845. org-complex-heading-regexp-format
  3846. (concat "^\\(\\*+\\)"
  3847. "\\(?: +" org-todo-regexp "\\)?"
  3848. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3849. "\\(?: +"
  3850. ;; Stats cookies can be stuck to body.
  3851. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3852. "\\(%s\\)"
  3853. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3854. "\\)"
  3855. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3856. "[ \t]*$")
  3857. org-todo-line-tags-regexp
  3858. (concat "^\\(\\*+\\)"
  3859. "\\(?: +" org-todo-regexp "\\)?"
  3860. "\\(?: +\\(.*?\\)\\)??"
  3861. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3862. "[ \t]*$"))
  3863. (org-compute-latex-and-related-regexp)))))
  3864. (defun org--setup-collect-keywords (regexp &optional files alist)
  3865. "Return setup keywords values as an alist.
  3866. REGEXP matches a subset of setup keywords. FILES is a list of
  3867. file names already visited. It is used to avoid circular setup
  3868. files. ALIST, when non-nil, is the alist computed so far.
  3869. Return value contains the following keys: `archive', `category',
  3870. `columns', `constants', `filetags', `link', `priorities',
  3871. `property', `scripts', `startup', `tags' and `todo'."
  3872. (org-with-wide-buffer
  3873. (goto-char (point-min))
  3874. (let ((case-fold-search t))
  3875. (while (re-search-forward regexp nil t)
  3876. (let ((element (org-element-at-point)))
  3877. (when (eq (org-element-type element) 'keyword)
  3878. (let ((key (org-element-property :key element))
  3879. (value (org-element-property :value element)))
  3880. (cond
  3881. ((equal key "ARCHIVE")
  3882. (when (org-string-nw-p value)
  3883. (push (cons 'archive value) alist)))
  3884. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3885. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3886. ((equal key "CONSTANTS")
  3887. (let* ((constants (assq 'constants alist))
  3888. (store (cdr constants)))
  3889. (dolist (pair (split-string value))
  3890. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3891. pair)
  3892. (let* ((name (match-string 1 pair))
  3893. (value (match-string 2 pair))
  3894. (old (assoc name store)))
  3895. (if old (setcdr old value)
  3896. (push (cons name value) store)))))
  3897. (if constants (setcdr constants store)
  3898. (push (cons 'constants store) alist))))
  3899. ((equal key "FILETAGS")
  3900. (when (org-string-nw-p value)
  3901. (let ((old (assq 'filetags alist))
  3902. (new (apply #'nconc
  3903. (mapcar (lambda (x) (org-split-string x ":"))
  3904. (split-string value)))))
  3905. (if old (setcdr old (append new (cdr old)))
  3906. (push (cons 'filetags new) alist)))))
  3907. ((equal key "LINK")
  3908. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3909. (let ((links (assq 'link alist))
  3910. (pair (cons (match-string-no-properties 1 value)
  3911. (match-string-no-properties 2 value))))
  3912. (if links (push pair (cdr links))
  3913. (push (list 'link pair) alist)))))
  3914. ((equal key "OPTIONS")
  3915. (when (and (org-string-nw-p value)
  3916. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3917. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3918. ((equal key "PRIORITIES")
  3919. (push (cons 'priorities
  3920. (let ((prio (split-string value)))
  3921. (if (< (length prio) 3) '(?A ?C ?B)
  3922. (mapcar #'string-to-char prio))))
  3923. alist))
  3924. ((equal key "PROPERTY")
  3925. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3926. (let* ((property (assq 'property alist))
  3927. (value (org--update-property-plist
  3928. (match-string-no-properties 1 value)
  3929. (match-string-no-properties 2 value)
  3930. (cdr property))))
  3931. (if property (setcdr property value)
  3932. (push (cons 'property value) alist)))))
  3933. ((equal key "STARTUP")
  3934. (let ((startup (assq 'startup alist)))
  3935. (if startup
  3936. (setcdr startup
  3937. (append (cdr startup) (split-string value)))
  3938. (push (cons 'startup (split-string value)) alist))))
  3939. ((equal key "TAGS")
  3940. (let ((tag-cell (assq 'tags alist)))
  3941. (if tag-cell
  3942. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3943. (push (cons 'tags value) alist))))
  3944. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3945. (let ((todo (assq 'todo alist))
  3946. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3947. (split-string value))))
  3948. (if todo (push value (cdr todo))
  3949. (push (list 'todo value) alist))))
  3950. ((equal key "SETUPFILE")
  3951. (unless buffer-read-only ; Do not check in Gnus messages.
  3952. (let ((f (and (org-string-nw-p value)
  3953. (expand-file-name (org-strip-quotes value)))))
  3954. (when (and f (file-readable-p f) (not (member f files)))
  3955. (with-temp-buffer
  3956. (setq default-directory (file-name-directory f))
  3957. (insert-file-contents f)
  3958. (setq alist
  3959. ;; Fake Org mode to benefit from cache
  3960. ;; without recurring needlessly.
  3961. (let ((major-mode 'org-mode))
  3962. (org--setup-collect-keywords
  3963. regexp (cons f files) alist)))))))))))))))
  3964. alist)
  3965. (defun org-tag-string-to-alist (s)
  3966. "Return tag alist associated to string S.
  3967. S is a value for TAGS keyword or produced with
  3968. `org-tag-alist-to-string'. Return value is an alist suitable for
  3969. `org-tag-alist' or `org-tag-persistent-alist'."
  3970. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3971. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3972. "\\(?:(\\(.\\))\\)?\\'"))
  3973. alist group-flag)
  3974. (dolist (tokens lines (cdr (nreverse alist)))
  3975. (push '(:newline) alist)
  3976. (while tokens
  3977. (let ((token (pop tokens)))
  3978. (pcase token
  3979. ("{"
  3980. (push '(:startgroup) alist)
  3981. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3982. ("}"
  3983. (push '(:endgroup) alist)
  3984. (setq group-flag nil))
  3985. ("["
  3986. (push '(:startgrouptag) alist)
  3987. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3988. ("]"
  3989. (push '(:endgrouptag) alist)
  3990. (setq group-flag nil))
  3991. (":"
  3992. (push '(:grouptags) alist))
  3993. ((guard (string-match tag-re token))
  3994. (let ((tag (match-string 1 token))
  3995. (key (and (match-beginning 2)
  3996. (string-to-char (match-string 2 token)))))
  3997. ;; Push all tags in groups, no matter if they already
  3998. ;; appear somewhere else in the list.
  3999. (when (or group-flag (not (assoc tag alist)))
  4000. (push (cons tag key) alist))))))))))
  4001. (defun org-tag-alist-to-string (alist &optional skip-key)
  4002. "Return tag string associated to ALIST.
  4003. ALIST is an alist, as defined in `org-tag-alist' or
  4004. `org-tag-persistent-alist', or produced with
  4005. `org-tag-string-to-alist'.
  4006. Return value is a string suitable as a value for \"TAGS\"
  4007. keyword.
  4008. When optional argument SKIP-KEY is non-nil, skip selection keys
  4009. next to tags."
  4010. (mapconcat (lambda (token)
  4011. (pcase token
  4012. (`(:startgroup) "{")
  4013. (`(:endgroup) "}")
  4014. (`(:startgrouptag) "[")
  4015. (`(:endgrouptag) "]")
  4016. (`(:grouptags) ":")
  4017. (`(:newline) "\\n")
  4018. ((and
  4019. (guard (not skip-key))
  4020. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4021. (format "%s(%c)" tag key))
  4022. (`(,(and tag (pred stringp)) . ,_) tag)
  4023. (_ (user-error "Invalid tag token: %S" token))))
  4024. alist
  4025. " "))
  4026. (defun org-tag-alist-to-groups (alist)
  4027. "Return group alist from tag ALIST.
  4028. ALIST is an alist, as defined in `org-tag-alist' or
  4029. `org-tag-persistent-alist', or produced with
  4030. `org-tag-string-to-alist'. Return value is an alist following
  4031. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4032. a string, summarizing TAGS, as a list of strings."
  4033. (let (groups group-status current-group)
  4034. (dolist (token alist (nreverse groups))
  4035. (pcase token
  4036. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4037. (`(,(or :endgroup :endgrouptag))
  4038. (when (eq group-status 'append)
  4039. (push (nreverse current-group) groups))
  4040. (setq group-status nil current-group nil))
  4041. (`(:grouptags) (setq group-status 'append))
  4042. ((and `(,tag . ,_) (guard group-status))
  4043. (if (eq group-status 'append) (push tag current-group)
  4044. (setq current-group (list tag))))
  4045. (_ nil)))))
  4046. (defvar org--file-cache (make-hash-table :test #'equal)
  4047. "Hash table to store contents of files referenced via a URL.
  4048. This is the cache of file URLs read using `org-file-contents'.")
  4049. (defun org-reset-file-cache ()
  4050. "Reset the cache of files downloaded by `org-file-contents'."
  4051. (clrhash org--file-cache))
  4052. (defun org-file-url-p (file)
  4053. "Non-nil if FILE is a URL."
  4054. (require 'ffap)
  4055. (string-match-p ffap-url-regexp file))
  4056. (defun org-file-contents (file &optional noerror nocache)
  4057. "Return the contents of FILE, as a string.
  4058. FILE can be a file name or URL.
  4059. If FILE is a URL, download the contents. If the URL contents are
  4060. already cached in the `org--file-cache' hash table, the download step
  4061. is skipped.
  4062. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4063. from file or URL.
  4064. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4065. is available. This option applies only if FILE is a URL."
  4066. (let* ((is-url (org-file-url-p file))
  4067. (cache (and is-url
  4068. (not nocache)
  4069. (gethash file org--file-cache))))
  4070. (cond
  4071. (cache)
  4072. (is-url
  4073. (with-current-buffer (url-retrieve-synchronously file)
  4074. (goto-char (point-min))
  4075. ;; Move point to after the url-retrieve header.
  4076. (search-forward "\n\n" nil :move)
  4077. ;; Search for the success code only in the url-retrieve header.
  4078. (if (save-excursion
  4079. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4080. ;; Update the cache `org--file-cache' and return contents.
  4081. (puthash file
  4082. (buffer-substring-no-properties (point) (point-max))
  4083. org--file-cache)
  4084. (funcall (if noerror #'message #'user-error)
  4085. "Unable to fetch file from %S"
  4086. file))))
  4087. (t
  4088. (with-temp-buffer
  4089. (condition-case nil
  4090. (progn
  4091. (insert-file-contents file)
  4092. (buffer-string))
  4093. (file-error
  4094. (funcall (if noerror #'message #'user-error)
  4095. "Unable to read file %S"
  4096. file))))))))
  4097. (defun org-extract-log-state-settings (x)
  4098. "Extract the log state setting from a TODO keyword string.
  4099. This will extract info from a string like \"WAIT(w@/!)\"."
  4100. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4101. (let ((kw (match-string 1 x))
  4102. (log1 (and (match-end 3) (match-string 3 x)))
  4103. (log2 (and (match-end 4) (match-string 4 x))))
  4104. (and (or log1 log2)
  4105. (list kw
  4106. (and log1 (if (equal log1 "!") 'time 'note))
  4107. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4108. (defun org-remove-keyword-keys (list)
  4109. "Remove a pair of parenthesis at the end of each string in LIST."
  4110. (mapcar (lambda (x)
  4111. (if (string-match "(.*)$" x)
  4112. (substring x 0 (match-beginning 0))
  4113. x))
  4114. list))
  4115. (defun org-assign-fast-keys (alist)
  4116. "Assign fast keys to a keyword-key alist.
  4117. Respect keys that are already there."
  4118. (let (new e (alt ?0))
  4119. (while (setq e (pop alist))
  4120. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4121. (cdr e)) ;; Key already assigned.
  4122. (push e new)
  4123. (let ((clist (string-to-list (downcase (car e))))
  4124. (used (append new alist)))
  4125. (when (= (car clist) ?@)
  4126. (pop clist))
  4127. (while (and clist (rassoc (car clist) used))
  4128. (pop clist))
  4129. (unless clist
  4130. (while (rassoc alt used)
  4131. (cl-incf alt)))
  4132. (push (cons (car e) (or (car clist) alt)) new))))
  4133. (nreverse new)))
  4134. ;;; Some variables used in various places
  4135. (defvar org-window-configuration nil
  4136. "Used in various places to store a window configuration.")
  4137. (defvar org-selected-window nil
  4138. "Used in various places to store a window configuration.")
  4139. (defvar org-finish-function nil
  4140. "Function to be called when `C-c C-c' is used.
  4141. This is for getting out of special buffers like capture.")
  4142. (defvar org-last-state)
  4143. ;; Defined somewhere in this file, but used before definition.
  4144. (defvar org-entities) ;; defined in org-entities.el
  4145. (defvar org-struct-menu)
  4146. (defvar org-org-menu)
  4147. (defvar org-tbl-menu)
  4148. ;;;; Define the Org mode
  4149. (defun org-before-change-function (_beg _end)
  4150. "Every change indicates that a table might need an update."
  4151. (setq org-table-may-need-update t))
  4152. (defvar org-mode-map)
  4153. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4154. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4155. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4156. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4157. (defvar bidi-paragraph-direction)
  4158. (defvar buffer-face-mode-face)
  4159. (require 'outline)
  4160. ;; Other stuff we need.
  4161. (require 'time-date)
  4162. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4163. (require 'easymenu)
  4164. (autoload 'easy-menu-add "easymenu")
  4165. (require 'overlay)
  4166. ;; (require 'org-macs) moved higher up in the file before it is first used
  4167. (require 'org-entities)
  4168. ;; (require 'org-compat) moved higher up in the file before it is first used
  4169. (require 'org-faces)
  4170. (require 'org-list)
  4171. (require 'org-pcomplete)
  4172. (require 'org-src)
  4173. (require 'org-footnote)
  4174. (require 'org-macro)
  4175. ;; babel
  4176. (require 'ob)
  4177. ;;;###autoload
  4178. (define-derived-mode org-mode outline-mode "Org"
  4179. "Outline-based notes management and organizer, alias
  4180. \"Carsten's outline-mode for keeping track of everything.\"
  4181. Org mode develops organizational tasks around a NOTES file which
  4182. contains information about projects as plain text. Org mode is
  4183. implemented on top of Outline mode, which is ideal to keep the content
  4184. of large files well structured. It supports ToDo items, deadlines and
  4185. time stamps, which magically appear in the diary listing of the Emacs
  4186. calendar. Tables are easily created with a built-in table editor.
  4187. Plain text URL-like links connect to websites, emails (VM), Usenet
  4188. messages (Gnus), BBDB entries, and any files related to the project.
  4189. For printing and sharing of notes, an Org file (or a part of it)
  4190. can be exported as a structured ASCII or HTML file.
  4191. The following commands are available:
  4192. \\{org-mode-map}"
  4193. (org-load-modules-maybe)
  4194. (org-install-agenda-files-menu)
  4195. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4196. (add-to-invisibility-spec '(org-hide-block . t))
  4197. (add-to-invisibility-spec '(org-hide-drawer . t))
  4198. (setq-local outline-regexp org-outline-regexp)
  4199. (setq-local outline-level 'org-outline-level)
  4200. (setq bidi-paragraph-direction 'left-to-right)
  4201. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4202. (unless org-display-table
  4203. (setq org-display-table (make-display-table)))
  4204. (set-display-table-slot
  4205. org-display-table 4
  4206. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4207. org-ellipsis)))
  4208. (setq buffer-display-table org-display-table))
  4209. (org-set-regexps-and-options)
  4210. (org-set-font-lock-defaults)
  4211. (when (and org-tag-faces (not org-tags-special-faces-re))
  4212. ;; tag faces set outside customize.... force initialization.
  4213. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4214. ;; Calc embedded
  4215. (setq-local calc-embedded-open-mode "# ")
  4216. ;; Modify a few syntax entries
  4217. (modify-syntax-entry ?\" "\"")
  4218. (modify-syntax-entry ?\\ "_")
  4219. (modify-syntax-entry ?~ "_")
  4220. (modify-syntax-entry ?< "(>")
  4221. (modify-syntax-entry ?> ")<")
  4222. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4223. ;; Activate before-change-function
  4224. (setq-local org-table-may-need-update t)
  4225. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4226. ;; Check for running clock before killing a buffer
  4227. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4228. ;; Initialize macros templates.
  4229. (org-macro-initialize-templates)
  4230. ;; Initialize radio targets.
  4231. (org-update-radio-target-regexp)
  4232. ;; Indentation.
  4233. (setq-local indent-line-function 'org-indent-line)
  4234. (setq-local indent-region-function 'org-indent-region)
  4235. ;; Filling and auto-filling.
  4236. (org-setup-filling)
  4237. ;; Comments.
  4238. (org-setup-comments-handling)
  4239. ;; Initialize cache.
  4240. (org-element-cache-reset)
  4241. ;; Beginning/end of defun
  4242. (setq-local beginning-of-defun-function 'org-backward-element)
  4243. (setq-local end-of-defun-function
  4244. (lambda ()
  4245. (if (not (org-at-heading-p))
  4246. (org-forward-element)
  4247. (org-forward-element)
  4248. (forward-char -1))))
  4249. ;; Next error for sparse trees
  4250. (setq-local next-error-function 'org-occur-next-match)
  4251. ;; Make commit log messages from Org documents easier.
  4252. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4253. ;; Make sure dependence stuff works reliably, even for users who set it
  4254. ;; too late :-(
  4255. (if org-enforce-todo-dependencies
  4256. (add-hook 'org-blocker-hook
  4257. 'org-block-todo-from-children-or-siblings-or-parent)
  4258. (remove-hook 'org-blocker-hook
  4259. 'org-block-todo-from-children-or-siblings-or-parent))
  4260. (if org-enforce-todo-checkbox-dependencies
  4261. (add-hook 'org-blocker-hook
  4262. 'org-block-todo-from-checkboxes)
  4263. (remove-hook 'org-blocker-hook
  4264. 'org-block-todo-from-checkboxes))
  4265. ;; Align options lines
  4266. (setq-local
  4267. align-mode-rules-list
  4268. '((org-in-buffer-settings
  4269. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4270. (modes . '(org-mode)))))
  4271. ;; Make isearch reveal context
  4272. (setq-local outline-isearch-open-invisible-function
  4273. (lambda (&rest _) (org-show-context 'isearch)))
  4274. ;; Setup the pcomplete hooks
  4275. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4276. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4277. (setq-local pcomplete-default-completion-function #'ignore)
  4278. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4279. (setq-local pcomplete-termination-string "")
  4280. (add-hook 'completion-at-point-functions
  4281. #'pcomplete-completions-at-point nil t)
  4282. (setq-local buffer-face-mode-face 'org-default)
  4283. ;; If empty file that did not turn on Org mode automatically, make
  4284. ;; it to.
  4285. (when (and org-insert-mode-line-in-empty-file
  4286. (called-interactively-p 'any)
  4287. (= (point-min) (point-max)))
  4288. (insert "# -*- mode: org -*-\n\n"))
  4289. (unless org-inhibit-startup
  4290. (org-unmodified
  4291. (when org-startup-with-beamer-mode (org-beamer-mode))
  4292. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4293. (org-table-map-tables
  4294. (cond ((and org-startup-align-all-tables
  4295. org-startup-shrink-all-tables)
  4296. (lambda () (org-table-align) (org-table-shrink)))
  4297. (org-startup-align-all-tables #'org-table-align)
  4298. (t #'org-table-shrink))
  4299. t))
  4300. (when org-startup-with-inline-images (org-display-inline-images))
  4301. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4302. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4303. (when org-startup-truncated (setq truncate-lines t))
  4304. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4305. ;; Try to set `org-hide' face correctly.
  4306. (let ((foreground (org-find-invisible-foreground)))
  4307. (when foreground
  4308. (set-face-foreground 'org-hide foreground))))
  4309. ;; Update `customize-package-emacs-version-alist'
  4310. (add-to-list 'customize-package-emacs-version-alist
  4311. '(Org ("8.0" . "24.4")
  4312. ("8.1" . "24.4")
  4313. ("8.2" . "24.4")
  4314. ("8.2.7" . "24.4")
  4315. ("8.3" . "26.1")
  4316. ("9.0" . "26.1")
  4317. ("9.1" . "26.1")
  4318. ("9.2" . "27.1")
  4319. ("9.3" . "27.1")))
  4320. (defvar org-mode-transpose-word-syntax-table
  4321. (let ((st (make-syntax-table text-mode-syntax-table)))
  4322. (dolist (c org-emphasis-alist st)
  4323. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4324. (when (fboundp 'abbrev-table-put)
  4325. (abbrev-table-put org-mode-abbrev-table
  4326. :parents (list text-mode-abbrev-table)))
  4327. (defun org-find-invisible-foreground ()
  4328. (let ((candidates (remove
  4329. "unspecified-bg"
  4330. (nconc
  4331. (list (face-background 'default)
  4332. (face-background 'org-default))
  4333. (mapcar
  4334. (lambda (alist)
  4335. (when (boundp alist)
  4336. (cdr (assq 'background-color (symbol-value alist)))))
  4337. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4338. (list (face-foreground 'org-hide))))))
  4339. (car (remove nil candidates))))
  4340. (defun org-current-time (&optional rounding-minutes past)
  4341. "Current time, possibly rounded to ROUNDING-MINUTES.
  4342. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4343. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4344. the rounding returns a past time."
  4345. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4346. (car org-time-stamp-rounding-minutes)))
  4347. (now (current-time)))
  4348. (if (< r 1)
  4349. now
  4350. (let* ((time (decode-time now))
  4351. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4352. (nthcdr 2 time))))
  4353. (if (or (not past) (org-time-less-p res now))
  4354. res
  4355. (org-time-subtract res (* r 60)))))))
  4356. (defun org-today ()
  4357. "Return today date, considering `org-extend-today-until'."
  4358. (time-to-days
  4359. (org-time-since (* 3600 org-extend-today-until))))
  4360. ;;;; Font-Lock stuff, including the activators
  4361. (require 'font-lock)
  4362. (defconst org-match-sexp-depth 3
  4363. "Number of stacked braces for sub/superscript matching.")
  4364. (defun org-create-multibrace-regexp (left right n)
  4365. "Create a regular expression which will match a balanced sexp.
  4366. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4367. as single character strings.
  4368. The regexp returned will match the entire expression including the
  4369. delimiters. It will also define a single group which contains the
  4370. match except for the outermost delimiters. The maximum depth of
  4371. stacked delimiters is N. Escaping delimiters is not possible."
  4372. (let* ((nothing (concat "[^" left right "]*?"))
  4373. (or "\\|")
  4374. (re nothing)
  4375. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4376. (while (> n 1)
  4377. (setq n (1- n)
  4378. re (concat re or next)
  4379. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4380. (concat left "\\(" re "\\)" right)))
  4381. (defconst org-match-substring-regexp
  4382. (concat
  4383. "\\(\\S-\\)\\([_^]\\)\\("
  4384. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4385. "\\|"
  4386. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4387. "\\|"
  4388. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4389. "The regular expression matching a sub- or superscript.")
  4390. (defconst org-match-substring-with-braces-regexp
  4391. (concat
  4392. "\\(\\S-\\)\\([_^]\\)"
  4393. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4394. "The regular expression matching a sub- or superscript, forcing braces.")
  4395. (defvar org-emph-face nil)
  4396. (defun org-do-emphasis-faces (limit)
  4397. "Run through the buffer and emphasize strings."
  4398. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4399. (car org-emphasis-regexp-components))))
  4400. (catch :exit
  4401. (while (re-search-forward quick-re limit t)
  4402. (let* ((marker (match-string 2))
  4403. (verbatim? (member marker '("~" "="))))
  4404. (when (save-excursion
  4405. (goto-char (match-beginning 0))
  4406. (and
  4407. ;; Do not match table hlines.
  4408. (not (and (equal marker "+")
  4409. (org-match-line
  4410. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4411. ;; Do not match headline stars. Do not consider
  4412. ;; stars of a headline as closing marker for bold
  4413. ;; markup either.
  4414. (not (and (equal marker "*")
  4415. (save-excursion
  4416. (forward-char)
  4417. (skip-chars-backward "*")
  4418. (looking-at-p org-outline-regexp-bol))))
  4419. ;; Match full emphasis markup regexp.
  4420. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4421. ;; Do not span over paragraph boundaries.
  4422. (not (string-match-p org-element-paragraph-separate
  4423. (match-string 2)))
  4424. ;; Do not span over cells in table rows.
  4425. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4426. (string-match-p "|" (match-string 4))))))
  4427. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4428. (m (if org-hide-emphasis-markers 4 2)))
  4429. (font-lock-prepend-text-property
  4430. (match-beginning m) (match-end m) 'face face)
  4431. (when verbatim?
  4432. (org-remove-flyspell-overlays-in
  4433. (match-beginning 0) (match-end 0))
  4434. (remove-text-properties (match-beginning 2) (match-end 2)
  4435. '(display t invisible t intangible t)))
  4436. (add-text-properties (match-beginning 2) (match-end 2)
  4437. '(font-lock-multiline t org-emphasis t))
  4438. (when org-hide-emphasis-markers
  4439. (add-text-properties (match-end 4) (match-beginning 5)
  4440. '(invisible org-link))
  4441. (add-text-properties (match-beginning 3) (match-end 3)
  4442. '(invisible org-link)))
  4443. (throw :exit t))))))))
  4444. (defun org-emphasize (&optional char)
  4445. "Insert or change an emphasis, i.e. a font like bold or italic.
  4446. If there is an active region, change that region to a new emphasis.
  4447. If there is no region, just insert the marker characters and position
  4448. the cursor between them.
  4449. CHAR should be the marker character. If it is a space, it means to
  4450. remove the emphasis of the selected region.
  4451. If CHAR is not given (for example in an interactive call) it will be
  4452. prompted for."
  4453. (interactive)
  4454. (let ((erc org-emphasis-regexp-components)
  4455. (string "") beg end move s)
  4456. (if (org-region-active-p)
  4457. (setq beg (region-beginning)
  4458. end (region-end)
  4459. string (buffer-substring beg end))
  4460. (setq move t))
  4461. (unless char
  4462. (message "Emphasis marker or tag: [%s]"
  4463. (mapconcat #'car org-emphasis-alist ""))
  4464. (setq char (read-char-exclusive)))
  4465. (if (equal char ?\s)
  4466. (setq s ""
  4467. move nil)
  4468. (unless (assoc (char-to-string char) org-emphasis-alist)
  4469. (user-error "No such emphasis marker: \"%c\"" char))
  4470. (setq s (char-to-string char)))
  4471. (while (and (> (length string) 1)
  4472. (equal (substring string 0 1) (substring string -1))
  4473. (assoc (substring string 0 1) org-emphasis-alist))
  4474. (setq string (substring string 1 -1)))
  4475. (setq string (concat s string s))
  4476. (when beg (delete-region beg end))
  4477. (unless (or (bolp)
  4478. (string-match (concat "[" (nth 0 erc) "\n]")
  4479. (char-to-string (char-before (point)))))
  4480. (insert " "))
  4481. (unless (or (eobp)
  4482. (string-match (concat "[" (nth 1 erc) "\n]")
  4483. (char-to-string (char-after (point)))))
  4484. (insert " ") (backward-char 1))
  4485. (insert string)
  4486. (and move (backward-char 1))))
  4487. (defconst org-nonsticky-props
  4488. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4489. (defsubst org-rear-nonsticky-at (pos)
  4490. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4491. (defun org-activate-links (limit)
  4492. "Add link properties to links.
  4493. This includes angle, plain, and bracket links."
  4494. (catch :exit
  4495. (while (re-search-forward org-link-any-re limit t)
  4496. (let* ((start (match-beginning 0))
  4497. (end (match-end 0))
  4498. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4499. (visible-end (or (match-end 3) (match-end 2)))
  4500. (style (cond ((eq ?< (char-after start)) 'angle)
  4501. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4502. (t 'plain))))
  4503. (when (and (memq style org-highlight-links)
  4504. ;; Do not span over paragraph boundaries.
  4505. (not (string-match-p org-element-paragraph-separate
  4506. (match-string 0)))
  4507. ;; Do not confuse plain links with tags.
  4508. (not (and (eq style 'plain)
  4509. (let ((face (get-text-property
  4510. (max (1- start) (point-min)) 'face)))
  4511. (if (consp face) (memq 'org-tag face)
  4512. (eq 'org-tag face))))))
  4513. (let* ((link-object (save-excursion
  4514. (goto-char start)
  4515. (save-match-data (org-element-link-parser))))
  4516. (link (org-element-property :raw-link link-object))
  4517. (type (org-element-property :type link-object))
  4518. (path (org-element-property :path link-object))
  4519. (properties ;for link's visible part
  4520. (list
  4521. 'face (pcase (org-link-get-parameter type :face)
  4522. ((and (pred functionp) face) (funcall face path))
  4523. ((and (pred facep) face) face)
  4524. ((and (pred consp) face) face) ;anonymous
  4525. (_ 'org-link))
  4526. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4527. 'highlight)
  4528. 'keymap (or (org-link-get-parameter type :keymap)
  4529. org-mouse-map)
  4530. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4531. ((and (pred stringp) echo) echo)
  4532. ((and (pred functionp) echo) echo)
  4533. (_ (concat "LINK: " link)))
  4534. 'htmlize-link (pcase (org-link-get-parameter type
  4535. :htmlize-link)
  4536. ((and (pred functionp) f) (funcall f))
  4537. (_ `(:uri ,link)))
  4538. 'font-lock-multiline t)))
  4539. (org-remove-flyspell-overlays-in start end)
  4540. (org-rear-nonsticky-at end)
  4541. (if (not (eq 'bracket style))
  4542. (add-text-properties start end properties)
  4543. ;; Handle invisible parts in bracket links.
  4544. (remove-text-properties start end '(invisible nil))
  4545. (let ((hidden
  4546. (append `(invisible
  4547. ,(or (org-link-get-parameter type :display)
  4548. 'org-link))
  4549. properties)))
  4550. (add-text-properties start visible-start hidden)
  4551. (add-text-properties visible-start visible-end properties)
  4552. (add-text-properties visible-end end hidden)
  4553. (org-rear-nonsticky-at visible-start)
  4554. (org-rear-nonsticky-at visible-end)))
  4555. (let ((f (org-link-get-parameter type :activate-func)))
  4556. (when (functionp f)
  4557. (funcall f start end path (eq style 'bracket))))
  4558. (throw :exit t))))) ;signal success
  4559. nil))
  4560. (defun org-activate-code (limit)
  4561. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4562. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4563. (remove-text-properties (match-beginning 0) (match-end 0)
  4564. '(display t invisible t intangible t))
  4565. t))
  4566. (defcustom org-src-fontify-natively t
  4567. "When non-nil, fontify code in code blocks.
  4568. See also the `org-block' face."
  4569. :type 'boolean
  4570. :version "26.1"
  4571. :package-version '(Org . "8.3")
  4572. :group 'org-appearance
  4573. :group 'org-babel)
  4574. (defcustom org-allow-promoting-top-level-subtree nil
  4575. "When non-nil, allow promoting a top level subtree.
  4576. The leading star of the top level headline will be replaced
  4577. by a #."
  4578. :type 'boolean
  4579. :version "24.1"
  4580. :group 'org-appearance)
  4581. (defun org-fontify-meta-lines-and-blocks (limit)
  4582. (condition-case nil
  4583. (org-fontify-meta-lines-and-blocks-1 limit)
  4584. (error (message "Org mode fontification error in %S at %d"
  4585. (current-buffer)
  4586. (line-number-at-pos)))))
  4587. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4588. "Fontify #+ lines and blocks."
  4589. (let ((case-fold-search t))
  4590. (when (re-search-forward
  4591. (rx bol (group (zero-or-more blank) "#"
  4592. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4593. space
  4594. eol))
  4595. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4596. (zero-or-more blank)
  4597. (group (group (zero-or-more (not (any " \t\n"))))
  4598. (zero-or-more blank)
  4599. (group (zero-or-more any)))))
  4600. limit t)
  4601. (let ((beg (match-beginning 0))
  4602. (end-of-beginline (match-end 0))
  4603. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4604. (block-end nil) ; will include \n after end of block content
  4605. (lang (match-string 7)) ; the language, if it is an src block
  4606. (bol-after-beginline (line-beginning-position 2))
  4607. (dc1 (downcase (match-string 2)))
  4608. (dc3 (downcase (match-string 3)))
  4609. (whole-blockline org-fontify-whole-block-delimiter-line)
  4610. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4611. (cond
  4612. ((and (match-end 4) (equal dc3 "+begin"))
  4613. ;; Truly a block
  4614. (setq block-type (downcase (match-string 5))
  4615. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4616. (when (re-search-forward
  4617. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4618. (seq (zero-or-more blank)
  4619. "#+end"
  4620. ,(match-string 4)
  4621. word-end
  4622. (zero-or-more any)))))
  4623. nil t) ;; on purpose, we look further than LIMIT
  4624. ;; We do have a matching #+end line
  4625. (setq beg-of-endline (match-beginning 0)
  4626. end-of-endline (match-end 0)
  4627. nl-before-endline (1- (match-beginning 0)))
  4628. (setq block-end (match-beginning 0)) ; includes the final newline.
  4629. (when quoting
  4630. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4631. (remove-text-properties beg end-of-endline
  4632. '(display t invisible t intangible t)))
  4633. (add-text-properties
  4634. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4635. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4636. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4637. (cond
  4638. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4639. (org-src-font-lock-fontify-block lang block-start block-end)
  4640. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4641. (quoting
  4642. (add-text-properties
  4643. bol-after-beginline beg-of-endline
  4644. (list 'face
  4645. (list :inherit
  4646. (let ((face-name
  4647. (intern (format "org-block-%s" lang))))
  4648. (append (and (facep face-name) (list face-name))
  4649. '(org-block)))))))
  4650. ((not org-fontify-quote-and-verse-blocks))
  4651. ((string= block-type "quote")
  4652. (add-face-text-property
  4653. bol-after-beginline beg-of-endline 'org-quote t))
  4654. ((string= block-type "verse")
  4655. (add-face-text-property
  4656. bol-after-beginline beg-of-endline 'org-verse t)))
  4657. ;; Fontify the #+begin and #+end lines of the blocks
  4658. (add-text-properties
  4659. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4660. '(face org-block-begin-line))
  4661. (unless (string-prefix-p "*" (match-string 1))
  4662. (add-text-properties
  4663. beg-of-endline
  4664. (if whole-blockline
  4665. (let ((beg-of-next-line (1+ end-of-endline)))
  4666. (min (point-max) beg-of-next-line))
  4667. (min (point-max) end-of-endline))
  4668. '(face org-block-end-line)))
  4669. t))
  4670. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4671. (org-remove-flyspell-overlays-in
  4672. (match-beginning 0)
  4673. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4674. (add-text-properties
  4675. beg (match-end 3)
  4676. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4677. '(font-lock-fontified t invisible t)
  4678. '(font-lock-fontified t face org-document-info-keyword)))
  4679. (add-text-properties
  4680. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4681. (if (string-equal dc1 "+title:")
  4682. '(font-lock-fontified t face org-document-title)
  4683. '(font-lock-fontified t face org-document-info))))
  4684. ((string-prefix-p "+caption" dc1)
  4685. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4686. (remove-text-properties (match-beginning 0) (match-end 0)
  4687. '(display t invisible t intangible t))
  4688. ;; Handle short captions.
  4689. (save-excursion
  4690. (beginning-of-line)
  4691. (looking-at (rx (group (zero-or-more blank)
  4692. "#+caption"
  4693. (optional "[" (zero-or-more any) "]")
  4694. ":")
  4695. (zero-or-more blank))))
  4696. (add-text-properties (line-beginning-position) (match-end 1)
  4697. '(font-lock-fontified t face org-meta-line))
  4698. (add-text-properties (match-end 0) (line-end-position)
  4699. '(font-lock-fontified t face org-block))
  4700. t)
  4701. ((member dc3 '(" " ""))
  4702. ; Just a comment, the plus was not there
  4703. (org-remove-flyspell-overlays-in beg (match-end 0))
  4704. (add-text-properties
  4705. beg (match-end 0)
  4706. '(font-lock-fontified t face font-lock-comment-face)))
  4707. (t ;; just any other in-buffer setting, but not indented
  4708. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4709. (remove-text-properties (match-beginning 0) (match-end 0)
  4710. '(display t invisible t intangible t))
  4711. (add-text-properties beg (match-end 0)
  4712. '(font-lock-fontified t face org-meta-line))
  4713. t))))))
  4714. (defun org-fontify-drawers (limit)
  4715. "Fontify drawers."
  4716. (when (re-search-forward org-drawer-regexp limit t)
  4717. (add-text-properties
  4718. (line-beginning-position) (line-beginning-position 2)
  4719. '(font-lock-fontified t face org-drawer))
  4720. (org-remove-flyspell-overlays-in
  4721. (line-beginning-position) (line-beginning-position 2))
  4722. t))
  4723. (defun org-fontify-macros (limit)
  4724. "Fontify macros."
  4725. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4726. (let ((begin (match-beginning 0))
  4727. (opening-end (match-beginning 1)))
  4728. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4729. (match-string 1))
  4730. (let ((end (match-end 1))
  4731. (closing-start (match-beginning 1)))
  4732. (add-text-properties
  4733. begin end
  4734. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4735. (org-remove-flyspell-overlays-in begin end)
  4736. (when org-hide-macro-markers
  4737. (add-text-properties begin opening-end '(invisible t))
  4738. (add-text-properties closing-start end '(invisible t)))
  4739. t)))))
  4740. (defun org-fontify-extend-region (beg end _old-len)
  4741. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4742. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4743. (extend (lambda (r1 r2 dir)
  4744. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4745. (replace-regexp-in-string "[][]" r2
  4746. (match-string-no-properties 0)))))
  4747. (re-search-forward (regexp-quote re) nil t dir)))))
  4748. (save-match-data
  4749. (save-excursion
  4750. (goto-char beg)
  4751. (back-to-indentation)
  4752. (cond ((looking-at end-re)
  4753. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4754. ((looking-at begin-re)
  4755. (cons beg (or (funcall extend "end" "]" 1) end)))
  4756. (t (cons beg end)))))))
  4757. (defun org-activate-footnote-links (limit)
  4758. "Add text properties for footnotes."
  4759. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4760. (when fn
  4761. (let* ((beg (nth 1 fn))
  4762. (end (nth 2 fn))
  4763. (label (car fn))
  4764. (referencep (/= (line-beginning-position) beg)))
  4765. (when (and referencep (nth 3 fn))
  4766. (save-excursion
  4767. (goto-char beg)
  4768. (search-forward (or label "fn:"))
  4769. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4770. (add-text-properties beg end
  4771. (list 'mouse-face 'highlight
  4772. 'keymap org-mouse-map
  4773. 'help-echo
  4774. (if referencep "Footnote reference"
  4775. "Footnote definition")
  4776. 'font-lock-fontified t
  4777. 'font-lock-multiline t
  4778. 'face 'org-footnote))))))
  4779. (defun org-activate-dates (limit)
  4780. "Add text properties for dates."
  4781. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4782. (not (equal (char-before (match-beginning 0)) 91)))
  4783. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4784. (add-text-properties (match-beginning 0) (match-end 0)
  4785. (list 'mouse-face 'highlight
  4786. 'keymap org-mouse-map))
  4787. (org-rear-nonsticky-at (match-end 0))
  4788. (when org-display-custom-times
  4789. ;; If it's a date range, activate custom time for second date.
  4790. (when (match-end 3)
  4791. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4792. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4793. t))
  4794. (defun org-activate-target-links (limit)
  4795. "Add text properties for target matches."
  4796. (when org-target-link-regexp
  4797. (let ((case-fold-search t))
  4798. ;; `org-target-link-regexp' matches one character before the
  4799. ;; actual target.
  4800. (unless (bolp) (forward-char -1))
  4801. (when (re-search-forward org-target-link-regexp limit t)
  4802. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4803. (add-text-properties (match-beginning 1) (match-end 1)
  4804. (list 'mouse-face 'highlight
  4805. 'keymap org-mouse-map
  4806. 'help-echo "Radio target link"
  4807. 'org-linked-text t))
  4808. (org-rear-nonsticky-at (match-end 1))
  4809. t))))
  4810. (defvar org-latex-and-related-regexp nil
  4811. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4812. (defun org-compute-latex-and-related-regexp ()
  4813. "Compute regular expression for LaTeX, entities and sub/superscript.
  4814. Result depends on variable `org-highlight-latex-and-related'."
  4815. (let ((re-sub
  4816. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4817. ((eq org-use-sub-superscripts '{})
  4818. (list org-match-substring-with-braces-regexp))
  4819. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4820. (re-latex
  4821. (when (or (memq 'latex org-highlight-latex-and-related)
  4822. (memq 'native org-highlight-latex-and-related))
  4823. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4824. (delq nil
  4825. (mapcar (lambda (x)
  4826. (and (member (car x) matchers) (nth 1 x)))
  4827. org-latex-regexps)))))
  4828. (re-entities
  4829. (when (memq 'entities org-highlight-latex-and-related)
  4830. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4831. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4832. (setq-local org-latex-and-related-regexp
  4833. (mapconcat #'identity
  4834. (append re-latex re-entities re-sub)
  4835. "\\|"))))
  4836. (defun org-do-latex-and-related (_limit)
  4837. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4838. Stop at first highlighted object, if any. Return t if some
  4839. highlighting was done, nil otherwise."
  4840. (when (org-string-nw-p org-latex-and-related-regexp)
  4841. (catch 'found
  4842. (while (re-search-forward org-latex-and-related-regexp
  4843. nil t) ;; on purpose, we ignore LIMIT
  4844. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4845. org-special-keyword)))
  4846. (save-excursion
  4847. (goto-char (1+ (match-beginning 0)))
  4848. (face-at-point nil t)))
  4849. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4850. '(?_ ?^))
  4851. 1
  4852. 0))
  4853. (start (+ offset (match-beginning 0)))
  4854. (end (match-end 0)))
  4855. (if (memq 'native org-highlight-latex-and-related)
  4856. (org-src-font-lock-fontify-block "latex" start end)
  4857. (font-lock-prepend-text-property start end
  4858. 'face 'org-latex-and-related))
  4859. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4860. '(font-lock-multiline t)))
  4861. (throw 'found t)))
  4862. nil)))
  4863. (defun org-restart-font-lock ()
  4864. "Restart `font-lock-mode', to force refontification."
  4865. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4866. (font-lock-mode -1)
  4867. (font-lock-mode 1)))
  4868. (defun org-activate-tags (limit)
  4869. (when (re-search-forward org-tag-line-re limit t)
  4870. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4871. (add-text-properties (match-beginning 1) (match-end 1)
  4872. (list 'mouse-face 'highlight
  4873. 'keymap org-mouse-map))
  4874. (org-rear-nonsticky-at (match-end 1))
  4875. t))
  4876. (defun org-outline-level ()
  4877. "Compute the outline level of the heading at point.
  4878. If this is called at a normal headline, the level is the number
  4879. of stars. Use `org-reduced-level' to remove the effect of
  4880. `org-odd-levels'. Unlike to `org-current-level', this function
  4881. takes into consideration inlinetasks."
  4882. (org-with-wide-buffer
  4883. (end-of-line)
  4884. (if (re-search-backward org-outline-regexp-bol nil t)
  4885. (1- (- (match-end 0) (match-beginning 0)))
  4886. 0)))
  4887. (defvar org-font-lock-keywords nil)
  4888. (defsubst org-re-property (property &optional literal allow-null value)
  4889. "Return a regexp matching a PROPERTY line.
  4890. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4891. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4892. non-nil, match properties even without a value.
  4893. Match group 3 is set to the value when it exists. If there is no
  4894. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4895. With optional argument VALUE, match only property lines with
  4896. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4897. unless LITERAL is non-nil."
  4898. (concat
  4899. "^\\(?4:[ \t]*\\)"
  4900. (format "\\(?1::\\(?2:%s\\):\\)"
  4901. (if literal property (regexp-quote property)))
  4902. (cond (value
  4903. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4904. (if literal value (regexp-quote value))))
  4905. (allow-null
  4906. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4907. (t
  4908. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4909. (defconst org-property-re
  4910. (org-re-property "\\S-+" 'literal t)
  4911. "Regular expression matching a property line.
  4912. There are four matching groups:
  4913. 1: :PROPKEY: including the leading and trailing colon,
  4914. 2: PROPKEY without the leading and trailing colon,
  4915. 3: PROPVAL without leading or trailing spaces,
  4916. 4: the indentation of the current line,
  4917. 5: trailing whitespace.")
  4918. (defvar org-font-lock-hook nil
  4919. "Functions to be called for special font lock stuff.")
  4920. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4921. (defvar org-font-lock-set-keywords-hook nil
  4922. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4923. This is called after `org-font-lock-extra-keywords' is defined, but before
  4924. it is installed to be used by font lock. This can be useful if something
  4925. needs to be inserted at a specific position in the font-lock sequence.")
  4926. (defun org-font-lock-hook (limit)
  4927. "Run `org-font-lock-hook' within LIMIT."
  4928. (run-hook-with-args 'org-font-lock-hook limit))
  4929. (defun org-set-font-lock-defaults ()
  4930. "Set font lock defaults for the current buffer."
  4931. (let* ((em org-fontify-emphasized-text)
  4932. (lk org-highlight-links)
  4933. (org-font-lock-extra-keywords
  4934. (list
  4935. ;; Call the hook
  4936. '(org-font-lock-hook)
  4937. ;; Headlines
  4938. `(,(if org-fontify-whole-heading-line
  4939. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4940. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4941. (1 (org-get-level-face 1))
  4942. (2 (org-get-level-face 2))
  4943. (3 (org-get-level-face 3)))
  4944. ;; Table lines
  4945. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4946. (1 'org-table t))
  4947. ;; Table internals
  4948. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4949. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4950. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4951. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4952. ;; Properties
  4953. (list org-property-re
  4954. '(1 'org-special-keyword t)
  4955. '(3 'org-property-value t))
  4956. ;; Drawers
  4957. '(org-fontify-drawers)
  4958. ;; Link related fontification.
  4959. '(org-activate-links)
  4960. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4961. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4962. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4963. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4964. ;; Targets.
  4965. (list org-radio-target-regexp '(0 'org-target t))
  4966. (list org-target-regexp '(0 'org-target t))
  4967. ;; Diary sexps.
  4968. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4969. ;; Macro
  4970. '(org-fontify-macros)
  4971. ;; TODO keyword
  4972. (list (format org-heading-keyword-regexp-format
  4973. org-todo-regexp)
  4974. '(2 (org-get-todo-face 2) t))
  4975. ;; DONE
  4976. (if org-fontify-done-headline
  4977. (list (format org-heading-keyword-regexp-format
  4978. (concat
  4979. "\\(?:"
  4980. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4981. "\\)"))
  4982. '(2 'org-headline-done t))
  4983. nil)
  4984. ;; Priorities
  4985. '(org-font-lock-add-priority-faces)
  4986. ;; Tags
  4987. '(org-font-lock-add-tag-faces)
  4988. ;; Tags groups
  4989. (when (and org-group-tags org-tag-groups-alist)
  4990. (list (concat org-outline-regexp-bol ".+\\(:"
  4991. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4992. ":\\).*$")
  4993. '(1 'org-tag-group prepend)))
  4994. ;; Special keywords
  4995. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4996. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4997. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4998. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4999. ;; Emphasis
  5000. (when em '(org-do-emphasis-faces))
  5001. ;; Checkboxes
  5002. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5003. 1 'org-checkbox prepend)
  5004. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5005. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5006. (0 (org-get-checkbox-statistics-face) t)))
  5007. ;; Description list items
  5008. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5009. 1 'org-list-dt prepend)
  5010. ;; ARCHIVEd headings
  5011. (list (concat
  5012. org-outline-regexp-bol
  5013. "\\(.*:" org-archive-tag ":.*\\)")
  5014. '(1 'org-archived prepend))
  5015. ;; Specials
  5016. '(org-do-latex-and-related)
  5017. '(org-fontify-entities)
  5018. '(org-raise-scripts)
  5019. ;; Code
  5020. '(org-activate-code (1 'org-code t))
  5021. ;; COMMENT
  5022. (list (format
  5023. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5024. org-todo-regexp
  5025. org-comment-string)
  5026. '(9 'org-special-keyword t))
  5027. ;; Blocks and meta lines
  5028. '(org-fontify-meta-lines-and-blocks))))
  5029. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5030. (run-hooks 'org-font-lock-set-keywords-hook)
  5031. ;; Now set the full font-lock-keywords
  5032. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5033. (setq-local font-lock-defaults
  5034. '(org-font-lock-keywords t nil nil backward-paragraph))
  5035. (setq-local font-lock-extend-after-change-region-function
  5036. #'org-fontify-extend-region)
  5037. (kill-local-variable 'font-lock-keywords)
  5038. nil))
  5039. (defun org-toggle-pretty-entities ()
  5040. "Toggle the composition display of entities as UTF8 characters."
  5041. (interactive)
  5042. (setq-local org-pretty-entities (not org-pretty-entities))
  5043. (org-restart-font-lock)
  5044. (if org-pretty-entities
  5045. (message "Entities are now displayed as UTF8 characters")
  5046. (save-restriction
  5047. (widen)
  5048. (decompose-region (point-min) (point-max))
  5049. (message "Entities are now displayed as plain text"))))
  5050. (defvar-local org-custom-properties-overlays nil
  5051. "List of overlays used for custom properties.")
  5052. (defun org-toggle-custom-properties-visibility ()
  5053. "Display or hide properties in `org-custom-properties'."
  5054. (interactive)
  5055. (if org-custom-properties-overlays
  5056. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5057. (setq org-custom-properties-overlays nil))
  5058. (when org-custom-properties
  5059. (org-with-wide-buffer
  5060. (goto-char (point-min))
  5061. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5062. (while (re-search-forward regexp nil t)
  5063. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5064. (when (and end (< (point) end))
  5065. ;; Hide first custom property in current drawer.
  5066. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5067. (overlay-put o 'invisible t)
  5068. (overlay-put o 'org-custom-property t)
  5069. (push o org-custom-properties-overlays))
  5070. ;; Hide additional custom properties in the same drawer.
  5071. (while (re-search-forward regexp end t)
  5072. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5073. (overlay-put o 'invisible t)
  5074. (overlay-put o 'org-custom-property t)
  5075. (push o org-custom-properties-overlays)))))
  5076. ;; Each entry is limited to a single property drawer.
  5077. (outline-next-heading)))))))
  5078. (defun org-fontify-entities (limit)
  5079. "Find an entity to fontify."
  5080. (let (ee)
  5081. (when org-pretty-entities
  5082. (catch 'match
  5083. ;; "\_ "-family is left out on purpose. Only the first one,
  5084. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5085. ;; confusing when adding a second white space character.
  5086. (while (re-search-forward
  5087. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5088. limit t)
  5089. (when (and (not (org-at-comment-p))
  5090. (setq ee (org-entity-get (match-string 1)))
  5091. (= (length (nth 6 ee)) 1))
  5092. (let* ((end (if (equal (match-string 2) "{}")
  5093. (match-end 2)
  5094. (match-end 1))))
  5095. (add-text-properties
  5096. (match-beginning 0) end
  5097. (list 'font-lock-fontified t))
  5098. (compose-region (match-beginning 0) end
  5099. (nth 6 ee) nil)
  5100. (backward-char 1)
  5101. (throw 'match t))))
  5102. nil))))
  5103. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5104. "Fontify string S like in Org mode."
  5105. (with-temp-buffer
  5106. (insert s)
  5107. (let ((org-odd-levels-only odd-levels))
  5108. (org-mode)
  5109. (org-font-lock-ensure)
  5110. (buffer-string))))
  5111. (defvar org-m nil)
  5112. (defvar org-l nil)
  5113. (defvar org-f nil)
  5114. (defun org-get-level-face (n)
  5115. "Get the right face for match N in font-lock matching of headlines."
  5116. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5117. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5118. (if org-cycle-level-faces
  5119. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5120. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5121. (cond
  5122. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5123. ((eq n 2) org-f)
  5124. (t (unless org-level-color-stars-only org-f))))
  5125. (defun org-face-from-face-or-color (context inherit face-or-color)
  5126. "Create a face list that inherits INHERIT, but sets the foreground color.
  5127. When FACE-OR-COLOR is not a string, just return it."
  5128. (if (stringp face-or-color)
  5129. (list :inherit inherit
  5130. (cdr (assoc context org-faces-easy-properties))
  5131. face-or-color)
  5132. face-or-color))
  5133. (defun org-get-todo-face (kwd)
  5134. "Get the right face for a TODO keyword KWD.
  5135. If KWD is a number, get the corresponding match group."
  5136. (when (numberp kwd) (setq kwd (match-string kwd)))
  5137. (or (org-face-from-face-or-color
  5138. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5139. (and (member kwd org-done-keywords) 'org-done)
  5140. 'org-todo))
  5141. (defun org-get-priority-face (priority)
  5142. "Get the right face for PRIORITY.
  5143. PRIORITY is a character."
  5144. (or (org-face-from-face-or-color
  5145. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5146. 'org-priority))
  5147. (defun org-get-tag-face (tag)
  5148. "Get the right face for TAG.
  5149. If TAG is a number, get the corresponding match group."
  5150. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5151. (or (org-face-from-face-or-color
  5152. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5153. 'org-tag)))
  5154. (defun org-font-lock-add-priority-faces (limit)
  5155. "Add the special priority faces."
  5156. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5157. (add-text-properties
  5158. (match-beginning 1) (match-end 1)
  5159. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5160. 'font-lock-fontified t))))
  5161. (defun org-font-lock-add-tag-faces (limit)
  5162. "Add the special tag faces."
  5163. (when (and org-tag-faces org-tags-special-faces-re)
  5164. (while (re-search-forward org-tags-special-faces-re limit t)
  5165. (add-text-properties (match-beginning 1) (match-end 1)
  5166. (list 'face (org-get-tag-face 1)
  5167. 'font-lock-fontified t))
  5168. (backward-char 1))))
  5169. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5170. "Remove fontification and activation overlays from links."
  5171. (font-lock-default-unfontify-region beg end)
  5172. (let* ((buffer-undo-list t)
  5173. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5174. (inhibit-modification-hooks t)
  5175. deactivate-mark buffer-file-name buffer-file-truename)
  5176. (decompose-region beg end)
  5177. (remove-text-properties beg end
  5178. '(mouse-face t keymap t org-linked-text t
  5179. invisible t intangible t
  5180. org-emphasis t))
  5181. (org-remove-font-lock-display-properties beg end)))
  5182. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5183. ((raise 0.3) (height 0.7))
  5184. ((raise -0.5))
  5185. ((raise 0.5)))
  5186. "Display properties for showing superscripts and subscripts.")
  5187. (defun org-remove-font-lock-display-properties (beg end)
  5188. "Remove specific display properties that have been added by font lock.
  5189. The will remove the raise properties that are used to show superscripts
  5190. and subscripts."
  5191. (let (next prop)
  5192. (while (< beg end)
  5193. (setq next (next-single-property-change beg 'display nil end)
  5194. prop (get-text-property beg 'display))
  5195. (when (member prop org-script-display)
  5196. (put-text-property beg next 'display nil))
  5197. (setq beg next))))
  5198. (defun org-raise-scripts (limit)
  5199. "Add raise properties to sub/superscripts."
  5200. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5201. (re-search-forward
  5202. (if (eq org-use-sub-superscripts t)
  5203. org-match-substring-regexp
  5204. org-match-substring-with-braces-regexp)
  5205. limit t))
  5206. (let* ((pos (point)) table-p comment-p
  5207. (mpos (match-beginning 3))
  5208. (emph-p (get-text-property mpos 'org-emphasis))
  5209. (link-p (get-text-property mpos 'mouse-face))
  5210. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5211. (goto-char (point-at-bol))
  5212. (setq table-p (looking-at-p org-table-dataline-regexp)
  5213. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5214. (goto-char pos)
  5215. ;; Handle a_b^c
  5216. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5217. (unless (or comment-p emph-p link-p keyw-p)
  5218. (put-text-property (match-beginning 3) (match-end 0)
  5219. 'display
  5220. (if (equal (char-after (match-beginning 2)) ?^)
  5221. (nth (if table-p 3 1) org-script-display)
  5222. (nth (if table-p 2 0) org-script-display)))
  5223. (add-text-properties (match-beginning 2) (match-end 2)
  5224. (list 'invisible t))
  5225. (when (and (eq (char-after (match-beginning 3)) ?{)
  5226. (eq (char-before (match-end 3)) ?}))
  5227. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5228. (list 'invisible t))
  5229. (add-text-properties (1- (match-end 3)) (match-end 3)
  5230. (list 'invisible t))))
  5231. t)))
  5232. (defun org-remove-empty-overlays-at (pos)
  5233. "Remove outline overlays that do not contain non-white stuff."
  5234. (dolist (o (overlays-at pos))
  5235. (and (eq 'outline (overlay-get o 'invisible))
  5236. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5237. (overlay-end o))))
  5238. (delete-overlay o))))
  5239. (defun org-show-empty-lines-in-parent ()
  5240. "Move to the parent and re-show empty lines before visible headlines."
  5241. (save-excursion
  5242. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5243. (org-cycle-show-empty-lines context))))
  5244. (defun org-files-list ()
  5245. "Return `org-agenda-files' list, plus all open Org files.
  5246. This is useful for operations that need to scan all of a user's
  5247. open and agenda-wise Org files."
  5248. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5249. (dolist (buf (buffer-list))
  5250. (with-current-buffer buf
  5251. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5252. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5253. :test #'equal))))
  5254. files))
  5255. (defsubst org-entry-beginning-position ()
  5256. "Return the beginning position of the current entry."
  5257. (save-excursion (org-back-to-heading t) (point)))
  5258. (defsubst org-entry-end-position ()
  5259. "Return the end position of the current entry."
  5260. (save-excursion (outline-next-heading) (point)))
  5261. (defun org-subtree-end-visible-p ()
  5262. "Is the end of the current subtree visible?"
  5263. (pos-visible-in-window-p
  5264. (save-excursion (org-end-of-subtree t) (point))))
  5265. (defun org-first-headline-recenter ()
  5266. "Move cursor to the first headline and recenter the headline."
  5267. (let ((window (get-buffer-window)))
  5268. (when window
  5269. (goto-char (point-min))
  5270. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5271. (set-window-start window (line-beginning-position))))))
  5272. ;;; Visibility (headlines, blocks, drawers)
  5273. ;;;; Headlines visibility
  5274. (defun org-show-entry ()
  5275. "Show the body directly following this heading.
  5276. Show the heading too, if it is currently invisible."
  5277. (interactive)
  5278. (save-excursion
  5279. (ignore-errors
  5280. (org-back-to-heading t)
  5281. (org-flag-region
  5282. (line-end-position 0)
  5283. (save-excursion
  5284. (if (re-search-forward
  5285. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5286. (match-beginning 1)
  5287. (point-max)))
  5288. nil
  5289. 'outline))))
  5290. (defun org-show-children (&optional level)
  5291. "Show all direct subheadings of this heading.
  5292. Prefix arg LEVEL is how many levels below the current level
  5293. should be shown. Default is enough to cause the following
  5294. heading to appear."
  5295. (interactive "p")
  5296. (save-excursion
  5297. (org-back-to-heading t)
  5298. (let* ((current-level (funcall outline-level))
  5299. (max-level (org-get-valid-level
  5300. current-level
  5301. (if level (prefix-numeric-value level) 1)))
  5302. (end (save-excursion (org-end-of-subtree t t)))
  5303. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5304. (past-first-child nil)
  5305. ;; Make sure to skip inlinetasks.
  5306. (re (format regexp-fmt
  5307. current-level
  5308. (cond
  5309. ((not (featurep 'org-inlinetask)) "")
  5310. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5311. 3))
  5312. (t (1- org-inlinetask-min-level))))))
  5313. ;; Display parent heading.
  5314. (org-flag-heading nil)
  5315. (forward-line)
  5316. ;; Display children. First child may be deeper than expected
  5317. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5318. ;; MAX-LEVEL accordingly.
  5319. (while (re-search-forward re end t)
  5320. (unless past-first-child
  5321. (setq re (format regexp-fmt
  5322. current-level
  5323. (max (funcall outline-level) max-level)))
  5324. (setq past-first-child t))
  5325. (org-flag-heading nil)))))
  5326. (defun org-show-subtree ()
  5327. "Show everything after this heading at deeper levels."
  5328. (interactive)
  5329. (org-flag-region
  5330. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5331. ;;;; Blocks visibility
  5332. (defun org-hide-block-toggle-maybe ()
  5333. "Toggle visibility of block at point.
  5334. Unlike to `org-hide-block-toggle', this function does not throw
  5335. an error. Return a non-nil value when toggling is successful."
  5336. (interactive)
  5337. (ignore-errors (org-hide-block-toggle)))
  5338. (defun org-hide-block-toggle (&optional force)
  5339. "Toggle the visibility of the current block.
  5340. When optional argument FORCE is `off', make block visible. If it
  5341. is non-nil, hide it unconditionally. Throw an error when not at
  5342. a block. Return a non-nil value when toggling is successful."
  5343. (interactive)
  5344. (let ((element (org-element-at-point)))
  5345. (unless (memq (org-element-type element)
  5346. '(center-block comment-block dynamic-block example-block
  5347. export-block quote-block special-block
  5348. src-block verse-block))
  5349. (user-error "Not at a block"))
  5350. (let* ((post (org-element-property :post-affiliated element))
  5351. (start (save-excursion
  5352. (goto-char post)
  5353. (line-end-position)))
  5354. (end (save-excursion
  5355. (goto-char (org-element-property :end element))
  5356. (skip-chars-backward " \t\n")
  5357. (line-end-position))))
  5358. ;; Do nothing when not before or at the block opening line or at
  5359. ;; the block closing line.
  5360. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5361. (cond ((eq force 'off)
  5362. (org-flag-region start end nil 'org-hide-block))
  5363. (force
  5364. (org-flag-region start end t 'org-hide-block))
  5365. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5366. (org-flag-region start end nil 'org-hide-block))
  5367. (t
  5368. (org-flag-region start end t 'org-hide-block)))
  5369. ;; When the block is hidden away, make sure point is left in
  5370. ;; a visible part of the buffer.
  5371. (when (invisible-p (max (1- (point)) (point-min)))
  5372. (goto-char post))
  5373. ;; Signal success.
  5374. t))))
  5375. (defun org-hide-block-toggle-all ()
  5376. "Toggle the visibility of all blocks in the current buffer."
  5377. (org-block-map 'org-hide-block-toggle))
  5378. (defun org-hide-block-all ()
  5379. "Fold all blocks in the current buffer."
  5380. (interactive)
  5381. (org-show-all '(blocks))
  5382. (org-block-map 'org-hide-block-toggle-maybe))
  5383. ;;;; Drawers visibility
  5384. (defun org-cycle-hide-drawers (state &optional exceptions)
  5385. "Re-hide all drawers after a visibility state change.
  5386. STATE should be one of the symbols listed in the docstring of
  5387. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5388. a list of strings specifying which drawers should not be hidden."
  5389. (when (and (derived-mode-p 'org-mode)
  5390. (not (memq state '(overview folded contents))))
  5391. (save-excursion
  5392. (let* ((globalp (eq state 'all))
  5393. (beg (if globalp (point-min) (point)))
  5394. (end (if globalp (point-max)
  5395. (if (eq state 'children)
  5396. (save-excursion (outline-next-heading) (point))
  5397. (org-end-of-subtree t)))))
  5398. (goto-char beg)
  5399. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5400. (unless (member-ignore-case (match-string 1) exceptions)
  5401. (let ((drawer (org-element-at-point)))
  5402. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5403. (org-flag-drawer t drawer)
  5404. ;; Make sure to skip drawer entirely or we might flag
  5405. ;; it another time when matching its ending line with
  5406. ;; `org-drawer-regexp'.
  5407. (goto-char (org-element-property :end drawer))))))))))
  5408. (defun org-flag-drawer (flag &optional element beg end)
  5409. "When FLAG is non-nil, hide the drawer we are at.
  5410. Otherwise make it visible.
  5411. When optional argument ELEMENT is a parsed drawer, as returned by
  5412. `org-element-at-point', hide or show that drawer instead.
  5413. When buffer positions BEG and END are provided, hide or show that
  5414. region as a drawer without further ado."
  5415. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5416. (let ((drawer (or element
  5417. (and (save-excursion
  5418. (beginning-of-line)
  5419. (looking-at-p org-drawer-regexp))
  5420. (org-element-at-point)))))
  5421. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5422. (let ((post (org-element-property :post-affiliated drawer)))
  5423. (org-flag-region
  5424. (save-excursion (goto-char post) (line-end-position))
  5425. (save-excursion (goto-char (org-element-property :end drawer))
  5426. (skip-chars-backward " \t\n")
  5427. (line-end-position))
  5428. flag 'org-hide-drawer)
  5429. ;; When the drawer is hidden away, make sure point lies in
  5430. ;; a visible part of the buffer.
  5431. (when (invisible-p (max (1- (point)) (point-min)))
  5432. (goto-char post)))))))
  5433. ;;;; Visibility cycling
  5434. (defvar-local org-cycle-global-status nil)
  5435. (put 'org-cycle-global-status 'org-state t)
  5436. (defvar-local org-cycle-subtree-status nil)
  5437. (put 'org-cycle-subtree-status 'org-state t)
  5438. (defun org-show-all (&optional types)
  5439. "Show all contents in the visible part of the buffer.
  5440. By default, the function expands headings, blocks and drawers.
  5441. When optional argument TYPE is a list of symbols among `blocks',
  5442. `drawers' and `headings', to only expand one specific type."
  5443. (interactive)
  5444. (dolist (type (or types '(blocks drawers headings)))
  5445. (org-flag-region (point-min) (point-max) nil
  5446. (pcase type
  5447. (`blocks 'org-hide-block)
  5448. (`drawers 'org-hide-drawer)
  5449. (`headings 'outline)
  5450. (_ (error "Invalid type: %S" type))))))
  5451. ;;;###autoload
  5452. (defun org-cycle (&optional arg)
  5453. "TAB-action and visibility cycling for Org mode.
  5454. This is the command invoked in Org mode by the `TAB' key. Its main
  5455. purpose is outline visibility cycling, but it also invokes other actions
  5456. in special contexts.
  5457. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5458. the entire
  5459. buffer through 3 states (global cycling)
  5460. 1. OVERVIEW: Show only top-level headlines.
  5461. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5462. 3. SHOW ALL: Show everything.
  5463. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5464. switch to the startup visibility,
  5465. determined by the variable `org-startup-folded', and by any VISIBILITY
  5466. properties in the buffer.
  5467. With a `\\[universal-argument] \\[universal-argument] \
  5468. \\[universal-argument]' prefix argument, show the entire buffer, including
  5469. any drawers.
  5470. When inside a table, re-align the table and move to the next field.
  5471. When point is at the beginning of a headline, rotate the subtree started
  5472. by this line through 3 different states (local cycling)
  5473. 1. FOLDED: Only the main headline is shown.
  5474. 2. CHILDREN: The main headline and the direct children are shown.
  5475. From this state, you can move to one of the children
  5476. and zoom in further.
  5477. 3. SUBTREE: Show the entire subtree, including body text.
  5478. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5479. When point is at the beginning of an empty headline and the variable
  5480. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5481. of the headline by demoting and promoting it to likely levels. This
  5482. speeds up creation document structure by pressing `TAB' once or several
  5483. times right after creating a new headline.
  5484. When there is a numeric prefix, go up to a heading with level ARG, do
  5485. a `show-subtree' and return to the previous cursor position. If ARG
  5486. is negative, go up that many levels.
  5487. When point is not at the beginning of a headline, execute the global
  5488. binding for `TAB', which is re-indenting the line. See the option
  5489. `org-cycle-emulate-tab' for details.
  5490. As a special case, if point is at the beginning of the buffer and there is
  5491. no headline in line 1, this function will act as if called with prefix arg
  5492. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5493. prefix arg, but only
  5494. if the variable `org-cycle-global-at-bob' is t."
  5495. (interactive "P")
  5496. (org-load-modules-maybe)
  5497. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5498. (and org-cycle-level-after-item/entry-creation
  5499. (or (org-cycle-level)
  5500. (org-cycle-item-indentation))))
  5501. (let* ((limit-level
  5502. (or org-cycle-max-level
  5503. (and (boundp 'org-inlinetask-min-level)
  5504. org-inlinetask-min-level
  5505. (1- org-inlinetask-min-level))))
  5506. (nstars (and limit-level
  5507. (if org-odd-levels-only
  5508. (and limit-level (1- (* limit-level 2)))
  5509. limit-level)))
  5510. (org-outline-regexp
  5511. (if (not (derived-mode-p 'org-mode))
  5512. outline-regexp
  5513. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5514. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5515. (not (looking-at org-outline-regexp))))
  5516. (org-cycle-hook
  5517. (if bob-special
  5518. (delq 'org-optimize-window-after-visibility-change
  5519. (copy-sequence org-cycle-hook))
  5520. org-cycle-hook))
  5521. (pos (point)))
  5522. (cond
  5523. ((equal arg '(16))
  5524. (setq last-command 'dummy)
  5525. (org-set-startup-visibility)
  5526. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5527. ((equal arg '(64))
  5528. (org-show-all)
  5529. (org-unlogged-message "Entire buffer visible, including drawers"))
  5530. ((equal arg '(4)) (org-cycle-internal-global))
  5531. ;; Try hiding block at point.
  5532. ((org-hide-block-toggle-maybe))
  5533. ;; Try cdlatex TAB completion
  5534. ((org-try-cdlatex-tab))
  5535. ;; Table: enter it or move to the next field.
  5536. ((org-at-table-p 'any)
  5537. (if (org-at-table.el-p)
  5538. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5539. Use `\\[org-edit-special]' to edit table.el tables"))
  5540. (if arg (org-table-edit-field t)
  5541. (org-table-justify-field-maybe)
  5542. (call-interactively 'org-table-next-field))))
  5543. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5544. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5545. (bob-special (org-cycle-internal-global))
  5546. ;; Drawers: delegate to `org-flag-drawer'.
  5547. ((save-excursion
  5548. (beginning-of-line 1)
  5549. (looking-at org-drawer-regexp))
  5550. (org-flag-drawer ; toggle block visibility
  5551. (not (get-char-property (match-end 0) 'invisible))))
  5552. ;; Show-subtree, ARG levels up from here.
  5553. ((integerp arg)
  5554. (save-excursion
  5555. (org-back-to-heading)
  5556. (outline-up-heading (if (< arg 0) (- arg)
  5557. (- (funcall outline-level) arg)))
  5558. (org-show-subtree)))
  5559. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5560. ((and (featurep 'org-inlinetask)
  5561. (org-inlinetask-at-task-p)
  5562. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5563. (org-inlinetask-toggle-visibility))
  5564. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5565. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5566. (save-excursion (move-beginning-of-line 1)
  5567. (looking-at org-outline-regexp)))
  5568. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5569. (org-cycle-internal-local))
  5570. ;; From there: TAB emulation and template completion.
  5571. (buffer-read-only (org-back-to-heading))
  5572. ((run-hook-with-args-until-success
  5573. 'org-tab-after-check-for-cycling-hook))
  5574. ((run-hook-with-args-until-success
  5575. 'org-tab-before-tab-emulation-hook))
  5576. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5577. (or (not (bolp))
  5578. (not (looking-at org-outline-regexp))))
  5579. (call-interactively (global-key-binding "\t")))
  5580. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5581. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5582. (or (and (eq org-cycle-emulate-tab 'white)
  5583. (= (match-end 0) (point-at-eol)))
  5584. (and (eq org-cycle-emulate-tab 'whitestart)
  5585. (>= (match-end 0) pos))))
  5586. t
  5587. (eq org-cycle-emulate-tab t))
  5588. (call-interactively (global-key-binding "\t")))
  5589. (t (save-excursion
  5590. (org-back-to-heading)
  5591. (org-cycle)))))))
  5592. (defun org-cycle-internal-global ()
  5593. "Do the global cycling action."
  5594. ;; Hack to avoid display of messages for .org attachments in Gnus
  5595. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5596. (cond
  5597. ((and (eq last-command this-command)
  5598. (eq org-cycle-global-status 'overview))
  5599. ;; We just created the overview - now do table of contents
  5600. ;; This can be slow in very large buffers, so indicate action
  5601. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5602. (unless ga (org-unlogged-message "CONTENTS..."))
  5603. (org-content)
  5604. (unless ga (org-unlogged-message "CONTENTS...done"))
  5605. (setq org-cycle-global-status 'contents)
  5606. (run-hook-with-args 'org-cycle-hook 'contents))
  5607. ((and (eq last-command this-command)
  5608. (eq org-cycle-global-status 'contents))
  5609. ;; We just showed the table of contents - now show everything
  5610. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5611. (org-show-all '(headings blocks))
  5612. (unless ga (org-unlogged-message "SHOW ALL"))
  5613. (setq org-cycle-global-status 'all)
  5614. (run-hook-with-args 'org-cycle-hook 'all))
  5615. (t
  5616. ;; Default action: go to overview
  5617. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5618. (org-overview)
  5619. (unless ga (org-unlogged-message "OVERVIEW"))
  5620. (setq org-cycle-global-status 'overview)
  5621. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5622. (defvar org-called-with-limited-levels nil
  5623. "Non-nil when `org-with-limited-levels' is currently active.")
  5624. (defun org-cycle-internal-local ()
  5625. "Do the local cycling action."
  5626. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5627. ;; First, determine end of headline (EOH), end of subtree or item
  5628. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5629. (save-excursion
  5630. (if (org-at-item-p)
  5631. (progn
  5632. (beginning-of-line)
  5633. (setq struct (org-list-struct))
  5634. (setq eoh (point-at-eol))
  5635. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5636. (setq has-children (org-list-has-child-p (point) struct)))
  5637. (org-back-to-heading)
  5638. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5639. (setq eos (save-excursion (org-end-of-subtree t t)
  5640. (when (bolp) (backward-char)) (point)))
  5641. (setq has-children
  5642. (or
  5643. (save-excursion
  5644. (let ((level (funcall outline-level)))
  5645. (outline-next-heading)
  5646. (and (org-at-heading-p t)
  5647. (> (funcall outline-level) level))))
  5648. (and (eq org-cycle-include-plain-lists 'integrate)
  5649. (save-excursion
  5650. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5651. ;; Determine end invisible part of buffer (EOL)
  5652. (beginning-of-line 2)
  5653. (while (and (not (eobp)) ;This is like `next-line'.
  5654. (get-char-property (1- (point)) 'invisible))
  5655. (goto-char (next-single-char-property-change (point) 'invisible))
  5656. (and (eolp) (beginning-of-line 2)))
  5657. (setq eol (point)))
  5658. ;; Find out what to do next and set `this-command'
  5659. (cond
  5660. ((= eos eoh)
  5661. ;; Nothing is hidden behind this heading
  5662. (unless (org-before-first-heading-p)
  5663. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5664. (org-unlogged-message "EMPTY ENTRY")
  5665. (setq org-cycle-subtree-status nil)
  5666. (save-excursion
  5667. (goto-char eos)
  5668. (outline-next-heading)
  5669. (when (org-invisible-p) (org-flag-heading nil))))
  5670. ((and (or (>= eol eos)
  5671. (not (string-match "\\S-" (buffer-substring eol eos))))
  5672. (or has-children
  5673. (not (setq children-skipped
  5674. org-cycle-skip-children-state-if-no-children))))
  5675. ;; Entire subtree is hidden in one line: children view
  5676. (unless (org-before-first-heading-p)
  5677. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5678. (if (org-at-item-p)
  5679. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5680. (org-show-entry)
  5681. (org-with-limited-levels (org-show-children))
  5682. (org-show-set-visibility 'canonical)
  5683. ;; Fold every list in subtree to top-level items.
  5684. (when (eq org-cycle-include-plain-lists 'integrate)
  5685. (save-excursion
  5686. (org-back-to-heading)
  5687. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5688. (beginning-of-line 1)
  5689. (let* ((struct (org-list-struct))
  5690. (prevs (org-list-prevs-alist struct))
  5691. (end (org-list-get-bottom-point struct)))
  5692. (dolist (e (org-list-get-all-items (point) struct prevs))
  5693. (org-list-set-item-visibility e struct 'folded))
  5694. (goto-char (if (< end eos) end eos)))))))
  5695. (org-unlogged-message "CHILDREN")
  5696. (save-excursion
  5697. (goto-char eos)
  5698. (outline-next-heading)
  5699. (when (org-invisible-p) (org-flag-heading nil)))
  5700. (setq org-cycle-subtree-status 'children)
  5701. (unless (org-before-first-heading-p)
  5702. (run-hook-with-args 'org-cycle-hook 'children)))
  5703. ((or children-skipped
  5704. (and (eq last-command this-command)
  5705. (eq org-cycle-subtree-status 'children)))
  5706. ;; We just showed the children, or no children are there,
  5707. ;; now show everything.
  5708. (unless (org-before-first-heading-p)
  5709. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5710. (org-flag-region eoh eos nil 'outline)
  5711. (org-unlogged-message
  5712. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5713. (setq org-cycle-subtree-status 'subtree)
  5714. (unless (org-before-first-heading-p)
  5715. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5716. (t
  5717. ;; Default action: hide the subtree.
  5718. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5719. (org-flag-region eoh eos t 'outline)
  5720. (org-unlogged-message "FOLDED")
  5721. (setq org-cycle-subtree-status 'folded)
  5722. (unless (org-before-first-heading-p)
  5723. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5724. ;;;###autoload
  5725. (defun org-global-cycle (&optional arg)
  5726. "Cycle the global visibility. For details see `org-cycle'.
  5727. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5728. With a numeric prefix, show all headlines up to that level."
  5729. (interactive "P")
  5730. (let ((org-cycle-include-plain-lists
  5731. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5732. (cond
  5733. ((integerp arg)
  5734. (org-show-all '(headings blocks))
  5735. (outline-hide-sublevels arg)
  5736. (setq org-cycle-global-status 'contents))
  5737. ((equal arg '(4))
  5738. (org-set-startup-visibility)
  5739. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5740. (t
  5741. (org-cycle '(4))))))
  5742. (defun org-set-startup-visibility ()
  5743. "Set the visibility required by startup options and properties."
  5744. (cond
  5745. ((eq org-startup-folded t)
  5746. (org-overview))
  5747. ((eq org-startup-folded 'content)
  5748. (org-content))
  5749. ((or (eq org-startup-folded 'showeverything)
  5750. (eq org-startup-folded nil))
  5751. (org-show-all)))
  5752. (unless (eq org-startup-folded 'showeverything)
  5753. (when org-hide-block-startup (org-hide-block-all))
  5754. (org-set-visibility-according-to-property)
  5755. (org-cycle-hide-archived-subtrees 'all)
  5756. (org-cycle-hide-drawers 'all)
  5757. (org-cycle-show-empty-lines t)))
  5758. (defun org-set-visibility-according-to-property ()
  5759. "Switch subtree visibility according to VISIBILITY property."
  5760. (interactive)
  5761. (let ((regexp (org-re-property "VISIBILITY")))
  5762. (org-with-point-at 1
  5763. (while (re-search-forward regexp nil t)
  5764. (let ((state (match-string 3)))
  5765. (if (not (org-at-property-p)) (outline-next-heading)
  5766. (save-excursion
  5767. (org-back-to-heading t)
  5768. (org-flag-subtree t)
  5769. (org-reveal)
  5770. (pcase state
  5771. ("folded"
  5772. (org-flag-subtree t))
  5773. ("children"
  5774. (org-show-hidden-entry)
  5775. (org-show-children))
  5776. ("content"
  5777. (save-excursion
  5778. (save-restriction
  5779. (org-narrow-to-subtree)
  5780. (org-content))))
  5781. ((or "all" "showall")
  5782. (outline-show-subtree))
  5783. (_ nil)))
  5784. (org-end-of-subtree)))))))
  5785. (defun org-overview ()
  5786. "Switch to overview mode, showing only top-level headlines.
  5787. This shows all headlines with a level equal or greater than the level
  5788. of the first headline in the buffer. This is important, because if the
  5789. first headline is not level one, then (hide-sublevels 1) gives confusing
  5790. results."
  5791. (interactive)
  5792. (save-excursion
  5793. (let ((level
  5794. (save-excursion
  5795. (goto-char (point-min))
  5796. (when (re-search-forward org-outline-regexp-bol nil t)
  5797. (goto-char (match-beginning 0))
  5798. (funcall outline-level)))))
  5799. (and level (outline-hide-sublevels level)))))
  5800. (defun org-content (&optional arg)
  5801. "Show all headlines in the buffer, like a table of contents.
  5802. With numerical argument N, show content up to level N."
  5803. (interactive "P")
  5804. (org-overview)
  5805. (save-excursion
  5806. ;; Visit all headings and show their offspring
  5807. (and (integerp arg) (org-overview))
  5808. (goto-char (point-max))
  5809. (catch 'exit
  5810. (while (and (progn (condition-case nil
  5811. (outline-previous-visible-heading 1)
  5812. (error (goto-char (point-min))))
  5813. t)
  5814. (looking-at org-outline-regexp))
  5815. (if (integerp arg)
  5816. (org-show-children (1- arg))
  5817. (outline-show-branches))
  5818. (when (bobp) (throw 'exit nil))))))
  5819. (defun org-optimize-window-after-visibility-change (state)
  5820. "Adjust the window after a change in outline visibility.
  5821. This function is the default value of the hook `org-cycle-hook'."
  5822. (when (get-buffer-window (current-buffer))
  5823. (cond
  5824. ((eq state 'content) nil)
  5825. ((eq state 'all) nil)
  5826. ((eq state 'folded) nil)
  5827. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5828. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5829. (defun org-clean-visibility-after-subtree-move ()
  5830. "Fix visibility issues after moving a subtree."
  5831. ;; First, find a reasonable region to look at:
  5832. ;; Start two siblings above, end three below
  5833. (let* ((beg (save-excursion
  5834. (and (org-get-last-sibling)
  5835. (org-get-last-sibling))
  5836. (point)))
  5837. (end (save-excursion
  5838. (and (org-get-next-sibling)
  5839. (org-get-next-sibling)
  5840. (org-get-next-sibling))
  5841. (if (org-at-heading-p)
  5842. (point-at-eol)
  5843. (point))))
  5844. (level (looking-at "\\*+"))
  5845. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5846. (save-excursion
  5847. (save-restriction
  5848. (narrow-to-region beg end)
  5849. (when re
  5850. ;; Properly fold already folded siblings
  5851. (goto-char (point-min))
  5852. (while (re-search-forward re nil t)
  5853. (when (and (not (org-invisible-p))
  5854. (org-invisible-p (line-end-position)))
  5855. (outline-hide-entry))))
  5856. (org-cycle-hide-drawers 'all)
  5857. (org-cycle-show-empty-lines 'overview)))))
  5858. (defun org-cycle-show-empty-lines (state)
  5859. "Show empty lines above all visible headlines.
  5860. The region to be covered depends on STATE when called through
  5861. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5862. entire buffer covered. Note that an empty line is only shown if there
  5863. are at least `org-cycle-separator-lines' empty lines before the headline."
  5864. (when (/= org-cycle-separator-lines 0)
  5865. (save-excursion
  5866. (let* ((n (abs org-cycle-separator-lines))
  5867. (re (cond
  5868. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5869. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5870. (t (let ((ns (number-to-string (- n 2))))
  5871. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5872. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5873. beg end)
  5874. (cond
  5875. ((memq state '(overview contents t))
  5876. (setq beg (point-min) end (point-max)))
  5877. ((memq state '(children folded))
  5878. (setq beg (point)
  5879. end (progn (org-end-of-subtree t t)
  5880. (line-beginning-position 2)))))
  5881. (when beg
  5882. (goto-char beg)
  5883. (while (re-search-forward re end t)
  5884. (unless (get-char-property (match-end 1) 'invisible)
  5885. (let ((e (match-end 1))
  5886. (b (if (>= org-cycle-separator-lines 0)
  5887. (match-beginning 1)
  5888. (save-excursion
  5889. (goto-char (match-beginning 0))
  5890. (skip-chars-backward " \t\n")
  5891. (line-end-position)))))
  5892. (org-flag-region b e nil 'outline))))))))
  5893. ;; Never hide empty lines at the end of the file.
  5894. (save-excursion
  5895. (goto-char (point-max))
  5896. (outline-previous-heading)
  5897. (outline-end-of-heading)
  5898. (when (and (looking-at "[ \t\n]+")
  5899. (= (match-end 0) (point-max)))
  5900. (org-flag-region (point) (match-end 0) nil 'outline))))
  5901. ;;;; Reveal point location
  5902. (defun org-show-context (&optional key)
  5903. "Make sure point and context are visible.
  5904. Optional argument KEY, when non-nil, is a symbol. See
  5905. `org-show-context-detail' for allowed values and how much is to
  5906. be shown."
  5907. (org-show-set-visibility
  5908. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5909. ((cdr (assq key org-show-context-detail)))
  5910. (t (cdr (assq 'default org-show-context-detail))))))
  5911. (defun org-show-set-visibility (detail)
  5912. "Set visibility around point according to DETAIL.
  5913. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5914. `tree', `canonical' or t. See `org-show-context-detail' for more
  5915. information."
  5916. ;; Show current heading and possibly its entry, following headline
  5917. ;; or all children.
  5918. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5919. (org-flag-heading nil)
  5920. (org-show-entry)
  5921. ;; If point is hidden within a drawer or a block, make sure to
  5922. ;; expose it.
  5923. (dolist (o (overlays-at (point)))
  5924. (when (memq (overlay-get o 'invisible)
  5925. '(org-hide-block org-hide-drawer outline))
  5926. (delete-overlay o)))
  5927. (unless (org-before-first-heading-p)
  5928. (org-with-limited-levels
  5929. (cl-case detail
  5930. ((tree canonical t) (org-show-children))
  5931. ((nil minimal ancestors))
  5932. (t (save-excursion
  5933. (outline-next-heading)
  5934. (org-flag-heading nil)))))))
  5935. ;; Show all siblings.
  5936. (when (eq detail 'lineage) (org-show-siblings))
  5937. ;; Show ancestors, possibly with their children.
  5938. (when (memq detail '(ancestors lineage tree canonical t))
  5939. (save-excursion
  5940. (while (org-up-heading-safe)
  5941. (org-flag-heading nil)
  5942. (when (memq detail '(canonical t)) (org-show-entry))
  5943. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5944. (defvar org-reveal-start-hook nil
  5945. "Hook run before revealing a location.")
  5946. (defun org-reveal (&optional siblings)
  5947. "Show current entry, hierarchy above it, and the following headline.
  5948. This can be used to show a consistent set of context around
  5949. locations exposed with `org-show-context'.
  5950. With optional argument SIBLINGS, on each level of the hierarchy all
  5951. siblings are shown. This repairs the tree structure to what it would
  5952. look like when opened with hierarchical calls to `org-cycle'.
  5953. With a \\[universal-argument] \\[universal-argument] prefix, \
  5954. go to the parent and show the entire tree."
  5955. (interactive "P")
  5956. (run-hooks 'org-reveal-start-hook)
  5957. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5958. ((equal siblings '(16))
  5959. (save-excursion
  5960. (when (org-up-heading-safe)
  5961. (org-show-subtree)
  5962. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5963. (t (org-show-set-visibility 'lineage))))
  5964. ;;; Indirect buffer display of subtrees
  5965. (defvar org-indirect-dedicated-frame nil
  5966. "This is the frame being used for indirect tree display.")
  5967. (defvar org-last-indirect-buffer nil)
  5968. (defun org-tree-to-indirect-buffer (&optional arg)
  5969. "Create indirect buffer and narrow it to current subtree.
  5970. With a numerical prefix ARG, go up to this level and then take that tree.
  5971. If ARG is negative, go up that many levels.
  5972. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5973. indirect buffer previously made with this command, to avoid proliferation of
  5974. indirect buffers. However, when you call the command with a \
  5975. `\\[universal-argument]' prefix, or
  5976. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5977. so that you can work with several indirect buffers at the same time. If
  5978. `org-indirect-buffer-display' is `dedicated-frame', the \
  5979. `\\[universal-argument]' prefix also
  5980. requests that a new frame be made for the new buffer, so that the dedicated
  5981. frame is not changed."
  5982. (interactive "P")
  5983. (let ((cbuf (current-buffer))
  5984. (cwin (selected-window))
  5985. (pos (point))
  5986. beg end level heading ibuf)
  5987. (save-excursion
  5988. (org-back-to-heading t)
  5989. (when (numberp arg)
  5990. (setq level (org-outline-level))
  5991. (when (< arg 0) (setq arg (+ level arg)))
  5992. (while (> (setq level (org-outline-level)) arg)
  5993. (org-up-heading-safe)))
  5994. (setq beg (point)
  5995. heading (org-get-heading 'no-tags))
  5996. (org-end-of-subtree t t)
  5997. (when (org-at-heading-p) (backward-char 1))
  5998. (setq end (point)))
  5999. (when (and (buffer-live-p org-last-indirect-buffer)
  6000. (not (eq org-indirect-buffer-display 'new-frame))
  6001. (not arg))
  6002. (kill-buffer org-last-indirect-buffer))
  6003. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6004. org-last-indirect-buffer ibuf)
  6005. (cond
  6006. ((or (eq org-indirect-buffer-display 'new-frame)
  6007. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6008. (select-frame (make-frame))
  6009. (delete-other-windows)
  6010. (pop-to-buffer-same-window ibuf)
  6011. (org-set-frame-title heading))
  6012. ((eq org-indirect-buffer-display 'dedicated-frame)
  6013. (raise-frame
  6014. (select-frame (or (and org-indirect-dedicated-frame
  6015. (frame-live-p org-indirect-dedicated-frame)
  6016. org-indirect-dedicated-frame)
  6017. (setq org-indirect-dedicated-frame (make-frame)))))
  6018. (delete-other-windows)
  6019. (pop-to-buffer-same-window ibuf)
  6020. (org-set-frame-title (concat "Indirect: " heading)))
  6021. ((eq org-indirect-buffer-display 'current-window)
  6022. (pop-to-buffer-same-window ibuf))
  6023. ((eq org-indirect-buffer-display 'other-window)
  6024. (pop-to-buffer ibuf))
  6025. (t (error "Invalid value")))
  6026. (narrow-to-region beg end)
  6027. (org-show-all '(headings blocks))
  6028. (goto-char pos)
  6029. (run-hook-with-args 'org-cycle-hook 'all)
  6030. (and (window-live-p cwin) (select-window cwin))))
  6031. (defun org-get-indirect-buffer (&optional buffer heading)
  6032. (setq buffer (or buffer (current-buffer)))
  6033. (let ((n 1) (base (buffer-name buffer)) bname)
  6034. (while (buffer-live-p
  6035. (get-buffer
  6036. (setq bname
  6037. (concat base "-"
  6038. (if heading (concat heading "-" (number-to-string n))
  6039. (number-to-string n))))))
  6040. (setq n (1+ n)))
  6041. (condition-case nil
  6042. (make-indirect-buffer buffer bname 'clone)
  6043. (error (make-indirect-buffer buffer bname)))))
  6044. (defun org-set-frame-title (title)
  6045. "Set the title of the current frame to the string TITLE."
  6046. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6047. ;;;; Structure editing
  6048. ;;; Inserting headlines
  6049. (defun org--line-empty-p (n)
  6050. "Is the Nth next line empty?
  6051. Counts the current line as N = 1 and the previous line as N = 0;
  6052. see `beginning-of-line'."
  6053. (save-excursion
  6054. (and (not (bobp))
  6055. (or (beginning-of-line n) t)
  6056. (save-match-data
  6057. (looking-at "[ \t]*$")))))
  6058. (defun org-previous-line-empty-p ()
  6059. "Is the previous line a blank line?
  6060. When NEXT is non-nil, check the next line instead."
  6061. (org--line-empty-p 0))
  6062. (defun org-next-line-empty-p ()
  6063. "Is the previous line a blank line?
  6064. When NEXT is non-nil, check the next line instead."
  6065. (org--line-empty-p 2))
  6066. (defun org--blank-before-heading-p (&optional parent)
  6067. "Non-nil when an empty line should precede a new heading here.
  6068. When optional argument PARENT is non-nil, consider parent
  6069. headline instead of current one."
  6070. (pcase (assq 'heading org-blank-before-new-entry)
  6071. (`(heading . auto)
  6072. (save-excursion
  6073. (org-with-limited-levels
  6074. (unless (and (org-before-first-heading-p)
  6075. (not (outline-next-heading)))
  6076. (org-back-to-heading t)
  6077. (when parent (org-up-heading-safe))
  6078. (cond ((not (bobp))
  6079. (org-previous-line-empty-p))
  6080. ((outline-next-heading)
  6081. (org-previous-line-empty-p))
  6082. ;; Ignore trailing spaces on last buffer line.
  6083. ((progn (skip-chars-backward " \t") (bolp))
  6084. (org-previous-line-empty-p))
  6085. (t nil))))))
  6086. (`(heading . ,value) value)
  6087. (_ nil)))
  6088. (defun org-insert-heading (&optional arg invisible-ok top)
  6089. "Insert a new heading or an item with the same depth at point.
  6090. If point is at the beginning of a heading, insert a new heading
  6091. or a new headline above the current one. When at the beginning
  6092. of a regular line of text, turn it into a heading.
  6093. If point is in the middle of a line, split it and create a new
  6094. headline with the text in the current line after point (see
  6095. `org-M-RET-may-split-line' on how to modify this behavior). As
  6096. a special case, on a headline, splitting can only happen on the
  6097. title itself. E.g., this excludes breaking stars or tags.
  6098. With a `\\[universal-argument]' prefix, set \
  6099. `org-insert-heading-respect-content' to
  6100. a non-nil value for the duration of the command. This forces the
  6101. insertion of a heading after the current subtree, independently
  6102. on the location of point.
  6103. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6104. insert the heading at the end of the tree
  6105. above the current heading. For example, if point is within a
  6106. 2nd-level heading, then it will insert a 2nd-level heading at
  6107. the end of the 1st-level parent subtree.
  6108. When INVISIBLE-OK is set, stop at invisible headlines when going
  6109. back. This is important for non-interactive uses of the
  6110. command.
  6111. When optional argument TOP is non-nil, insert a level 1 heading,
  6112. unconditionally."
  6113. (interactive "P")
  6114. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6115. (level (org-current-level))
  6116. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6117. (cond
  6118. ((or org-insert-heading-respect-content
  6119. (member arg '((4) (16)))
  6120. (and (not invisible-ok)
  6121. (invisible-p (max (1- (point)) (point-min)))))
  6122. ;; Position point at the location of insertion. Make sure we
  6123. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6124. (org-with-limited-levels
  6125. (if (not level) (outline-next-heading) ;before first headline
  6126. (org-back-to-heading invisible-ok)
  6127. (when (equal arg '(16)) (org-up-heading-safe))
  6128. (org-end-of-subtree)))
  6129. (unless (bolp) (insert "\n"))
  6130. (unless (and blank? (org-previous-line-empty-p))
  6131. (org-N-empty-lines-before-current (if blank? 1 0)))
  6132. (insert stars " ")
  6133. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6134. ;; is visible.
  6135. (unless invisible-ok
  6136. (pcase (get-char-property-and-overlay (point) 'invisible)
  6137. (`(outline . ,o)
  6138. (move-overlay o (overlay-start o) (line-end-position 0)))
  6139. (_ nil))))
  6140. ;; At a headline...
  6141. ((org-at-heading-p)
  6142. (cond ((bolp)
  6143. (when blank? (save-excursion (insert "\n")))
  6144. (save-excursion (insert stars " \n"))
  6145. (unless (and blank? (org-previous-line-empty-p))
  6146. (org-N-empty-lines-before-current (if blank? 1 0)))
  6147. (end-of-line))
  6148. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6149. (org-match-line org-complex-heading-regexp)
  6150. (org-pos-in-match-range (point) 4))
  6151. ;; Grab the text that should moved to the new headline.
  6152. ;; Preserve tags.
  6153. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6154. (if (looking-at "[ \t]*$") (replace-match "")
  6155. (org-align-tags))
  6156. (end-of-line)
  6157. (when blank? (insert "\n"))
  6158. (insert "\n" stars " ")
  6159. (when (org-string-nw-p split) (insert split))))
  6160. (t
  6161. (end-of-line)
  6162. (when blank? (insert "\n"))
  6163. (insert "\n" stars " "))))
  6164. ;; On regular text, turn line into a headline or split, if
  6165. ;; appropriate.
  6166. ((bolp)
  6167. (insert stars " ")
  6168. (unless (and blank? (org-previous-line-empty-p))
  6169. (org-N-empty-lines-before-current (if blank? 1 0))))
  6170. (t
  6171. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6172. (end-of-line))
  6173. (insert "\n" stars " ")
  6174. (unless (and blank? (org-previous-line-empty-p))
  6175. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6176. (run-hooks 'org-insert-heading-hook))
  6177. (defun org-N-empty-lines-before-current (n)
  6178. "Make the number of empty lines before current exactly N.
  6179. So this will delete or add empty lines."
  6180. (let ((column (current-column)))
  6181. (beginning-of-line)
  6182. (unless (bobp)
  6183. (let ((start (save-excursion
  6184. (skip-chars-backward " \r\t\n")
  6185. (line-end-position))))
  6186. (delete-region start (line-end-position 0))))
  6187. (insert (make-string n ?\n))
  6188. (move-to-column column)))
  6189. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6190. "Return the heading of the current entry, without the stars.
  6191. When NO-TAGS is non-nil, don't include tags.
  6192. When NO-TODO is non-nil, don't include TODO keywords.
  6193. When NO-PRIORITY is non-nil, don't include priority cookie.
  6194. When NO-COMMENT is non-nil, don't include COMMENT string.
  6195. Return nil before first heading."
  6196. (unless (org-before-first-heading-p)
  6197. (save-excursion
  6198. (org-back-to-heading t)
  6199. (let ((case-fold-search nil))
  6200. (looking-at org-complex-heading-regexp)
  6201. (let ((todo (and (not no-todo) (match-string 2)))
  6202. (priority (and (not no-priority) (match-string 3)))
  6203. (headline (pcase (match-string 4)
  6204. (`nil "")
  6205. ((and (guard no-comment) h)
  6206. (replace-regexp-in-string
  6207. (eval-when-compile
  6208. (format "\\`%s[ \t]+" org-comment-string))
  6209. "" h))
  6210. (h h)))
  6211. (tags (and (not no-tags) (match-string 5))))
  6212. (mapconcat #'identity
  6213. (delq nil (list todo priority headline tags))
  6214. " "))))))
  6215. (defun org-heading-components ()
  6216. "Return the components of the current heading.
  6217. This is a list with the following elements:
  6218. - the level as an integer
  6219. - the reduced level, different if `org-odd-levels-only' is set.
  6220. - the TODO keyword, or nil
  6221. - the priority character, like ?A, or nil if no priority is given
  6222. - the headline text itself, or the tags string if no headline text
  6223. - the tags string, or nil."
  6224. (save-excursion
  6225. (org-back-to-heading t)
  6226. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6227. (list (length (match-string 1))
  6228. (org-reduced-level (length (match-string 1)))
  6229. (match-string-no-properties 2)
  6230. (and (match-end 3) (aref (match-string 3) 2))
  6231. (match-string-no-properties 4)
  6232. (match-string-no-properties 5)))))
  6233. (defun org-get-entry ()
  6234. "Get the entry text, after heading, entire subtree."
  6235. (save-excursion
  6236. (org-back-to-heading t)
  6237. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6238. (defun org-edit-headline (&optional heading)
  6239. "Edit the current headline.
  6240. Set it to HEADING when provided."
  6241. (interactive)
  6242. (org-with-wide-buffer
  6243. (org-back-to-heading t)
  6244. (let ((case-fold-search nil))
  6245. (when (looking-at org-complex-heading-regexp)
  6246. (let* ((old (match-string-no-properties 4))
  6247. (new (save-match-data
  6248. (org-trim (or heading (read-string "Edit: " old))))))
  6249. (unless (equal old new)
  6250. (if old (replace-match new t t nil 4)
  6251. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6252. (insert " " new))
  6253. (org-align-tags)
  6254. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6255. (defun org-insert-heading-after-current ()
  6256. "Insert a new heading with same level as current, after current subtree."
  6257. (interactive)
  6258. (org-back-to-heading)
  6259. (org-insert-heading)
  6260. (org-move-subtree-down)
  6261. (end-of-line 1))
  6262. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6263. "Insert heading with `org-insert-heading-respect-content' set to t."
  6264. (interactive)
  6265. (org-insert-heading '(4) invisible-ok))
  6266. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6267. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6268. (interactive)
  6269. (org-insert-todo-heading force-state '(4)))
  6270. (defun org-insert-todo-heading (arg &optional force-heading)
  6271. "Insert a new heading with the same level and TODO state as current heading.
  6272. If the heading has no TODO state, or if the state is DONE, use
  6273. the first state (TODO by default). Also with one prefix arg,
  6274. force first state. With two prefix args, force inserting at the
  6275. end of the parent subtree.
  6276. When called at a plain list item, insert a new item with an
  6277. unchecked check box."
  6278. (interactive "P")
  6279. (when (or force-heading (not (org-insert-item 'checkbox)))
  6280. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6281. force-heading))
  6282. (save-excursion
  6283. (org-forward-heading-same-level -1)
  6284. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6285. (let* ((new-mark-x
  6286. (if (or (equal arg '(4))
  6287. (not (match-beginning 2))
  6288. (member (match-string 2) org-done-keywords))
  6289. (car org-todo-keywords-1)
  6290. (match-string 2)))
  6291. (new-mark
  6292. (or
  6293. (run-hook-with-args-until-success
  6294. 'org-todo-get-default-hook new-mark-x nil)
  6295. new-mark-x)))
  6296. (beginning-of-line 1)
  6297. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6298. (if org-treat-insert-todo-heading-as-state-change
  6299. (org-todo new-mark)
  6300. (insert new-mark " "))))
  6301. (when org-provide-todo-statistics
  6302. (org-update-parent-todo-statistics))))
  6303. (defun org-insert-subheading (arg)
  6304. "Insert a new subheading and demote it.
  6305. Works for outline headings and for plain lists alike."
  6306. (interactive "P")
  6307. (org-insert-heading arg)
  6308. (cond
  6309. ((org-at-heading-p) (org-do-demote))
  6310. ((org-at-item-p) (org-indent-item))))
  6311. (defun org-insert-todo-subheading (arg)
  6312. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6313. Works for outline headings and for plain lists alike."
  6314. (interactive "P")
  6315. (org-insert-todo-heading arg)
  6316. (cond
  6317. ((org-at-heading-p) (org-do-demote))
  6318. ((org-at-item-p) (org-indent-item))))
  6319. ;;; Promotion and Demotion
  6320. (defvar org-after-demote-entry-hook nil
  6321. "Hook run after an entry has been demoted.
  6322. The cursor will be at the beginning of the entry.
  6323. When a subtree is being demoted, the hook will be called for each node.")
  6324. (defvar org-after-promote-entry-hook nil
  6325. "Hook run after an entry has been promoted.
  6326. The cursor will be at the beginning of the entry.
  6327. When a subtree is being promoted, the hook will be called for each node.")
  6328. (defun org-promote-subtree ()
  6329. "Promote the entire subtree.
  6330. See also `org-promote'."
  6331. (interactive)
  6332. (save-excursion
  6333. (org-with-limited-levels (org-map-tree 'org-promote)))
  6334. (org-fix-position-after-promote))
  6335. (defun org-demote-subtree ()
  6336. "Demote the entire subtree.
  6337. See `org-demote' and `org-promote'."
  6338. (interactive)
  6339. (save-excursion
  6340. (org-with-limited-levels (org-map-tree 'org-demote)))
  6341. (org-fix-position-after-promote))
  6342. (defun org-do-promote ()
  6343. "Promote the current heading higher up the tree.
  6344. If the region is active in `transient-mark-mode', promote all
  6345. headings in the region."
  6346. (interactive)
  6347. (save-excursion
  6348. (if (org-region-active-p)
  6349. (org-map-region 'org-promote (region-beginning) (region-end))
  6350. (org-promote)))
  6351. (org-fix-position-after-promote))
  6352. (defun org-do-demote ()
  6353. "Demote the current heading lower down the tree.
  6354. If the region is active in `transient-mark-mode', demote all
  6355. headings in the region."
  6356. (interactive)
  6357. (save-excursion
  6358. (if (org-region-active-p)
  6359. (org-map-region 'org-demote (region-beginning) (region-end))
  6360. (org-demote)))
  6361. (org-fix-position-after-promote))
  6362. (defun org-fix-position-after-promote ()
  6363. "Fix cursor position and indentation after demoting/promoting."
  6364. (let ((pos (point)))
  6365. (when (save-excursion
  6366. (beginning-of-line)
  6367. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6368. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6369. (cond ((eobp) (insert " "))
  6370. ((eolp) (insert " "))
  6371. ((equal (char-after) ?\s) (forward-char 1))))))
  6372. (defun org-current-level ()
  6373. "Return the level of the current entry, or nil if before the first headline.
  6374. The level is the number of stars at the beginning of the
  6375. headline. Use `org-reduced-level' to remove the effect of
  6376. `org-odd-levels'. Unlike to `org-outline-level', this function
  6377. ignores inlinetasks."
  6378. (let ((level (org-with-limited-levels (org-outline-level))))
  6379. (and (> level 0) level)))
  6380. (defun org-get-previous-line-level ()
  6381. "Return the outline depth of the last headline before the current line.
  6382. Returns 0 for the first headline in the buffer, and nil if before the
  6383. first headline."
  6384. (and (org-current-level)
  6385. (or (and (/= (line-beginning-position) (point-min))
  6386. (save-excursion (beginning-of-line 0) (org-current-level)))
  6387. 0)))
  6388. (defun org-reduced-level (l)
  6389. "Compute the effective level of a heading.
  6390. This takes into account the setting of `org-odd-levels-only'."
  6391. (cond
  6392. ((zerop l) 0)
  6393. (org-odd-levels-only (1+ (floor (/ l 2))))
  6394. (t l)))
  6395. (defun org-level-increment ()
  6396. "Return the number of stars that will be added or removed at a
  6397. time to headlines when structure editing, based on the value of
  6398. `org-odd-levels-only'."
  6399. (if org-odd-levels-only 2 1))
  6400. (defun org-get-valid-level (level &optional change)
  6401. "Rectify a level change under the influence of `org-odd-levels-only'.
  6402. LEVEL is a current level, CHANGE is by how much the level should
  6403. be modified. Even if CHANGE is nil, LEVEL may be returned
  6404. modified because even level numbers will become the next higher
  6405. odd number. Returns values greater than 0."
  6406. (if org-odd-levels-only
  6407. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6408. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6409. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6410. (max 1 (+ level (or change 0)))))
  6411. (defun org-promote ()
  6412. "Promote the current heading higher up the tree."
  6413. (org-with-wide-buffer
  6414. (org-back-to-heading t)
  6415. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6416. after-change-functions))
  6417. (level (save-match-data (funcall outline-level)))
  6418. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6419. (diff (abs (- level (length up-head) -1))))
  6420. (cond
  6421. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6422. (replace-match "# " nil t))
  6423. ((= level 1)
  6424. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6425. (t (replace-match up-head nil t)))
  6426. (unless (= level 1)
  6427. (when org-auto-align-tags (org-align-tags))
  6428. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6429. (run-hooks 'org-after-promote-entry-hook))))
  6430. (defun org-demote ()
  6431. "Demote the current heading lower down the tree."
  6432. (org-with-wide-buffer
  6433. (org-back-to-heading t)
  6434. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6435. after-change-functions))
  6436. (level (save-match-data (funcall outline-level)))
  6437. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6438. (diff (abs (- level (length down-head) -1))))
  6439. (replace-match down-head nil t)
  6440. (when org-auto-align-tags (org-align-tags))
  6441. (when org-adapt-indentation (org-fixup-indentation diff))
  6442. (run-hooks 'org-after-demote-entry-hook))))
  6443. (defun org-cycle-level ()
  6444. "Cycle the level of an empty headline through possible states.
  6445. This goes first to child, then to parent, level, then up the hierarchy.
  6446. After top level, it switches back to sibling level."
  6447. (interactive)
  6448. (let ((org-adapt-indentation nil))
  6449. (when (org-point-at-end-of-empty-headline)
  6450. (setq this-command 'org-cycle-level) ; Only needed for caching
  6451. (let ((cur-level (org-current-level))
  6452. (prev-level (org-get-previous-line-level)))
  6453. (cond
  6454. ;; If first headline in file, promote to top-level.
  6455. ((= prev-level 0)
  6456. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6457. do (org-do-promote)))
  6458. ;; If same level as prev, demote one.
  6459. ((= prev-level cur-level)
  6460. (org-do-demote))
  6461. ;; If parent is top-level, promote to top level if not already.
  6462. ((= prev-level 1)
  6463. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6464. do (org-do-promote)))
  6465. ;; If top-level, return to prev-level.
  6466. ((= cur-level 1)
  6467. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6468. do (org-do-demote)))
  6469. ;; If less than prev-level, promote one.
  6470. ((< cur-level prev-level)
  6471. (org-do-promote))
  6472. ;; If deeper than prev-level, promote until higher than
  6473. ;; prev-level.
  6474. ((> cur-level prev-level)
  6475. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6476. do (org-do-promote))))
  6477. t))))
  6478. (defun org-map-tree (fun)
  6479. "Call FUN for every heading underneath the current one."
  6480. (org-back-to-heading t)
  6481. (let ((level (funcall outline-level)))
  6482. (save-excursion
  6483. (funcall fun)
  6484. (while (and (progn
  6485. (outline-next-heading)
  6486. (> (funcall outline-level) level))
  6487. (not (eobp)))
  6488. (funcall fun)))))
  6489. (defun org-map-region (fun beg end)
  6490. "Call FUN for every heading between BEG and END."
  6491. (let ((org-ignore-region t))
  6492. (save-excursion
  6493. (setq end (copy-marker end))
  6494. (goto-char beg)
  6495. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6496. (< (point) end))
  6497. (funcall fun))
  6498. (while (and (progn
  6499. (outline-next-heading)
  6500. (< (point) end))
  6501. (not (eobp)))
  6502. (funcall fun)))))
  6503. (defun org-fixup-indentation (diff)
  6504. "Change the indentation in the current entry by DIFF.
  6505. DIFF is an integer. Indentation is done according to the
  6506. following rules:
  6507. - Planning information and property drawers are always indented
  6508. according to the new level of the headline;
  6509. - Footnote definitions and their contents are ignored;
  6510. - Inlinetasks' boundaries are not shifted;
  6511. - Empty lines are ignored;
  6512. - Other lines' indentation are shifted by DIFF columns, unless
  6513. it would introduce a structural change in the document, in
  6514. which case no shifting is done at all.
  6515. Assume point is at a heading or an inlinetask beginning."
  6516. (org-with-wide-buffer
  6517. (narrow-to-region (line-beginning-position)
  6518. (save-excursion
  6519. (if (org-with-limited-levels (org-at-heading-p))
  6520. (org-with-limited-levels (outline-next-heading))
  6521. (org-inlinetask-goto-end))
  6522. (point)))
  6523. (forward-line)
  6524. ;; Indent properly planning info and property drawer.
  6525. (when (looking-at-p org-planning-line-re)
  6526. (org-indent-line)
  6527. (forward-line))
  6528. (when (looking-at org-property-drawer-re)
  6529. (goto-char (match-end 0))
  6530. (forward-line)
  6531. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6532. (catch 'no-shift
  6533. (when (zerop diff) (throw 'no-shift nil))
  6534. ;; If DIFF is negative, first check if a shift is possible at all
  6535. ;; (e.g., it doesn't break structure). This can only happen if
  6536. ;; some contents are not properly indented.
  6537. (let ((case-fold-search t))
  6538. (when (< diff 0)
  6539. (let ((diff (- diff))
  6540. (forbidden-re (concat org-outline-regexp
  6541. "\\|"
  6542. (substring org-footnote-definition-re 1))))
  6543. (save-excursion
  6544. (while (not (eobp))
  6545. (cond
  6546. ((looking-at-p "[ \t]*$") (forward-line))
  6547. ((and (looking-at-p org-footnote-definition-re)
  6548. (let ((e (org-element-at-point)))
  6549. (and (eq (org-element-type e) 'footnote-definition)
  6550. (goto-char (org-element-property :end e))))))
  6551. ((looking-at-p org-outline-regexp) (forward-line))
  6552. ;; Give up if shifting would move before column 0 or
  6553. ;; if it would introduce a headline or a footnote
  6554. ;; definition.
  6555. (t
  6556. (skip-chars-forward " \t")
  6557. (let ((ind (current-column)))
  6558. (when (or (< ind diff)
  6559. (and (= ind diff) (looking-at-p forbidden-re)))
  6560. (throw 'no-shift nil)))
  6561. ;; Ignore contents of example blocks and source
  6562. ;; blocks if their indentation is meant to be
  6563. ;; preserved. Jump to block's closing line.
  6564. (beginning-of-line)
  6565. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6566. (let ((e (org-element-at-point)))
  6567. (and (memq (org-element-type e)
  6568. '(example-block src-block))
  6569. (or org-src-preserve-indentation
  6570. (org-element-property :preserve-indent e))
  6571. (goto-char (org-element-property :end e))
  6572. (progn (skip-chars-backward " \r\t\n")
  6573. (beginning-of-line)
  6574. t))))
  6575. (forward-line))))))))
  6576. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6577. ;; by DIFF. Also skip contents of source or example blocks
  6578. ;; when indentation is meant to be preserved.
  6579. (while (not (eobp))
  6580. (cond
  6581. ((and (looking-at-p org-footnote-definition-re)
  6582. (let ((e (org-element-at-point)))
  6583. (and (eq (org-element-type e) 'footnote-definition)
  6584. (goto-char (org-element-property :end e))))))
  6585. ((looking-at-p org-outline-regexp) (forward-line))
  6586. ((looking-at-p "[ \t]*$") (forward-line))
  6587. (t
  6588. (indent-line-to (+ (current-indentation) diff))
  6589. (beginning-of-line)
  6590. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6591. (let ((e (org-element-at-point)))
  6592. (and (memq (org-element-type e)
  6593. '(example-block src-block))
  6594. (or org-src-preserve-indentation
  6595. (org-element-property :preserve-indent e))
  6596. (goto-char (org-element-property :end e))
  6597. (progn (skip-chars-backward " \r\t\n")
  6598. (beginning-of-line)
  6599. t))))
  6600. (forward-line)))))))))
  6601. (defun org-convert-to-odd-levels ()
  6602. "Convert an Org file with all levels allowed to one with odd levels.
  6603. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6604. level 5 etc."
  6605. (interactive)
  6606. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6607. (let ((outline-level 'org-outline-level)
  6608. (org-odd-levels-only nil) n)
  6609. (save-excursion
  6610. (goto-char (point-min))
  6611. (while (re-search-forward "^\\*\\*+ " nil t)
  6612. (setq n (- (length (match-string 0)) 2))
  6613. (while (>= (setq n (1- n)) 0)
  6614. (org-demote))
  6615. (end-of-line 1))))))
  6616. (defun org-convert-to-oddeven-levels ()
  6617. "Convert an Org file with only odd levels to one with odd/even levels.
  6618. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6619. file contains a section with an even level, conversion would
  6620. destroy the structure of the file. An error is signaled in this
  6621. case."
  6622. (interactive)
  6623. (goto-char (point-min))
  6624. ;; First check if there are no even levels
  6625. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6626. (org-show-set-visibility 'canonical)
  6627. (error "Not all levels are odd in this file. Conversion not possible"))
  6628. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6629. (let ((outline-regexp org-outline-regexp)
  6630. (outline-level 'org-outline-level)
  6631. (org-odd-levels-only nil) n)
  6632. (save-excursion
  6633. (goto-char (point-min))
  6634. (while (re-search-forward "^\\*\\*+ " nil t)
  6635. (setq n (/ (1- (length (match-string 0))) 2))
  6636. (while (>= (setq n (1- n)) 0)
  6637. (org-promote))
  6638. (end-of-line 1))))))
  6639. (defun org-tr-level (n)
  6640. "Make N odd if required."
  6641. (if org-odd-levels-only (1+ (/ n 2)) n))
  6642. ;;; Vertical tree motion, cutting and pasting of subtrees
  6643. (defun org-move-subtree-up (&optional arg)
  6644. "Move the current subtree up past ARG headlines of the same level."
  6645. (interactive "p")
  6646. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6647. (defun org-move-subtree-down (&optional arg)
  6648. "Move the current subtree down past ARG headlines of the same level."
  6649. (interactive "p")
  6650. (setq arg (prefix-numeric-value arg))
  6651. (org-preserve-local-variables
  6652. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6653. 'org-get-last-sibling))
  6654. (ins-point (make-marker))
  6655. (cnt (abs arg))
  6656. (col (current-column))
  6657. beg end txt folded)
  6658. ;; Select the tree
  6659. (org-back-to-heading)
  6660. (setq beg (point))
  6661. (save-match-data
  6662. (save-excursion (outline-end-of-heading)
  6663. (setq folded (org-invisible-p)))
  6664. (progn (org-end-of-subtree nil t)
  6665. (unless (eobp) (backward-char))))
  6666. (outline-next-heading)
  6667. (setq end (point))
  6668. (goto-char beg)
  6669. ;; Find insertion point, with error handling
  6670. (while (> cnt 0)
  6671. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6672. (goto-char beg)
  6673. (user-error "Cannot move past superior level or buffer limit"))
  6674. (setq cnt (1- cnt)))
  6675. (when (> arg 0)
  6676. ;; Moving forward - still need to move over subtree
  6677. (org-end-of-subtree t t)
  6678. (save-excursion
  6679. (org-back-over-empty-lines)
  6680. (or (bolp) (newline))))
  6681. (move-marker ins-point (point))
  6682. (setq txt (buffer-substring beg end))
  6683. (org-save-markers-in-region beg end)
  6684. (delete-region beg end)
  6685. (org-remove-empty-overlays-at beg)
  6686. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6687. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6688. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6689. (let ((bbb (point)))
  6690. (insert-before-markers txt)
  6691. (org-reinstall-markers-in-region bbb)
  6692. (move-marker ins-point bbb))
  6693. (or (bolp) (insert "\n"))
  6694. (goto-char ins-point)
  6695. (org-skip-whitespace)
  6696. (move-marker ins-point nil)
  6697. (if folded
  6698. (org-flag-subtree t)
  6699. (org-show-entry)
  6700. (org-show-children))
  6701. (org-clean-visibility-after-subtree-move)
  6702. ;; move back to the initial column we were at
  6703. (move-to-column col))))
  6704. (defvar org-subtree-clip ""
  6705. "Clipboard for cut and paste of subtrees.
  6706. This is actually only a copy of the kill, because we use the normal kill
  6707. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6708. (defvar org-subtree-clip-folded nil
  6709. "Was the last copied subtree folded?
  6710. This is used to fold the tree back after pasting.")
  6711. (defun org-cut-subtree (&optional n)
  6712. "Cut the current subtree into the clipboard.
  6713. With prefix arg N, cut this many sequential subtrees.
  6714. This is a short-hand for marking the subtree and then cutting it."
  6715. (interactive "p")
  6716. (org-copy-subtree n 'cut))
  6717. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6718. "Copy the current subtree into the clipboard.
  6719. With prefix arg N, copy this many sequential subtrees.
  6720. This is a short-hand for marking the subtree and then copying it.
  6721. If CUT is non-nil, actually cut the subtree.
  6722. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6723. of some markers in the region, even if CUT is non-nil. This is
  6724. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6725. (interactive "p")
  6726. (org-preserve-local-variables
  6727. (let (beg end folded (beg0 (point)))
  6728. (if (called-interactively-p 'any)
  6729. (org-back-to-heading nil) ; take what looks like a subtree
  6730. (org-back-to-heading t)) ; take what is really there
  6731. (setq beg (point))
  6732. (skip-chars-forward " \t\r\n")
  6733. (save-match-data
  6734. (if nosubtrees
  6735. (outline-next-heading)
  6736. (save-excursion (outline-end-of-heading)
  6737. (setq folded (org-invisible-p)))
  6738. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6739. (org-end-of-subtree t t)))
  6740. ;; Include the end of an inlinetask
  6741. (when (and (featurep 'org-inlinetask)
  6742. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6743. "END[ \t]*$")))
  6744. (end-of-line))
  6745. (setq end (point))
  6746. (goto-char beg0)
  6747. (when (> end beg)
  6748. (setq org-subtree-clip-folded folded)
  6749. (when (or cut force-store-markers)
  6750. (org-save-markers-in-region beg end))
  6751. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6752. (setq org-subtree-clip (current-kill 0))
  6753. (message "%s: Subtree(s) with %d characters"
  6754. (if cut "Cut" "Copied")
  6755. (length org-subtree-clip))))))
  6756. (defun org-paste-subtree (&optional level tree for-yank remove)
  6757. "Paste the clipboard as a subtree, with modification of headline level.
  6758. The entire subtree is promoted or demoted in order to match a new headline
  6759. level.
  6760. If the cursor is at the beginning of a headline, the same level as
  6761. that headline is used to paste the tree.
  6762. If not, the new level is derived from the *visible* headings
  6763. before and after the insertion point, and taken to be the inferior headline
  6764. level of the two. So if the previous visible heading is level 3 and the
  6765. next is level 4 (or vice versa), level 4 will be used for insertion.
  6766. This makes sure that the subtree remains an independent subtree and does
  6767. not swallow low level entries.
  6768. You can also force a different level, either by using a numeric prefix
  6769. argument, or by inserting the heading marker by hand. For example, if the
  6770. cursor is after \"*****\", then the tree will be shifted to level 5.
  6771. If optional TREE is given, use this text instead of the kill ring.
  6772. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6773. move back over whitespace before inserting, and move point to the end of
  6774. the inserted text when done.
  6775. When REMOVE is non-nil, remove the subtree from the clipboard."
  6776. (interactive "P")
  6777. (setq tree (or tree (and kill-ring (current-kill 0))))
  6778. (unless (org-kill-is-subtree-p tree)
  6779. (user-error
  6780. (substitute-command-keys
  6781. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6782. (org-with-limited-levels
  6783. (let* ((visp (not (org-invisible-p)))
  6784. (txt tree)
  6785. (old-level (if (string-match org-outline-regexp-bol txt)
  6786. (- (match-end 0) (match-beginning 0) 1)
  6787. -1))
  6788. (force-level
  6789. (cond
  6790. (level (prefix-numeric-value level))
  6791. ;; When point is after the stars in an otherwise empty
  6792. ;; headline, use the number of stars as the forced level.
  6793. ((and (org-match-line "^\\*+[ \t]*$")
  6794. (not (eq ?* (char-after))))
  6795. (org-outline-level))
  6796. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6797. (previous-level
  6798. (save-excursion
  6799. (org-previous-visible-heading 1)
  6800. (if (org-at-heading-p) (org-outline-level) 1)))
  6801. (next-level
  6802. (save-excursion
  6803. (if (org-at-heading-p) (org-outline-level)
  6804. (org-next-visible-heading 1)
  6805. (if (org-at-heading-p) (org-outline-level) 1))))
  6806. (new-level (or force-level (max previous-level next-level)))
  6807. (shift (if (or (= old-level -1)
  6808. (= new-level -1)
  6809. (= old-level new-level))
  6810. 0
  6811. (- new-level old-level)))
  6812. (delta (if (> shift 0) -1 1))
  6813. (func (if (> shift 0) #'org-demote #'org-promote))
  6814. (org-odd-levels-only nil)
  6815. beg end newend)
  6816. ;; Remove the forced level indicator.
  6817. (when (and force-level (not level))
  6818. (delete-region (line-beginning-position) (point)))
  6819. ;; Paste before the next visible heading or at end of buffer,
  6820. ;; unless point is at the beginning of a headline.
  6821. (unless (and (bolp) (org-at-heading-p))
  6822. (org-next-visible-heading 1)
  6823. (unless (bolp) (insert "\n")))
  6824. (setq beg (point))
  6825. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6826. (insert-before-markers txt)
  6827. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6828. (setq newend (point))
  6829. (org-reinstall-markers-in-region beg)
  6830. (setq end (point))
  6831. (goto-char beg)
  6832. (skip-chars-forward " \t\n\r")
  6833. (setq beg (point))
  6834. (when (and (org-invisible-p) visp)
  6835. (save-excursion (outline-show-heading)))
  6836. ;; Shift if necessary.
  6837. (unless (= shift 0)
  6838. (save-restriction
  6839. (narrow-to-region beg end)
  6840. (while (not (= shift 0))
  6841. (org-map-region func (point-min) (point-max))
  6842. (setq shift (+ delta shift)))
  6843. (goto-char (point-min))
  6844. (setq newend (point-max))))
  6845. (when (or for-yank (called-interactively-p 'interactive))
  6846. (message "Clipboard pasted as level %d subtree" new-level))
  6847. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6848. kill-ring
  6849. (equal org-subtree-clip (current-kill 0))
  6850. org-subtree-clip-folded)
  6851. ;; The tree was folded before it was killed/copied
  6852. (org-flag-subtree t))
  6853. (when for-yank (goto-char newend))
  6854. (when remove (pop kill-ring)))))
  6855. (defun org-kill-is-subtree-p (&optional txt)
  6856. "Check if the current kill is an outline subtree, or a set of trees.
  6857. Returns nil if kill does not start with a headline, or if the first
  6858. headline level is not the largest headline level in the tree.
  6859. So this will actually accept several entries of equal levels as well,
  6860. which is OK for `org-paste-subtree'.
  6861. If optional TXT is given, check this string instead of the current kill."
  6862. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6863. (re (org-get-limited-outline-regexp))
  6864. (^re (concat "^" re))
  6865. (start-level (and kill
  6866. (string-match
  6867. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6868. kill)
  6869. (- (match-end 2) (match-beginning 2) 1)))
  6870. (start (1+ (or (match-beginning 2) -1))))
  6871. (if (not start-level)
  6872. (progn
  6873. nil) ;; does not even start with a heading
  6874. (catch 'exit
  6875. (while (setq start (string-match ^re kill (1+ start)))
  6876. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6877. (throw 'exit nil)))
  6878. t))))
  6879. (defvar org-markers-to-move nil
  6880. "Markers that should be moved with a cut-and-paste operation.
  6881. Those markers are stored together with their positions relative to
  6882. the start of the region.")
  6883. (defun org-save-markers-in-region (beg end)
  6884. "Check markers in region.
  6885. If these markers are between BEG and END, record their position relative
  6886. to BEG, so that after moving the block of text, we can put the markers back
  6887. into place.
  6888. This function gets called just before an entry or tree gets cut from the
  6889. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6890. called immediately, to move the markers with the entries."
  6891. (setq org-markers-to-move nil)
  6892. (when (featurep 'org-clock)
  6893. (org-clock-save-markers-for-cut-and-paste beg end))
  6894. (when (featurep 'org-agenda)
  6895. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6896. (defun org-check-and-save-marker (marker beg end)
  6897. "Check if MARKER is between BEG and END.
  6898. If yes, remember the marker and the distance to BEG."
  6899. (when (and (marker-buffer marker)
  6900. (equal (marker-buffer marker) (current-buffer))
  6901. (>= marker beg) (< marker end))
  6902. (push (cons marker (- marker beg)) org-markers-to-move)))
  6903. (defun org-reinstall-markers-in-region (beg)
  6904. "Move all remembered markers to their position relative to BEG."
  6905. (dolist (x org-markers-to-move)
  6906. (move-marker (car x) (+ beg (cdr x))))
  6907. (setq org-markers-to-move nil))
  6908. (defun org-narrow-to-subtree ()
  6909. "Narrow buffer to the current subtree."
  6910. (interactive)
  6911. (save-excursion
  6912. (save-match-data
  6913. (org-with-limited-levels
  6914. (narrow-to-region
  6915. (progn (org-back-to-heading t) (point))
  6916. (progn (org-end-of-subtree t t)
  6917. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6918. (point)))))))
  6919. (defun org-toggle-narrow-to-subtree ()
  6920. "Narrow to the subtree at point or widen a narrowed buffer."
  6921. (interactive)
  6922. (if (buffer-narrowed-p)
  6923. (widen)
  6924. (org-narrow-to-subtree)))
  6925. (defun org-narrow-to-block ()
  6926. "Narrow buffer to the current block."
  6927. (interactive)
  6928. (let* ((case-fold-search t)
  6929. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6930. "^[ \t]*#\\+end_.*")))
  6931. (if blockp
  6932. (narrow-to-region (car blockp) (cdr blockp))
  6933. (user-error "Not in a block"))))
  6934. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6935. "Clone the task (subtree) at point N times.
  6936. The clones will be inserted as siblings.
  6937. In interactive use, the user will be prompted for the number of
  6938. clones to be produced. If the entry has a timestamp, the user
  6939. will also be prompted for a time shift, which may be a repeater
  6940. as used in time stamps, for example `+3d'. To disable this,
  6941. you can call the function with a universal prefix argument.
  6942. When a valid repeater is given and the entry contains any time
  6943. stamps, the clones will become a sequence in time, with time
  6944. stamps in the subtree shifted for each clone produced. If SHIFT
  6945. is nil or the empty string, time stamps will be left alone. The
  6946. ID property of the original subtree is removed.
  6947. In each clone, all the CLOCK entries will be removed. This
  6948. prevents Org from considering that the clocked times overlap.
  6949. If the original subtree did contain time stamps with a repeater,
  6950. the following will happen:
  6951. - the repeater will be removed in each clone
  6952. - an additional clone will be produced, with the current, unshifted
  6953. date(s) in the entry.
  6954. - the original entry will be placed *after* all the clones, with
  6955. repeater intact.
  6956. - the start days in the repeater in the original entry will be shifted
  6957. to past the last clone.
  6958. In this way you can spell out a number of instances of a repeating task,
  6959. and still retain the repeater to cover future instances of the task.
  6960. As described above, N+1 clones are produced when the original
  6961. subtree has a repeater. Setting N to 0, then, can be used to
  6962. remove the repeater from a subtree and create a shifted clone
  6963. with the original repeater."
  6964. (interactive "nNumber of clones to produce: ")
  6965. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6966. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6967. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6968. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6969. (shift
  6970. (or shift
  6971. (if (and (not (equal current-prefix-arg '(4)))
  6972. (save-excursion
  6973. (goto-char beg)
  6974. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6975. (read-from-minibuffer
  6976. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6977. ""))) ;No time shift
  6978. (doshift
  6979. (and (org-string-nw-p shift)
  6980. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6981. shift)
  6982. (user-error "Invalid shift specification %s" shift)))))
  6983. (goto-char end-of-tree)
  6984. (unless (bolp) (insert "\n"))
  6985. (let* ((end (point))
  6986. (template (buffer-substring beg end))
  6987. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6988. (shift-what (pcase (and doshift (match-string 2 shift))
  6989. (`nil nil)
  6990. ("d" 'day)
  6991. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6992. ("m" 'month)
  6993. ("y" 'year)
  6994. (_ (error "Unsupported time unit"))))
  6995. (nmin 1)
  6996. (nmax n)
  6997. (n-no-remove -1)
  6998. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6999. (idprop (org-entry-get beg "ID")))
  7000. (when (and doshift
  7001. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7002. template))
  7003. (delete-region beg end)
  7004. (setq end beg)
  7005. (setq nmin 0)
  7006. (setq nmax (1+ nmax))
  7007. (setq n-no-remove nmax))
  7008. (goto-char end)
  7009. (cl-loop for n from nmin to nmax do
  7010. (insert
  7011. ;; Prepare clone.
  7012. (with-temp-buffer
  7013. (insert template)
  7014. (org-mode)
  7015. (goto-char (point-min))
  7016. (org-show-subtree)
  7017. (and idprop (if org-clone-delete-id
  7018. (org-entry-delete nil "ID")
  7019. (org-id-get-create t)))
  7020. (unless (= n 0)
  7021. (while (re-search-forward org-clock-line-re nil t)
  7022. (delete-region (line-beginning-position)
  7023. (line-beginning-position 2)))
  7024. (goto-char (point-min))
  7025. (while (re-search-forward org-drawer-regexp nil t)
  7026. (org-remove-empty-drawer-at (point))))
  7027. (goto-char (point-min))
  7028. (when doshift
  7029. (while (re-search-forward org-ts-regexp-both nil t)
  7030. (org-timestamp-change (* n shift-n) shift-what))
  7031. (unless (= n n-no-remove)
  7032. (goto-char (point-min))
  7033. (while (re-search-forward org-ts-regexp nil t)
  7034. (save-excursion
  7035. (goto-char (match-beginning 0))
  7036. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7037. (delete-region (match-beginning 1) (match-end 1)))))))
  7038. (buffer-string)))))
  7039. (goto-char beg)))
  7040. ;;; Outline Sorting
  7041. (defun org-sort (&optional with-case)
  7042. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7043. Optional argument WITH-CASE means sort case-sensitively."
  7044. (interactive "P")
  7045. (org-call-with-arg
  7046. (cond ((org-at-table-p) #'org-table-sort-lines)
  7047. ((org-at-item-p) #'org-sort-list)
  7048. (t #'org-sort-entries))
  7049. with-case))
  7050. (defun org-sort-remove-invisible (s)
  7051. "Remove invisible part of links and emphasis markers from string S."
  7052. (remove-text-properties 0 (length s) org-rm-props s)
  7053. (replace-regexp-in-string
  7054. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7055. (replace-regexp-in-string
  7056. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7057. (org-link-display-format s)
  7058. t t) t t))
  7059. (defvar org-priority-regexp) ; defined later in the file
  7060. (defvar org-after-sorting-entries-or-items-hook nil
  7061. "Hook that is run after a bunch of entries or items have been sorted.
  7062. When children are sorted, the cursor is in the parent line when this
  7063. hook gets called. When a region or a plain list is sorted, the cursor
  7064. will be in the first entry of the sorted region/list.")
  7065. (defun org-sort-entries
  7066. (&optional with-case sorting-type getkey-func compare-func property
  7067. interactive?)
  7068. "Sort entries on a certain level of an outline tree.
  7069. If there is an active region, the entries in the region are sorted.
  7070. Else, if the cursor is before the first entry, sort the top-level items.
  7071. Else, the children of the entry at point are sorted.
  7072. Sorting can be alphabetically, numerically, by date/time as given by
  7073. a time stamp, by a property, by priority order, or by a custom function.
  7074. The command prompts for the sorting type unless it has been given to the
  7075. function through the SORTING-TYPE argument, which needs to be a character,
  7076. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7077. the precise meaning of each character:
  7078. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7079. c By creation time, which is assumed to be the first inactive time stamp
  7080. at the beginning of a line.
  7081. d By deadline date/time.
  7082. k By clocking time.
  7083. n Numerically, by converting the beginning of the entry/item to a number.
  7084. o By order of TODO keywords.
  7085. p By priority according to the cookie.
  7086. r By the value of a property.
  7087. s By scheduled date/time.
  7088. t By date/time, either the first active time stamp in the entry, or, if
  7089. none exist, by the first inactive one.
  7090. Capital letters will reverse the sort order.
  7091. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7092. called with point at the beginning of the record. It must return a
  7093. value that is compatible with COMPARE-FUNC, the function used to
  7094. compare entries.
  7095. Comparing entries ignores case by default. However, with an optional argument
  7096. WITH-CASE, the sorting considers case as well.
  7097. Sorting is done against the visible part of the headlines, it ignores hidden
  7098. links.
  7099. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7100. A non-nil value for INTERACTIVE? is used to signal that this
  7101. function is being called interactively."
  7102. (interactive (list current-prefix-arg nil nil nil nil t))
  7103. (let ((case-func (if with-case 'identity 'downcase))
  7104. start beg end stars re re2
  7105. txt what tmp)
  7106. ;; Find beginning and end of region to sort
  7107. (cond
  7108. ((org-region-active-p)
  7109. ;; we will sort the region
  7110. (setq end (region-end)
  7111. what "region")
  7112. (goto-char (region-beginning))
  7113. (unless (org-at-heading-p) (outline-next-heading))
  7114. (setq start (point)))
  7115. ((or (org-at-heading-p)
  7116. (ignore-errors (progn (org-back-to-heading) t)))
  7117. ;; we will sort the children of the current headline
  7118. (org-back-to-heading)
  7119. (setq start (point)
  7120. end (progn (org-end-of-subtree t t)
  7121. (or (bolp) (insert "\n"))
  7122. (when (>= (org-back-over-empty-lines) 1)
  7123. (forward-line 1))
  7124. (point))
  7125. what "children")
  7126. (goto-char start)
  7127. (outline-show-subtree)
  7128. (outline-next-heading))
  7129. (t
  7130. ;; we will sort the top-level entries in this file
  7131. (goto-char (point-min))
  7132. (or (org-at-heading-p) (outline-next-heading))
  7133. (setq start (point))
  7134. (goto-char (point-max))
  7135. (beginning-of-line 1)
  7136. (when (looking-at ".*?\\S-")
  7137. ;; File ends in a non-white line
  7138. (end-of-line 1)
  7139. (insert "\n"))
  7140. (setq end (point-max))
  7141. (setq what "top-level")
  7142. (goto-char start)
  7143. (org-show-all '(headings blocks))))
  7144. (setq beg (point))
  7145. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7146. (looking-at "\\(\\*+\\)")
  7147. (setq stars (match-string 1)
  7148. re (concat "^" (regexp-quote stars) " +")
  7149. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7150. txt (buffer-substring beg end))
  7151. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7152. (when (and (not (equal stars "*")) (string-match re2 txt))
  7153. (user-error "Region to sort contains a level above the first entry"))
  7154. (unless sorting-type
  7155. (message
  7156. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7157. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7158. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7159. what)
  7160. (setq sorting-type (read-char-exclusive)))
  7161. (unless getkey-func
  7162. (and (= (downcase sorting-type) ?f)
  7163. (setq getkey-func
  7164. (or (and interactive?
  7165. (org-read-function
  7166. "Function for extracting keys: "))
  7167. (error "Missing key extractor")))))
  7168. (and (= (downcase sorting-type) ?r)
  7169. (not property)
  7170. (setq property
  7171. (completing-read "Property: "
  7172. (mapcar #'list (org-buffer-property-keys t))
  7173. nil t)))
  7174. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7175. (message "Sorting entries...")
  7176. (save-restriction
  7177. (narrow-to-region start end)
  7178. (let ((restore-clock?
  7179. ;; The clock marker is lost when using `sort-subr'; mark
  7180. ;; the clock with temporary `:org-clock-marker-backup'
  7181. ;; text property.
  7182. (when (and (eq (org-clock-is-active) (current-buffer))
  7183. (<= start (marker-position org-clock-marker))
  7184. (>= end (marker-position org-clock-marker)))
  7185. (with-silent-modifications
  7186. (put-text-property (1- org-clock-marker) org-clock-marker
  7187. :org-clock-marker-backup t))
  7188. t))
  7189. (dcst (downcase sorting-type))
  7190. (case-fold-search nil)
  7191. (now (current-time)))
  7192. (org-preserve-local-variables
  7193. (sort-subr
  7194. (/= dcst sorting-type)
  7195. ;; This function moves to the beginning character of the
  7196. ;; "record" to be sorted.
  7197. (lambda nil
  7198. (if (re-search-forward re nil t)
  7199. (goto-char (match-beginning 0))
  7200. (goto-char (point-max))))
  7201. ;; This function moves to the last character of the "record" being
  7202. ;; sorted.
  7203. (lambda nil
  7204. (save-match-data
  7205. (condition-case nil
  7206. (outline-forward-same-level 1)
  7207. (error
  7208. (goto-char (point-max))))))
  7209. ;; This function returns the value that gets sorted against.
  7210. (lambda ()
  7211. (cond
  7212. ((= dcst ?n)
  7213. (string-to-number
  7214. (org-sort-remove-invisible (org-get-heading t t t t))))
  7215. ((= dcst ?a)
  7216. (funcall case-func
  7217. (org-sort-remove-invisible (org-get-heading t t t t))))
  7218. ((= dcst ?k)
  7219. (or (get-text-property (point) :org-clock-minutes) 0))
  7220. ((= dcst ?t)
  7221. (let ((end (save-excursion (outline-next-heading) (point))))
  7222. (if (or (re-search-forward org-ts-regexp end t)
  7223. (re-search-forward org-ts-regexp-both end t))
  7224. (org-time-string-to-seconds (match-string 0))
  7225. (float-time now))))
  7226. ((= dcst ?c)
  7227. (let ((end (save-excursion (outline-next-heading) (point))))
  7228. (if (re-search-forward
  7229. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7230. end t)
  7231. (org-time-string-to-seconds (match-string 0))
  7232. (float-time now))))
  7233. ((= dcst ?s)
  7234. (let ((end (save-excursion (outline-next-heading) (point))))
  7235. (if (re-search-forward org-scheduled-time-regexp end t)
  7236. (org-time-string-to-seconds (match-string 1))
  7237. (float-time now))))
  7238. ((= dcst ?d)
  7239. (let ((end (save-excursion (outline-next-heading) (point))))
  7240. (if (re-search-forward org-deadline-time-regexp end t)
  7241. (org-time-string-to-seconds (match-string 1))
  7242. (float-time now))))
  7243. ((= dcst ?p)
  7244. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7245. (string-to-char (match-string 2))
  7246. org-default-priority))
  7247. ((= dcst ?r)
  7248. (or (org-entry-get nil property) ""))
  7249. ((= dcst ?o)
  7250. (when (looking-at org-complex-heading-regexp)
  7251. (let* ((m (match-string 2))
  7252. (s (if (member m org-done-keywords) '- '+)))
  7253. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7254. ((= dcst ?f)
  7255. (if getkey-func
  7256. (progn
  7257. (setq tmp (funcall getkey-func))
  7258. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7259. tmp)
  7260. (error "Invalid key function `%s'" getkey-func)))
  7261. (t (error "Invalid sorting type `%c'" sorting-type))))
  7262. nil
  7263. (cond
  7264. ((= dcst ?a) 'org-string-collate-lessp)
  7265. ((= dcst ?f)
  7266. (or compare-func
  7267. (and interactive?
  7268. (org-read-function
  7269. (concat "Function for comparing keys "
  7270. "(empty for default `sort-subr' predicate): ")
  7271. 'allow-empty))))
  7272. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7273. (org-cycle-hide-drawers 'all)
  7274. (when restore-clock?
  7275. (move-marker org-clock-marker
  7276. (1+ (next-single-property-change
  7277. start :org-clock-marker-backup)))
  7278. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7279. '(:org-clock-marker-backup t)))))
  7280. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7281. (message "Sorting entries...done")))
  7282. (defun org-contextualize-keys (alist contexts)
  7283. "Return valid elements in ALIST depending on CONTEXTS.
  7284. `org-agenda-custom-commands' or `org-capture-templates' are the
  7285. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7286. or `org-capture-templates-contexts' are the associated contexts
  7287. definitions."
  7288. (let ((contexts
  7289. ;; normalize contexts
  7290. (mapcar
  7291. (lambda(c) (cond ((listp (cadr c))
  7292. (list (car c) (car c) (nth 1 c)))
  7293. ((string= "" (cadr c))
  7294. (list (car c) (car c) (nth 2 c)))
  7295. (t c)))
  7296. contexts))
  7297. (a alist) r s)
  7298. ;; loop over all commands or templates
  7299. (dolist (c a)
  7300. (let (vrules repl)
  7301. (cond
  7302. ((not (assoc (car c) contexts))
  7303. (push c r))
  7304. ((and (assoc (car c) contexts)
  7305. (setq vrules (org-contextualize-validate-key
  7306. (car c) contexts)))
  7307. (mapc (lambda (vr)
  7308. (unless (equal (car vr) (cadr vr))
  7309. (setq repl vr)))
  7310. vrules)
  7311. (if (not repl) (push c r)
  7312. (push (cadr repl) s)
  7313. (push
  7314. (cons (car c)
  7315. (cdr (or (assoc (cadr repl) alist)
  7316. (error "Undefined key `%s' as contextual replacement for `%s'"
  7317. (cadr repl) (car c)))))
  7318. r))))))
  7319. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7320. (delq
  7321. nil
  7322. (delete-dups
  7323. (mapcar (lambda (x)
  7324. (let ((tpl (car x)))
  7325. (unless (delq
  7326. nil
  7327. (mapcar (lambda (y)
  7328. (equal y tpl))
  7329. s))
  7330. x)))
  7331. (reverse r))))))
  7332. (defun org-contextualize-validate-key (key contexts)
  7333. "Check CONTEXTS for agenda or capture KEY."
  7334. (let (res)
  7335. (dolist (r contexts)
  7336. (dolist (rr (car (last r)))
  7337. (when
  7338. (and (equal key (car r))
  7339. (if (functionp rr) (funcall rr)
  7340. (or (and (eq (car rr) 'in-file)
  7341. (buffer-file-name)
  7342. (string-match (cdr rr) (buffer-file-name)))
  7343. (and (eq (car rr) 'in-mode)
  7344. (string-match (cdr rr) (symbol-name major-mode)))
  7345. (and (eq (car rr) 'in-buffer)
  7346. (string-match (cdr rr) (buffer-name)))
  7347. (when (and (eq (car rr) 'not-in-file)
  7348. (buffer-file-name))
  7349. (not (string-match (cdr rr) (buffer-file-name))))
  7350. (when (eq (car rr) 'not-in-mode)
  7351. (not (string-match (cdr rr) (symbol-name major-mode))))
  7352. (when (eq (car rr) 'not-in-buffer)
  7353. (not (string-match (cdr rr) (buffer-name)))))))
  7354. (push r res))))
  7355. (delete-dups (delq nil res))))
  7356. ;; Defined to provide a value for defcustom, since there is no
  7357. ;; string-collate-greaterp in Emacs.
  7358. (defun org-string-collate-greaterp (s1 s2)
  7359. "Return non-nil if S1 is greater than S2 in collation order."
  7360. (not (org-string-collate-lessp s1 s2)))
  7361. ;;;###autoload
  7362. (defun org-run-like-in-org-mode (cmd)
  7363. "Run a command, pretending that the current buffer is in Org mode.
  7364. This will temporarily bind local variables that are typically bound in
  7365. Org mode to the values they have in Org mode, and then interactively
  7366. call CMD."
  7367. (org-load-modules-maybe)
  7368. (let (binds)
  7369. (dolist (var (org-get-local-variables))
  7370. (when (or (not (boundp (car var)))
  7371. (eq (symbol-value (car var))
  7372. (default-value (car var))))
  7373. (push (list (car var) `(quote ,(cadr var))) binds)))
  7374. (eval `(let ,binds
  7375. (call-interactively (quote ,cmd))))))
  7376. (defun org-get-category (&optional pos force-refresh)
  7377. "Get the category applying to position POS."
  7378. (save-match-data
  7379. (when force-refresh (org-refresh-category-properties))
  7380. (let ((pos (or pos (point))))
  7381. (or (get-text-property pos 'org-category)
  7382. (progn (org-refresh-category-properties)
  7383. (get-text-property pos 'org-category))))))
  7384. ;;; Refresh properties
  7385. (defun org-refresh-properties (dprop tprop)
  7386. "Refresh buffer text properties.
  7387. DPROP is the drawer property and TPROP is either the
  7388. corresponding text property to set, or an alist with each element
  7389. being a text property (as a symbol) and a function to apply to
  7390. the value of the drawer property."
  7391. (let* ((case-fold-search t)
  7392. (inhibit-read-only t)
  7393. (inherit? (org-property-inherit-p dprop))
  7394. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7395. (global (and inherit? (org--property-global-value dprop nil))))
  7396. (with-silent-modifications
  7397. (org-with-point-at 1
  7398. ;; Set global values (e.g., values defined through
  7399. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7400. (when global (put-text-property (point-min) (point-max) tprop global))
  7401. ;; Set local values.
  7402. (while (re-search-forward property-re nil t)
  7403. (when (org-at-property-p)
  7404. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7405. (outline-next-heading))))))
  7406. (defun org-refresh-property (tprop p &optional inherit)
  7407. "Refresh the buffer text property TPROP from the drawer property P.
  7408. The refresh happens only for the current headline, or the whole
  7409. subtree if optional argument INHERIT is non-nil."
  7410. (unless (org-before-first-heading-p)
  7411. (save-excursion
  7412. (org-back-to-heading t)
  7413. (let ((start (point))
  7414. (end (save-excursion
  7415. (if inherit (org-end-of-subtree t t)
  7416. (or (outline-next-heading) (point-max))))))
  7417. (if (symbolp tprop)
  7418. ;; TPROP is a text property symbol.
  7419. (put-text-property start end tprop p)
  7420. ;; TPROP is an alist with (property . function) elements.
  7421. (pcase-dolist (`(,prop . ,f) tprop)
  7422. (put-text-property start end prop (funcall f p))))))))
  7423. (defun org-refresh-category-properties ()
  7424. "Refresh category text properties in the buffer."
  7425. (let ((case-fold-search t)
  7426. (inhibit-read-only t)
  7427. (default-category
  7428. (cond ((null org-category)
  7429. (if buffer-file-name
  7430. (file-name-sans-extension
  7431. (file-name-nondirectory buffer-file-name))
  7432. "???"))
  7433. ((symbolp org-category) (symbol-name org-category))
  7434. (t org-category))))
  7435. (with-silent-modifications
  7436. (org-with-wide-buffer
  7437. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7438. ;; This is the default category for the buffer. If none is
  7439. ;; found, fall-back to `org-category' or buffer file name.
  7440. (put-text-property
  7441. (point-min) (point-max)
  7442. 'org-category
  7443. (catch 'buffer-category
  7444. (goto-char (point-max))
  7445. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7446. (let ((element (org-element-at-point)))
  7447. (when (eq (org-element-type element) 'keyword)
  7448. (throw 'buffer-category
  7449. (org-element-property :value element)))))
  7450. default-category))
  7451. ;; Set subtree specific categories.
  7452. (goto-char (point-min))
  7453. (let ((regexp (org-re-property "CATEGORY")))
  7454. (while (re-search-forward regexp nil t)
  7455. (let ((value (match-string-no-properties 3)))
  7456. (when (org-at-property-p)
  7457. (put-text-property
  7458. (save-excursion (org-back-to-heading t) (point))
  7459. (save-excursion (org-end-of-subtree t t) (point))
  7460. 'org-category
  7461. value)))))))))
  7462. (defun org-refresh-stats-properties ()
  7463. "Refresh stats text properties in the buffer."
  7464. (with-silent-modifications
  7465. (org-with-point-at 1
  7466. (let ((regexp (concat org-outline-regexp-bol
  7467. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7468. (while (re-search-forward regexp nil t)
  7469. (let* ((numerator (string-to-number (match-string 1)))
  7470. (denominator (and (match-end 2)
  7471. (string-to-number (match-string 2))))
  7472. (stats (cond ((not denominator) numerator) ;percent
  7473. ((= denominator 0) 0)
  7474. (t (/ (* numerator 100) denominator)))))
  7475. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7476. 'org-stats stats)))))))
  7477. (defun org-refresh-effort-properties ()
  7478. "Refresh effort properties."
  7479. (org-refresh-properties
  7480. org-effort-property
  7481. '((effort . identity)
  7482. (effort-minutes . org-duration-to-minutes))))
  7483. (defun org-find-file-at-mouse (ev)
  7484. "Open file link or URL at mouse."
  7485. (interactive "e")
  7486. (mouse-set-point ev)
  7487. (org-open-at-point 'in-emacs))
  7488. (defun org-open-at-mouse (ev)
  7489. "Open file link or URL at mouse.
  7490. See the docstring of `org-open-file' for details."
  7491. (interactive "e")
  7492. (mouse-set-point ev)
  7493. (when (eq major-mode 'org-agenda-mode)
  7494. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7495. (org-open-at-point))
  7496. (defvar org-window-config-before-follow-link nil
  7497. "The window configuration before following a link.
  7498. This is saved in case the need arises to restore it.")
  7499. (defun org--file-default-apps ()
  7500. "Return the default applications for this operating system."
  7501. (pcase system-type
  7502. (`darwin org-file-apps-macos)
  7503. (`windows-nt org-file-apps-windowsnt)
  7504. (_ org-file-apps-gnu)))
  7505. (defun org--file-apps-entry-dlink-p (entry)
  7506. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7507. It assumes that is the case when the entry uses a regular
  7508. expression which has at least one grouping construct and the
  7509. action is either a Lisp form or a command string containing
  7510. \"%1\", i.e., using at least one subexpression match as
  7511. a parameter."
  7512. (pcase entry
  7513. (`(,selector . ,action)
  7514. (and (stringp selector)
  7515. (> (regexp-opt-depth selector) 0)
  7516. (or (and (stringp action)
  7517. (string-match "%[0-9]" action))
  7518. (consp action))))
  7519. (_ nil)))
  7520. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7521. "Convert extensions to regular expressions in the cars of LIST.
  7522. Also, weed out any non-string entries, because the return value
  7523. is used only for regexp matching.
  7524. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7525. point to the symbol `emacs', indicating that the file should be
  7526. opened in Emacs."
  7527. (append
  7528. (delq nil
  7529. (mapcar (lambda (x)
  7530. (unless (not (stringp (car x)))
  7531. (if (string-match "\\W" (car x))
  7532. x
  7533. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7534. list))
  7535. (when add-auto-mode
  7536. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7537. ;;;###autoload
  7538. (defun org-open-file (path &optional in-emacs line search)
  7539. "Open the file at PATH.
  7540. First, this expands any special file name abbreviations. Then the
  7541. configuration variable `org-file-apps' is checked if it contains an
  7542. entry for this file type, and if yes, the corresponding command is launched.
  7543. If no application is found, Emacs simply visits the file.
  7544. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7545. With a double \\[universal-argument] \\[universal-argument] \
  7546. prefix arg, Org tries to avoid opening in Emacs
  7547. and to use an external application to visit the file.
  7548. Optional LINE specifies a line to go to, optional SEARCH a string
  7549. to search for. If LINE or SEARCH is given, the file will be
  7550. opened in Emacs, unless an entry from `org-file-apps' that makes
  7551. use of groups in a regexp matches.
  7552. If you want to change the way frames are used when following a
  7553. link, please customize `org-link-frame-setup'.
  7554. If the file does not exist, throw an error."
  7555. (let* ((file (if (equal path "") buffer-file-name
  7556. (substitute-in-file-name (expand-file-name path))))
  7557. (file-apps (append org-file-apps (org--file-default-apps)))
  7558. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7559. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7560. file-apps))
  7561. (remp (and (assq 'remote apps) (file-remote-p file)))
  7562. (dirp (unless remp (file-directory-p file)))
  7563. (file (if (and dirp org-open-directory-means-index-dot-org)
  7564. (concat (file-name-as-directory file) "index.org")
  7565. file))
  7566. (a-m-a-p (assq 'auto-mode apps))
  7567. (dfile (downcase file))
  7568. ;; Reconstruct the original link from the PATH, LINE and
  7569. ;; SEARCH args.
  7570. (link (cond (line (concat file "::" (number-to-string line)))
  7571. (search (concat file "::" search))
  7572. (t file)))
  7573. (dlink (downcase link))
  7574. (ext
  7575. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7576. (match-string 1 dfile)))
  7577. (save-position-maybe
  7578. (let ((old-buffer (current-buffer))
  7579. (old-pos (point))
  7580. (old-mode major-mode))
  7581. (lambda ()
  7582. (and (derived-mode-p 'org-mode)
  7583. (eq old-mode 'org-mode)
  7584. (or (not (eq old-buffer (current-buffer)))
  7585. (not (eq old-pos (point))))
  7586. (org-mark-ring-push old-pos old-buffer)))))
  7587. cmd link-match-data)
  7588. (cond
  7589. ((member in-emacs '((16) system))
  7590. (setq cmd (cdr (assq 'system apps))))
  7591. (in-emacs (setq cmd 'emacs))
  7592. (t
  7593. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7594. (and dirp (cdr (assq 'directory apps)))
  7595. ;; First, try matching against apps-dlink if we
  7596. ;; get a match here, store the match data for
  7597. ;; later.
  7598. (let ((match (assoc-default dlink apps-dlink
  7599. 'string-match)))
  7600. (if match
  7601. (progn (setq link-match-data (match-data))
  7602. match)
  7603. (progn (setq in-emacs (or in-emacs line search))
  7604. nil))) ; if we have no match in apps-dlink,
  7605. ; always open the file in emacs if line or search
  7606. ; is given (for backwards compatibility)
  7607. (assoc-default dfile
  7608. (org--file-apps-regexp-alist apps a-m-a-p)
  7609. 'string-match)
  7610. (cdr (assoc ext apps))
  7611. (cdr (assq t apps))))))
  7612. (when (eq cmd 'system)
  7613. (setq cmd (cdr (assq 'system apps))))
  7614. (when (eq cmd 'default)
  7615. (setq cmd (cdr (assoc t apps))))
  7616. (when (eq cmd 'mailcap)
  7617. (require 'mailcap)
  7618. (mailcap-parse-mailcaps)
  7619. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7620. (command (mailcap-mime-info mime-type)))
  7621. (if (stringp command)
  7622. (setq cmd command)
  7623. (setq cmd 'emacs))))
  7624. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7625. (not (file-exists-p file))
  7626. (not org-open-non-existing-files))
  7627. (user-error "No such file: %s" file))
  7628. (cond
  7629. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7630. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7631. (while (string-match "['\"]%s['\"]" cmd)
  7632. (setq cmd (replace-match "%s" t t cmd)))
  7633. (setq cmd (replace-regexp-in-string
  7634. "%s"
  7635. (shell-quote-argument (convert-standard-filename file))
  7636. cmd
  7637. nil t))
  7638. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7639. (save-match-data
  7640. (let ((match-index 1)
  7641. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7642. (set-match-data link-match-data)
  7643. (while (<= match-index number-of-groups)
  7644. (let ((regex (concat "%" (number-to-string match-index)))
  7645. (replace-with (match-string match-index dlink)))
  7646. (while (string-match regex cmd)
  7647. (setq cmd (replace-match replace-with t t cmd))))
  7648. (setq match-index (+ match-index 1)))))
  7649. (save-window-excursion
  7650. (message "Running %s...done" cmd)
  7651. (start-process-shell-command cmd nil cmd)
  7652. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7653. ((or (stringp cmd)
  7654. (eq cmd 'emacs))
  7655. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7656. (widen)
  7657. (cond (line (org-goto-line line)
  7658. (when (derived-mode-p 'org-mode) (org-reveal)))
  7659. (search (condition-case err
  7660. (org-link-search search)
  7661. ;; Save position before error-ing out so user
  7662. ;; can easily move back to the original buffer.
  7663. (error (funcall save-position-maybe)
  7664. (error (nth 1 err)))))))
  7665. ((functionp cmd)
  7666. (save-match-data
  7667. (set-match-data link-match-data)
  7668. (condition-case nil
  7669. (funcall cmd file link)
  7670. ;; FIXME: Remove this check when most default installations
  7671. ;; of Emacs have at least Org 9.0.
  7672. ((debug wrong-number-of-arguments wrong-type-argument
  7673. invalid-function)
  7674. (user-error "Please see Org News for version 9.0 about \
  7675. `org-file-apps'--Lisp error: %S" cmd)))))
  7676. ((consp cmd)
  7677. ;; FIXME: Remove this check when most default installations of
  7678. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7679. ;; fall back to `org-link-frame-setup' for an old usage of
  7680. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7681. (user-error "Please see Org News for version 9.0 about \
  7682. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7683. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7684. (funcall save-position-maybe)))
  7685. ;;;###autoload
  7686. (defun org-open-at-point-global ()
  7687. "Follow a link or a time-stamp like Org mode does.
  7688. Also follow links and emails as seen by `thing-at-point'.
  7689. This command can be called in any mode to follow an external
  7690. link or a time-stamp that has Org mode syntax. Its behavior
  7691. is undefined when called on internal links like fuzzy links.
  7692. Raise a user error when there is nothing to follow."
  7693. (interactive)
  7694. (let ((tap-url (thing-at-point 'url))
  7695. (tap-email (thing-at-point 'email)))
  7696. (cond ((org-in-regexp org-link-any-re)
  7697. (org-link-open-from-string (match-string-no-properties 0)))
  7698. ((or (org-in-regexp org-ts-regexp-both nil t)
  7699. (org-in-regexp org-tsr-regexp-both nil t))
  7700. (org-follow-timestamp-link))
  7701. (tap-url (org-link-open-from-string tap-url))
  7702. (tap-email (org-link-open-from-string
  7703. (concat "mailto:" tap-email)))
  7704. (t (user-error "No link found")))))
  7705. (defvar org-open-at-point-functions nil
  7706. "Hook that is run when following a link at point.
  7707. Functions in this hook must return t if they identify and follow
  7708. a link at point. If they don't find anything interesting at point,
  7709. they must return nil.")
  7710. (defun org-open-at-point (&optional arg)
  7711. "Open link, timestamp, footnote or tags at point.
  7712. When point is on a link, follow it. Normally, files will be
  7713. opened by an appropriate application. If the optional prefix
  7714. argument ARG is non-nil, Emacs will visit the file. With
  7715. a double prefix argument, try to open outside of Emacs, in the
  7716. application the system uses for this file type.
  7717. When point is on a timestamp, open the agenda at the day
  7718. specified.
  7719. When point is a footnote definition, move to the first reference
  7720. found. If it is on a reference, move to the associated
  7721. definition.
  7722. When point is on a headline, display a list of every link in the
  7723. entry, so it is possible to pick one, or all, of them. If point
  7724. is on a tag, call `org-tags-view' instead.
  7725. On top of syntactically correct links, this function also tries
  7726. to open links and time-stamps in comments, node properties, and
  7727. keywords if point is on something looking like a timestamp or
  7728. a link."
  7729. (interactive "P")
  7730. (org-load-modules-maybe)
  7731. (setq org-window-config-before-follow-link (current-window-configuration))
  7732. (org-remove-occur-highlights nil nil t)
  7733. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7734. (let* ((context
  7735. ;; Only consider supported types, even if they are not the
  7736. ;; closest one.
  7737. (org-element-lineage
  7738. (org-element-context)
  7739. '(clock comment comment-block footnote-definition
  7740. footnote-reference headline inline-src-block inlinetask
  7741. keyword link node-property planning src-block timestamp)
  7742. t))
  7743. (type (org-element-type context))
  7744. (value (org-element-property :value context)))
  7745. (cond
  7746. ((not type) (user-error "No link found"))
  7747. ;; No valid link at point. For convenience, look if something
  7748. ;; looks like a link under point in some specific places.
  7749. ((memq type '(comment comment-block node-property keyword))
  7750. (call-interactively #'org-open-at-point-global))
  7751. ;; On a headline or an inlinetask, but not on a timestamp,
  7752. ;; a link, a footnote reference.
  7753. ((memq type '(headline inlinetask))
  7754. (org-match-line org-complex-heading-regexp)
  7755. (let ((tags-beg (match-beginning 5))
  7756. (tags-end (match-end 5)))
  7757. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7758. ;; On tags.
  7759. (org-tags-view
  7760. arg
  7761. (save-excursion
  7762. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7763. (end-tag (search-forward ":" tags-end nil 2)))
  7764. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7765. ;; Not on tags.
  7766. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7767. (`(nil . ,_)
  7768. (require 'org-attach)
  7769. (when (org-attach-dir)
  7770. (message "Opening attachment")
  7771. (if (equal arg '(4))
  7772. (org-attach-reveal-in-emacs)
  7773. (org-attach-reveal))))
  7774. (`(,links . ,links-end)
  7775. (dolist (link (if (stringp links) (list links) links))
  7776. (search-forward link nil links-end)
  7777. (goto-char (match-beginning 0))
  7778. (org-open-at-point arg)))))))
  7779. ;; On a footnote reference or at definition's label.
  7780. ((or (eq type 'footnote-reference)
  7781. (and (eq type 'footnote-definition)
  7782. (save-excursion
  7783. ;; Do not validate action when point is on the
  7784. ;; spaces right after the footnote label, in order
  7785. ;; to be on par with behavior on links.
  7786. (skip-chars-forward " \t")
  7787. (let ((begin
  7788. (org-element-property :contents-begin context)))
  7789. (if begin (< (point) begin)
  7790. (= (org-element-property :post-affiliated context)
  7791. (line-beginning-position)))))))
  7792. (org-footnote-action))
  7793. ;; On a planning line. Check if we are really on a timestamp.
  7794. ((and (eq type 'planning)
  7795. (org-in-regexp org-ts-regexp-both nil t))
  7796. (org-follow-timestamp-link))
  7797. ;; On a clock line, make sure point is on the timestamp
  7798. ;; before opening it.
  7799. ((and (eq type 'clock)
  7800. value
  7801. (>= (point) (org-element-property :begin value))
  7802. (<= (point) (org-element-property :end value)))
  7803. (org-follow-timestamp-link))
  7804. ((eq type 'src-block) (org-babel-open-src-block-result))
  7805. ;; Do nothing on white spaces after an object.
  7806. ((>= (point)
  7807. (save-excursion
  7808. (goto-char (org-element-property :end context))
  7809. (skip-chars-backward " \t")
  7810. (point)))
  7811. (user-error "No link found"))
  7812. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7813. ((eq type 'timestamp) (org-follow-timestamp-link))
  7814. ((eq type 'link) (org-link-open context arg))
  7815. (t (user-error "No link found")))))
  7816. (run-hook-with-args 'org-follow-link-hook))
  7817. ;;;###autoload
  7818. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7819. "Offer links in the current entry and return the selected link.
  7820. If there is only one link, return it.
  7821. If NTH is an integer, return the NTH link found.
  7822. If ZERO is a string, check also this string for a link, and if
  7823. there is one, return it."
  7824. (with-current-buffer buffer
  7825. (org-with-wide-buffer
  7826. (goto-char marker)
  7827. (let ((cnt ?0)
  7828. have-zero end links link c)
  7829. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7830. (push (match-string 0 zero) links)
  7831. (setq cnt (1- cnt) have-zero t))
  7832. (save-excursion
  7833. (org-back-to-heading t)
  7834. (setq end (save-excursion (outline-next-heading) (point)))
  7835. (while (re-search-forward org-link-any-re end t)
  7836. (push (match-string 0) links))
  7837. (setq links (org-uniquify (reverse links))))
  7838. (cond
  7839. ((null links)
  7840. (message "No links"))
  7841. ((equal (length links) 1)
  7842. (setq link (car links)))
  7843. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7844. (setq link (nth (if have-zero nth (1- nth)) links)))
  7845. (t ; we have to select a link
  7846. (save-excursion
  7847. (save-window-excursion
  7848. (delete-other-windows)
  7849. (with-output-to-temp-buffer "*Select Link*"
  7850. (dolist (l links)
  7851. (cond
  7852. ((not (string-match org-link-bracket-re l))
  7853. (princ (format "[%c] %s\n" (cl-incf cnt)
  7854. (org-unbracket-string "<" ">" l))))
  7855. ((match-end 2)
  7856. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7857. (match-string 2 l) (match-string 1 l))))
  7858. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7859. (match-string 1 l)))))))
  7860. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7861. (message "Select link to open, RET to open all:")
  7862. (setq c (read-char-exclusive))
  7863. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7864. (when (equal c ?q) (user-error "Abort"))
  7865. (if (equal c ?\C-m)
  7866. (setq link links)
  7867. (setq nth (- c ?0))
  7868. (when have-zero (setq nth (1+ nth)))
  7869. (unless (and (integerp nth) (>= (length links) nth))
  7870. (user-error "Invalid link selection"))
  7871. (setq link (nth (1- nth) links)))))
  7872. (cons link end)))))
  7873. ;;; File search
  7874. (defun org-do-occur (regexp &optional cleanup)
  7875. "Call the Emacs command `occur'.
  7876. If CLEANUP is non-nil, remove the printout of the regular expression
  7877. in the *Occur* buffer. This is useful if the regex is long and not useful
  7878. to read."
  7879. (occur regexp)
  7880. (when cleanup
  7881. (let ((cwin (selected-window)) win beg end)
  7882. (when (setq win (get-buffer-window "*Occur*"))
  7883. (select-window win))
  7884. (goto-char (point-min))
  7885. (when (re-search-forward "match[a-z]+" nil t)
  7886. (setq beg (match-end 0))
  7887. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7888. (setq end (1- (match-beginning 0)))))
  7889. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7890. (goto-char (point-min))
  7891. (select-window cwin))))
  7892. ;;; The Mark Ring
  7893. (defvar org-mark-ring nil
  7894. "Mark ring for positions before jumps in Org mode.")
  7895. (defvar org-mark-ring-last-goto nil
  7896. "Last position in the mark ring used to go back.")
  7897. ;; Fill and close the ring
  7898. (setq org-mark-ring nil)
  7899. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7900. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7901. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7902. org-mark-ring)
  7903. (defun org-mark-ring-push (&optional pos buffer)
  7904. "Put the current position into the mark ring and rotate it.
  7905. Also push position into the Emacs mark ring. If optional
  7906. argument POS and BUFFER are not nil, mark this location instead."
  7907. (interactive)
  7908. (let ((pos (or pos (point)))
  7909. (buffer (or buffer (current-buffer))))
  7910. (with-current-buffer buffer
  7911. (org-with-point-at pos (push-mark nil t)))
  7912. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7913. (move-marker (car org-mark-ring) pos buffer))
  7914. (message
  7915. (substitute-command-keys
  7916. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7917. (defun org-mark-ring-goto (&optional n)
  7918. "Jump to the previous position in the mark ring.
  7919. With prefix arg N, jump back that many stored positions. When
  7920. called several times in succession, walk through the entire ring.
  7921. Org mode commands jumping to a different position in the current file,
  7922. or to another Org file, automatically push the old position onto the ring."
  7923. (interactive "p")
  7924. (let (p m)
  7925. (if (eq last-command this-command)
  7926. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7927. (setq p org-mark-ring))
  7928. (setq org-mark-ring-last-goto p)
  7929. (setq m (car p))
  7930. (pop-to-buffer-same-window (marker-buffer m))
  7931. (goto-char m)
  7932. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7933. ;;; Following specific links
  7934. (defvar org-agenda-buffer-tmp-name)
  7935. (defvar org-agenda-start-on-weekday)
  7936. (defun org-follow-timestamp-link ()
  7937. "Open an agenda view for the time-stamp date/range at point."
  7938. (cond
  7939. ((org-at-date-range-p t)
  7940. (let ((org-agenda-start-on-weekday)
  7941. (t1 (match-string 1))
  7942. (t2 (match-string 2)) tt1 tt2)
  7943. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7944. tt2 (time-to-days (org-time-string-to-time t2)))
  7945. (let ((org-agenda-buffer-tmp-name
  7946. (format "*Org Agenda(a:%s)"
  7947. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7948. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7949. ((org-at-timestamp-p 'lax)
  7950. (let ((org-agenda-buffer-tmp-name
  7951. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7952. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7953. (substring (match-string 1) 0 10)))
  7954. 1)))
  7955. (t (error "This should not happen"))))
  7956. ;;; Following file links
  7957. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7958. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7959. (declare-function mailcap-mime-info
  7960. "mailcap" (string &optional request no-decode))
  7961. (defvar org-wait nil)
  7962. ;;;; Refiling
  7963. (defun org-get-org-file ()
  7964. "Read a filename, with default directory `org-directory'."
  7965. (let ((default (or org-default-notes-file remember-data-file)))
  7966. (read-file-name (format "File name [%s]: " default)
  7967. (file-name-as-directory org-directory)
  7968. default)))
  7969. (defun org-notes-order-reversed-p ()
  7970. "Check if the current file should receive notes in reversed order."
  7971. (cond
  7972. ((not org-reverse-note-order) nil)
  7973. ((eq t org-reverse-note-order) t)
  7974. ((not (listp org-reverse-note-order)) nil)
  7975. (t (catch 'exit
  7976. (dolist (entry org-reverse-note-order)
  7977. (when (string-match (car entry) buffer-file-name)
  7978. (throw 'exit (cdr entry))))))))
  7979. (defvar org-refile-target-table nil
  7980. "The list of refile targets, created by `org-refile'.")
  7981. (defvar org-agenda-new-buffers nil
  7982. "Buffers created to visit agenda files.")
  7983. (defvar org-refile-cache nil
  7984. "Cache for refile targets.")
  7985. (defvar org-refile-markers nil
  7986. "All the markers used for caching refile locations.")
  7987. (defun org-refile-marker (pos)
  7988. "Get a new refile marker, but only if caching is in use."
  7989. (if (not org-refile-use-cache)
  7990. pos
  7991. (let ((m (make-marker)))
  7992. (move-marker m pos)
  7993. (push m org-refile-markers)
  7994. m)))
  7995. (defun org-refile-cache-clear ()
  7996. "Clear the refile cache and disable all the markers."
  7997. (dolist (m org-refile-markers) (move-marker m nil))
  7998. (setq org-refile-markers nil)
  7999. (setq org-refile-cache nil)
  8000. (message "Refile cache has been cleared"))
  8001. (defun org-refile-cache-check-set (set)
  8002. "Check if all the markers in the cache still have live buffers."
  8003. (let (marker)
  8004. (catch 'exit
  8005. (while (and set (setq marker (nth 3 (pop set))))
  8006. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  8007. (when (and marker (null (marker-buffer marker)))
  8008. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  8009. (sit-for 3)
  8010. (throw 'exit nil)))
  8011. t)))
  8012. (defun org-refile-cache-put (set &rest identifiers)
  8013. "Push the refile targets SET into the cache, under IDENTIFIERS."
  8014. (let* ((key (sha1 (prin1-to-string identifiers)))
  8015. (entry (assoc key org-refile-cache)))
  8016. (if entry
  8017. (setcdr entry set)
  8018. (push (cons key set) org-refile-cache))))
  8019. (defun org-refile-cache-get (&rest identifiers)
  8020. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8021. (cond
  8022. ((not org-refile-cache) nil)
  8023. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8024. (t
  8025. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8026. org-refile-cache))))
  8027. (and set (org-refile-cache-check-set set) set)))))
  8028. (defvar org-outline-path-cache nil
  8029. "Alist between buffer positions and outline paths.
  8030. It value is an alist (POSITION . PATH) where POSITION is the
  8031. buffer position at the beginning of an entry and PATH is a list
  8032. of strings describing the outline path for that entry, in reverse
  8033. order.")
  8034. (defun org-refile-get-targets (&optional default-buffer)
  8035. "Produce a table with refile targets."
  8036. (let ((case-fold-search nil)
  8037. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8038. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8039. targets tgs files desc descre)
  8040. (message "Getting targets...")
  8041. (with-current-buffer (or default-buffer (current-buffer))
  8042. (dolist (entry entries)
  8043. (setq files (car entry) desc (cdr entry))
  8044. (cond
  8045. ((null files) (setq files (list (current-buffer))))
  8046. ((eq files 'org-agenda-files)
  8047. (setq files (org-agenda-files 'unrestricted)))
  8048. ((and (symbolp files) (fboundp files))
  8049. (setq files (funcall files)))
  8050. ((and (symbolp files) (boundp files))
  8051. (setq files (symbol-value files))))
  8052. (when (stringp files) (setq files (list files)))
  8053. (cond
  8054. ((eq (car desc) :tag)
  8055. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8056. ((eq (car desc) :todo)
  8057. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8058. ((eq (car desc) :regexp)
  8059. (setq descre (cdr desc)))
  8060. ((eq (car desc) :level)
  8061. (setq descre (concat "^\\*\\{" (number-to-string
  8062. (if org-odd-levels-only
  8063. (1- (* 2 (cdr desc)))
  8064. (cdr desc)))
  8065. "\\}[ \t]")))
  8066. ((eq (car desc) :maxlevel)
  8067. (setq descre (concat "^\\*\\{1," (number-to-string
  8068. (if org-odd-levels-only
  8069. (1- (* 2 (cdr desc)))
  8070. (cdr desc)))
  8071. "\\}[ \t]")))
  8072. (t (error "Bad refiling target description %s" desc)))
  8073. (dolist (f files)
  8074. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8075. (or
  8076. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8077. (progn
  8078. (when (bufferp f)
  8079. (setq f (buffer-file-name (buffer-base-buffer f))))
  8080. (setq f (and f (expand-file-name f)))
  8081. (when (eq org-refile-use-outline-path 'file)
  8082. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8083. (when (eq org-refile-use-outline-path 'buffer-name)
  8084. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8085. (when (eq org-refile-use-outline-path 'full-file-path)
  8086. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8087. (org-with-wide-buffer
  8088. (goto-char (point-min))
  8089. (setq org-outline-path-cache nil)
  8090. (while (re-search-forward descre nil t)
  8091. (beginning-of-line)
  8092. (let ((case-fold-search nil))
  8093. (looking-at org-complex-heading-regexp))
  8094. (let ((begin (point))
  8095. (heading (match-string-no-properties 4)))
  8096. (unless (or (and
  8097. org-refile-target-verify-function
  8098. (not
  8099. (funcall org-refile-target-verify-function)))
  8100. (not heading))
  8101. (let ((re (format org-complex-heading-regexp-format
  8102. (regexp-quote heading)))
  8103. (target
  8104. (if (not org-refile-use-outline-path) heading
  8105. (mapconcat
  8106. #'identity
  8107. (append
  8108. (pcase org-refile-use-outline-path
  8109. (`file (list (file-name-nondirectory
  8110. (buffer-file-name
  8111. (buffer-base-buffer)))))
  8112. (`full-file-path
  8113. (list (buffer-file-name
  8114. (buffer-base-buffer))))
  8115. (`buffer-name
  8116. (list (buffer-name
  8117. (buffer-base-buffer))))
  8118. (_ nil))
  8119. (mapcar (lambda (s) (replace-regexp-in-string
  8120. "/" "\\/" s nil t))
  8121. (org-get-outline-path t t)))
  8122. "/"))))
  8123. (push (list target f re (org-refile-marker (point)))
  8124. tgs)))
  8125. (when (= (point) begin)
  8126. ;; Verification function has not moved point.
  8127. (end-of-line)))))))
  8128. (when org-refile-use-cache
  8129. (org-refile-cache-put tgs (buffer-file-name) descre))
  8130. (setq targets (append tgs targets))))))
  8131. (message "Getting targets...done")
  8132. (delete-dups (nreverse targets))))
  8133. (defun org--get-outline-path-1 (&optional use-cache)
  8134. "Return outline path to current headline.
  8135. Outline path is a list of strings, in reverse order. When
  8136. optional argument USE-CACHE is non-nil, make use of a cache. See
  8137. `org-get-outline-path' for details.
  8138. Assume buffer is widened and point is on a headline."
  8139. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8140. (let ((p (point))
  8141. (heading (let ((case-fold-search nil))
  8142. (looking-at org-complex-heading-regexp)
  8143. (if (not (match-end 4)) ""
  8144. ;; Remove statistics cookies.
  8145. (org-trim
  8146. (org-link-display-format
  8147. (replace-regexp-in-string
  8148. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8149. (match-string-no-properties 4))))))))
  8150. (if (org-up-heading-safe)
  8151. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8152. (when use-cache
  8153. (push (cons p path) org-outline-path-cache))
  8154. path)
  8155. ;; This is a new root node. Since we assume we are moving
  8156. ;; forward, we can drop previous cache so as to limit number
  8157. ;; of associations there.
  8158. (let ((path (list heading)))
  8159. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8160. path)))))
  8161. (defun org-get-outline-path (&optional with-self use-cache)
  8162. "Return the outline path to the current entry.
  8163. An outline path is a list of ancestors for current headline, as
  8164. a list of strings. Statistics cookies are removed and links are
  8165. replaced with their description, if any, or their path otherwise.
  8166. When optional argument WITH-SELF is non-nil, the path also
  8167. includes the current headline.
  8168. When optional argument USE-CACHE is non-nil, cache outline paths
  8169. between calls to this function so as to avoid backtracking. This
  8170. argument is useful when planning to find more than one outline
  8171. path in the same document. In that case, there are two
  8172. conditions to satisfy:
  8173. - `org-outline-path-cache' is set to nil before starting the
  8174. process;
  8175. - outline paths are computed by increasing buffer positions."
  8176. (org-with-wide-buffer
  8177. (and (or (and with-self (org-back-to-heading t))
  8178. (org-up-heading-safe))
  8179. (reverse (org--get-outline-path-1 use-cache)))))
  8180. (defun org-format-outline-path (path &optional width prefix separator)
  8181. "Format the outline path PATH for display.
  8182. WIDTH is the maximum number of characters that is available.
  8183. PREFIX is a prefix to be included in the returned string,
  8184. such as the file name.
  8185. SEPARATOR is inserted between the different parts of the path,
  8186. the default is \"/\"."
  8187. (setq width (or width 79))
  8188. (setq path (delq nil path))
  8189. (unless (> width 0)
  8190. (user-error "Argument `width' must be positive"))
  8191. (setq separator (or separator "/"))
  8192. (let* ((org-odd-levels-only nil)
  8193. (fpath (concat
  8194. prefix (and prefix path separator)
  8195. (mapconcat
  8196. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8197. (cl-loop for head in path
  8198. for n from 0
  8199. collect (org-add-props
  8200. head nil 'face
  8201. (nth (% n org-n-level-faces) org-level-faces)))
  8202. separator))))
  8203. (when (> (length fpath) width)
  8204. (if (< width 7)
  8205. ;; It's unlikely that `width' will be this small, but don't
  8206. ;; waste characters by adding ".." if it is.
  8207. (setq fpath (substring fpath 0 width))
  8208. (setf (substring fpath (- width 2)) "..")))
  8209. fpath))
  8210. (defun org-display-outline-path (&optional file current separator just-return-string)
  8211. "Display the current outline path in the echo area.
  8212. If FILE is non-nil, prepend the output with the file name.
  8213. If CURRENT is non-nil, append the current heading to the output.
  8214. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8215. the different parts of the path and defaults to \"/\".
  8216. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8217. (interactive "P")
  8218. (let* (case-fold-search
  8219. (bfn (buffer-file-name (buffer-base-buffer)))
  8220. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8221. res)
  8222. (when current (setq path (append path
  8223. (save-excursion
  8224. (org-back-to-heading t)
  8225. (when (looking-at org-complex-heading-regexp)
  8226. (list (match-string 4)))))))
  8227. (setq res
  8228. (org-format-outline-path
  8229. path
  8230. (1- (frame-width))
  8231. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8232. separator))
  8233. (if just-return-string
  8234. (org-no-properties res)
  8235. (org-unlogged-message "%s" res))))
  8236. (defvar org-refile-history nil
  8237. "History for refiling operations.")
  8238. (defvar org-after-refile-insert-hook nil
  8239. "Hook run after `org-refile' has inserted its stuff at the new location.
  8240. Note that this is still *before* the stuff will be removed from
  8241. the *old* location.")
  8242. (defvar org-capture-last-stored-marker)
  8243. (defvar org-refile-keep nil
  8244. "Non-nil means `org-refile' will copy instead of refile.")
  8245. (defun org-copy ()
  8246. "Like `org-refile', but copy."
  8247. (interactive)
  8248. (let ((org-refile-keep t))
  8249. (org-refile nil nil nil "Copy")))
  8250. (defun org-refile (&optional arg default-buffer rfloc msg)
  8251. "Move the entry or entries at point to another heading.
  8252. The list of target headings is compiled using the information in
  8253. `org-refile-targets', which see.
  8254. At the target location, the entry is filed as a subitem of the
  8255. target heading. Depending on `org-reverse-note-order', the new
  8256. subitem will either be the first or the last subitem.
  8257. If there is an active region, all entries in that region will be
  8258. refiled. However, the region must fulfill the requirement that
  8259. the first heading sets the top-level of the moved text.
  8260. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8261. location
  8262. and not actually move anything.
  8263. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8264. location where the last
  8265. refiling operation has put the subtree.
  8266. With a numeric prefix argument of `2', refile to the running clock.
  8267. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8268. being set to t and copy to the target location, don't move it.
  8269. Beware that keeping refiled entries may result in duplicated ID
  8270. properties.
  8271. RFLOC can be a refile location obtained in a different way.
  8272. MSG is a string to replace \"Refile\" in the default prompt with
  8273. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8274. See also `org-refile-use-outline-path'.
  8275. If you are using target caching (see `org-refile-use-cache'), you
  8276. have to clear the target cache in order to find new targets.
  8277. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8278. prefix argument (`C-u C-u C-u C-c C-w')."
  8279. (interactive "P")
  8280. (if (member arg '(0 (64)))
  8281. (org-refile-cache-clear)
  8282. (let* ((actionmsg (cond (msg msg)
  8283. ((equal arg 3) "Refile (and keep)")
  8284. (t "Refile")))
  8285. (regionp (org-region-active-p))
  8286. (region-start (and regionp (region-beginning)))
  8287. (region-end (and regionp (region-end)))
  8288. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8289. pos it nbuf file level reversed)
  8290. (setq last-command nil)
  8291. (when regionp
  8292. (goto-char region-start)
  8293. (beginning-of-line)
  8294. (setq region-start (point))
  8295. (unless (or (org-kill-is-subtree-p
  8296. (buffer-substring region-start region-end))
  8297. (prog1 org-refile-active-region-within-subtree
  8298. (let ((s (point-at-eol)))
  8299. (org-toggle-heading)
  8300. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8301. (user-error "The region is not a (sequence of) subtree(s)")))
  8302. (if (equal arg '(16))
  8303. (org-refile-goto-last-stored)
  8304. (when (or
  8305. (and (equal arg 2)
  8306. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8307. (prog1
  8308. (setq it (list (or org-clock-heading "running clock")
  8309. (buffer-file-name
  8310. (marker-buffer org-clock-hd-marker))
  8311. ""
  8312. (marker-position org-clock-hd-marker)))
  8313. (setq arg nil)))
  8314. (setq it
  8315. (or rfloc
  8316. (let (heading-text)
  8317. (save-excursion
  8318. (unless (and arg (listp arg))
  8319. (org-back-to-heading t)
  8320. (setq heading-text
  8321. (replace-regexp-in-string
  8322. org-link-bracket-re
  8323. "\\2"
  8324. (or (nth 4 (org-heading-components))
  8325. ""))))
  8326. (org-refile-get-location
  8327. (cond ((and arg (listp arg)) "Goto")
  8328. (regionp (concat actionmsg " region to"))
  8329. (t (concat actionmsg " subtree \""
  8330. heading-text "\" to")))
  8331. default-buffer
  8332. (and (not (equal '(4) arg))
  8333. org-refile-allow-creating-parent-nodes)))))))
  8334. (setq file (nth 1 it)
  8335. pos (nth 3 it))
  8336. (when (and (not arg)
  8337. pos
  8338. (equal (buffer-file-name) file)
  8339. (if regionp
  8340. (and (>= pos region-start)
  8341. (<= pos region-end))
  8342. (and (>= pos (point))
  8343. (< pos (save-excursion
  8344. (org-end-of-subtree t t))))))
  8345. (error "Cannot refile to position inside the tree or region"))
  8346. (setq nbuf (or (find-buffer-visiting file)
  8347. (find-file-noselect file)))
  8348. (if (and arg (not (equal arg 3)))
  8349. (progn
  8350. (pop-to-buffer-same-window nbuf)
  8351. (goto-char (cond (pos)
  8352. ((org-notes-order-reversed-p) (point-min))
  8353. (t (point-max))))
  8354. (org-show-context 'org-goto))
  8355. (if regionp
  8356. (progn
  8357. (org-kill-new (buffer-substring region-start region-end))
  8358. (org-save-markers-in-region region-start region-end))
  8359. (org-copy-subtree 1 nil t))
  8360. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8361. (find-file-noselect file)))
  8362. (setq reversed (org-notes-order-reversed-p))
  8363. (org-with-wide-buffer
  8364. (if pos
  8365. (progn
  8366. (goto-char pos)
  8367. (setq level (org-get-valid-level (funcall outline-level) 1))
  8368. (goto-char
  8369. (if reversed
  8370. (or (outline-next-heading) (point-max))
  8371. (or (save-excursion (org-get-next-sibling))
  8372. (org-end-of-subtree t t)
  8373. (point-max)))))
  8374. (setq level 1)
  8375. (if (not reversed)
  8376. (goto-char (point-max))
  8377. (goto-char (point-min))
  8378. (or (outline-next-heading) (goto-char (point-max)))))
  8379. (unless (bolp) (newline))
  8380. (org-paste-subtree level nil nil t)
  8381. ;; Record information, according to `org-log-refile'.
  8382. ;; Do not prompt for a note when refiling multiple
  8383. ;; headlines, however. Simply add a time stamp.
  8384. (cond
  8385. ((not org-log-refile))
  8386. (regionp
  8387. (org-map-region
  8388. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8389. (point)
  8390. (+ (point) (- region-end region-start))))
  8391. (t
  8392. (org-add-log-setup 'refile nil nil org-log-refile)))
  8393. (and org-auto-align-tags
  8394. (let ((org-loop-over-headlines-in-active-region nil))
  8395. (org-align-tags)))
  8396. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8397. :last-refile)))
  8398. (when bookmark-name
  8399. (with-demoted-errors
  8400. (bookmark-set bookmark-name))))
  8401. ;; If we are refiling for capture, make sure that the
  8402. ;; last-capture pointers point here
  8403. (when (bound-and-true-p org-capture-is-refiling)
  8404. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8405. :last-capture-marker)))
  8406. (when bookmark-name
  8407. (with-demoted-errors
  8408. (bookmark-set bookmark-name))))
  8409. (move-marker org-capture-last-stored-marker (point)))
  8410. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8411. (run-hooks 'org-after-refile-insert-hook)))
  8412. (unless org-refile-keep
  8413. (if regionp
  8414. (delete-region (point) (+ (point) (- region-end region-start)))
  8415. (org-preserve-local-variables
  8416. (delete-region
  8417. (and (org-back-to-heading t) (point))
  8418. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8419. (when (featurep 'org-inlinetask)
  8420. (org-inlinetask-remove-END-maybe))
  8421. (setq org-markers-to-move nil)
  8422. (message "%s to \"%s\" in file %s: done" actionmsg
  8423. (car it) file)))))))
  8424. (defun org-refile-goto-last-stored ()
  8425. "Go to the location where the last refile was stored."
  8426. (interactive)
  8427. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8428. (message "This is the location of the last refile"))
  8429. (defun org-refile--get-location (refloc tbl)
  8430. "When user refile to REFLOC, find the associated target in TBL.
  8431. Also check `org-refile-target-table'."
  8432. (car (delq
  8433. nil
  8434. (mapcar
  8435. (lambda (r) (or (assoc r tbl)
  8436. (assoc r org-refile-target-table)))
  8437. (list (replace-regexp-in-string "/$" "" refloc)
  8438. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8439. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8440. "Prompt the user for a refile location, using PROMPT.
  8441. PROMPT should not be suffixed with a colon and a space, because
  8442. this function appends the default value from
  8443. `org-refile-history' automatically, if that is not empty."
  8444. (let ((org-refile-targets org-refile-targets)
  8445. (org-refile-use-outline-path org-refile-use-outline-path))
  8446. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8447. (unless org-refile-target-table
  8448. (user-error "No refile targets"))
  8449. (let* ((cbuf (current-buffer))
  8450. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8451. (cfunc (if (and org-refile-use-outline-path
  8452. org-outline-path-complete-in-steps)
  8453. #'org-olpath-completing-read
  8454. #'completing-read))
  8455. (extra (if org-refile-use-outline-path "/" ""))
  8456. (cbnex (concat (buffer-name) extra))
  8457. (filename (and cfn (expand-file-name cfn)))
  8458. (tbl (mapcar
  8459. (lambda (x)
  8460. (if (and (not (member org-refile-use-outline-path
  8461. '(file full-file-path)))
  8462. (not (equal filename (nth 1 x))))
  8463. (cons (concat (car x) extra " ("
  8464. (file-name-nondirectory (nth 1 x)) ")")
  8465. (cdr x))
  8466. (cons (concat (car x) extra) (cdr x))))
  8467. org-refile-target-table))
  8468. (completion-ignore-case t)
  8469. cdef
  8470. (prompt (concat prompt
  8471. (or (and (car org-refile-history)
  8472. (concat " (default " (car org-refile-history) ")"))
  8473. (and (assoc cbnex tbl) (setq cdef cbnex)
  8474. (concat " (default " cbnex ")"))) ": "))
  8475. pa answ parent-target child parent old-hist)
  8476. (setq old-hist org-refile-history)
  8477. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8478. nil 'org-refile-history (or cdef (car org-refile-history))))
  8479. (if (setq pa (org-refile--get-location answ tbl))
  8480. (progn
  8481. (org-refile-check-position pa)
  8482. (when (or (not org-refile-history)
  8483. (not (eq old-hist org-refile-history))
  8484. (not (equal (car pa) (car org-refile-history))))
  8485. (setq org-refile-history
  8486. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8487. org-refile-history
  8488. (cdr org-refile-history))))
  8489. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8490. (pop org-refile-history)))
  8491. pa)
  8492. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8493. (progn
  8494. (setq parent (match-string 1 answ)
  8495. child (match-string 2 answ))
  8496. (setq parent-target (org-refile--get-location parent tbl))
  8497. (when (and parent-target
  8498. (or (eq new-nodes t)
  8499. (and (eq new-nodes 'confirm)
  8500. (y-or-n-p (format "Create new node \"%s\"? "
  8501. child)))))
  8502. (org-refile-new-child parent-target child)))
  8503. (user-error "Invalid target location")))))
  8504. (declare-function org-string-nw-p "org-macs" (s))
  8505. (defun org-refile-check-position (refile-pointer)
  8506. "Check if the refile pointer matches the headline to which it points."
  8507. (let* ((file (nth 1 refile-pointer))
  8508. (re (nth 2 refile-pointer))
  8509. (pos (nth 3 refile-pointer))
  8510. buffer)
  8511. (if (and (not (markerp pos)) (not file))
  8512. (user-error "Please indicate a target file in the refile path")
  8513. (when (org-string-nw-p re)
  8514. (setq buffer (if (markerp pos)
  8515. (marker-buffer pos)
  8516. (or (find-buffer-visiting file)
  8517. (find-file-noselect file))))
  8518. (with-current-buffer buffer
  8519. (org-with-wide-buffer
  8520. (goto-char pos)
  8521. (beginning-of-line 1)
  8522. (unless (looking-at-p re)
  8523. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8524. (defun org-refile-new-child (parent-target child)
  8525. "Use refile target PARENT-TARGET to add new CHILD below it."
  8526. (unless parent-target
  8527. (error "Cannot find parent for new node"))
  8528. (let ((file (nth 1 parent-target))
  8529. (pos (nth 3 parent-target))
  8530. level)
  8531. (with-current-buffer (or (find-buffer-visiting file)
  8532. (find-file-noselect file))
  8533. (org-with-wide-buffer
  8534. (if pos
  8535. (goto-char pos)
  8536. (goto-char (point-max))
  8537. (unless (bolp) (newline)))
  8538. (when (looking-at org-outline-regexp)
  8539. (setq level (funcall outline-level))
  8540. (org-end-of-subtree t t))
  8541. (org-back-over-empty-lines)
  8542. (insert "\n" (make-string
  8543. (if pos (org-get-valid-level level 1) 1) ?*)
  8544. " " child "\n")
  8545. (beginning-of-line 0)
  8546. (list (concat (car parent-target) "/" child) file "" (point))))))
  8547. (defun org-olpath-completing-read (prompt collection &rest args)
  8548. "Read an outline path like a file name."
  8549. (let ((thetable collection))
  8550. (apply #'completing-read
  8551. prompt
  8552. (lambda (string predicate &optional flag)
  8553. (cond
  8554. ((eq flag nil) (try-completion string thetable))
  8555. ((eq flag t)
  8556. (let ((l (length string)))
  8557. (mapcar (lambda (x)
  8558. (let ((r (substring x l))
  8559. (f (if (string-match " ([^)]*)$" x)
  8560. (match-string 0 x)
  8561. "")))
  8562. (if (string-match "/" r)
  8563. (concat string (substring r 0 (match-end 0)) f)
  8564. x)))
  8565. (all-completions string thetable predicate))))
  8566. ;; Exact match?
  8567. ((eq flag 'lambda) (assoc string thetable))))
  8568. args)))
  8569. ;;;; Dynamic blocks
  8570. (defun org-find-dblock (name)
  8571. "Find the first dynamic block with name NAME in the buffer.
  8572. If not found, stay at current position and return nil."
  8573. (let ((case-fold-search t) pos)
  8574. (save-excursion
  8575. (goto-char (point-min))
  8576. (setq pos (and (re-search-forward
  8577. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8578. (match-beginning 0))))
  8579. (when pos (goto-char pos))
  8580. pos))
  8581. (defun org-create-dblock (plist)
  8582. "Create a dynamic block section, with parameters taken from PLIST.
  8583. PLIST must contain a :name entry which is used as the name of the block."
  8584. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8585. (end-of-line 1)
  8586. (newline))
  8587. (let ((col (current-column))
  8588. (name (plist-get plist :name)))
  8589. (insert "#+BEGIN: " name)
  8590. (while plist
  8591. (if (eq (car plist) :name)
  8592. (setq plist (cddr plist))
  8593. (insert " " (prin1-to-string (pop plist)))))
  8594. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8595. (beginning-of-line -2)))
  8596. (defun org-prepare-dblock ()
  8597. "Prepare dynamic block for refresh.
  8598. This empties the block, puts the cursor at the insert position and returns
  8599. the property list including an extra property :name with the block name."
  8600. (unless (looking-at org-dblock-start-re)
  8601. (user-error "Not at a dynamic block"))
  8602. (let* ((begdel (1+ (match-end 0)))
  8603. (name (org-no-properties (match-string 1)))
  8604. (params (append (list :name name)
  8605. (read (concat "(" (match-string 3) ")")))))
  8606. (save-excursion
  8607. (beginning-of-line 1)
  8608. (skip-chars-forward " \t")
  8609. (setq params (plist-put params :indentation-column (current-column))))
  8610. (unless (re-search-forward org-dblock-end-re nil t)
  8611. (error "Dynamic block not terminated"))
  8612. (setq params
  8613. (append params
  8614. (list :content (buffer-substring
  8615. begdel (match-beginning 0)))))
  8616. (delete-region begdel (match-beginning 0))
  8617. (goto-char begdel)
  8618. (open-line 1)
  8619. params))
  8620. (defun org-map-dblocks (&optional command)
  8621. "Apply COMMAND to all dynamic blocks in the current buffer.
  8622. If COMMAND is not given, use `org-update-dblock'."
  8623. (let ((cmd (or command 'org-update-dblock)))
  8624. (save-excursion
  8625. (goto-char (point-min))
  8626. (while (re-search-forward org-dblock-start-re nil t)
  8627. (goto-char (match-beginning 0))
  8628. (save-excursion
  8629. (condition-case nil
  8630. (funcall cmd)
  8631. (error (message "Error during update of dynamic block"))))
  8632. (unless (re-search-forward org-dblock-end-re nil t)
  8633. (error "Dynamic block not terminated"))))))
  8634. (defvar org-dynamic-block-alist nil
  8635. "Alist defining all the Org dynamic blocks.
  8636. The key is the dynamic block type name, as a string. The value
  8637. is the function used to insert the dynamic block.
  8638. Use `org-dynamic-block-define' to populate it.")
  8639. (defun org-dynamic-block-function (type)
  8640. "Return function associated to a given dynamic block type.
  8641. TYPE is the dynamic block type, as a string."
  8642. (cdr (assoc type org-dynamic-block-alist)))
  8643. (defun org-dynamic-block-types ()
  8644. "List all defined dynamic block types."
  8645. (mapcar #'car org-dynamic-block-alist))
  8646. (defun org-dynamic-block-define (type func)
  8647. "Define dynamic block TYPE with FUNC.
  8648. TYPE is a string. FUNC is the function creating the dynamic
  8649. block of such type."
  8650. (pcase (assoc type org-dynamic-block-alist)
  8651. (`nil (push (cons type func) org-dynamic-block-alist))
  8652. (def (setcdr def func))))
  8653. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8654. "Insert a dynamic block of type TYPE.
  8655. When used interactively, select the dynamic block types among
  8656. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8657. is non-nil, call the dynamic block function interactively."
  8658. (interactive (list (completing-read "Dynamic block: "
  8659. (org-dynamic-block-types))
  8660. t))
  8661. (pcase (org-dynamic-block-function type)
  8662. (`nil (error "No such dynamic block: %S" type))
  8663. ((and f (pred functionp))
  8664. (if interactive-p (call-interactively f) (funcall f)))
  8665. (_ (error "Invalid function for dynamic block %S" type))))
  8666. (defun org-dblock-update (&optional arg)
  8667. "User command for updating dynamic blocks.
  8668. Update the dynamic block at point. With prefix ARG, update all dynamic
  8669. blocks in the buffer."
  8670. (interactive "P")
  8671. (if arg
  8672. (org-update-all-dblocks)
  8673. (or (looking-at org-dblock-start-re)
  8674. (org-beginning-of-dblock))
  8675. (org-update-dblock)))
  8676. (defun org-update-dblock ()
  8677. "Update the dynamic block at point.
  8678. This means to empty the block, parse for parameters and then call
  8679. the correct writing function."
  8680. (interactive)
  8681. (save-excursion
  8682. (let* ((win (selected-window))
  8683. (pos (point))
  8684. (line (org-current-line))
  8685. (params (org-prepare-dblock))
  8686. (name (plist-get params :name))
  8687. (indent (plist-get params :indentation-column))
  8688. (cmd (intern (concat "org-dblock-write:" name))))
  8689. (message "Updating dynamic block `%s' at line %d..." name line)
  8690. (funcall cmd params)
  8691. (message "Updating dynamic block `%s' at line %d...done" name line)
  8692. (goto-char pos)
  8693. (when (and indent (> indent 0))
  8694. (setq indent (make-string indent ?\ ))
  8695. (save-excursion
  8696. (select-window win)
  8697. (org-beginning-of-dblock)
  8698. (forward-line 1)
  8699. (while (not (looking-at org-dblock-end-re))
  8700. (insert indent)
  8701. (beginning-of-line 2))
  8702. (when (looking-at org-dblock-end-re)
  8703. (and (looking-at "[ \t]+")
  8704. (replace-match ""))
  8705. (insert indent)))))))
  8706. (defun org-beginning-of-dblock ()
  8707. "Find the beginning of the dynamic block at point.
  8708. Error if there is no such block at point."
  8709. (let ((pos (point))
  8710. beg)
  8711. (end-of-line 1)
  8712. (if (and (re-search-backward org-dblock-start-re nil t)
  8713. (setq beg (match-beginning 0))
  8714. (re-search-forward org-dblock-end-re nil t)
  8715. (> (match-end 0) pos))
  8716. (goto-char beg)
  8717. (goto-char pos)
  8718. (error "Not in a dynamic block"))))
  8719. (defun org-update-all-dblocks ()
  8720. "Update all dynamic blocks in the buffer.
  8721. This function can be used in a hook."
  8722. (interactive)
  8723. (when (derived-mode-p 'org-mode)
  8724. (org-map-dblocks 'org-update-dblock)))
  8725. ;;;; Completion
  8726. (declare-function org-export-backend-options "ox" (cl-x) t)
  8727. (defun org-get-export-keywords ()
  8728. "Return a list of all currently understood export keywords.
  8729. Export keywords include options, block names, attributes and
  8730. keywords relative to each registered export back-end."
  8731. (let (keywords)
  8732. (dolist (backend
  8733. (bound-and-true-p org-export-registered-backends)
  8734. (delq nil keywords))
  8735. ;; Back-end name (for keywords, like #+LATEX:)
  8736. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8737. (dolist (option-entry (org-export-backend-options backend))
  8738. ;; Back-end options.
  8739. (push (nth 1 option-entry) keywords)))))
  8740. (defconst org-options-keywords
  8741. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8742. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8743. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8744. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8745. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8746. (defcustom org-structure-template-alist
  8747. '(("a" . "export ascii")
  8748. ("c" . "center")
  8749. ("C" . "comment")
  8750. ("e" . "example")
  8751. ("E" . "export")
  8752. ("h" . "export html")
  8753. ("l" . "export latex")
  8754. ("q" . "quote")
  8755. ("s" . "src")
  8756. ("v" . "verse"))
  8757. "An alist of keys and block types.
  8758. `org-insert-structure-template' will display a menu with this
  8759. list of templates to choose from. The block type is inserted,
  8760. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8761. The menu keys are defined by the car of each entry in this alist.
  8762. If two entries have the keys \"a\" and \"aa\" respectively, the
  8763. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8764. latter will be inserted by typing \"aa\". If an entry with the
  8765. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8766. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8767. block can be inserted by pressing TAB after the string \"<KEY\"."
  8768. :group 'org-edit-structure
  8769. :type '(repeat
  8770. (cons (string :tag "Key")
  8771. (string :tag "Template")))
  8772. :package-version '(Org . "9.2"))
  8773. (defun org--check-org-structure-template-alist (&optional checklist)
  8774. "Check whether `org-structure-template-alist' is set up correctly.
  8775. In particular, check if the Org 9.2 format is used as opposed to
  8776. previous format.
  8777. "
  8778. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8779. (or (eval checklist)
  8780. org-structure-template-alist))))
  8781. (when elm
  8782. (org-display-warning
  8783. (format "
  8784. Please update the entries of `%s'.
  8785. In Org 9.2 the format was changed from something like
  8786. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8787. to something like
  8788. (\"s\" . \"src\")
  8789. Please refer to the documentation of `org-structure-template-alist'.
  8790. The following entries must be updated:
  8791. %s"
  8792. (or checklist 'org-structure-template-alist)
  8793. (pp-to-string elm))))))
  8794. (defun org--insert-structure-template-mks ()
  8795. "Present `org-structure-template-alist' with `org-mks'.
  8796. Menus are added if keys require more than one keystroke. Tabs
  8797. are added to single key entries when more than one stroke is
  8798. needed. Keys longer than two characters are reduced to two
  8799. characters."
  8800. (org--check-org-structure-template-alist)
  8801. (let* (case-fold-search
  8802. (templates (append org-structure-template-alist
  8803. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8804. (keys (mapcar #'car templates))
  8805. (start-letters
  8806. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8807. ;; Sort each element of `org-structure-template-alist' into
  8808. ;; sublists according to the first letter.
  8809. (superlist
  8810. (mapcar (lambda (letter)
  8811. (list letter
  8812. (cl-remove-if-not
  8813. (apply-partially #'string-match-p (concat "^" letter))
  8814. templates :key #'car)))
  8815. start-letters)))
  8816. (org-mks
  8817. (apply #'append
  8818. ;; Make an `org-mks' table. If only one element is
  8819. ;; present in a sublist, make it part of the top-menu,
  8820. ;; otherwise make a submenu according to the starting
  8821. ;; letter and populate it.
  8822. (mapcar (lambda (sublist)
  8823. (if (eq 1 (length (cadr sublist)))
  8824. (mapcar (lambda (elm)
  8825. (list (substring (car elm) 0 1)
  8826. (cdr elm) ""))
  8827. (cadr sublist))
  8828. ;; Create submenu.
  8829. (let* ((topkey (car sublist))
  8830. (elms (cadr sublist))
  8831. (keys (mapcar #'car elms))
  8832. (long (> (length elms) 3)))
  8833. (append
  8834. (list
  8835. ;; Make a description of the submenu.
  8836. (list topkey
  8837. (concat
  8838. (mapconcat #'cdr
  8839. (cl-subseq elms 0 (if long 3 (length elms)))
  8840. ", ")
  8841. (when long ", ..."))))
  8842. ;; List of entries in submenu.
  8843. (cl-mapcar #'list
  8844. (org--insert-structure-template-unique-keys keys)
  8845. (mapcar #'cdr elms)
  8846. (make-list (length elms) ""))))))
  8847. superlist))
  8848. "Select a key\n============"
  8849. "Key: ")))
  8850. (defun org--insert-structure-template-unique-keys (keys)
  8851. "Make a list of unique, two characters long elements from KEYS.
  8852. Elements of length one have a tab appended. Elements of length
  8853. two are kept as is. Longer elements are truncated to length two.
  8854. If an element cannot be made unique, an error is raised."
  8855. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8856. menu-keys)
  8857. (dolist (key ordered-keys)
  8858. (let ((potential-key
  8859. (cl-case (length key)
  8860. (1 (concat key "\t"))
  8861. (2 key)
  8862. (otherwise
  8863. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8864. (mapcar (apply-partially #'concat (substring key 0 1))
  8865. (split-string (substring key 1) "" t)))))))
  8866. (if (or (not potential-key) (assoc potential-key menu-keys))
  8867. (user-error "Could not make unique key for %s." key)
  8868. (push (cons potential-key key) menu-keys))))
  8869. (mapcar #'car
  8870. (cl-sort menu-keys #'<
  8871. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8872. (defun org-insert-structure-template (type)
  8873. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8874. Select a block from `org-structure-template-alist' then type
  8875. either RET, TAB or SPC to write the block type. With an active
  8876. region, wrap the region in the block. Otherwise, insert an empty
  8877. block."
  8878. (interactive
  8879. (list (pcase (org--insert-structure-template-mks)
  8880. (`("\t" . ,_) (read-string "Structure type: "))
  8881. (`(,_ ,choice . ,_) choice))))
  8882. (let* ((region? (use-region-p))
  8883. (region-start (and region? (region-beginning)))
  8884. (region-end (and region? (copy-marker (region-end))))
  8885. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8886. (verbatim? (string-match-p
  8887. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8888. type)))
  8889. (when region? (goto-char region-start))
  8890. (let ((column (current-indentation)))
  8891. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8892. (beginning-of-line)
  8893. (insert "\n"))
  8894. (save-excursion
  8895. (indent-to column)
  8896. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8897. (when region?
  8898. (when verbatim? (org-escape-code-in-region (point) region-end))
  8899. (goto-char region-end)
  8900. ;; Ignore empty lines at the end of the region.
  8901. (skip-chars-backward " \r\t\n")
  8902. (end-of-line))
  8903. (unless (bolp) (insert "\n"))
  8904. (indent-to column)
  8905. (insert (format "#+end_%s" (car (split-string type))))
  8906. (if (looking-at "[ \t]*$") (replace-match "")
  8907. (insert "\n"))
  8908. (when (and (eobp) (not (bolp))) (insert "\n")))
  8909. (if extended? (end-of-line)
  8910. (forward-line)
  8911. (skip-chars-forward " \t")))))
  8912. ;;;; TODO, DEADLINE, Comments
  8913. (defun org-toggle-comment ()
  8914. "Change the COMMENT state of an entry."
  8915. (interactive)
  8916. (save-excursion
  8917. (org-back-to-heading)
  8918. (let ((case-fold-search nil))
  8919. (looking-at org-complex-heading-regexp))
  8920. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8921. (skip-chars-forward " \t")
  8922. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8923. (if (org-in-commented-heading-p t)
  8924. (delete-region (point)
  8925. (progn (search-forward " " (line-end-position) 'move)
  8926. (skip-chars-forward " \t")
  8927. (point)))
  8928. (insert org-comment-string)
  8929. (unless (eolp) (insert " ")))))
  8930. (defvar org-last-todo-state-is-todo nil
  8931. "This is non-nil when the last TODO state change led to a TODO state.
  8932. If the last change removed the TODO tag or switched to DONE, then
  8933. this is nil.")
  8934. (defvar org-todo-setup-filter-hook nil
  8935. "Hook for functions that pre-filter todo specs.
  8936. Each function takes a todo spec and returns either nil or the spec
  8937. transformed into canonical form." )
  8938. (defvar org-todo-get-default-hook nil
  8939. "Hook for functions that get a default item for todo.
  8940. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8941. nil or a string to be used for the todo mark." )
  8942. (defvar org-agenda-headline-snapshot-before-repeat)
  8943. (defun org-current-effective-time ()
  8944. "Return current time adjusted for `org-extend-today-until' variable."
  8945. (let* ((ct (org-current-time))
  8946. (dct (decode-time ct))
  8947. (ct1
  8948. (cond
  8949. (org-use-last-clock-out-time-as-effective-time
  8950. (or (org-clock-get-last-clock-out-time) ct))
  8951. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8952. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8953. (t ct))))
  8954. ct1))
  8955. (defun org-todo-yesterday (&optional arg)
  8956. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8957. (interactive "P")
  8958. (if (eq major-mode 'org-agenda-mode)
  8959. (apply 'org-agenda-todo-yesterday arg)
  8960. (let* ((org-use-effective-time t)
  8961. (hour (nth 2 (decode-time (org-current-time))))
  8962. (org-extend-today-until (1+ hour)))
  8963. (org-todo arg))))
  8964. (defvar org-block-entry-blocking ""
  8965. "First entry preventing the TODO state change.")
  8966. (defun org-cancel-repeater ()
  8967. "Cancel a repeater by setting its numeric value to zero."
  8968. (interactive)
  8969. (save-excursion
  8970. (org-back-to-heading t)
  8971. (let ((bound1 (point))
  8972. (bound0 (save-excursion (outline-next-heading) (point))))
  8973. (when (and (re-search-forward
  8974. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8975. org-deadline-time-regexp "\\)\\|\\("
  8976. org-ts-regexp "\\)")
  8977. bound0 t)
  8978. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8979. bound1 t))
  8980. (replace-match "0" t nil nil 1)))))
  8981. (defvar org-state)
  8982. (defvar org-blocked-by-checkboxes)
  8983. (defun org-todo (&optional arg)
  8984. "Change the TODO state of an item.
  8985. The state of an item is given by a keyword at the start of the heading,
  8986. like
  8987. *** TODO Write paper
  8988. *** DONE Call mom
  8989. The different keywords are specified in the variable `org-todo-keywords'.
  8990. By default the available states are \"TODO\" and \"DONE\". So, for this
  8991. example: when the item starts with TODO, it is changed to DONE.
  8992. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8993. DONE are present, add TODO at the beginning of the heading.
  8994. You can set up single-character keys to fast-select the new state. See the
  8995. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8996. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8997. and take a
  8998. logging note.
  8999. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  9000. next set of TODO \
  9001. keywords (nextset).
  9002. Another way to achieve this is `S-C-<right>'.
  9003. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9004. prefix, circumvent any state blocking.
  9005. With numeric prefix arg, switch to the Nth state.
  9006. With a numeric prefix arg of 0, inhibit note taking for the change.
  9007. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  9008. When called through ELisp, arg is also interpreted in the following way:
  9009. `none' -> empty state
  9010. \"\" -> switch to empty state
  9011. `done' -> switch to DONE
  9012. `nextset' -> switch to the next set of keywords
  9013. `previousset' -> switch to the previous set of keywords
  9014. \"WAITING\" -> switch to the specified keyword, but only if it
  9015. really is a member of `org-todo-keywords'."
  9016. (interactive "P")
  9017. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9018. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9019. 'region-start-level 'region))
  9020. org-loop-over-headlines-in-active-region)
  9021. (org-map-entries
  9022. `(org-todo ,arg)
  9023. org-loop-over-headlines-in-active-region
  9024. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9025. (when (equal arg '(16)) (setq arg 'nextset))
  9026. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9027. (let ((org-blocker-hook org-blocker-hook)
  9028. commentp
  9029. case-fold-search)
  9030. (when (equal arg '(64))
  9031. (setq arg nil org-blocker-hook nil))
  9032. (when (and org-blocker-hook
  9033. (or org-inhibit-blocking
  9034. (org-entry-get nil "NOBLOCKING")))
  9035. (setq org-blocker-hook nil))
  9036. (save-excursion
  9037. (catch 'exit
  9038. (org-back-to-heading t)
  9039. (when (org-in-commented-heading-p t)
  9040. (org-toggle-comment)
  9041. (setq commentp t))
  9042. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9043. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9044. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9045. (let* ((match-data (match-data))
  9046. (startpos (copy-marker (line-beginning-position)))
  9047. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9048. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9049. (org-log-done org-log-done)
  9050. (org-log-repeat org-log-repeat)
  9051. (org-todo-log-states org-todo-log-states)
  9052. (org-inhibit-logging
  9053. (if (equal arg 0)
  9054. (progn (setq arg nil) 'note) org-inhibit-logging))
  9055. (this (match-string 1))
  9056. (hl-pos (match-beginning 0))
  9057. (head (org-get-todo-sequence-head this))
  9058. (ass (assoc head org-todo-kwd-alist))
  9059. (interpret (nth 1 ass))
  9060. (done-word (nth 3 ass))
  9061. (final-done-word (nth 4 ass))
  9062. (org-last-state (or this ""))
  9063. (completion-ignore-case t)
  9064. (member (member this org-todo-keywords-1))
  9065. (tail (cdr member))
  9066. (org-state (cond
  9067. ((eq arg 'right)
  9068. ;; Next state
  9069. (if this
  9070. (if tail (car tail) nil)
  9071. (car org-todo-keywords-1)))
  9072. ((eq arg 'left)
  9073. ;; Previous state
  9074. (unless (equal member org-todo-keywords-1)
  9075. (if this
  9076. (nth (- (length org-todo-keywords-1)
  9077. (length tail) 2)
  9078. org-todo-keywords-1)
  9079. (org-last org-todo-keywords-1))))
  9080. (arg
  9081. ;; User or caller requests a specific state.
  9082. (cond
  9083. ((equal arg "") nil)
  9084. ((eq arg 'none) nil)
  9085. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9086. ((eq arg 'nextset)
  9087. (or (car (cdr (member head org-todo-heads)))
  9088. (car org-todo-heads)))
  9089. ((eq arg 'previousset)
  9090. (let ((org-todo-heads (reverse org-todo-heads)))
  9091. (or (car (cdr (member head org-todo-heads)))
  9092. (car org-todo-heads))))
  9093. ((car (member arg org-todo-keywords-1)))
  9094. ((stringp arg)
  9095. (user-error "State `%s' not valid in this file" arg))
  9096. ((nth (1- (prefix-numeric-value arg))
  9097. org-todo-keywords-1))))
  9098. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9099. ;; Use fast selection.
  9100. (org-fast-todo-selection this))
  9101. ((null member) (or head (car org-todo-keywords-1)))
  9102. ((equal this final-done-word) nil) ;-> make empty
  9103. ((null tail) nil) ;-> first entry
  9104. ((memq interpret '(type priority))
  9105. (if (eq this-command last-command)
  9106. (car tail)
  9107. (if (> (length tail) 0)
  9108. (or done-word (car org-done-keywords))
  9109. nil)))
  9110. (t
  9111. (car tail))))
  9112. (org-state (or
  9113. (run-hook-with-args-until-success
  9114. 'org-todo-get-default-hook org-state org-last-state)
  9115. org-state))
  9116. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9117. (change-plist (list :type 'todo-state-change :from this :to org-state
  9118. :position startpos))
  9119. dolog now-done-p)
  9120. (when org-blocker-hook
  9121. (let (org-blocked-by-checkboxes block-reason)
  9122. (setq org-last-todo-state-is-todo
  9123. (not (member this org-done-keywords)))
  9124. (unless (save-excursion
  9125. (save-match-data
  9126. (org-with-wide-buffer
  9127. (run-hook-with-args-until-failure
  9128. 'org-blocker-hook change-plist))))
  9129. (setq block-reason (if org-blocked-by-checkboxes
  9130. "contained checkboxes"
  9131. (format "\"%s\"" org-block-entry-blocking)))
  9132. (if (called-interactively-p 'interactive)
  9133. (user-error "TODO state change from %s to %s blocked (by %s)"
  9134. this org-state block-reason)
  9135. ;; Fail silently.
  9136. (message "TODO state change from %s to %s blocked (by %s)"
  9137. this org-state block-reason)
  9138. (throw 'exit nil)))))
  9139. (store-match-data match-data)
  9140. (replace-match next t t)
  9141. (cond ((equal this org-state)
  9142. (message "TODO state was already %s" (org-trim next)))
  9143. ((not (pos-visible-in-window-p hl-pos))
  9144. (message "TODO state changed to %s" (org-trim next))))
  9145. (unless head
  9146. (setq head (org-get-todo-sequence-head org-state)
  9147. ass (assoc head org-todo-kwd-alist)
  9148. interpret (nth 1 ass)
  9149. done-word (nth 3 ass)
  9150. final-done-word (nth 4 ass)))
  9151. (when (memq arg '(nextset previousset))
  9152. (message "Keyword-Set %d/%d: %s"
  9153. (- (length org-todo-sets) -1
  9154. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9155. (length org-todo-sets)
  9156. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9157. (setq org-last-todo-state-is-todo
  9158. (not (member org-state org-done-keywords)))
  9159. (setq now-done-p (and (member org-state org-done-keywords)
  9160. (not (member this org-done-keywords))))
  9161. (and logging (org-local-logging logging))
  9162. (when (or (and (or org-todo-log-states org-log-done)
  9163. (not (eq org-inhibit-logging t))
  9164. (not (memq arg '(nextset previousset))))
  9165. force-log)
  9166. ;; We need to look at recording a time and note.
  9167. (setq dolog (or (if force-log 'note)
  9168. (nth 1 (assoc org-state org-todo-log-states))
  9169. (nth 2 (assoc this org-todo-log-states))))
  9170. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9171. (setq dolog 'time))
  9172. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9173. (and org-state
  9174. (member org-state org-not-done-keywords)
  9175. (not (member this org-not-done-keywords))))
  9176. ;; This is now a todo state and was not one before
  9177. ;; If there was a CLOSED time stamp, get rid of it.
  9178. (org-add-planning-info nil nil 'closed))
  9179. (when (and now-done-p org-log-done)
  9180. ;; It is now done, and it was not done before.
  9181. (org-add-planning-info 'closed (org-current-effective-time))
  9182. (when (and (not dolog) (eq 'note org-log-done))
  9183. (org-add-log-setup 'done org-state this 'note)))
  9184. (when (and org-state dolog)
  9185. ;; This is a non-nil state, and we need to log it.
  9186. (org-add-log-setup 'state org-state this dolog)))
  9187. ;; Fixup tag positioning.
  9188. (org-todo-trigger-tag-changes org-state)
  9189. (when org-auto-align-tags (org-align-tags))
  9190. (when org-provide-todo-statistics
  9191. (org-update-parent-todo-statistics))
  9192. (when (bound-and-true-p org-clock-out-when-done)
  9193. (org-clock-out-if-current))
  9194. (run-hooks 'org-after-todo-state-change-hook)
  9195. (when (and arg (not (member org-state org-done-keywords)))
  9196. (setq head (org-get-todo-sequence-head org-state)))
  9197. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9198. ;; Do we need to trigger a repeat?
  9199. (when now-done-p
  9200. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9201. ;; This is for the agenda, take a snapshot of the headline.
  9202. (save-match-data
  9203. (setq org-agenda-headline-snapshot-before-repeat
  9204. (org-get-heading))))
  9205. (org-auto-repeat-maybe org-state))
  9206. ;; Fixup cursor location if close to the keyword.
  9207. (when (and (outline-on-heading-p)
  9208. (not (bolp))
  9209. (save-excursion (beginning-of-line 1)
  9210. (looking-at org-todo-line-regexp))
  9211. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9212. (goto-char (or (match-end 2) (match-end 1)))
  9213. (and (looking-at " ")
  9214. (not (looking-at " *:"))
  9215. (just-one-space)))
  9216. (when org-trigger-hook
  9217. (save-excursion
  9218. (run-hook-with-args 'org-trigger-hook change-plist)))
  9219. (when commentp (org-toggle-comment))))))))
  9220. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9221. "Block turning an entry into a TODO, using the hierarchy.
  9222. This checks whether the current task should be blocked from state
  9223. changes. Such blocking occurs when:
  9224. 1. The task has children which are not all in a completed state.
  9225. 2. A task has a parent with the property :ORDERED:, and there
  9226. are siblings prior to the current task with incomplete
  9227. status.
  9228. 3. The parent of the task is blocked because it has siblings that should
  9229. be done first, or is child of a block grandparent TODO entry."
  9230. (if (not org-enforce-todo-dependencies)
  9231. t ; if locally turned off don't block
  9232. (catch 'dont-block
  9233. ;; If this is not a todo state change, or if this entry is already DONE,
  9234. ;; do not block
  9235. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9236. (member (plist-get change-plist :from)
  9237. (cons 'done org-done-keywords))
  9238. (member (plist-get change-plist :to)
  9239. (cons 'todo org-not-done-keywords))
  9240. (not (plist-get change-plist :to)))
  9241. (throw 'dont-block t))
  9242. ;; If this task has children, and any are undone, it's blocked
  9243. (save-excursion
  9244. (org-back-to-heading t)
  9245. (let ((this-level (funcall outline-level)))
  9246. (outline-next-heading)
  9247. (let ((child-level (funcall outline-level)))
  9248. (while (and (not (eobp))
  9249. (> child-level this-level))
  9250. ;; this todo has children, check whether they are all
  9251. ;; completed
  9252. (when (and (not (org-entry-is-done-p))
  9253. (org-entry-is-todo-p))
  9254. (setq org-block-entry-blocking (org-get-heading))
  9255. (throw 'dont-block nil))
  9256. (outline-next-heading)
  9257. (setq child-level (funcall outline-level))))))
  9258. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9259. ;; any previous siblings are undone, it's blocked
  9260. (save-excursion
  9261. (org-back-to-heading t)
  9262. (let* ((pos (point))
  9263. (parent-pos (and (org-up-heading-safe) (point)))
  9264. (case-fold-search nil))
  9265. (unless parent-pos (throw 'dont-block t)) ; no parent
  9266. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9267. (forward-line 1)
  9268. (re-search-forward org-not-done-heading-regexp pos t))
  9269. (setq org-block-entry-blocking (match-string 0))
  9270. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9271. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9272. (while t
  9273. (goto-char parent-pos)
  9274. (unless (looking-at org-not-done-heading-regexp)
  9275. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9276. (setq pos (point))
  9277. (setq parent-pos (and (org-up-heading-safe) (point)))
  9278. (unless parent-pos (throw 'dont-block t)) ; no parent
  9279. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9280. (forward-line 1)
  9281. (re-search-forward org-not-done-heading-regexp pos t)
  9282. (setq org-block-entry-blocking (org-get-heading)))
  9283. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9284. (defcustom org-track-ordered-property-with-tag nil
  9285. "Should the ORDERED property also be shown as a tag?
  9286. The ORDERED property decides if an entry should require subtasks to be
  9287. completed in sequence. Since a property is not very visible, setting
  9288. this option means that toggling the ORDERED property with the command
  9289. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9290. not relevant for the behavior, but it makes things more visible.
  9291. Note that toggling the tag with tags commands will not change the property
  9292. and therefore not influence behavior!
  9293. This can be t, meaning the tag ORDERED should be used. It can also be a
  9294. string to select a different tag for this task."
  9295. :group 'org-todo
  9296. :type '(choice
  9297. (const :tag "No tracking" nil)
  9298. (const :tag "Track with ORDERED tag" t)
  9299. (string :tag "Use other tag")))
  9300. (defun org-toggle-ordered-property ()
  9301. "Toggle the ORDERED property of the current entry.
  9302. For better visibility, you can track the value of this property with a tag.
  9303. See variable `org-track-ordered-property-with-tag'."
  9304. (interactive)
  9305. (let* ((t1 org-track-ordered-property-with-tag)
  9306. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9307. (save-excursion
  9308. (org-back-to-heading)
  9309. (if (org-entry-get nil "ORDERED")
  9310. (progn
  9311. (org-delete-property "ORDERED")
  9312. (and tag (org-toggle-tag tag 'off))
  9313. (message "Subtasks can be completed in arbitrary order"))
  9314. (org-entry-put nil "ORDERED" "t")
  9315. (and tag (org-toggle-tag tag 'on))
  9316. (message "Subtasks must be completed in sequence")))))
  9317. (defun org-block-todo-from-checkboxes (change-plist)
  9318. "Block turning an entry into a TODO, using checkboxes.
  9319. This checks whether the current task should be blocked from state
  9320. changes because there are unchecked boxes in this entry."
  9321. (if (not org-enforce-todo-checkbox-dependencies)
  9322. t ; if locally turned off don't block
  9323. (catch 'dont-block
  9324. ;; If this is not a todo state change, or if this entry is already DONE,
  9325. ;; do not block
  9326. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9327. (member (plist-get change-plist :from)
  9328. (cons 'done org-done-keywords))
  9329. (member (plist-get change-plist :to)
  9330. (cons 'todo org-not-done-keywords))
  9331. (not (plist-get change-plist :to)))
  9332. (throw 'dont-block t))
  9333. ;; If this task has checkboxes that are not checked, it's blocked
  9334. (save-excursion
  9335. (org-back-to-heading t)
  9336. (let ((beg (point)) end)
  9337. (outline-next-heading)
  9338. (setq end (point))
  9339. (goto-char beg)
  9340. (when (org-list-search-forward
  9341. (concat (org-item-beginning-re)
  9342. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9343. "\\[[- ]\\]")
  9344. end t)
  9345. (when (boundp 'org-blocked-by-checkboxes)
  9346. (setq org-blocked-by-checkboxes t))
  9347. (throw 'dont-block nil))))
  9348. t))) ; do not block
  9349. (defun org-entry-blocked-p ()
  9350. "Non-nil if entry at point is blocked."
  9351. (and (not (org-entry-get nil "NOBLOCKING"))
  9352. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9353. (not (run-hook-with-args-until-failure
  9354. 'org-blocker-hook
  9355. (list :type 'todo-state-change
  9356. :position (point)
  9357. :from 'todo
  9358. :to 'done)))))
  9359. (defun org-update-statistics-cookies (all)
  9360. "Update the statistics cookie, either from TODO or from checkboxes.
  9361. This should be called with the cursor in a line with a statistics
  9362. cookie. When called with a \\[universal-argument] prefix, update
  9363. all statistics cookies in the buffer."
  9364. (interactive "P")
  9365. (if all
  9366. (progn
  9367. (org-update-checkbox-count 'all)
  9368. (org-map-entries 'org-update-parent-todo-statistics))
  9369. (if (not (org-at-heading-p))
  9370. (org-update-checkbox-count)
  9371. (let ((pos (point-marker))
  9372. end l1 l2)
  9373. (ignore-errors (org-back-to-heading t))
  9374. (if (not (org-at-heading-p))
  9375. (org-update-checkbox-count)
  9376. (setq l1 (org-outline-level))
  9377. (setq end (save-excursion
  9378. (outline-next-heading)
  9379. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9380. (point)))
  9381. (if (and (save-excursion
  9382. (re-search-forward
  9383. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9384. (not (save-excursion (re-search-forward
  9385. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9386. (org-update-checkbox-count)
  9387. (if (and l2 (> l2 l1))
  9388. (progn
  9389. (goto-char end)
  9390. (org-update-parent-todo-statistics))
  9391. (goto-char pos)
  9392. (beginning-of-line 1)
  9393. (while (re-search-forward
  9394. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9395. (point-at-eol) t)
  9396. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9397. (goto-char pos)
  9398. (move-marker pos nil)))))
  9399. (defvar org-entry-property-inherited-from) ;; defined below
  9400. (defun org-update-parent-todo-statistics ()
  9401. "Update any statistics cookie in the parent of the current headline.
  9402. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9403. the entire subtree and this will travel up the hierarchy and update
  9404. statistics everywhere."
  9405. (let* ((prop (save-excursion (org-up-heading-safe)
  9406. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9407. (recursive (or (not org-hierarchical-todo-statistics)
  9408. (and prop (string-match "\\<recursive\\>" prop))))
  9409. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9410. 0))
  9411. (first t)
  9412. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9413. level ltoggle l1 new ndel
  9414. (cnt-all 0) (cnt-done 0) is-percent kwd
  9415. checkbox-beg cookie-present)
  9416. (catch 'exit
  9417. (save-excursion
  9418. (beginning-of-line 1)
  9419. (setq ltoggle (funcall outline-level))
  9420. ;; Three situations are to consider:
  9421. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9422. ;; to the top-level ancestor on the headline;
  9423. ;; 2. If parent has "recursive" property, repeat up to the
  9424. ;; headline setting that property, taking inheritance into
  9425. ;; account;
  9426. ;; 3. Else, move up to direct parent and proceed only once.
  9427. (while (and (setq level (org-up-heading-safe))
  9428. (or recursive first)
  9429. (>= (point) lim))
  9430. (setq first nil cookie-present nil)
  9431. (unless (and level
  9432. (not (string-match
  9433. "\\<checkbox\\>"
  9434. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9435. "")))))
  9436. (throw 'exit nil))
  9437. (while (re-search-forward box-re (point-at-eol) t)
  9438. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9439. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9440. (save-match-data
  9441. (unless (outline-next-heading) (throw 'exit nil))
  9442. (while (and (looking-at org-complex-heading-regexp)
  9443. (> (setq l1 (length (match-string 1))) level))
  9444. (setq kwd (and (or recursive (= l1 ltoggle))
  9445. (match-string 2)))
  9446. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9447. (and (eq org-provide-todo-statistics t)
  9448. (or (member kwd org-done-keywords)))
  9449. (and (listp org-provide-todo-statistics)
  9450. (stringp (car org-provide-todo-statistics))
  9451. (or (member kwd org-provide-todo-statistics)
  9452. (member kwd org-done-keywords)))
  9453. (and (listp org-provide-todo-statistics)
  9454. (listp (car org-provide-todo-statistics))
  9455. (or (member kwd (car org-provide-todo-statistics))
  9456. (and (member kwd org-done-keywords)
  9457. (member kwd (cadr org-provide-todo-statistics))))))
  9458. (setq cnt-all (1+ cnt-all))
  9459. (and (eq org-provide-todo-statistics t)
  9460. kwd
  9461. (setq cnt-all (1+ cnt-all))))
  9462. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9463. (member kwd org-done-keywords))
  9464. (and (listp org-provide-todo-statistics)
  9465. (listp (car org-provide-todo-statistics))
  9466. (member kwd org-done-keywords)
  9467. (member kwd (cadr org-provide-todo-statistics)))
  9468. (and (listp org-provide-todo-statistics)
  9469. (stringp (car org-provide-todo-statistics))
  9470. (member kwd org-done-keywords)))
  9471. (setq cnt-done (1+ cnt-done)))
  9472. (outline-next-heading)))
  9473. (setq new
  9474. (if is-percent
  9475. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9476. (max 1 cnt-all)))
  9477. (format "[%d/%d]" cnt-done cnt-all))
  9478. ndel (- (match-end 0) checkbox-beg))
  9479. (goto-char checkbox-beg)
  9480. (insert new)
  9481. (delete-region (point) (+ (point) ndel))
  9482. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9483. (when cookie-present
  9484. (run-hook-with-args 'org-after-todo-statistics-hook
  9485. cnt-done (- cnt-all cnt-done))))))
  9486. (run-hooks 'org-todo-statistics-hook)))
  9487. (defvar org-after-todo-statistics-hook nil
  9488. "Hook that is called after a TODO statistics cookie has been updated.
  9489. Each function is called with two arguments: the number of not-done entries
  9490. and the number of done entries.
  9491. For example, the following function, when added to this hook, will switch
  9492. an entry to DONE when all children are done, and back to TODO when new
  9493. entries are set to a TODO status. Note that this hook is only called
  9494. when there is a statistics cookie in the headline!
  9495. (defun org-summary-todo (n-done n-not-done)
  9496. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9497. (let (org-log-done org-log-states) ; turn off logging
  9498. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9499. ")
  9500. (defvar org-todo-statistics-hook nil
  9501. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9502. This hook runs even if there is no statistics cookie present, in which case
  9503. `org-after-todo-statistics-hook' would not run.")
  9504. (defun org-todo-trigger-tag-changes (state)
  9505. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9506. (let ((l org-todo-state-tags-triggers)
  9507. changes)
  9508. (when (or (not state) (equal state ""))
  9509. (setq changes (append changes (cdr (assoc "" l)))))
  9510. (when (and (stringp state) (> (length state) 0))
  9511. (setq changes (append changes (cdr (assoc state l)))))
  9512. (when (member state org-not-done-keywords)
  9513. (setq changes (append changes (cdr (assq 'todo l)))))
  9514. (when (member state org-done-keywords)
  9515. (setq changes (append changes (cdr (assq 'done l)))))
  9516. (dolist (c changes)
  9517. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9518. (defun org-local-logging (value)
  9519. "Get logging settings from a property VALUE."
  9520. ;; Directly set the variables, they are already local.
  9521. (setq org-log-done nil
  9522. org-log-repeat nil
  9523. org-todo-log-states nil)
  9524. (dolist (w (split-string value))
  9525. (let (a)
  9526. (cond
  9527. ((setq a (assoc w org-startup-options))
  9528. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9529. (set (nth 1 a) (nth 2 a))))
  9530. ((setq a (org-extract-log-state-settings w))
  9531. (and (member (car a) org-todo-keywords-1)
  9532. (push a org-todo-log-states)))))))
  9533. (defun org-get-todo-sequence-head (kwd)
  9534. "Return the head of the TODO sequence to which KWD belongs.
  9535. If KWD is not set, check if there is a text property remembering the
  9536. right sequence."
  9537. (let (p)
  9538. (cond
  9539. ((not kwd)
  9540. (or (get-text-property (point-at-bol) 'org-todo-head)
  9541. (progn
  9542. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9543. nil (point-at-eol)))
  9544. (get-text-property p 'org-todo-head))))
  9545. ((not (member kwd org-todo-keywords-1))
  9546. (car org-todo-keywords-1))
  9547. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9548. (defun org-fast-todo-selection (&optional current-state)
  9549. "Fast TODO keyword selection with single keys.
  9550. Returns the new TODO keyword, or nil if no state change should occur.
  9551. When CURRENT-STATE is given and selection letters are not unique globally,
  9552. prefer a state in the current sequence over on in another sequence."
  9553. (let* ((fulltable org-todo-key-alist)
  9554. (head (org-get-todo-sequence-head current-state))
  9555. (done-keywords org-done-keywords) ;; needed for the faces.
  9556. (maxlen (apply 'max (mapcar
  9557. (lambda (x)
  9558. (if (stringp (car x)) (string-width (car x)) 0))
  9559. fulltable)))
  9560. (expert (equal org-use-fast-todo-selection 'expert))
  9561. (prompt "")
  9562. (fwidth (+ maxlen 3 1 3))
  9563. (ncol (/ (- (window-width) 4) fwidth))
  9564. tg cnt e c tbl subtable
  9565. groups ingroup in-current-sequence)
  9566. (save-excursion
  9567. (save-window-excursion
  9568. (if expert
  9569. (set-buffer (get-buffer-create " *Org todo*"))
  9570. (delete-other-windows)
  9571. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9572. (org-switch-to-buffer-other-window " *Org todo*"))
  9573. (erase-buffer)
  9574. (setq-local org-done-keywords done-keywords)
  9575. (setq tbl fulltable cnt 0)
  9576. (while (setq e (pop tbl))
  9577. (cond
  9578. ((equal e '(:startgroup))
  9579. (push '() groups) (setq ingroup t)
  9580. (unless (= cnt 0)
  9581. (setq cnt 0)
  9582. (insert "\n"))
  9583. (setq prompt (concat prompt "{"))
  9584. (insert "{ "))
  9585. ((equal e '(:endgroup))
  9586. (setq ingroup nil cnt 0 in-current-sequence nil)
  9587. (setq prompt (concat prompt "}"))
  9588. (insert "}\n"))
  9589. ((equal e '(:newline))
  9590. (unless (= cnt 0)
  9591. (setq cnt 0)
  9592. (insert "\n")
  9593. (setq e (car tbl))
  9594. (while (equal (car tbl) '(:newline))
  9595. (insert "\n")
  9596. (setq tbl (cdr tbl)))))
  9597. (t
  9598. (setq tg (car e) c (cdr e))
  9599. (if (equal tg head) (setq in-current-sequence t))
  9600. (when ingroup (push tg (car groups)))
  9601. (when in-current-sequence (push e subtable))
  9602. (setq tg (org-add-props tg nil 'face
  9603. (org-get-todo-face tg)))
  9604. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9605. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9606. (insert "[" c "] " tg (make-string
  9607. (- fwidth 4 (length tg)) ?\ ))
  9608. (when (and (= (setq cnt (1+ cnt)) ncol)
  9609. ;; Avoid lines with just a closing delimiter.
  9610. (not (equal (car tbl) '(:endgroup))))
  9611. (insert "\n")
  9612. (when ingroup (insert " "))
  9613. (setq cnt 0)))))
  9614. (insert "\n")
  9615. (goto-char (point-min))
  9616. (unless expert (org-fit-window-to-buffer))
  9617. (message (concat "[a-z..]:Set [SPC]:clear"
  9618. (if expert (concat "\n" prompt) "")))
  9619. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9620. (setq subtable (nreverse subtable))
  9621. (cond
  9622. ((or (= c ?\C-g)
  9623. (and (= c ?q) (not (rassoc c fulltable))))
  9624. (setq quit-flag t))
  9625. ((= c ?\ ) nil)
  9626. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9627. tg (car e))
  9628. tg)
  9629. (t (setq quit-flag t)))))))
  9630. (defun org-entry-is-todo-p ()
  9631. (member (org-get-todo-state) org-not-done-keywords))
  9632. (defun org-entry-is-done-p ()
  9633. (member (org-get-todo-state) org-done-keywords))
  9634. (defun org-get-todo-state ()
  9635. "Return the TODO keyword of the current subtree."
  9636. (save-excursion
  9637. (org-back-to-heading t)
  9638. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9639. (match-end 2)
  9640. (match-string 2))))
  9641. (defun org-at-date-range-p (&optional inactive-ok)
  9642. "Non-nil if point is inside a date range.
  9643. When optional argument INACTIVE-OK is non-nil, also consider
  9644. inactive time ranges.
  9645. When this function returns a non-nil value, match data is set
  9646. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9647. on INACTIVE-OK."
  9648. (interactive)
  9649. (save-excursion
  9650. (catch 'exit
  9651. (let ((pos (point)))
  9652. (skip-chars-backward "^[<\r\n")
  9653. (skip-chars-backward "<[")
  9654. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9655. (>= (match-end 0) pos)
  9656. (throw 'exit t))
  9657. (skip-chars-backward "^<[\r\n")
  9658. (skip-chars-backward "<[")
  9659. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9660. (>= (match-end 0) pos)
  9661. (throw 'exit t)))
  9662. nil)))
  9663. (defun org-get-repeat (&optional timestamp)
  9664. "Check if there is a time-stamp with repeater in this entry.
  9665. Return the repeater, as a string, or nil. Also return nil when
  9666. this function is called before first heading.
  9667. When optional argument TIMESTAMP is a string, extract the
  9668. repeater from there instead."
  9669. (save-match-data
  9670. (cond (timestamp
  9671. (and (string-match org-repeat-re timestamp)
  9672. (match-string-no-properties 1 timestamp)))
  9673. ((org-before-first-heading-p) nil)
  9674. (t
  9675. (save-excursion
  9676. (org-back-to-heading t)
  9677. (let ((end (org-entry-end-position)))
  9678. (catch :repeat
  9679. (while (re-search-forward org-repeat-re end t)
  9680. (when (save-match-data (org-at-timestamp-p 'agenda))
  9681. (throw :repeat (match-string-no-properties 1)))))))))))
  9682. (defvar org-last-changed-timestamp)
  9683. (defvar org-last-inserted-timestamp)
  9684. (defvar org-log-post-message)
  9685. (defvar org-log-note-purpose)
  9686. (defvar org-log-note-how nil)
  9687. (defvar org-log-note-extra)
  9688. (defun org-auto-repeat-maybe (done-word)
  9689. "Check if the current headline contains a repeated time-stamp.
  9690. If yes, set TODO state back to what it was and change the base date
  9691. of repeating deadline/scheduled time stamps to new date.
  9692. This function is run automatically after each state change to a DONE state."
  9693. (let* ((repeat (org-get-repeat))
  9694. (aa (assoc org-last-state org-todo-kwd-alist))
  9695. (interpret (nth 1 aa))
  9696. (head (nth 2 aa))
  9697. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9698. (msg "Entry repeats: ")
  9699. (org-log-done nil)
  9700. (org-todo-log-states nil)
  9701. (end (copy-marker (org-entry-end-position))))
  9702. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9703. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9704. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9705. (and (stringp org-todo-repeat-to-state)
  9706. org-todo-repeat-to-state)
  9707. (and org-todo-repeat-to-state org-last-state))))
  9708. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9709. to-state)
  9710. ((eq interpret 'type) org-last-state)
  9711. (head)
  9712. (t 'none))))
  9713. (org-back-to-heading t)
  9714. (org-add-planning-info nil nil 'closed)
  9715. ;; When `org-log-repeat' is non-nil or entry contains
  9716. ;; a clock, set LAST_REPEAT property.
  9717. (when (or org-log-repeat
  9718. (catch :clock
  9719. (save-excursion
  9720. (while (re-search-forward org-clock-line-re end t)
  9721. (when (org-at-clock-log-p) (throw :clock t))))))
  9722. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9723. (org-time-stamp-format t t))))
  9724. (when org-log-repeat
  9725. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9726. (memq 'org-add-log-note post-command-hook))
  9727. ;; We are already setup for some record.
  9728. (when (eq org-log-repeat 'note)
  9729. ;; Make sure we take a note, not only a time stamp.
  9730. (setq org-log-note-how 'note))
  9731. ;; Set up for taking a record.
  9732. (org-add-log-setup 'state
  9733. (or done-word (car org-done-keywords))
  9734. org-last-state
  9735. org-log-repeat)))
  9736. ;; Time-stamps without a repeater are usually skipped. However,
  9737. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9738. ;; longer relevant.
  9739. (save-excursion
  9740. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9741. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9742. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9743. ;; Update every time-stamp with a repeater in the entry.
  9744. (let ((planning-re (regexp-opt
  9745. (list org-scheduled-string org-deadline-string))))
  9746. (while (re-search-forward org-repeat-re end t)
  9747. (let* ((ts (match-string 0))
  9748. (type (if (not (org-at-planning-p)) "Plain:"
  9749. (save-excursion
  9750. (re-search-backward
  9751. planning-re (line-beginning-position) t)
  9752. (match-string 0)))))
  9753. (when (and (org-at-timestamp-p 'agenda)
  9754. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9755. (let ((n (string-to-number (match-string 2 ts)))
  9756. (what (match-string 3 ts)))
  9757. (when (equal what "w") (setq n (* n 7) what "d"))
  9758. (when (and (equal what "h")
  9759. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9760. ts)))
  9761. (user-error
  9762. "Cannot repeat in %d hour(s) because no hour has been set"
  9763. n))
  9764. ;; Preparation, see if we need to modify the start
  9765. ;; date for the change.
  9766. (when (match-end 1)
  9767. (let ((time (save-match-data (org-time-string-to-time ts)))
  9768. (repeater-type (match-string 1 ts)))
  9769. (cond
  9770. ((equal "." repeater-type)
  9771. ;; Shift starting date to today.
  9772. (org-timestamp-change (- (org-today) (time-to-days time))
  9773. 'day))
  9774. ((equal "+" repeater-type)
  9775. (let ((nshiftmax 10)
  9776. (nshift 0))
  9777. (while (or (= nshift 0)
  9778. (not (org-time-less-p nil time)))
  9779. (when (= nshiftmax (cl-incf nshift))
  9780. (or (y-or-n-p
  9781. (format "%d repeater intervals were not \
  9782. enough to shift date past today. Continue? "
  9783. nshift))
  9784. (user-error "Abort")))
  9785. (org-timestamp-change n (cdr (assoc what whata)))
  9786. (org-in-regexp org-ts-regexp3)
  9787. (setq ts (match-string 1))
  9788. (setq time
  9789. (save-match-data
  9790. (org-time-string-to-time ts)))))
  9791. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9792. ;; Rematch, so that we have everything in place
  9793. ;; for the real shift.
  9794. (org-in-regexp org-ts-regexp3)
  9795. (setq ts (match-string 1))
  9796. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9797. ts)))))
  9798. (save-excursion
  9799. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9800. (setq msg
  9801. (concat msg type " " org-last-changed-timestamp " ")))))))
  9802. (run-hooks 'org-todo-repeat-hook)
  9803. (setq org-log-post-message msg)
  9804. (message msg))))
  9805. (defun org-show-todo-tree (arg)
  9806. "Make a compact tree which shows all headlines marked with TODO.
  9807. The tree will show the lines where the regexp matches, and all higher
  9808. headlines above the match.
  9809. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9810. With a numeric prefix N, construct a sparse tree for the Nth element
  9811. of `org-todo-keywords-1'."
  9812. (interactive "P")
  9813. (let ((case-fold-search nil)
  9814. (kwd-re
  9815. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9816. ((equal arg '(4))
  9817. (let ((kwd
  9818. (completing-read "Keyword (or KWD1|KWD2|...): "
  9819. (mapcar #'list org-todo-keywords-1))))
  9820. (concat "\\("
  9821. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9822. "\\)\\>")))
  9823. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9824. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9825. org-todo-keywords-1)))
  9826. (t (user-error "Invalid prefix argument: %s" arg)))))
  9827. (message "%d TODO entries found"
  9828. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9829. (defun org--deadline-or-schedule (arg type time)
  9830. "Insert DEADLINE or SCHEDULE information in current entry.
  9831. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9832. `org-schedule' for information about ARG and TIME arguments."
  9833. (let* ((deadline? (eq type 'deadline))
  9834. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9835. (log (if deadline? org-log-redeadline org-log-reschedule))
  9836. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9837. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9838. ;; Save repeater cookie from either TIME or current scheduled
  9839. ;; time stamp. We are going to insert it back at the end of
  9840. ;; the process.
  9841. (repeater (or (and (org-string-nw-p time)
  9842. ;; We use `org-repeat-re' because we need
  9843. ;; to tell the difference between a real
  9844. ;; repeater and a time delta, e.g. "+2d".
  9845. (string-match org-repeat-re time)
  9846. (match-string 1 time))
  9847. (and (org-string-nw-p old-date)
  9848. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9849. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9850. old-date)
  9851. (match-string 1 old-date)))))
  9852. (pcase arg
  9853. (`(4)
  9854. (if (not old-date)
  9855. (message (if deadline? "Entry had no deadline to remove"
  9856. "Entry was not scheduled"))
  9857. (when (and old-date log)
  9858. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9859. nil old-date log))
  9860. (org-remove-timestamp-with-keyword keyword)
  9861. (message (if deadline? "Entry no longer has a deadline."
  9862. "Entry is no longer scheduled."))))
  9863. (`(16)
  9864. (save-excursion
  9865. (org-back-to-heading t)
  9866. (let ((regexp (if deadline? org-deadline-time-regexp
  9867. org-scheduled-time-regexp)))
  9868. (if (not (re-search-forward regexp (line-end-position 2) t))
  9869. (user-error (if deadline? "No deadline information to update"
  9870. "No scheduled information to update"))
  9871. (let* ((rpl0 (match-string 1))
  9872. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9873. (msg (if deadline? "Warn starting from" "Delay until")))
  9874. (replace-match
  9875. (concat keyword
  9876. " <" rpl
  9877. (format " -%dd"
  9878. (abs (- (time-to-days
  9879. (save-match-data
  9880. (org-read-date
  9881. nil t nil msg old-date-time)))
  9882. (time-to-days old-date-time))))
  9883. ">") t t))))))
  9884. (_
  9885. (org-add-planning-info type time 'closed)
  9886. (when (and old-date
  9887. log
  9888. (not (equal old-date org-last-inserted-timestamp)))
  9889. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9890. org-last-inserted-timestamp
  9891. old-date
  9892. log))
  9893. (when repeater
  9894. (save-excursion
  9895. (org-back-to-heading t)
  9896. (when (re-search-forward
  9897. (concat keyword " " org-last-inserted-timestamp)
  9898. (line-end-position 2)
  9899. t)
  9900. (goto-char (1- (match-end 0)))
  9901. (insert " " repeater)
  9902. (setq org-last-inserted-timestamp
  9903. (concat (substring org-last-inserted-timestamp 0 -1)
  9904. " " repeater
  9905. (substring org-last-inserted-timestamp -1))))))
  9906. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9907. org-last-inserted-timestamp)))))
  9908. (defun org-deadline (arg &optional time)
  9909. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9910. With one universal prefix argument, remove any deadline from the item.
  9911. With two universal prefix arguments, prompt for a warning delay.
  9912. With argument TIME, set the deadline at the corresponding date. TIME
  9913. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9914. (interactive "P")
  9915. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9916. (org-map-entries
  9917. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9918. nil
  9919. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9920. 'region-start-level
  9921. 'region)
  9922. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9923. (org--deadline-or-schedule arg 'deadline time)))
  9924. (defun org-schedule (arg &optional time)
  9925. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9926. With one universal prefix argument, remove any scheduling date from the item.
  9927. With two universal prefix arguments, prompt for a delay cookie.
  9928. With argument TIME, scheduled at the corresponding date. TIME can
  9929. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9930. (interactive "P")
  9931. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9932. (org-map-entries
  9933. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9934. nil
  9935. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9936. 'region-start-level
  9937. 'region)
  9938. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9939. (org--deadline-or-schedule arg 'scheduled time)))
  9940. (defun org-get-scheduled-time (pom &optional inherit)
  9941. "Get the scheduled time as a time tuple, of a format suitable
  9942. for calling org-schedule with, or if there is no scheduling,
  9943. returns nil."
  9944. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9945. (when time
  9946. (org-time-string-to-time time))))
  9947. (defun org-get-deadline-time (pom &optional inherit)
  9948. "Get the deadline as a time tuple, of a format suitable for
  9949. calling org-deadline with, or if there is no scheduling, returns
  9950. nil."
  9951. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9952. (when time
  9953. (org-time-string-to-time time))))
  9954. (defun org-remove-timestamp-with-keyword (keyword)
  9955. "Remove all time stamps with KEYWORD in the current entry."
  9956. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9957. beg)
  9958. (save-excursion
  9959. (org-back-to-heading t)
  9960. (setq beg (point))
  9961. (outline-next-heading)
  9962. (while (re-search-backward re beg t)
  9963. (replace-match "")
  9964. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9965. (equal (char-before) ?\ ))
  9966. (backward-delete-char 1)
  9967. (when (string-match "^[ \t]*$" (buffer-substring
  9968. (point-at-bol) (point-at-eol)))
  9969. (delete-region (point-at-bol)
  9970. (min (point-max) (1+ (point-at-eol))))))))))
  9971. (defvar org-time-was-given) ; dynamically scoped parameter
  9972. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9973. (defun org-at-planning-p ()
  9974. "Non-nil when point is on a planning info line."
  9975. ;; This is as accurate and faster than `org-element-at-point' since
  9976. ;; planning info location is fixed in the section.
  9977. (org-with-wide-buffer
  9978. (beginning-of-line)
  9979. (and (looking-at-p org-planning-line-re)
  9980. (eq (point)
  9981. (ignore-errors
  9982. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9983. (org-back-to-heading t)
  9984. (org-with-limited-levels (org-back-to-heading t)))
  9985. (line-beginning-position 2))))))
  9986. (defun org-add-planning-info (what &optional time &rest remove)
  9987. "Insert new timestamp with keyword in the planning line.
  9988. WHAT indicates what kind of time stamp to add. It is a symbol
  9989. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9990. the time to use. If none is given, the user is prompted for
  9991. a date. REMOVE indicates what kind of entries to remove. An old
  9992. WHAT entry will also be removed."
  9993. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9994. (catch 'exit
  9995. (when (and (memq what '(scheduled deadline))
  9996. (or (not time)
  9997. (and (stringp time)
  9998. (string-match "^[-+]+[0-9]" time))))
  9999. ;; Try to get a default date/time from existing timestamp
  10000. (save-excursion
  10001. (org-back-to-heading t)
  10002. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10003. (when (re-search-forward (if (eq what 'scheduled)
  10004. org-scheduled-time-regexp
  10005. org-deadline-time-regexp)
  10006. end t)
  10007. (setq ts (match-string 1)
  10008. default-time (org-time-string-to-time ts)
  10009. default-input (and ts (org-get-compact-tod ts)))))))
  10010. (when what
  10011. (setq time
  10012. (if (stringp time)
  10013. ;; This is a string (relative or absolute), set
  10014. ;; proper date.
  10015. (apply #'encode-time
  10016. (org-read-date-analyze
  10017. time default-time (decode-time default-time)))
  10018. ;; If necessary, get the time from the user
  10019. (or time (org-read-date nil 'to-time nil
  10020. (cl-case what
  10021. (deadline "DEADLINE")
  10022. (scheduled "SCHEDULED")
  10023. (otherwise nil))
  10024. default-time default-input)))))
  10025. (org-with-wide-buffer
  10026. (org-back-to-heading t)
  10027. (forward-line)
  10028. (unless (bolp) (insert "\n"))
  10029. (cond ((looking-at-p org-planning-line-re)
  10030. ;; Move to current indentation.
  10031. (skip-chars-forward " \t")
  10032. ;; Check if we have to remove something.
  10033. (dolist (type (if what (cons what remove) remove))
  10034. (save-excursion
  10035. (when (re-search-forward
  10036. (cl-case type
  10037. (closed org-closed-time-regexp)
  10038. (deadline org-deadline-time-regexp)
  10039. (scheduled org-scheduled-time-regexp)
  10040. (otherwise
  10041. (error "Invalid planning type: %s" type)))
  10042. (line-end-position) t)
  10043. ;; Delete until next keyword or end of line.
  10044. (delete-region
  10045. (match-beginning 0)
  10046. (if (re-search-forward org-keyword-time-not-clock-regexp
  10047. (line-end-position)
  10048. t)
  10049. (match-beginning 0)
  10050. (line-end-position))))))
  10051. ;; If there is nothing more to add and no more keyword
  10052. ;; is left, remove the line completely.
  10053. (if (and (looking-at-p "[ \t]*$") (not what))
  10054. (delete-region (line-beginning-position)
  10055. (line-beginning-position 2))
  10056. ;; If we removed last keyword, do not leave trailing
  10057. ;; white space at the end of line.
  10058. (let ((p (point)))
  10059. (save-excursion
  10060. (end-of-line)
  10061. (unless (= (skip-chars-backward " \t" p) 0)
  10062. (delete-region (point) (line-end-position)))))))
  10063. ((not what) (throw 'exit nil)) ; Nothing to do.
  10064. (t (insert-before-markers "\n")
  10065. (backward-char 1)
  10066. (when org-adapt-indentation
  10067. (indent-to-column (1+ (org-outline-level))))))
  10068. (when what
  10069. ;; Insert planning keyword.
  10070. (insert (cl-case what
  10071. (closed org-closed-string)
  10072. (deadline org-deadline-string)
  10073. (scheduled org-scheduled-string)
  10074. (otherwise (error "Invalid planning type: %s" what)))
  10075. " ")
  10076. ;; Insert associated timestamp.
  10077. (let ((ts (org-insert-time-stamp
  10078. time
  10079. (or org-time-was-given
  10080. (and (eq what 'closed) org-log-done-with-time))
  10081. (eq what 'closed)
  10082. nil nil (list org-end-time-was-given))))
  10083. (unless (eolp) (insert " "))
  10084. ts))))))
  10085. (defvar org-log-note-marker (make-marker)
  10086. "Marker pointing at the entry where the note is to be inserted.")
  10087. (defvar org-log-note-purpose nil)
  10088. (defvar org-log-note-state nil)
  10089. (defvar org-log-note-previous-state nil)
  10090. (defvar org-log-note-extra nil)
  10091. (defvar org-log-note-window-configuration nil)
  10092. (defvar org-log-note-return-to (make-marker))
  10093. (defvar org-log-note-effective-time nil
  10094. "Remembered current time so that dynamically scoped
  10095. `org-extend-today-until' affects timestamps in state change log")
  10096. (defvar org-log-post-message nil
  10097. "Message to be displayed after a log note has been stored.
  10098. The auto-repeater uses this.")
  10099. (defun org-add-note ()
  10100. "Add a note to the current entry.
  10101. This is done in the same way as adding a state change note."
  10102. (interactive)
  10103. (org-add-log-setup 'note))
  10104. (defun org-log-beginning (&optional create)
  10105. "Return expected start of log notes in current entry.
  10106. When optional argument CREATE is non-nil, the function creates
  10107. a drawer to store notes, if necessary. Returned position ignores
  10108. narrowing."
  10109. (org-with-wide-buffer
  10110. (let ((drawer (org-log-into-drawer)))
  10111. (cond
  10112. (drawer
  10113. (org-end-of-meta-data)
  10114. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10115. (end (if (org-at-heading-p) (point)
  10116. (save-excursion (outline-next-heading) (point))))
  10117. (case-fold-search t))
  10118. (catch 'exit
  10119. ;; Try to find existing drawer.
  10120. (while (re-search-forward regexp end t)
  10121. (let ((element (org-element-at-point)))
  10122. (when (eq (org-element-type element) 'drawer)
  10123. (let ((cend (org-element-property :contents-end element)))
  10124. (when (and (not org-log-states-order-reversed) cend)
  10125. (goto-char cend)))
  10126. (throw 'exit nil))))
  10127. ;; No drawer found. Create one, if permitted.
  10128. (when create
  10129. (unless (bolp) (insert "\n"))
  10130. (let ((beg (point)))
  10131. (insert ":" drawer ":\n:END:\n")
  10132. (org-indent-region beg (point))
  10133. (org-flag-region
  10134. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10135. (end-of-line -1)))))
  10136. (t
  10137. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10138. (skip-chars-forward " \t\n")
  10139. (beginning-of-line)
  10140. (unless org-log-states-order-reversed
  10141. (org-skip-over-state-notes)
  10142. (skip-chars-backward " \t\n")
  10143. (forward-line)))))
  10144. (if (bolp) (point) (line-beginning-position 2))))
  10145. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10146. "Set up the post command hook to take a note.
  10147. If this is about to TODO state change, the new state is expected in STATE.
  10148. HOW is an indicator what kind of note should be created.
  10149. EXTRA is additional text that will be inserted into the notes buffer."
  10150. (move-marker org-log-note-marker (point))
  10151. (setq org-log-note-purpose purpose
  10152. org-log-note-state state
  10153. org-log-note-previous-state prev-state
  10154. org-log-note-how how
  10155. org-log-note-extra extra
  10156. org-log-note-effective-time (org-current-effective-time))
  10157. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10158. (defun org-skip-over-state-notes ()
  10159. "Skip past the list of State notes in an entry."
  10160. (when (ignore-errors (goto-char (org-in-item-p)))
  10161. (let* ((struct (org-list-struct))
  10162. (prevs (org-list-prevs-alist struct))
  10163. (regexp
  10164. (concat "[ \t]*- +"
  10165. (replace-regexp-in-string
  10166. " +" " +"
  10167. (org-replace-escapes
  10168. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10169. `(("%d" . ,org-ts-regexp-inactive)
  10170. ("%D" . ,org-ts-regexp)
  10171. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10172. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10173. ("%t" . ,org-ts-regexp-inactive)
  10174. ("%T" . ,org-ts-regexp)
  10175. ("%u" . ".*?")
  10176. ("%U" . ".*?")))))))
  10177. (while (looking-at-p regexp)
  10178. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10179. (org-list-get-item-end (point) struct)))))))
  10180. (defun org-add-log-note (&optional _purpose)
  10181. "Pop up a window for taking a note, and add this note later."
  10182. (remove-hook 'post-command-hook 'org-add-log-note)
  10183. (setq org-log-note-window-configuration (current-window-configuration))
  10184. (delete-other-windows)
  10185. (move-marker org-log-note-return-to (point))
  10186. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10187. (goto-char org-log-note-marker)
  10188. (org-switch-to-buffer-other-window "*Org Note*")
  10189. (erase-buffer)
  10190. (if (memq org-log-note-how '(time state))
  10191. (org-store-log-note)
  10192. (let ((org-inhibit-startup t)) (org-mode))
  10193. (insert (format "# Insert note for %s.
  10194. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10195. (cl-case org-log-note-purpose
  10196. (clock-out "stopped clock")
  10197. (done "closed todo item")
  10198. (reschedule "rescheduling")
  10199. (delschedule "no longer scheduled")
  10200. (redeadline "changing deadline")
  10201. (deldeadline "removing deadline")
  10202. (refile "refiling")
  10203. (note "this entry")
  10204. (state
  10205. (format "state change from \"%s\" to \"%s\""
  10206. (or org-log-note-previous-state "")
  10207. (or org-log-note-state "")))
  10208. (t (error "This should not happen")))))
  10209. (when org-log-note-extra (insert org-log-note-extra))
  10210. (setq-local org-finish-function 'org-store-log-note)
  10211. (run-hooks 'org-log-buffer-setup-hook)))
  10212. (defvar org-note-abort nil) ; dynamically scoped
  10213. (defun org-store-log-note ()
  10214. "Finish taking a log note, and insert it to where it belongs."
  10215. (let ((txt (prog1 (buffer-string)
  10216. (kill-buffer)))
  10217. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10218. lines)
  10219. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10220. (setq txt (replace-match "" t t txt)))
  10221. (when (string-match "\\s-+\\'" txt)
  10222. (setq txt (replace-match "" t t txt)))
  10223. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10224. (when (org-string-nw-p note)
  10225. (setq note
  10226. (org-replace-escapes
  10227. note
  10228. (list (cons "%u" (user-login-name))
  10229. (cons "%U" user-full-name)
  10230. (cons "%t" (format-time-string
  10231. (org-time-stamp-format 'long 'inactive)
  10232. org-log-note-effective-time))
  10233. (cons "%T" (format-time-string
  10234. (org-time-stamp-format 'long nil)
  10235. org-log-note-effective-time))
  10236. (cons "%d" (format-time-string
  10237. (org-time-stamp-format nil 'inactive)
  10238. org-log-note-effective-time))
  10239. (cons "%D" (format-time-string
  10240. (org-time-stamp-format nil nil)
  10241. org-log-note-effective-time))
  10242. (cons "%s" (cond
  10243. ((not org-log-note-state) "")
  10244. ((string-match-p org-ts-regexp
  10245. org-log-note-state)
  10246. (format "\"[%s]\""
  10247. (substring org-log-note-state 1 -1)))
  10248. (t (format "\"%s\"" org-log-note-state))))
  10249. (cons "%S"
  10250. (cond
  10251. ((not org-log-note-previous-state) "")
  10252. ((string-match-p org-ts-regexp
  10253. org-log-note-previous-state)
  10254. (format "\"[%s]\""
  10255. (substring
  10256. org-log-note-previous-state 1 -1)))
  10257. (t (format "\"%s\""
  10258. org-log-note-previous-state)))))))
  10259. (when lines (setq note (concat note " \\\\")))
  10260. (push note lines))
  10261. (when (and lines (not org-note-abort))
  10262. (with-current-buffer (marker-buffer org-log-note-marker)
  10263. (org-with-wide-buffer
  10264. ;; Find location for the new note.
  10265. (goto-char org-log-note-marker)
  10266. (set-marker org-log-note-marker nil)
  10267. ;; Note associated to a clock is to be located right after
  10268. ;; the clock. Do not move point.
  10269. (unless (eq org-log-note-purpose 'clock-out)
  10270. (goto-char (org-log-beginning t)))
  10271. ;; Make sure point is at the beginning of an empty line.
  10272. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10273. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10274. ;; In an existing list, add a new item at the top level.
  10275. ;; Otherwise, indent line like a regular one.
  10276. (let ((itemp (org-in-item-p)))
  10277. (if itemp
  10278. (indent-line-to
  10279. (let ((struct (save-excursion
  10280. (goto-char itemp) (org-list-struct))))
  10281. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10282. (org-indent-line)))
  10283. (insert (org-list-bullet-string "-") (pop lines))
  10284. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10285. (dolist (line lines)
  10286. (insert "\n")
  10287. (indent-line-to ind)
  10288. (insert line)))
  10289. (message "Note stored")
  10290. (org-back-to-heading t))
  10291. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10292. ;; from within `org-add-log-note' because `buffer-undo-list'
  10293. ;; is then modified outside of `org-with-remote-undo'.
  10294. (when (eq this-command 'org-agenda-todo)
  10295. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10296. ;; Don't add undo information when called from `org-agenda-todo'.
  10297. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10298. (set-window-configuration org-log-note-window-configuration)
  10299. (with-current-buffer (marker-buffer org-log-note-return-to)
  10300. (goto-char org-log-note-return-to))
  10301. (move-marker org-log-note-return-to nil)
  10302. (when org-log-post-message (message "%s" org-log-post-message))))
  10303. (defun org-remove-empty-drawer-at (pos)
  10304. "Remove an empty drawer at position POS.
  10305. POS may also be a marker."
  10306. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10307. (org-with-wide-buffer
  10308. (goto-char pos)
  10309. (let ((drawer (org-element-at-point)))
  10310. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10311. (not (org-element-property :contents-begin drawer)))
  10312. (delete-region (org-element-property :begin drawer)
  10313. (progn (goto-char (org-element-property :end drawer))
  10314. (skip-chars-backward " \r\t\n")
  10315. (forward-line)
  10316. (point))))))))
  10317. (defvar org-ts-type nil)
  10318. (defun org-sparse-tree (&optional arg type)
  10319. "Create a sparse tree, prompt for the details.
  10320. This command can create sparse trees. You first need to select the type
  10321. of match used to create the tree:
  10322. t Show all TODO entries.
  10323. T Show entries with a specific TODO keyword.
  10324. m Show entries selected by a tags/property match.
  10325. p Enter a property name and its value (both with completion on existing
  10326. names/values) and show entries with that property.
  10327. r Show entries matching a regular expression (`/' can be used as well).
  10328. b Show deadlines and scheduled items before a date.
  10329. a Show deadlines and scheduled items after a date.
  10330. d Show deadlines due within `org-deadline-warning-days'.
  10331. D Show deadlines and scheduled items between a date range."
  10332. (interactive "P")
  10333. (setq type (or type org-sparse-tree-default-date-type))
  10334. (setq org-ts-type type)
  10335. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10336. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10337. \[c]ycle through date types: %s"
  10338. (cl-case type
  10339. (all "all timestamps")
  10340. (scheduled "only scheduled")
  10341. (deadline "only deadline")
  10342. (active "only active timestamps")
  10343. (inactive "only inactive timestamps")
  10344. (closed "with a closed time-stamp")
  10345. (otherwise "scheduled/deadline")))
  10346. (let ((answer (read-char-exclusive)))
  10347. (cl-case answer
  10348. (?c
  10349. (org-sparse-tree
  10350. arg
  10351. (cadr
  10352. (memq type '(nil all scheduled deadline active inactive closed)))))
  10353. (?d (call-interactively 'org-check-deadlines))
  10354. (?b (call-interactively 'org-check-before-date))
  10355. (?a (call-interactively 'org-check-after-date))
  10356. (?D (call-interactively 'org-check-dates-range))
  10357. (?t (call-interactively 'org-show-todo-tree))
  10358. (?T (org-show-todo-tree '(4)))
  10359. (?m (call-interactively 'org-match-sparse-tree))
  10360. ((?p ?P)
  10361. (let* ((kwd (completing-read
  10362. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10363. (value (completing-read
  10364. "Value: " (mapcar #'list (org-property-values kwd)))))
  10365. (unless (string-match "\\`{.*}\\'" value)
  10366. (setq value (concat "\"" value "\"")))
  10367. (org-match-sparse-tree arg (concat kwd "=" value))))
  10368. ((?r ?R ?/) (call-interactively 'org-occur))
  10369. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10370. (defvar-local org-occur-highlights nil
  10371. "List of overlays used for occur matches.")
  10372. (defvar-local org-occur-parameters nil
  10373. "Parameters of the active org-occur calls.
  10374. This is a list, each call to org-occur pushes as cons cell,
  10375. containing the regular expression and the callback, onto the list.
  10376. The list can contain several entries if `org-occur' has been called
  10377. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10378. will only contain one set of parameters. When the highlights are
  10379. removed (for example with `C-c C-c', or with the next edit (depending
  10380. on `org-remove-highlights-with-change'), this variable is emptied
  10381. as well.")
  10382. (defun org-occur (regexp &optional keep-previous callback)
  10383. "Make a compact tree which shows all matches of REGEXP.
  10384. The tree will show the lines where the regexp matches, and any other context
  10385. defined in `org-show-context-detail', which see.
  10386. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10387. done by a previous call to `org-occur' will be kept, to allow stacking of
  10388. calls to this command.
  10389. Optional argument CALLBACK can be a function of no argument. In this case,
  10390. it is called with point at the end of the match, match data being set
  10391. accordingly. Current match is shown only if the return value is non-nil.
  10392. The function must neither move point nor alter narrowing."
  10393. (interactive "sRegexp: \nP")
  10394. (when (equal regexp "")
  10395. (user-error "Regexp cannot be empty"))
  10396. (unless keep-previous
  10397. (org-remove-occur-highlights nil nil t))
  10398. (push (cons regexp callback) org-occur-parameters)
  10399. (let ((cnt 0))
  10400. (save-excursion
  10401. (goto-char (point-min))
  10402. (when (or (not keep-previous) ; do not want to keep
  10403. (not org-occur-highlights)) ; no previous matches
  10404. ;; hide everything
  10405. (org-overview))
  10406. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10407. (isearch-no-upper-case-p regexp t)
  10408. org-occur-case-fold-search)))
  10409. (while (re-search-forward regexp nil t)
  10410. (when (or (not callback)
  10411. (save-match-data (funcall callback)))
  10412. (setq cnt (1+ cnt))
  10413. (when org-highlight-sparse-tree-matches
  10414. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10415. (org-show-context 'occur-tree)))))
  10416. (when org-remove-highlights-with-change
  10417. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10418. nil 'local))
  10419. (unless org-sparse-tree-open-archived-trees
  10420. (org-hide-archived-subtrees (point-min) (point-max)))
  10421. (run-hooks 'org-occur-hook)
  10422. (when (called-interactively-p 'interactive)
  10423. (message "%d match(es) for regexp %s" cnt regexp))
  10424. cnt))
  10425. (defun org-occur-next-match (&optional n _reset)
  10426. "Function for `next-error-function' to find sparse tree matches.
  10427. N is the number of matches to move, when negative move backwards.
  10428. This function always goes back to the starting point when no
  10429. match is found."
  10430. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10431. (search-func (if (< n 0)
  10432. 'previous-single-char-property-change
  10433. 'next-single-char-property-change))
  10434. (n (abs n))
  10435. (pos (point))
  10436. p1)
  10437. (catch 'exit
  10438. (while (setq p1 (funcall search-func (point) 'org-type))
  10439. (when (equal p1 limit)
  10440. (goto-char pos)
  10441. (user-error "No more matches"))
  10442. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10443. (setq n (1- n))
  10444. (when (= n 0)
  10445. (goto-char p1)
  10446. (throw 'exit (point))))
  10447. (goto-char p1))
  10448. (goto-char p1)
  10449. (user-error "No more matches"))))
  10450. (defun org-highlight-new-match (beg end)
  10451. "Highlight from BEG to END and mark the highlight is an occur headline."
  10452. (let ((ov (make-overlay beg end)))
  10453. (overlay-put ov 'face 'secondary-selection)
  10454. (overlay-put ov 'org-type 'org-occur)
  10455. (push ov org-occur-highlights)))
  10456. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10457. "Remove the occur highlights from the buffer.
  10458. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10459. from the `before-change-functions' in the current buffer."
  10460. (interactive)
  10461. (unless org-inhibit-highlight-removal
  10462. (mapc #'delete-overlay org-occur-highlights)
  10463. (setq org-occur-highlights nil)
  10464. (setq org-occur-parameters nil)
  10465. (unless noremove
  10466. (remove-hook 'before-change-functions
  10467. 'org-remove-occur-highlights 'local))))
  10468. ;;;; Priorities
  10469. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10470. "Regular expression matching the priority indicator.")
  10471. (defun org-priority-up ()
  10472. "Increase the priority of the current item."
  10473. (interactive)
  10474. (org-priority 'up))
  10475. (defun org-priority-down ()
  10476. "Decrease the priority of the current item."
  10477. (interactive)
  10478. (org-priority 'down))
  10479. (defun org-priority (&optional action show)
  10480. "Change the priority of an item.
  10481. When called interactively with a `\\[universal-argument]' prefix,
  10482. show the priority in the minibuffer instead of changing it.
  10483. When called programmatically, ACTION can be `set', `up', `down',
  10484. or a character."
  10485. (interactive "P")
  10486. (when show
  10487. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10488. ;; passed the SHOW argument should be removed.
  10489. (warn "`org-priority' called with deprecated SHOW argument"))
  10490. (if (equal action '(4))
  10491. (org-show-priority)
  10492. (unless org-enable-priority-commands
  10493. (user-error "Priority commands are disabled"))
  10494. (setq action (or action 'set))
  10495. (let (current new news have remove)
  10496. (save-excursion
  10497. (org-back-to-heading t)
  10498. (when (looking-at org-priority-regexp)
  10499. (setq current (string-to-char (match-string 2))
  10500. have t))
  10501. (cond
  10502. ((eq action 'remove)
  10503. (setq remove t new ?\ ))
  10504. ((or (eq action 'set)
  10505. (integerp action))
  10506. (if (not (eq action 'set))
  10507. (setq new action)
  10508. (message "Priority %c-%c, SPC to remove: "
  10509. org-highest-priority org-lowest-priority)
  10510. (save-match-data
  10511. (setq new (read-char-exclusive))))
  10512. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10513. (= (upcase org-lowest-priority) org-lowest-priority))
  10514. (setq new (upcase new)))
  10515. (cond ((equal new ?\s) (setq remove t))
  10516. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10517. (user-error "Priority must be between `%c' and `%c'"
  10518. org-highest-priority org-lowest-priority))))
  10519. ((eq action 'up)
  10520. (setq new (if have
  10521. (1- current) ; normal cycling
  10522. ;; last priority was empty
  10523. (if (eq last-command this-command)
  10524. org-lowest-priority ; wrap around empty to lowest
  10525. ;; default
  10526. (if org-priority-start-cycle-with-default
  10527. org-default-priority
  10528. (1- org-default-priority))))))
  10529. ((eq action 'down)
  10530. (setq new (if have
  10531. (1+ current) ; normal cycling
  10532. ;; last priority was empty
  10533. (if (eq last-command this-command)
  10534. org-highest-priority ; wrap around empty to highest
  10535. ;; default
  10536. (if org-priority-start-cycle-with-default
  10537. org-default-priority
  10538. (1+ org-default-priority))))))
  10539. (t (user-error "Invalid action")))
  10540. (when (or (< (upcase new) org-highest-priority)
  10541. (> (upcase new) org-lowest-priority))
  10542. (if (and (memq action '(up down))
  10543. (not have) (not (eq last-command this-command)))
  10544. ;; `new' is from default priority
  10545. (error
  10546. "The default can not be set, see `org-default-priority' why")
  10547. ;; normal cycling: `new' is beyond highest/lowest priority
  10548. ;; and is wrapped around to the empty priority
  10549. (setq remove t)))
  10550. (setq news (format "%c" new))
  10551. (if have
  10552. (if remove
  10553. (replace-match "" t t nil 1)
  10554. (replace-match news t t nil 2))
  10555. (if remove
  10556. (user-error "No priority cookie found in line")
  10557. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10558. (if (match-end 2)
  10559. (progn
  10560. (goto-char (match-end 2))
  10561. (insert " [#" news "]"))
  10562. (goto-char (match-beginning 3))
  10563. (insert "[#" news "] "))))
  10564. (org-align-tags))
  10565. (if remove
  10566. (message "Priority removed")
  10567. (message "Priority of current item set to %s" news)))))
  10568. (defun org-show-priority ()
  10569. "Show the priority of the current item.
  10570. This priority is composed of the main priority given with the [#A] cookies,
  10571. and by additional input from the age of a schedules or deadline entry."
  10572. (interactive)
  10573. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10574. (org-get-at-bol 'priority)
  10575. (save-excursion
  10576. (save-match-data
  10577. (beginning-of-line)
  10578. (and (looking-at org-heading-regexp)
  10579. (org-get-priority (match-string 0))))))))
  10580. (message "Priority is %d" (if pri pri -1000))))
  10581. (defun org-get-priority (s)
  10582. "Find priority cookie and return priority."
  10583. (save-match-data
  10584. (if (functionp org-get-priority-function)
  10585. (funcall org-get-priority-function s)
  10586. (if (not (string-match org-priority-regexp s))
  10587. (* 1000 (- org-lowest-priority org-default-priority))
  10588. (* 1000 (- org-lowest-priority
  10589. (string-to-char (match-string 2 s))))))))
  10590. ;;;; Tags
  10591. (defvar org-agenda-archives-mode)
  10592. (defvar org-map-continue-from nil
  10593. "Position from where mapping should continue.
  10594. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10595. (defvar org-scanner-tags nil
  10596. "The current tag list while the tags scanner is running.")
  10597. (defvar org-trust-scanner-tags nil
  10598. "Should `org-get-tags' use the tags for the scanner.
  10599. This is for internal dynamical scoping only.
  10600. When this is non-nil, the function `org-get-tags' will return the value
  10601. of `org-scanner-tags' instead of building the list by itself. This
  10602. can lead to large speed-ups when the tags scanner is used in a file with
  10603. many entries, and when the list of tags is retrieved, for example to
  10604. obtain a list of properties. Building the tags list for each entry in such
  10605. a file becomes an N^2 operation - but with this variable set, it scales
  10606. as N.")
  10607. (defvar org--matcher-tags-todo-only nil)
  10608. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10609. "Scan headline tags with inheritance and produce output ACTION.
  10610. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10611. or `agenda' to produce an entry list for an agenda view. It can also be
  10612. a Lisp form or a function that should be called at each matched headline, in
  10613. this case the return value is a list of all return values from these calls.
  10614. MATCHER is a function accepting three arguments, returning
  10615. a non-nil value whenever a given set of tags qualifies a headline
  10616. for inclusion. See `org-make-tags-matcher' for more information.
  10617. As a special case, it can also be set to t (respectively nil) in
  10618. order to match all (respectively none) headline.
  10619. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10620. included in the output.
  10621. START-LEVEL can be a string with asterisks, reducing the scope to
  10622. headlines matching this string."
  10623. (require 'org-agenda)
  10624. (let* ((re (concat "^"
  10625. (if start-level
  10626. ;; Get the correct level to match
  10627. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10628. org-outline-regexp)
  10629. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10630. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10631. (props (list 'face 'default
  10632. 'done-face 'org-agenda-done
  10633. 'undone-face 'default
  10634. 'mouse-face 'highlight
  10635. 'org-not-done-regexp org-not-done-regexp
  10636. 'org-todo-regexp org-todo-regexp
  10637. 'org-complex-heading-regexp org-complex-heading-regexp
  10638. 'help-echo
  10639. (format "mouse-2 or RET jump to Org file %S"
  10640. (abbreviate-file-name
  10641. (or (buffer-file-name (buffer-base-buffer))
  10642. (buffer-name (buffer-base-buffer)))))))
  10643. (org-map-continue-from nil)
  10644. lspos tags tags-list
  10645. (tags-alist (list (cons 0 org-file-tags)))
  10646. (llast 0) rtn rtn1 level category i txt
  10647. todo marker entry priority
  10648. ts-date ts-date-type ts-date-pair)
  10649. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10650. (setq action (list 'lambda nil action)))
  10651. (save-excursion
  10652. (goto-char (point-min))
  10653. (when (eq action 'sparse-tree)
  10654. (org-overview)
  10655. (org-remove-occur-highlights))
  10656. (while (let (case-fold-search)
  10657. (re-search-forward re nil t))
  10658. (setq org-map-continue-from nil)
  10659. (catch :skip
  10660. ;; Ignore closing parts of inline tasks.
  10661. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10662. (throw :skip t))
  10663. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10664. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10665. (goto-char (setq lspos (match-beginning 0)))
  10666. (setq level (org-reduced-level (org-outline-level))
  10667. category (org-get-category))
  10668. (when (eq action 'agenda)
  10669. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10670. ts-date (car ts-date-pair)
  10671. ts-date-type (cdr ts-date-pair)))
  10672. (setq i llast llast level)
  10673. ;; remove tag lists from same and sublevels
  10674. (while (>= i level)
  10675. (when (setq entry (assoc i tags-alist))
  10676. (setq tags-alist (delete entry tags-alist)))
  10677. (setq i (1- i)))
  10678. ;; add the next tags
  10679. (when tags
  10680. (setq tags (org-split-string tags ":")
  10681. tags-alist
  10682. (cons (cons level tags) tags-alist)))
  10683. ;; compile tags for current headline
  10684. (setq tags-list
  10685. (if org-use-tag-inheritance
  10686. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10687. tags)
  10688. org-scanner-tags tags-list)
  10689. (when org-use-tag-inheritance
  10690. (setcdr (car tags-alist)
  10691. (mapcar (lambda (x)
  10692. (setq x (copy-sequence x))
  10693. (org-add-prop-inherited x))
  10694. (cdar tags-alist))))
  10695. (when (and tags org-use-tag-inheritance
  10696. (or (not (eq t org-use-tag-inheritance))
  10697. org-tags-exclude-from-inheritance))
  10698. ;; Selective inheritance, remove uninherited ones.
  10699. (setcdr (car tags-alist)
  10700. (org-remove-uninherited-tags (cdar tags-alist))))
  10701. (when (and
  10702. ;; eval matcher only when the todo condition is OK
  10703. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10704. (if (functionp matcher)
  10705. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10706. (funcall matcher todo tags-list level))
  10707. matcher))
  10708. ;; Call the skipper, but return t if it does not
  10709. ;; skip, so that the `and' form continues evaluating.
  10710. (progn
  10711. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10712. t)
  10713. ;; Check if timestamps are deselecting this entry
  10714. (or (not todo-only)
  10715. (and (member todo org-todo-keywords-1)
  10716. (or (not org-agenda-tags-todo-honor-ignore-options)
  10717. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10718. ;; select this headline
  10719. (cond
  10720. ((eq action 'sparse-tree)
  10721. (and org-highlight-sparse-tree-matches
  10722. (org-get-heading) (match-end 0)
  10723. (org-highlight-new-match
  10724. (match-beginning 1) (match-end 1)))
  10725. (org-show-context 'tags-tree))
  10726. ((eq action 'agenda)
  10727. (setq txt (org-agenda-format-item
  10728. ""
  10729. (concat
  10730. (if (eq org-tags-match-list-sublevels 'indented)
  10731. (make-string (1- level) ?.) "")
  10732. (org-get-heading))
  10733. (make-string level ?\s)
  10734. category
  10735. tags-list)
  10736. priority (org-get-priority txt))
  10737. (goto-char lspos)
  10738. (setq marker (org-agenda-new-marker))
  10739. (org-add-props txt props
  10740. 'org-marker marker 'org-hd-marker marker 'org-category category
  10741. 'todo-state todo
  10742. 'ts-date ts-date
  10743. 'priority priority
  10744. 'type (concat "tagsmatch" ts-date-type))
  10745. (push txt rtn))
  10746. ((functionp action)
  10747. (setq org-map-continue-from nil)
  10748. (save-excursion
  10749. (setq rtn1 (funcall action))
  10750. (push rtn1 rtn)))
  10751. (t (user-error "Invalid action")))
  10752. ;; if we are to skip sublevels, jump to end of subtree
  10753. (unless org-tags-match-list-sublevels
  10754. (org-end-of-subtree t)
  10755. (backward-char 1))))
  10756. ;; Get the correct position from where to continue
  10757. (if org-map-continue-from
  10758. (goto-char org-map-continue-from)
  10759. (and (= (point) lspos) (end-of-line 1)))))
  10760. (when (and (eq action 'sparse-tree)
  10761. (not org-sparse-tree-open-archived-trees))
  10762. (org-hide-archived-subtrees (point-min) (point-max)))
  10763. (nreverse rtn)))
  10764. (defun org-remove-uninherited-tags (tags)
  10765. "Remove all tags that are not inherited from the list TAGS."
  10766. (cond
  10767. ((eq org-use-tag-inheritance t)
  10768. (if org-tags-exclude-from-inheritance
  10769. (org-delete-all org-tags-exclude-from-inheritance tags)
  10770. tags))
  10771. ((not org-use-tag-inheritance) nil)
  10772. ((stringp org-use-tag-inheritance)
  10773. (delq nil (mapcar
  10774. (lambda (x)
  10775. (if (and (string-match org-use-tag-inheritance x)
  10776. (not (member x org-tags-exclude-from-inheritance)))
  10777. x nil))
  10778. tags)))
  10779. ((listp org-use-tag-inheritance)
  10780. (delq nil (mapcar
  10781. (lambda (x)
  10782. (if (member x org-use-tag-inheritance) x nil))
  10783. tags)))))
  10784. (defun org-match-sparse-tree (&optional todo-only match)
  10785. "Create a sparse tree according to tags string MATCH.
  10786. MATCH is a string with match syntax. It can contain a selection
  10787. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10788. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10789. those. See the manual for details.
  10790. If optional argument TODO-ONLY is non-nil, only select lines that
  10791. are also TODO tasks."
  10792. (interactive "P")
  10793. (org-agenda-prepare-buffers (list (current-buffer)))
  10794. (let ((org--matcher-tags-todo-only todo-only))
  10795. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10796. org--matcher-tags-todo-only)))
  10797. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10798. (defvar org-cached-props nil)
  10799. (defun org-cached-entry-get (pom property)
  10800. (if (or (eq t org-use-property-inheritance)
  10801. (and (stringp org-use-property-inheritance)
  10802. (let ((case-fold-search t))
  10803. (string-match-p org-use-property-inheritance property)))
  10804. (and (listp org-use-property-inheritance)
  10805. (member-ignore-case property org-use-property-inheritance)))
  10806. ;; Caching is not possible, check it directly.
  10807. (org-entry-get pom property 'inherit)
  10808. ;; Get all properties, so we can do complicated checks easily.
  10809. (cdr (assoc-string property
  10810. (or org-cached-props
  10811. (setq org-cached-props (org-entry-properties pom)))
  10812. t))))
  10813. (defun org-global-tags-completion-table (&optional files)
  10814. "Return the list of all tags in all agenda buffer/files.
  10815. Optional FILES argument is a list of files which can be used
  10816. instead of the agenda files."
  10817. (save-excursion
  10818. (org-uniquify
  10819. (delq nil
  10820. (apply #'append
  10821. (mapcar
  10822. (lambda (file)
  10823. (set-buffer (find-file-noselect file))
  10824. (org--tag-add-to-alist
  10825. (org-get-buffer-tags)
  10826. (mapcar (lambda (x)
  10827. (and (stringp (car-safe x))
  10828. (list (car-safe x))))
  10829. org-current-tag-alist)))
  10830. (if (car-safe files) files
  10831. (org-agenda-files))))))))
  10832. (defun org-make-tags-matcher (match)
  10833. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10834. Returns a cons of the selection string MATCH and a function
  10835. implementing the matcher.
  10836. The matcher is to be called at an Org entry, with point on the
  10837. headline, and returns non-nil if the entry matches the selection
  10838. string MATCH. It must be called with three arguments: the TODO
  10839. keyword at the entry (or nil if none), the list of all tags at
  10840. the entry including inherited ones and the reduced level of the
  10841. headline. Additionally, the category of the entry, if any, must
  10842. be specified as the text property `org-category' on the headline.
  10843. This function sets the variable `org--matcher-tags-todo-only' to
  10844. a non-nil value if the matcher restricts matching to TODO
  10845. entries, otherwise it is not touched.
  10846. See also `org-scan-tags'."
  10847. (unless match
  10848. ;; Get a new match request, with completion against the global
  10849. ;; tags table and the local tags in current buffer.
  10850. (let ((org-last-tags-completion-table
  10851. (org--tag-add-to-alist
  10852. (org-get-buffer-tags)
  10853. (org-global-tags-completion-table))))
  10854. (setq match
  10855. (completing-read
  10856. "Match: "
  10857. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10858. (let ((match0 match)
  10859. (re (concat
  10860. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10861. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10862. "\\([<>=]\\{1,2\\}\\)"
  10863. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10864. "\\|" org-tag-re "\\)"))
  10865. (start 0)
  10866. tagsmatch todomatch tagsmatcher todomatcher)
  10867. ;; Expand group tags.
  10868. (setq match (org-tags-expand match))
  10869. ;; Check if there is a TODO part of this match, which would be the
  10870. ;; part after a "/". To make sure that this slash is not part of
  10871. ;; a property value to be matched against, we also check that
  10872. ;; there is no / after that slash. First, find the last slash.
  10873. (let ((s 0))
  10874. (while (string-match "/+" match s)
  10875. (setq start (match-beginning 0))
  10876. (setq s (match-end 0))))
  10877. (if (and (string-match "/+" match start)
  10878. (not (string-match-p "\"" match start)))
  10879. ;; Match contains also a TODO-matching request.
  10880. (progn
  10881. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10882. (setq todomatch (substring match (match-end 0)))
  10883. (when (string-prefix-p "!" todomatch)
  10884. (setq org--matcher-tags-todo-only t)
  10885. (setq todomatch (substring todomatch 1)))
  10886. (when (string-match "\\`\\s-*\\'" todomatch)
  10887. (setq todomatch nil)))
  10888. ;; Only matching tags.
  10889. (setq tagsmatch match)
  10890. (setq todomatch nil))
  10891. ;; Make the tags matcher.
  10892. (when (org-string-nw-p tagsmatch)
  10893. (let ((orlist nil)
  10894. (orterms (org-split-string tagsmatch "|"))
  10895. term)
  10896. (while (setq term (pop orterms))
  10897. (while (and (equal (substring term -1) "\\") orterms)
  10898. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10899. (while (string-match re term)
  10900. (let* ((rest (substring term (match-end 0)))
  10901. (minus (and (match-end 1)
  10902. (equal (match-string 1 term) "-")))
  10903. (tag (save-match-data
  10904. (replace-regexp-in-string
  10905. "\\\\-" "-" (match-string 2 term))))
  10906. (regexp (eq (string-to-char tag) ?{))
  10907. (levelp (match-end 4))
  10908. (propp (match-end 5))
  10909. (mm
  10910. (cond
  10911. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10912. (levelp
  10913. `(,(org-op-to-function (match-string 3 term))
  10914. level
  10915. ,(string-to-number (match-string 4 term))))
  10916. (propp
  10917. (let* ((gv (pcase (upcase (match-string 5 term))
  10918. ("CATEGORY"
  10919. '(get-text-property (point) 'org-category))
  10920. ("TODO" 'todo)
  10921. (p `(org-cached-entry-get nil ,p))))
  10922. (pv (match-string 7 term))
  10923. (regexp (eq (string-to-char pv) ?{))
  10924. (strp (eq (string-to-char pv) ?\"))
  10925. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10926. (po (org-op-to-function (match-string 6 term)
  10927. (if timep 'time strp))))
  10928. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10929. (when timep (setq pv (org-matcher-time pv)))
  10930. (cond ((and regexp (eq po '/=))
  10931. `(not (string-match ,pv (or ,gv ""))))
  10932. (regexp `(string-match ,pv (or ,gv "")))
  10933. (strp `(,po (or ,gv "") ,pv))
  10934. (t
  10935. `(,po
  10936. (string-to-number (or ,gv ""))
  10937. ,(string-to-number pv))))))
  10938. (t `(member ,tag tags-list)))))
  10939. (push (if minus `(not ,mm) mm) tagsmatcher)
  10940. (setq term rest)))
  10941. (push `(and ,@tagsmatcher) orlist)
  10942. (setq tagsmatcher nil))
  10943. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10944. ;; Make the TODO matcher.
  10945. (when (org-string-nw-p todomatch)
  10946. (let ((orlist nil))
  10947. (dolist (term (org-split-string todomatch "|"))
  10948. (while (string-match re term)
  10949. (let* ((minus (and (match-end 1)
  10950. (equal (match-string 1 term) "-")))
  10951. (kwd (match-string 2 term))
  10952. (regexp (eq (string-to-char kwd) ?{))
  10953. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10954. `(equal todo ,kwd))))
  10955. (push (if minus `(not ,mm) mm) todomatcher))
  10956. (setq term (substring term (match-end 0))))
  10957. (push (if (> (length todomatcher) 1)
  10958. (cons 'and todomatcher)
  10959. (car todomatcher))
  10960. orlist)
  10961. (setq todomatcher nil))
  10962. (setq todomatcher (cons 'or orlist))))
  10963. ;; Return the string and function of the matcher. If no
  10964. ;; tags-specific or todo-specific matcher exists, match
  10965. ;; everything.
  10966. (let ((matcher (if (and tagsmatcher todomatcher)
  10967. `(and ,tagsmatcher ,todomatcher)
  10968. (or tagsmatcher todomatcher t))))
  10969. (when org--matcher-tags-todo-only
  10970. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10971. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10972. (defun org--tags-expand-group (group tag-groups expanded)
  10973. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10974. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10975. an accumulator used in recursive calls."
  10976. (dolist (tag group)
  10977. (unless (member tag expanded)
  10978. (let ((group (assoc tag tag-groups)))
  10979. (push tag expanded)
  10980. (when group
  10981. (setq expanded
  10982. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10983. expanded)
  10984. (defun org-tags-expand (match &optional single-as-list downcased)
  10985. "Expand group tags in MATCH.
  10986. This replaces every group tag in MATCH with a regexp tag search.
  10987. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10988. will be replaced like this:
  10989. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10990. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10991. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10992. Replacing by a regexp preserves the structure of the match.
  10993. E.g., this expansion
  10994. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10995. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10996. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10997. A group tag in MATCH can contain regular expressions of its own.
  10998. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10999. will be replaced like this:
  11000. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11001. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11002. assumed to be a single group tag, and the function will return
  11003. the list of tags in this group.
  11004. When DOWNCASED is non-nil, expand downcased TAGS."
  11005. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11006. (let ((tag-groups
  11007. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11008. (if (not downcased) g
  11009. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  11010. (cond
  11011. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11012. (org-group-tags
  11013. (let* ((case-fold-search t)
  11014. (tag-syntax org-mode-syntax-table)
  11015. (group-keys (mapcar #'car tag-groups))
  11016. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11017. (return-match (if downcased (downcase match) match)))
  11018. ;; Mark regexp-expressions in the match-expression so that we
  11019. ;; do not replace them later on.
  11020. (let ((s 0))
  11021. (while (string-match "{.+?}" return-match s)
  11022. (setq s (match-end 0))
  11023. (add-text-properties
  11024. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11025. ;; @ and _ are allowed as word-components in tags.
  11026. (modify-syntax-entry ?@ "w" tag-syntax)
  11027. (modify-syntax-entry ?_ "w" tag-syntax)
  11028. ;; For each tag token found in MATCH, compute a regexp and it
  11029. (with-syntax-table tag-syntax
  11030. (replace-regexp-in-string
  11031. key-regexp
  11032. (lambda (m)
  11033. (if (get-text-property (match-beginning 2) 'regexp m)
  11034. m ;regexp tag: ignore
  11035. (let* ((operator (match-string 1 m))
  11036. (tag-token (let ((tag (match-string 2 m)))
  11037. (list (if downcased (downcase tag) tag))))
  11038. regexp-tags regular-tags)
  11039. ;; Partition tags between regexp and regular tags.
  11040. ;; Remove curly bracket syntax from regexp tags.
  11041. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11042. (save-match-data
  11043. (if (string-match "{\\(.+?\\)}" tag)
  11044. (push (match-string 1 tag) regexp-tags)
  11045. (push tag regular-tags))))
  11046. ;; Replace tag token by the appropriate regexp.
  11047. ;; Regular tags need to be regexp-quoted, whereas
  11048. ;; regexp-tags are inserted as-is.
  11049. (let ((regular (regexp-opt regular-tags))
  11050. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11051. (concat operator
  11052. (cond
  11053. ((null regular-tags) (format "{%s}" regexp))
  11054. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11055. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11056. return-match
  11057. t t))))
  11058. (t match))))
  11059. (defun org-op-to-function (op &optional stringp)
  11060. "Turn an operator into the appropriate function."
  11061. (setq op
  11062. (cond
  11063. ((equal op "<" ) '(< org-string< org-time<))
  11064. ((equal op ">" ) '(> org-string> org-time>))
  11065. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11066. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11067. ((member op '("=" "==")) '(= string= org-time=))
  11068. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11069. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11070. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11071. (defvar org-tags-overlay (make-overlay 1 1))
  11072. (delete-overlay org-tags-overlay)
  11073. (defun org-add-prop-inherited (s)
  11074. (add-text-properties 0 (length s) '(inherited t) s)
  11075. s)
  11076. (defun org-toggle-tag (tag &optional onoff)
  11077. "Toggle the tag TAG for the current line.
  11078. If ONOFF is `on' or `off', don't toggle but set to this state."
  11079. (save-excursion
  11080. (org-back-to-heading t)
  11081. (let ((current
  11082. ;; Reverse the tags list so any new tag is appended to the
  11083. ;; current list of tags.
  11084. (nreverse (org-get-tags nil t)))
  11085. res)
  11086. (pcase onoff
  11087. (`off (setq current (delete tag current)))
  11088. ((or `on (guard (not (member tag current))))
  11089. (setq res t)
  11090. (cl-pushnew tag current :test #'equal))
  11091. (_ (setq current (delete tag current))))
  11092. (org-set-tags (nreverse current))
  11093. res)))
  11094. (defun org--align-tags-here (to-col)
  11095. "Align tags on the current headline to TO-COL.
  11096. Assume point is on a headline. Preserve point when aligning
  11097. tags."
  11098. (when (org-match-line org-tag-line-re)
  11099. (let* ((tags-start (match-beginning 1))
  11100. (blank-start (save-excursion
  11101. (goto-char tags-start)
  11102. (skip-chars-backward " \t")
  11103. (point)))
  11104. (new (max (if (>= to-col 0) to-col
  11105. (- (abs to-col) (string-width (match-string 1))))
  11106. ;; Introduce at least one space after the heading
  11107. ;; or the stars.
  11108. (save-excursion
  11109. (goto-char blank-start)
  11110. (1+ (current-column)))))
  11111. (current
  11112. (save-excursion (goto-char tags-start) (current-column)))
  11113. (origin (point-marker))
  11114. (column (current-column))
  11115. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11116. (when (/= new current)
  11117. (delete-region blank-start tags-start)
  11118. (goto-char blank-start)
  11119. (let ((indent-tabs-mode nil)) (indent-to new))
  11120. ;; Try to move back to original position. If point was in the
  11121. ;; blanks before the tags, ORIGIN marker is of no use because
  11122. ;; it now points to BLANK-START. Use COLUMN instead.
  11123. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11124. (defun org-set-tags-command (&optional arg)
  11125. "Set the tags for the current visible entry.
  11126. When called with `\\[universal-argument]' prefix argument ARG, \
  11127. realign all tags
  11128. in the current buffer.
  11129. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11130. unconditionally do not
  11131. offer the fast tag selection interface.
  11132. If a region is active, set tags in the region according to the
  11133. setting of `org-loop-over-headlines-in-active-region'.
  11134. This function is for interactive use only;
  11135. in Lisp code use `org-set-tags' instead."
  11136. (interactive "P")
  11137. (let ((org-use-fast-tag-selection
  11138. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11139. (cond
  11140. ((equal '(4) arg) (org-align-tags t))
  11141. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11142. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11143. (org-map-entries
  11144. #'org-set-tags-command
  11145. nil
  11146. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11147. 'region-start-level
  11148. 'region)
  11149. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11150. (t
  11151. (save-excursion
  11152. (org-back-to-heading)
  11153. (let* ((all-tags (org-get-tags))
  11154. (table (setq org-last-tags-completion-table
  11155. (org--tag-add-to-alist
  11156. (and org-complete-tags-always-offer-all-agenda-tags
  11157. (org-global-tags-completion-table
  11158. (org-agenda-files)))
  11159. (or org-current-tag-alist (org-get-buffer-tags)))))
  11160. (current-tags
  11161. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11162. all-tags))
  11163. (inherited-tags
  11164. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11165. all-tags))
  11166. (tags
  11167. (replace-regexp-in-string
  11168. ;; Ignore all forbidden characters in tags.
  11169. "[^[:alnum:]_@#%]+" ":"
  11170. (if (or (eq t org-use-fast-tag-selection)
  11171. (and org-use-fast-tag-selection
  11172. (delq nil (mapcar #'cdr table))))
  11173. (org-fast-tag-selection
  11174. current-tags
  11175. inherited-tags
  11176. table
  11177. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11178. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11179. (org-trim (completing-read
  11180. "Tags: "
  11181. #'org-tags-completion-function
  11182. nil nil (org-make-tag-string current-tags)
  11183. 'org-tags-history)))))))
  11184. (org-set-tags tags)))))
  11185. ;; `save-excursion' may not replace the point at the right
  11186. ;; position.
  11187. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  11188. (looking-at-p " "))
  11189. (forward-char))))
  11190. (defun org-align-tags (&optional all)
  11191. "Align tags in current entry.
  11192. When optional argument ALL is non-nil, align all tags in the
  11193. visible part of the buffer."
  11194. (let ((get-indent-column
  11195. (lambda ()
  11196. (let ((offset (if (bound-and-true-p org-indent-mode)
  11197. (* (1- org-indent-indentation-per-level)
  11198. (1- (org-current-level)))
  11199. 0)))
  11200. (+ org-tags-column
  11201. (if (> org-tags-column 0) (- offset) offset))))))
  11202. (if (and (not all) (org-at-heading-p))
  11203. (org--align-tags-here (funcall get-indent-column))
  11204. (save-excursion
  11205. (if all
  11206. (progn
  11207. (goto-char (point-min))
  11208. (while (re-search-forward org-tag-line-re nil t)
  11209. (org--align-tags-here (funcall get-indent-column))))
  11210. (org-back-to-heading t)
  11211. (org--align-tags-here (funcall get-indent-column)))))))
  11212. (defun org-set-tags (tags)
  11213. "Set the tags of the current entry to TAGS, replacing current tags.
  11214. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11215. If TAGS is nil or the empty string, all tags are removed.
  11216. This function assumes point is on a headline."
  11217. (org-with-wide-buffer
  11218. (let ((tags (pcase tags
  11219. ((pred listp) tags)
  11220. ((pred stringp) (split-string (org-trim tags) ":" t))
  11221. (_ (error "Invalid tag specification: %S" tags))))
  11222. (old-tags (org-get-tags nil t))
  11223. (tags-change? nil))
  11224. (when (functionp org-tags-sort-function)
  11225. (setq tags (sort tags org-tags-sort-function)))
  11226. (setq tags-change? (not (equal tags old-tags)))
  11227. (when tags-change?
  11228. ;; Delete previous tags and any trailing white space.
  11229. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11230. (line-end-position)))
  11231. (skip-chars-backward " \t")
  11232. (delete-region (point) (line-end-position))
  11233. ;; Deleting white spaces may break an otherwise empty headline.
  11234. ;; Re-introduce one space in this case.
  11235. (unless (org-at-heading-p) (insert " "))
  11236. (when tags
  11237. (save-excursion (insert " " (org-make-tag-string tags)))
  11238. ;; When text is being inserted on an invisible region
  11239. ;; boundary, it can be inadvertently sucked into
  11240. ;; invisibility.
  11241. (unless (org-invisible-p (line-beginning-position))
  11242. (org-flag-region (point) (line-end-position) nil 'outline))))
  11243. ;; Align tags, if any.
  11244. (when tags (org-align-tags))
  11245. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11246. (defun org-change-tag-in-region (beg end tag off)
  11247. "Add or remove TAG for each entry in the region.
  11248. This works in the agenda, and also in an Org buffer."
  11249. (interactive
  11250. (list (region-beginning) (region-end)
  11251. (let ((org-last-tags-completion-table
  11252. (if (derived-mode-p 'org-mode)
  11253. (org--tag-add-to-alist
  11254. (org-get-buffer-tags)
  11255. (org-global-tags-completion-table))
  11256. (org-global-tags-completion-table))))
  11257. (completing-read
  11258. "Tag: " 'org-tags-completion-function nil nil nil
  11259. 'org-tags-history))
  11260. (progn
  11261. (message "[s]et or [r]emove? ")
  11262. (equal (read-char-exclusive) ?r))))
  11263. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11264. (let ((agendap (equal major-mode 'org-agenda-mode))
  11265. l1 l2 m buf pos newhead (cnt 0))
  11266. (goto-char end)
  11267. (setq l2 (1- (org-current-line)))
  11268. (goto-char beg)
  11269. (setq l1 (org-current-line))
  11270. (cl-loop for l from l1 to l2 do
  11271. (org-goto-line l)
  11272. (setq m (get-text-property (point) 'org-hd-marker))
  11273. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11274. (and agendap m))
  11275. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11276. pos (if agendap m (point)))
  11277. (with-current-buffer buf
  11278. (save-excursion
  11279. (save-restriction
  11280. (goto-char pos)
  11281. (setq cnt (1+ cnt))
  11282. (org-toggle-tag tag (if off 'off 'on))
  11283. (setq newhead (org-get-heading)))))
  11284. (and agendap (org-agenda-change-all-lines newhead m))))
  11285. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11286. (defun org-tags-completion-function (string _predicate &optional flag)
  11287. "Complete tag STRING.
  11288. FLAG specifies the type of completion operation to perform. This
  11289. function is passed as a collection function to `completing-read',
  11290. which see."
  11291. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11292. (confirm (lambda (x) (stringp (car x))))
  11293. (prefix ""))
  11294. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11295. (setq prefix (match-string 1 string))
  11296. (setq string (match-string 2 string)))
  11297. (pcase flag
  11298. (`t (all-completions string org-last-tags-completion-table confirm))
  11299. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11300. (`nil
  11301. (pcase (try-completion string org-last-tags-completion-table confirm)
  11302. ((and completion (pred stringp))
  11303. (concat prefix
  11304. completion
  11305. (if (and org-add-colon-after-tag-completion
  11306. (assoc completion org-last-tags-completion-table))
  11307. ":"
  11308. "")))
  11309. (completion completion)))
  11310. (_ nil))))
  11311. (defun org-fast-tag-insert (kwd tags face &optional end)
  11312. "Insert KWD, and the TAGS, the latter with face FACE.
  11313. Also insert END."
  11314. (insert (format "%-12s" (concat kwd ":"))
  11315. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11316. (or end "")))
  11317. (defun org-fast-tag-show-exit (flag)
  11318. (save-excursion
  11319. (org-goto-line 3)
  11320. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11321. (replace-match ""))
  11322. (when flag
  11323. (end-of-line 1)
  11324. (org-move-to-column (- (window-width) 19) t)
  11325. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11326. (defun org-set-current-tags-overlay (current prefix)
  11327. "Add an overlay to CURRENT tag with PREFIX."
  11328. (let ((s (org-make-tag-string current)))
  11329. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11330. (org-overlay-display org-tags-overlay (concat prefix s))))
  11331. (defvar org-last-tag-selection-key nil)
  11332. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11333. "Fast tag selection with single keys.
  11334. CURRENT is the current list of tags in the headline, INHERITED is the
  11335. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11336. possibly with grouping information. TODO-TABLE is a similar table with
  11337. TODO keywords, should these have keys assigned to them.
  11338. If the keys are nil, a-z are automatically assigned.
  11339. Returns the new tags string, or nil to not change the current settings."
  11340. (let* ((fulltable (append table todo-table))
  11341. (maxlen (if (null fulltable) 0
  11342. (apply #'max
  11343. (mapcar (lambda (x)
  11344. (if (stringp (car x)) (string-width (car x))
  11345. 0))
  11346. fulltable))))
  11347. (buf (current-buffer))
  11348. (expert (eq org-fast-tag-selection-single-key 'expert))
  11349. (buffer-tags nil)
  11350. (fwidth (+ maxlen 3 1 3))
  11351. (ncol (/ (- (window-width) 4) fwidth))
  11352. (i-face 'org-done)
  11353. (c-face 'org-todo)
  11354. tg cnt e c char c1 c2 ntable tbl rtn
  11355. ov-start ov-end ov-prefix
  11356. (exit-after-next org-fast-tag-selection-single-key)
  11357. (done-keywords org-done-keywords)
  11358. groups ingroup intaggroup)
  11359. (save-excursion
  11360. (beginning-of-line)
  11361. (if (looking-at org-tag-line-re)
  11362. (setq ov-start (match-beginning 1)
  11363. ov-end (match-end 1)
  11364. ov-prefix "")
  11365. (setq ov-start (1- (point-at-eol))
  11366. ov-end (1+ ov-start))
  11367. (skip-chars-forward "^\n\r")
  11368. (setq ov-prefix
  11369. (concat
  11370. (buffer-substring (1- (point)) (point))
  11371. (if (> (current-column) org-tags-column)
  11372. " "
  11373. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11374. (move-overlay org-tags-overlay ov-start ov-end)
  11375. (save-excursion
  11376. (save-window-excursion
  11377. (if expert
  11378. (set-buffer (get-buffer-create " *Org tags*"))
  11379. (delete-other-windows)
  11380. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11381. (org-switch-to-buffer-other-window " *Org tags*"))
  11382. (erase-buffer)
  11383. (setq-local org-done-keywords done-keywords)
  11384. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11385. (org-fast-tag-insert "Current" current c-face "\n\n")
  11386. (org-fast-tag-show-exit exit-after-next)
  11387. (org-set-current-tags-overlay current ov-prefix)
  11388. (setq tbl fulltable char ?a cnt 0)
  11389. (while (setq e (pop tbl))
  11390. (cond
  11391. ((eq (car e) :startgroup)
  11392. (push '() groups) (setq ingroup t)
  11393. (unless (zerop cnt)
  11394. (setq cnt 0)
  11395. (insert "\n"))
  11396. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11397. ((eq (car e) :endgroup)
  11398. (setq ingroup nil cnt 0)
  11399. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11400. ((eq (car e) :startgrouptag)
  11401. (setq intaggroup t)
  11402. (unless (zerop cnt)
  11403. (setq cnt 0)
  11404. (insert "\n"))
  11405. (insert "[ "))
  11406. ((eq (car e) :endgrouptag)
  11407. (setq intaggroup nil cnt 0)
  11408. (insert "]\n"))
  11409. ((equal e '(:newline))
  11410. (unless (zerop cnt)
  11411. (setq cnt 0)
  11412. (insert "\n")
  11413. (setq e (car tbl))
  11414. (while (equal (car tbl) '(:newline))
  11415. (insert "\n")
  11416. (setq tbl (cdr tbl)))))
  11417. ((equal e '(:grouptags)) (insert " : "))
  11418. (t
  11419. (setq tg (copy-sequence (car e)) c2 nil)
  11420. (if (cdr e)
  11421. (setq c (cdr e))
  11422. ;; automatically assign a character.
  11423. (setq c1 (string-to-char
  11424. (downcase (substring
  11425. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11426. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11427. (while (or (rassoc char ntable) (rassoc char table))
  11428. (setq char (1+ char)))
  11429. (setq c2 c1))
  11430. (setq c (or c2 char)))
  11431. (when ingroup (push tg (car groups)))
  11432. (setq tg (org-add-props tg nil 'face
  11433. (cond
  11434. ((not (assoc tg table))
  11435. (org-get-todo-face tg))
  11436. ((member tg current) c-face)
  11437. ((member tg inherited) i-face))))
  11438. (when (equal (caar tbl) :grouptags)
  11439. (org-add-props tg nil 'face 'org-tag-group))
  11440. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11441. (insert "[" c "] " tg (make-string
  11442. (- fwidth 4 (length tg)) ?\ ))
  11443. (push (cons tg c) ntable)
  11444. (when (= (cl-incf cnt) ncol)
  11445. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11446. (insert "\n")
  11447. (when (or ingroup intaggroup) (insert " ")))
  11448. (setq cnt 0)))))
  11449. (setq ntable (nreverse ntable))
  11450. (insert "\n")
  11451. (goto-char (point-min))
  11452. (unless expert (org-fit-window-to-buffer))
  11453. (setq rtn
  11454. (catch 'exit
  11455. (while t
  11456. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11457. (if (not groups) "no " "")
  11458. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11459. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11460. (setq org-last-tag-selection-key c)
  11461. (cond
  11462. ((= c ?\r) (throw 'exit t))
  11463. ((= c ?!)
  11464. (setq groups (not groups))
  11465. (goto-char (point-min))
  11466. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11467. ((= c ?\C-c)
  11468. (if (not expert)
  11469. (org-fast-tag-show-exit
  11470. (setq exit-after-next (not exit-after-next)))
  11471. (setq expert nil)
  11472. (delete-other-windows)
  11473. (set-window-buffer (split-window-vertically) " *Org tags*")
  11474. (org-switch-to-buffer-other-window " *Org tags*")
  11475. (org-fit-window-to-buffer)))
  11476. ((or (= c ?\C-g)
  11477. (and (= c ?q) (not (rassoc c ntable))))
  11478. (delete-overlay org-tags-overlay)
  11479. (setq quit-flag t))
  11480. ((= c ?\ )
  11481. (setq current nil)
  11482. (when exit-after-next (setq exit-after-next 'now)))
  11483. ((= c ?\t)
  11484. (condition-case nil
  11485. (setq tg (completing-read
  11486. "Tag: "
  11487. (or buffer-tags
  11488. (with-current-buffer buf
  11489. (setq buffer-tags
  11490. (org-get-buffer-tags))))))
  11491. (quit (setq tg "")))
  11492. (when (string-match "\\S-" tg)
  11493. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11494. (if (member tg current)
  11495. (setq current (delete tg current))
  11496. (push tg current)))
  11497. (when exit-after-next (setq exit-after-next 'now)))
  11498. ((setq e (rassoc c todo-table) tg (car e))
  11499. (with-current-buffer buf
  11500. (save-excursion (org-todo tg)))
  11501. (when exit-after-next (setq exit-after-next 'now)))
  11502. ((setq e (rassoc c ntable) tg (car e))
  11503. (if (member tg current)
  11504. (setq current (delete tg current))
  11505. (cl-loop for g in groups do
  11506. (when (member tg g)
  11507. (dolist (x g) (setq current (delete x current)))))
  11508. (push tg current))
  11509. (when exit-after-next (setq exit-after-next 'now))))
  11510. ;; Create a sorted list
  11511. (setq current
  11512. (sort current
  11513. (lambda (a b)
  11514. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11515. (when (eq exit-after-next 'now) (throw 'exit t))
  11516. (goto-char (point-min))
  11517. (beginning-of-line 2)
  11518. (delete-region (point) (point-at-eol))
  11519. (org-fast-tag-insert "Current" current c-face)
  11520. (org-set-current-tags-overlay current ov-prefix)
  11521. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11522. (while (re-search-forward tag-re nil t)
  11523. (let ((tag (match-string 1)))
  11524. (add-text-properties
  11525. (match-beginning 1) (match-end 1)
  11526. (list 'face
  11527. (cond
  11528. ((member tag current) c-face)
  11529. ((member tag inherited) i-face)
  11530. (t (get-text-property (match-beginning 1) '
  11531. face))))))))
  11532. (goto-char (point-min)))))
  11533. (delete-overlay org-tags-overlay)
  11534. (if rtn
  11535. (mapconcat 'identity current ":")
  11536. nil)))))
  11537. (defun org-make-tag-string (tags)
  11538. "Return string associated to TAGS.
  11539. TAGS is a list of strings."
  11540. (if (null tags) ""
  11541. (format ":%s:" (mapconcat #'identity tags ":"))))
  11542. (defun org--get-local-tags ()
  11543. "Return list of tags for the current headline.
  11544. Assume point is at the beginning of the headline."
  11545. (and (looking-at org-tag-line-re)
  11546. (split-string (match-string-no-properties 2) ":" t)))
  11547. (defun org-get-tags (&optional pos local)
  11548. "Get the list of tags specified in the current headline.
  11549. When argument POS is non-nil, retrieve tags for headline at POS.
  11550. According to `org-use-tag-inheritance', tags may be inherited
  11551. from parent headlines, and from the whole document, through
  11552. `org-file-tags'. In this case, the returned list of tags
  11553. contains tags in this order: file tags, tags inherited from
  11554. parent headlines, local tags.
  11555. However, when optional argument LOCAL is non-nil, only return
  11556. tags specified at the headline.
  11557. Inherited tags have the `inherited' text property."
  11558. (if (and org-trust-scanner-tags
  11559. (or (not pos) (eq pos (point)))
  11560. (not local))
  11561. org-scanner-tags
  11562. (org-with-point-at (or pos (point))
  11563. (unless (org-before-first-heading-p)
  11564. (org-back-to-heading t)
  11565. (let ((ltags (org--get-local-tags)) itags)
  11566. (if (or local (not org-use-tag-inheritance)) ltags
  11567. (while (org-up-heading-safe)
  11568. (setq itags (append (mapcar #'org-add-prop-inherited
  11569. (org--get-local-tags))
  11570. itags)))
  11571. (setq itags (append org-file-tags itags))
  11572. (delete-dups
  11573. (append (org-remove-uninherited-tags itags) ltags))))))))
  11574. (defun org-get-buffer-tags ()
  11575. "Get a table of all tags used in the buffer, for completion."
  11576. (org-with-point-at 1
  11577. (let (tags)
  11578. (while (re-search-forward org-tag-line-re nil t)
  11579. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11580. tags)))
  11581. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11582. ;;;; The mapping API
  11583. (defvar org-agenda-skip-comment-trees)
  11584. (defvar org-agenda-skip-function)
  11585. (defun org-map-entries (func &optional match scope &rest skip)
  11586. "Call FUNC at each headline selected by MATCH in SCOPE.
  11587. FUNC is a function or a lisp form. The function will be called without
  11588. arguments, with the cursor positioned at the beginning of the headline.
  11589. The return values of all calls to the function will be collected and
  11590. returned as a list.
  11591. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11592. does not need to preserve point. After evaluation, the cursor will be
  11593. moved to the end of the line (presumably of the headline of the
  11594. processed entry) and search continues from there. Under some
  11595. circumstances, this may not produce the wanted results. For example,
  11596. if you have removed (e.g. archived) the current (sub)tree it could
  11597. mean that the next entry will be skipped entirely. In such cases, you
  11598. can specify the position from where search should continue by making
  11599. FUNC set the variable `org-map-continue-from' to the desired buffer
  11600. position.
  11601. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11602. Only headlines that are matched by this query will be considered during
  11603. the iteration. When MATCH is nil or t, all headlines will be
  11604. visited by the iteration.
  11605. SCOPE determines the scope of this command. It can be any of:
  11606. nil The current buffer, respecting the restriction if any
  11607. tree The subtree started with the entry at point
  11608. region The entries within the active region, if any
  11609. region-start-level
  11610. The entries within the active region, but only those at
  11611. the same level than the first one.
  11612. file The current buffer, without restriction
  11613. file-with-archives
  11614. The current buffer, and any archives associated with it
  11615. agenda All agenda files
  11616. agenda-with-archives
  11617. All agenda files with any archive files associated with them
  11618. \(file1 file2 ...)
  11619. If this is a list, all files in the list will be scanned
  11620. The remaining args are treated as settings for the skipping facilities of
  11621. the scanner. The following items can be given here:
  11622. archive skip trees with the archive tag
  11623. comment skip trees with the COMMENT keyword
  11624. function or Emacs Lisp form:
  11625. will be used as value for `org-agenda-skip-function', so
  11626. whenever the function returns a position, FUNC will not be
  11627. called for that entry and search will continue from the
  11628. position returned
  11629. If your function needs to retrieve the tags including inherited tags
  11630. at the *current* entry, you can use the value of the variable
  11631. `org-scanner-tags' which will be much faster than getting the value
  11632. with `org-get-tags'. If your function gets properties with
  11633. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11634. to t around the call to `org-entry-properties' to get the same speedup.
  11635. Note that if your function moves around to retrieve tags and properties at
  11636. a *different* entry, you cannot use these techniques."
  11637. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11638. (not (org-region-active-p)))
  11639. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11640. (org-agenda-skip-archived-trees (memq 'archive skip))
  11641. (org-agenda-skip-comment-trees (memq 'comment skip))
  11642. (org-agenda-skip-function
  11643. (car (org-delete-all '(comment archive) skip)))
  11644. (org-tags-match-list-sublevels t)
  11645. (start-level (eq scope 'region-start-level))
  11646. matcher res
  11647. org-todo-keywords-for-agenda
  11648. org-done-keywords-for-agenda
  11649. org-todo-keyword-alist-for-agenda
  11650. org-tag-alist-for-agenda
  11651. org--matcher-tags-todo-only)
  11652. (cond
  11653. ((eq match t) (setq matcher t))
  11654. ((eq match nil) (setq matcher t))
  11655. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11656. (save-excursion
  11657. (save-restriction
  11658. (cond ((eq scope 'tree)
  11659. (org-back-to-heading t)
  11660. (org-narrow-to-subtree)
  11661. (setq scope nil))
  11662. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11663. (org-region-active-p))
  11664. ;; If needed, set start-level to a string like "2"
  11665. (when start-level
  11666. (save-excursion
  11667. (goto-char (region-beginning))
  11668. (unless (org-at-heading-p) (outline-next-heading))
  11669. (setq start-level (org-current-level))))
  11670. (narrow-to-region (region-beginning)
  11671. (save-excursion
  11672. (goto-char (region-end))
  11673. (unless (and (bolp) (org-at-heading-p))
  11674. (outline-next-heading))
  11675. (point)))
  11676. (setq scope nil)))
  11677. (if (not scope)
  11678. (progn
  11679. (org-agenda-prepare-buffers
  11680. (and buffer-file-name (list buffer-file-name)))
  11681. (setq res
  11682. (org-scan-tags
  11683. func matcher org--matcher-tags-todo-only start-level)))
  11684. ;; Get the right scope
  11685. (cond
  11686. ((and scope (listp scope) (symbolp (car scope)))
  11687. (setq scope (eval scope)))
  11688. ((eq scope 'agenda)
  11689. (setq scope (org-agenda-files t)))
  11690. ((eq scope 'agenda-with-archives)
  11691. (setq scope (org-agenda-files t))
  11692. (setq scope (org-add-archive-files scope)))
  11693. ((eq scope 'file)
  11694. (setq scope (and buffer-file-name (list buffer-file-name))))
  11695. ((eq scope 'file-with-archives)
  11696. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11697. (org-agenda-prepare-buffers scope)
  11698. (dolist (file scope)
  11699. (with-current-buffer (org-find-base-buffer-visiting file)
  11700. (org-with-wide-buffer
  11701. (goto-char (point-min))
  11702. (setq res
  11703. (append
  11704. res
  11705. (org-scan-tags
  11706. func matcher org--matcher-tags-todo-only)))))))))
  11707. res)))
  11708. ;;; Properties API
  11709. (defconst org-special-properties
  11710. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11711. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11712. "The special properties valid in Org mode.
  11713. These are properties that are not defined in the property drawer,
  11714. but in some other way.")
  11715. (defconst org-default-properties
  11716. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11717. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11718. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11719. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11720. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11721. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11722. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11723. "Some properties that are used by Org mode for various purposes.
  11724. Being in this list makes sure that they are offered for completion.")
  11725. (defun org--valid-property-p (property)
  11726. "Non-nil when string PROPERTY is a valid property name."
  11727. (not
  11728. (or (equal property "")
  11729. (string-match-p "\\s-" property))))
  11730. (defun org--update-property-plist (key val props)
  11731. "Associate KEY to VAL in alist PROPS.
  11732. Modifications are made by side-effect. Return new alist."
  11733. (let* ((appending (string= (substring key -1) "+"))
  11734. (key (if appending (substring key 0 -1) key))
  11735. (old (assoc-string key props t)))
  11736. (if (not old) (cons (cons key val) props)
  11737. (setcdr old (if appending (concat (cdr old) " " val) val))
  11738. props)))
  11739. (defun org-get-property-block (&optional beg force)
  11740. "Return the (beg . end) range of the body of the property drawer.
  11741. BEG is the beginning of the current subtree, or of the part
  11742. before the first headline. If it is not given, it will be found.
  11743. If the drawer does not exist, create it if FORCE is non-nil, or
  11744. return nil."
  11745. (org-with-wide-buffer
  11746. (when beg (goto-char beg))
  11747. (unless (org-before-first-heading-p)
  11748. (let ((beg (cond (beg)
  11749. ((or (not (featurep 'org-inlinetask))
  11750. (org-inlinetask-in-task-p))
  11751. (org-back-to-heading t))
  11752. (t (org-with-limited-levels (org-back-to-heading t))))))
  11753. (forward-line)
  11754. (when (looking-at-p org-planning-line-re) (forward-line))
  11755. (cond ((looking-at org-property-drawer-re)
  11756. (forward-line)
  11757. (cons (point) (progn (goto-char (match-end 0))
  11758. (line-beginning-position))))
  11759. (force
  11760. (goto-char beg)
  11761. (org-insert-property-drawer)
  11762. (let ((pos (save-excursion (search-forward ":END:")
  11763. (line-beginning-position))))
  11764. (cons pos pos))))))))
  11765. (defun org-at-property-p ()
  11766. "Non-nil when point is inside a property drawer.
  11767. See `org-property-re' for match data, if applicable."
  11768. (save-excursion
  11769. (beginning-of-line)
  11770. (and (looking-at org-property-re)
  11771. (let ((property-drawer (save-match-data (org-get-property-block))))
  11772. (and property-drawer
  11773. (>= (point) (car property-drawer))
  11774. (< (point) (cdr property-drawer)))))))
  11775. (defun org-property-action ()
  11776. "Do an action on properties."
  11777. (interactive)
  11778. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11779. (let ((c (read-char-exclusive)))
  11780. (cl-case c
  11781. (?s (call-interactively #'org-set-property))
  11782. (?d (call-interactively #'org-delete-property))
  11783. (?D (call-interactively #'org-delete-property-globally))
  11784. (?c (call-interactively #'org-compute-property-at-point))
  11785. (otherwise (user-error "No such property action %c" c)))))
  11786. (defun org-inc-effort ()
  11787. "Increment the value of the effort property in the current entry."
  11788. (interactive)
  11789. (org-set-effort t))
  11790. (defvar org-clock-effort) ; Defined in org-clock.el.
  11791. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11792. (defun org-set-effort (&optional increment value)
  11793. "Set the effort property of the current entry.
  11794. If INCREMENT is non-nil, set the property to the next allowed
  11795. value. Otherwise, if optional argument VALUE is provided, use
  11796. it. Eventually, prompt for the new value if none of the previous
  11797. variables is set."
  11798. (interactive "P")
  11799. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11800. (current (org-entry-get nil org-effort-property))
  11801. (value
  11802. (cond
  11803. (increment
  11804. (unless allowed (user-error "Allowed effort values are not set"))
  11805. (or (cl-caadr (member (list current) allowed))
  11806. (user-error "Unknown value %S among allowed values" current)))
  11807. (value
  11808. (if (stringp value) value
  11809. (error "Invalid effort value: %S" value)))
  11810. (t
  11811. (let ((must-match
  11812. (and allowed
  11813. (not (get-text-property 0 'org-unrestricted
  11814. (caar allowed))))))
  11815. (completing-read "Effort: " allowed nil must-match))))))
  11816. ;; Test whether the value can be interpreted as a duration before
  11817. ;; inserting it in the buffer:
  11818. (org-duration-to-minutes value)
  11819. ;; Maybe update the effort value:
  11820. (unless (equal current value)
  11821. (org-entry-put nil org-effort-property value))
  11822. (org-refresh-property '((effort . identity)
  11823. (effort-minutes . org-duration-to-minutes))
  11824. value)
  11825. (when (equal (org-get-heading t t t t)
  11826. (bound-and-true-p org-clock-current-task))
  11827. (setq org-clock-effort value)
  11828. (org-clock-update-mode-line))
  11829. (message "%s is now %s" org-effort-property value)))
  11830. (defun org-entry-properties (&optional pom which)
  11831. "Get all properties of the current entry.
  11832. When POM is a buffer position, get all properties from the entry
  11833. there instead.
  11834. This includes the TODO keyword, the tags, time strings for
  11835. deadline, scheduled, and clocking, and any additional properties
  11836. defined in the entry.
  11837. If WHICH is nil or `all', get all properties. If WHICH is
  11838. `special' or `standard', only get that subclass. If WHICH is
  11839. a string, only get that property.
  11840. Return value is an alist. Keys are properties, as upcased
  11841. strings."
  11842. (org-with-point-at pom
  11843. (when (and (derived-mode-p 'org-mode)
  11844. (ignore-errors (org-back-to-heading t)))
  11845. (catch 'exit
  11846. (let* ((beg (point))
  11847. (specific (and (stringp which) (upcase which)))
  11848. (which (cond ((not specific) which)
  11849. ((member specific org-special-properties) 'special)
  11850. (t 'standard)))
  11851. props)
  11852. ;; Get the special properties, like TODO and TAGS.
  11853. (when (memq which '(nil all special))
  11854. (when (or (not specific) (string= specific "CLOCKSUM"))
  11855. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11856. (when clocksum
  11857. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11858. props)))
  11859. (when specific (throw 'exit props)))
  11860. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11861. (let ((clocksumt (get-text-property (point)
  11862. :org-clock-minutes-today)))
  11863. (when clocksumt
  11864. (push (cons "CLOCKSUM_T"
  11865. (org-duration-from-minutes clocksumt))
  11866. props)))
  11867. (when specific (throw 'exit props)))
  11868. (when (or (not specific) (string= specific "ITEM"))
  11869. (let ((case-fold-search nil))
  11870. (when (looking-at org-complex-heading-regexp)
  11871. (push (cons "ITEM"
  11872. (let ((title (match-string-no-properties 4)))
  11873. (if (org-string-nw-p title)
  11874. (org-remove-tabs title)
  11875. "")))
  11876. props)))
  11877. (when specific (throw 'exit props)))
  11878. (when (or (not specific) (string= specific "TODO"))
  11879. (let ((case-fold-search nil))
  11880. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11881. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11882. (when specific (throw 'exit props)))
  11883. (when (or (not specific) (string= specific "PRIORITY"))
  11884. (push (cons "PRIORITY"
  11885. (if (looking-at org-priority-regexp)
  11886. (match-string-no-properties 2)
  11887. (char-to-string org-default-priority)))
  11888. props)
  11889. (when specific (throw 'exit props)))
  11890. (when (or (not specific) (string= specific "FILE"))
  11891. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11892. props)
  11893. (when specific (throw 'exit props)))
  11894. (when (or (not specific) (string= specific "TAGS"))
  11895. (let ((tags (org-get-tags nil t)))
  11896. (when tags
  11897. (push (cons "TAGS" (org-make-tag-string tags))
  11898. props)))
  11899. (when specific (throw 'exit props)))
  11900. (when (or (not specific) (string= specific "ALLTAGS"))
  11901. (let ((tags (org-get-tags)))
  11902. (when tags
  11903. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11904. props)))
  11905. (when specific (throw 'exit props)))
  11906. (when (or (not specific) (string= specific "BLOCKED"))
  11907. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11908. (when specific (throw 'exit props)))
  11909. (when (or (not specific)
  11910. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11911. (forward-line)
  11912. (when (looking-at-p org-planning-line-re)
  11913. (end-of-line)
  11914. (let ((bol (line-beginning-position))
  11915. ;; Backward compatibility: time keywords used to
  11916. ;; be configurable (before 8.3). Make sure we
  11917. ;; get the correct keyword.
  11918. (key-assoc `(("CLOSED" . ,org-closed-string)
  11919. ("DEADLINE" . ,org-deadline-string)
  11920. ("SCHEDULED" . ,org-scheduled-string))))
  11921. (dolist (pair (if specific (list (assoc specific key-assoc))
  11922. key-assoc))
  11923. (save-excursion
  11924. (when (search-backward (cdr pair) bol t)
  11925. (goto-char (match-end 0))
  11926. (skip-chars-forward " \t")
  11927. (and (looking-at org-ts-regexp-both)
  11928. (push (cons (car pair)
  11929. (match-string-no-properties 0))
  11930. props)))))))
  11931. (when specific (throw 'exit props)))
  11932. (when (or (not specific)
  11933. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11934. (let ((find-ts
  11935. (lambda (end ts)
  11936. ;; Fix next time-stamp before END. TS is the
  11937. ;; list of time-stamps found so far.
  11938. (let ((ts ts)
  11939. (regexp (cond
  11940. ((string= specific "TIMESTAMP")
  11941. org-ts-regexp)
  11942. ((string= specific "TIMESTAMP_IA")
  11943. org-ts-regexp-inactive)
  11944. ((assoc "TIMESTAMP_IA" ts)
  11945. org-ts-regexp)
  11946. ((assoc "TIMESTAMP" ts)
  11947. org-ts-regexp-inactive)
  11948. (t org-ts-regexp-both))))
  11949. (catch 'next
  11950. (while (re-search-forward regexp end t)
  11951. (backward-char)
  11952. (let ((object (org-element-context)))
  11953. ;; Accept to match timestamps in node
  11954. ;; properties, too.
  11955. (when (memq (org-element-type object)
  11956. '(node-property timestamp))
  11957. (let ((type
  11958. (org-element-property :type object)))
  11959. (cond
  11960. ((and (memq type '(active active-range))
  11961. (not (equal specific "TIMESTAMP_IA")))
  11962. (unless (assoc "TIMESTAMP" ts)
  11963. (push (cons "TIMESTAMP"
  11964. (org-element-property
  11965. :raw-value object))
  11966. ts)
  11967. (when specific (throw 'exit ts))))
  11968. ((and (memq type '(inactive inactive-range))
  11969. (not (string= specific "TIMESTAMP")))
  11970. (unless (assoc "TIMESTAMP_IA" ts)
  11971. (push (cons "TIMESTAMP_IA"
  11972. (org-element-property
  11973. :raw-value object))
  11974. ts)
  11975. (when specific (throw 'exit ts))))))
  11976. ;; Both timestamp types are found,
  11977. ;; move to next part.
  11978. (when (= (length ts) 2) (throw 'next ts)))))
  11979. ts)))))
  11980. (goto-char beg)
  11981. ;; First look for timestamps within headline.
  11982. (let ((ts (funcall find-ts (line-end-position) nil)))
  11983. (if (= (length ts) 2) (setq props (nconc ts props))
  11984. ;; Then find timestamps in the section, skipping
  11985. ;; planning line.
  11986. (let ((end (save-excursion (outline-next-heading))))
  11987. (forward-line)
  11988. (when (looking-at-p org-planning-line-re) (forward-line))
  11989. (setq props (nconc (funcall find-ts end ts) props))))))))
  11990. ;; Get the standard properties, like :PROP:.
  11991. (when (memq which '(nil all standard))
  11992. ;; If we are looking after a specific property, delegate
  11993. ;; to `org-entry-get', which is faster. However, make an
  11994. ;; exception for "CATEGORY", since it can be also set
  11995. ;; through keywords (i.e. #+CATEGORY).
  11996. (if (and specific (not (equal specific "CATEGORY")))
  11997. (let ((value (org-entry-get beg specific nil t)))
  11998. (throw 'exit (and value (list (cons specific value)))))
  11999. (let ((range (org-get-property-block beg)))
  12000. (when range
  12001. (let ((end (cdr range)) seen-base)
  12002. (goto-char (car range))
  12003. ;; Unlike to `org--update-property-plist', we
  12004. ;; handle the case where base values is found
  12005. ;; after its extension. We also forbid standard
  12006. ;; properties to be named as special properties.
  12007. (while (re-search-forward org-property-re end t)
  12008. (let* ((key (upcase (match-string-no-properties 2)))
  12009. (extendp (string-match-p "\\+\\'" key))
  12010. (key-base (if extendp (substring key 0 -1) key))
  12011. (value (match-string-no-properties 3)))
  12012. (cond
  12013. ((member-ignore-case key-base org-special-properties))
  12014. (extendp
  12015. (setq props
  12016. (org--update-property-plist key value props)))
  12017. ((member key seen-base))
  12018. (t (push key seen-base)
  12019. (let ((p (assoc-string key props t)))
  12020. (if p (setcdr p (concat value " " (cdr p)))
  12021. (push (cons key value) props))))))))))))
  12022. (unless (assoc "CATEGORY" props)
  12023. (push (cons "CATEGORY" (org-get-category beg)) props)
  12024. (when (string= specific "CATEGORY") (throw 'exit props)))
  12025. ;; Return value.
  12026. props)))))
  12027. (defun org--property-local-values (property literal-nil)
  12028. "Return value for PROPERTY in current entry.
  12029. Value is a list whose car is the base value for PROPERTY and cdr
  12030. a list of accumulated values. Return nil if neither is found in
  12031. the entry. Also return nil when PROPERTY is set to \"nil\",
  12032. unless LITERAL-NIL is non-nil."
  12033. (let ((range (org-get-property-block)))
  12034. (when range
  12035. (goto-char (car range))
  12036. (let* ((case-fold-search t)
  12037. (end (cdr range))
  12038. (value
  12039. ;; Base value.
  12040. (save-excursion
  12041. (let ((v (and (re-search-forward
  12042. (org-re-property property nil t) end t)
  12043. (match-string-no-properties 3))))
  12044. (list (if literal-nil v (org-not-nil v)))))))
  12045. ;; Find additional values.
  12046. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12047. (while (re-search-forward property+ end t)
  12048. (push (match-string-no-properties 3) value)))
  12049. ;; Return final values.
  12050. (and (not (equal value '(nil))) (nreverse value))))))
  12051. (defun org--property-global-value (property literal-nil)
  12052. "Return value for PROPERTY in current buffer.
  12053. Return value is a string. Return nil if property is not set
  12054. globally. Also return nil when PROPERTY is set to \"nil\",
  12055. unless LITERAL-NIL is non-nil."
  12056. (let ((global
  12057. (cdr (or (assoc-string property org-file-properties t)
  12058. (assoc-string property org-global-properties t)
  12059. (assoc-string property org-global-properties-fixed t)))))
  12060. (if literal-nil global (org-not-nil global))))
  12061. (defun org-entry-get (pom property &optional inherit literal-nil)
  12062. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12063. If INHERIT is non-nil and the entry does not have the property,
  12064. then also check higher levels of the hierarchy. If INHERIT is
  12065. the symbol `selective', use inheritance only if the setting in
  12066. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12067. If the property is present but empty, the return value is the
  12068. empty string. If the property is not present at all, nil is
  12069. returned. In any other case, return the value as a string.
  12070. Search is case-insensitive.
  12071. If LITERAL-NIL is set, return the string value \"nil\" as
  12072. a string, do not interpret it as the list atom nil. This is used
  12073. for inheritance when a \"nil\" value can supersede a non-nil
  12074. value higher up the hierarchy."
  12075. (org-with-point-at pom
  12076. (cond
  12077. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12078. ;; We need a special property. Use `org-entry-properties' to
  12079. ;; retrieve it, but specify the wanted property.
  12080. (cdr (assoc-string property (org-entry-properties nil property))))
  12081. ((and inherit
  12082. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12083. (org-entry-get-with-inheritance property literal-nil))
  12084. (t
  12085. (let* ((local (org--property-local-values property literal-nil))
  12086. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12087. (if literal-nil value (org-not-nil value)))))))
  12088. (defun org-property-or-variable-value (var &optional inherit)
  12089. "Check if there is a property fixing the value of VAR.
  12090. If yes, return this value. If not, return the current value of the variable."
  12091. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12092. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12093. (read prop)
  12094. (symbol-value var))))
  12095. (defun org-entry-delete (pom property)
  12096. "Delete PROPERTY from entry at point-or-marker POM.
  12097. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12098. non-nil when a property was removed."
  12099. (org-with-point-at pom
  12100. (pcase (org-get-property-block)
  12101. (`(,begin . ,origin)
  12102. (let* ((end (copy-marker origin))
  12103. (re (org-re-property
  12104. (concat (regexp-quote property) "\\+?") t t)))
  12105. (goto-char begin)
  12106. (while (re-search-forward re end t)
  12107. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12108. ;; If drawer is empty, remove it altogether.
  12109. (when (= begin end)
  12110. (delete-region (line-beginning-position 0)
  12111. (line-beginning-position 2)))
  12112. ;; Return non-nil if some property was removed.
  12113. (prog1 (/= end origin) (set-marker end nil))))
  12114. (_ nil))))
  12115. ;; Multi-values properties are properties that contain multiple values
  12116. ;; These values are assumed to be single words, separated by whitespace.
  12117. (defun org-entry-add-to-multivalued-property (pom property value)
  12118. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12119. (let* ((old (org-entry-get pom property))
  12120. (values (and old (split-string old))))
  12121. (setq value (org-entry-protect-space value))
  12122. (unless (member value values)
  12123. (setq values (append values (list value)))
  12124. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12125. (defun org-entry-remove-from-multivalued-property (pom property value)
  12126. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12127. (let* ((old (org-entry-get pom property))
  12128. (values (and old (split-string old))))
  12129. (setq value (org-entry-protect-space value))
  12130. (when (member value values)
  12131. (setq values (delete value values))
  12132. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12133. (defun org-entry-member-in-multivalued-property (pom property value)
  12134. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12135. (let* ((old (org-entry-get pom property))
  12136. (values (and old (split-string old))))
  12137. (setq value (org-entry-protect-space value))
  12138. (member value values)))
  12139. (defun org-entry-get-multivalued-property (pom property)
  12140. "Return a list of values in a multivalued property."
  12141. (let* ((value (org-entry-get pom property))
  12142. (values (and value (split-string value))))
  12143. (mapcar #'org-entry-restore-space values)))
  12144. (defun org-entry-put-multivalued-property (pom property &rest values)
  12145. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12146. VALUES should be a list of strings. Spaces will be protected."
  12147. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12148. (let* ((value (org-entry-get pom property))
  12149. (values (and value (split-string value))))
  12150. (mapcar #'org-entry-restore-space values)))
  12151. (defun org-entry-protect-space (s)
  12152. "Protect spaces and newline in string S."
  12153. (while (string-match " " s)
  12154. (setq s (replace-match "%20" t t s)))
  12155. (while (string-match "\n" s)
  12156. (setq s (replace-match "%0A" t t s)))
  12157. s)
  12158. (defun org-entry-restore-space (s)
  12159. "Restore spaces and newline in string S."
  12160. (while (string-match "%20" s)
  12161. (setq s (replace-match " " t t s)))
  12162. (while (string-match "%0A" s)
  12163. (setq s (replace-match "\n" t t s)))
  12164. s)
  12165. (defvar org-entry-property-inherited-from (make-marker)
  12166. "Marker pointing to the entry from where a property was inherited.
  12167. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12168. location of the entry where the inheritance search matched. If there was
  12169. no match, the marker will point nowhere.
  12170. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12171. is set.")
  12172. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12173. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12174. The search will stop at the first ancestor which has the property defined.
  12175. If the value found is \"nil\", return nil to show that the property
  12176. should be considered as undefined (this is the meaning of nil here).
  12177. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12178. (move-marker org-entry-property-inherited-from nil)
  12179. (org-with-wide-buffer
  12180. (let (value)
  12181. (catch 'exit
  12182. (while t
  12183. (let ((v (org--property-local-values property literal-nil)))
  12184. (when v
  12185. (setq value
  12186. (concat (mapconcat #'identity (delq nil v) " ")
  12187. (and value " ")
  12188. value)))
  12189. (cond
  12190. ((car v)
  12191. (org-back-to-heading t)
  12192. (move-marker org-entry-property-inherited-from (point))
  12193. (throw 'exit nil))
  12194. ((org-up-heading-safe))
  12195. (t
  12196. (let ((global (org--property-global-value property literal-nil)))
  12197. (cond ((not global))
  12198. (value (setq value (concat global " " value)))
  12199. (t (setq value global))))
  12200. (throw 'exit nil))))))
  12201. (if literal-nil value (org-not-nil value)))))
  12202. (defvar org-property-changed-functions nil
  12203. "Hook called when the value of a property has changed.
  12204. Each hook function should accept two arguments, the name of the property
  12205. and the new value.")
  12206. (defun org-entry-put (pom property value)
  12207. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12208. If the value is nil, it is converted to the empty string. If it
  12209. is not a string, an error is raised. Also raise an error on
  12210. invalid property names.
  12211. PROPERTY can be any regular property (see
  12212. `org-special-properties'). It can also be \"TODO\",
  12213. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12214. For the last two properties, VALUE may have any of the special
  12215. values \"earlier\" and \"later\". The function then increases or
  12216. decreases scheduled or deadline date by one day."
  12217. (cond ((null value) (setq value ""))
  12218. ((not (stringp value)) (error "Properties values should be strings"))
  12219. ((not (org--valid-property-p property))
  12220. (user-error "Invalid property name: \"%s\"" property)))
  12221. (org-with-point-at pom
  12222. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12223. (org-back-to-heading t)
  12224. (org-with-limited-levels (org-back-to-heading t)))
  12225. (let ((beg (point)))
  12226. (cond
  12227. ((equal property "TODO")
  12228. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12229. ((not (member value org-todo-keywords-1))
  12230. (user-error "\"%s\" is not a valid TODO state" value)))
  12231. (org-todo value)
  12232. (org-align-tags))
  12233. ((equal property "PRIORITY")
  12234. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12235. (org-align-tags))
  12236. ((equal property "SCHEDULED")
  12237. (forward-line)
  12238. (if (and (looking-at-p org-planning-line-re)
  12239. (re-search-forward
  12240. org-scheduled-time-regexp (line-end-position) t))
  12241. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12242. ((string= value "later") (org-timestamp-change 1 'day))
  12243. ((string= value "") (org-schedule '(4)))
  12244. (t (org-schedule nil value)))
  12245. (if (member value '("earlier" "later" ""))
  12246. (call-interactively #'org-schedule)
  12247. (org-schedule nil value))))
  12248. ((equal property "DEADLINE")
  12249. (forward-line)
  12250. (if (and (looking-at-p org-planning-line-re)
  12251. (re-search-forward
  12252. org-deadline-time-regexp (line-end-position) t))
  12253. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12254. ((string= value "later") (org-timestamp-change 1 'day))
  12255. ((string= value "") (org-deadline '(4)))
  12256. (t (org-deadline nil value)))
  12257. (if (member value '("earlier" "later" ""))
  12258. (call-interactively #'org-deadline)
  12259. (org-deadline nil value))))
  12260. ((member property org-special-properties)
  12261. (error "The %s property cannot be set with `org-entry-put'" property))
  12262. (t
  12263. (let* ((range (org-get-property-block beg 'force))
  12264. (end (cdr range))
  12265. (case-fold-search t))
  12266. (goto-char (car range))
  12267. (if (re-search-forward (org-re-property property nil t) end t)
  12268. (progn (delete-region (match-beginning 0) (match-end 0))
  12269. (goto-char (match-beginning 0)))
  12270. (goto-char end)
  12271. (insert "\n")
  12272. (backward-char))
  12273. (insert ":" property ":")
  12274. (when value (insert " " value))
  12275. (org-indent-line)))))
  12276. (run-hook-with-args 'org-property-changed-functions property value)))
  12277. (defun org-buffer-property-keys (&optional specials defaults columns)
  12278. "Get all property keys in the current buffer.
  12279. When SPECIALS is non-nil, also list the special properties that
  12280. reflect things like tags and TODO state.
  12281. When DEFAULTS is non-nil, also include properties that has
  12282. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12283. DESCRIPTION, LOCATION, and LOGGING and others.
  12284. When COLUMNS in non-nil, also include property names given in
  12285. COLUMN formats in the current buffer."
  12286. (let ((case-fold-search t)
  12287. (props (append
  12288. (and specials org-special-properties)
  12289. (and defaults (cons org-effort-property org-default-properties))
  12290. nil)))
  12291. (org-with-wide-buffer
  12292. (goto-char (point-min))
  12293. (while (re-search-forward org-property-start-re nil t)
  12294. (catch :skip
  12295. (let ((range (org-get-property-block)))
  12296. (unless range (throw :skip nil))
  12297. (goto-char (car range))
  12298. (let ((begin (car range))
  12299. (end (cdr range)))
  12300. ;; Make sure that found property block is not located
  12301. ;; before current point, as it would generate an infloop.
  12302. ;; It can happen, for example, in the following
  12303. ;; situation:
  12304. ;;
  12305. ;; * Headline
  12306. ;; :PROPERTIES:
  12307. ;; ...
  12308. ;; :END:
  12309. ;; *************** Inlinetask
  12310. ;; #+BEGIN_EXAMPLE
  12311. ;; :PROPERTIES:
  12312. ;; #+END_EXAMPLE
  12313. ;;
  12314. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12315. (while (< (point) end)
  12316. (let ((p (progn (looking-at org-property-re)
  12317. (match-string-no-properties 2))))
  12318. ;; Only add true property name, not extension symbol.
  12319. (push (if (not (string-match-p "\\+\\'" p)) p
  12320. (substring p 0 -1))
  12321. props))
  12322. (forward-line))))
  12323. (outline-next-heading)))
  12324. (when columns
  12325. (goto-char (point-min))
  12326. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12327. (let ((element (org-element-at-point)))
  12328. (when (memq (org-element-type element) '(keyword node-property))
  12329. (let ((value (org-element-property :value element))
  12330. (start 0))
  12331. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12332. \\(?:{[^}]+}\\)?"
  12333. value start)
  12334. (setq start (match-end 0))
  12335. (let ((p (match-string-no-properties 1 value)))
  12336. (unless (member-ignore-case p org-special-properties)
  12337. (push p props))))))))))
  12338. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12339. (defun org-property-values (key)
  12340. "List all non-nil values of property KEY in current buffer."
  12341. (org-with-wide-buffer
  12342. (goto-char (point-min))
  12343. (let ((case-fold-search t)
  12344. (re (org-re-property key))
  12345. values)
  12346. (while (re-search-forward re nil t)
  12347. (push (org-entry-get (point) key) values))
  12348. (delete-dups values))))
  12349. (defun org-insert-property-drawer ()
  12350. "Insert a property drawer into the current entry.
  12351. Do nothing if the drawer already exists. The newly created
  12352. drawer is immediately hidden."
  12353. (org-with-wide-buffer
  12354. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12355. (org-back-to-heading t)
  12356. (org-with-limited-levels (org-back-to-heading t)))
  12357. (forward-line)
  12358. (when (looking-at-p org-planning-line-re) (forward-line))
  12359. (unless (looking-at-p org-property-drawer-re)
  12360. ;; Make sure we start editing a line from current entry, not from
  12361. ;; next one. It prevents extending text properties or overlays
  12362. ;; belonging to the latter.
  12363. (when (bolp) (backward-char))
  12364. (let ((begin (1+ (point)))
  12365. (inhibit-read-only t))
  12366. (insert "\n:PROPERTIES:\n:END:")
  12367. (org-flag-drawer t nil (line-end-position 0) (point))
  12368. (when (eobp) (insert "\n"))
  12369. (org-indent-region begin (point))))))
  12370. (defun org-insert-drawer (&optional arg drawer)
  12371. "Insert a drawer at point.
  12372. When optional argument ARG is non-nil, insert a property drawer.
  12373. Optional argument DRAWER, when non-nil, is a string representing
  12374. drawer's name. Otherwise, the user is prompted for a name.
  12375. If a region is active, insert the drawer around that region
  12376. instead.
  12377. Point is left between drawer's boundaries."
  12378. (interactive "P")
  12379. (let* ((drawer (if arg "PROPERTIES"
  12380. (or drawer (read-from-minibuffer "Drawer: ")))))
  12381. (cond
  12382. ;; With C-u, fall back on `org-insert-property-drawer'
  12383. (arg (org-insert-property-drawer))
  12384. ;; Check validity of suggested drawer's name.
  12385. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12386. (user-error "Invalid drawer name"))
  12387. ;; With an active region, insert a drawer at point.
  12388. ((not (org-region-active-p))
  12389. (progn
  12390. (unless (bolp) (insert "\n"))
  12391. (insert (format ":%s:\n\n:END:\n" drawer))
  12392. (forward-line -2)))
  12393. ;; Otherwise, insert the drawer at point
  12394. (t
  12395. (let ((rbeg (region-beginning))
  12396. (rend (copy-marker (region-end))))
  12397. (unwind-protect
  12398. (progn
  12399. (goto-char rbeg)
  12400. (beginning-of-line)
  12401. (when (save-excursion
  12402. (re-search-forward org-outline-regexp-bol rend t))
  12403. (user-error "Drawers cannot contain headlines"))
  12404. ;; Position point at the beginning of the first
  12405. ;; non-blank line in region. Insert drawer's opening
  12406. ;; there, then indent it.
  12407. (org-skip-whitespace)
  12408. (beginning-of-line)
  12409. (insert ":" drawer ":\n")
  12410. (forward-line -1)
  12411. (indent-for-tab-command)
  12412. ;; Move point to the beginning of the first blank line
  12413. ;; after the last non-blank line in region. Insert
  12414. ;; drawer's closing, then indent it.
  12415. (goto-char rend)
  12416. (skip-chars-backward " \r\t\n")
  12417. (insert "\n:END:")
  12418. (deactivate-mark t)
  12419. (indent-for-tab-command)
  12420. (unless (eolp) (insert "\n")))
  12421. ;; Clear marker, whatever the outcome of insertion is.
  12422. (set-marker rend nil)))))))
  12423. (defvar org-property-set-functions-alist nil
  12424. "Property set function alist.
  12425. Each entry should have the following format:
  12426. (PROPERTY . READ-FUNCTION)
  12427. The read function will be called with the same argument as
  12428. `org-completing-read'.")
  12429. (defun org-set-property-function (property)
  12430. "Get the function that should be used to set PROPERTY.
  12431. This is computed according to `org-property-set-functions-alist'."
  12432. (or (cdr (assoc property org-property-set-functions-alist))
  12433. 'org-completing-read))
  12434. (defun org-read-property-value (property &optional pom)
  12435. "Read value for PROPERTY, as a string.
  12436. When optional argument POM is non-nil, completion uses additional
  12437. information, i.e., allowed or existing values at point or marker
  12438. POM."
  12439. (let* ((completion-ignore-case t)
  12440. (allowed
  12441. (or (org-property-get-allowed-values nil property 'table)
  12442. (and pom (org-property-get-allowed-values pom property 'table))))
  12443. (current (org-entry-get nil property))
  12444. (prompt (format "%s value%s: "
  12445. property
  12446. (if (org-string-nw-p current)
  12447. (format " [%s]" current)
  12448. "")))
  12449. (set-function (org-set-property-function property)))
  12450. (org-trim
  12451. (if allowed
  12452. (funcall set-function
  12453. prompt allowed nil
  12454. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12455. (let ((all (mapcar #'list
  12456. (append (org-property-values property)
  12457. (and pom
  12458. (org-with-point-at pom
  12459. (org-property-values property)))))))
  12460. (funcall set-function prompt all nil nil "" nil current))))))
  12461. (defvar org-last-set-property nil)
  12462. (defvar org-last-set-property-value nil)
  12463. (defun org-read-property-name ()
  12464. "Read a property name."
  12465. (let ((completion-ignore-case t)
  12466. (default-prop (or (and (org-at-property-p)
  12467. (match-string-no-properties 2))
  12468. org-last-set-property)))
  12469. (org-completing-read
  12470. (concat "Property"
  12471. (if default-prop (concat " [" default-prop "]") "")
  12472. ": ")
  12473. (mapcar #'list (org-buffer-property-keys nil t t))
  12474. nil nil nil nil default-prop)))
  12475. (defun org-set-property-and-value (use-last)
  12476. "Allow to set [PROPERTY]: [value] direction from prompt.
  12477. When use-default, don't even ask, just use the last
  12478. \"[PROPERTY]: [value]\" string from the history."
  12479. (interactive "P")
  12480. (let* ((completion-ignore-case t)
  12481. (pv (or (and use-last org-last-set-property-value)
  12482. (org-completing-read
  12483. "Enter a \"[Property]: [value]\" pair: "
  12484. nil nil nil nil nil
  12485. org-last-set-property-value)))
  12486. prop val)
  12487. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12488. (setq prop (match-string 1 pv)
  12489. val (match-string 2 pv))
  12490. (org-set-property prop val))))
  12491. (defun org-set-property (property value)
  12492. "In the current entry, set PROPERTY to VALUE.
  12493. When called interactively, this will prompt for a property name, offering
  12494. completion on existing and default properties. And then it will prompt
  12495. for a value, offering completion either on allowed values (via an inherited
  12496. xxx_ALL property) or on existing values in other instances of this property
  12497. in the current file.
  12498. Throw an error when trying to set a property with an invalid name."
  12499. (interactive (list nil nil))
  12500. (let ((property (or property (org-read-property-name))))
  12501. ;; `org-entry-put' also makes the following check, but this one
  12502. ;; avoids polluting `org-last-set-property' and
  12503. ;; `org-last-set-property-value' needlessly.
  12504. (unless (org--valid-property-p property)
  12505. (user-error "Invalid property name: \"%s\"" property))
  12506. (let ((value (or value (org-read-property-value property)))
  12507. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12508. (setq org-last-set-property property)
  12509. (setq org-last-set-property-value (concat property ": " value))
  12510. ;; Possibly postprocess the inserted value:
  12511. (when fn (setq value (funcall fn value)))
  12512. (unless (equal (org-entry-get nil property) value)
  12513. (org-entry-put nil property value)))))
  12514. (defun org-find-property (property &optional value)
  12515. "Find first entry in buffer that sets PROPERTY.
  12516. When optional argument VALUE is non-nil, only consider an entry
  12517. if it contains PROPERTY set to this value. If PROPERTY should be
  12518. explicitly set to nil, use string \"nil\" for VALUE.
  12519. Return position where the entry begins, or nil if there is no
  12520. such entry. If narrowing is in effect, only search the visible
  12521. part of the buffer."
  12522. (save-excursion
  12523. (goto-char (point-min))
  12524. (let ((case-fold-search t)
  12525. (re (org-re-property property nil (not value) value)))
  12526. (catch 'exit
  12527. (while (re-search-forward re nil t)
  12528. (when (if value (org-at-property-p)
  12529. (org-entry-get (point) property nil t))
  12530. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12531. (defun org-delete-property (property)
  12532. "In the current entry, delete PROPERTY."
  12533. (interactive
  12534. (let* ((completion-ignore-case t)
  12535. (cat (org-entry-get (point) "CATEGORY"))
  12536. (props0 (org-entry-properties nil 'standard))
  12537. (props (if cat props0
  12538. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12539. (prop (if (< 1 (length props))
  12540. (completing-read "Property: " props nil t)
  12541. (caar props))))
  12542. (list prop)))
  12543. (if (not property)
  12544. (message "No property to delete in this entry")
  12545. (org-entry-delete nil property)
  12546. (message "Property \"%s\" deleted" property)))
  12547. (defun org-delete-property-globally (property)
  12548. "Remove PROPERTY globally, from all entries.
  12549. This function ignores narrowing, if any."
  12550. (interactive
  12551. (let* ((completion-ignore-case t)
  12552. (prop (completing-read
  12553. "Globally remove property: "
  12554. (mapcar #'list (org-buffer-property-keys)))))
  12555. (list prop)))
  12556. (org-with-wide-buffer
  12557. (goto-char (point-min))
  12558. (let ((count 0)
  12559. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12560. (while (re-search-forward re nil t)
  12561. (when (org-entry-delete (point) property) (cl-incf count)))
  12562. (message "Property \"%s\" removed from %d entries" property count))))
  12563. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12564. (defun org-compute-property-at-point ()
  12565. "Compute the property at point.
  12566. This looks for an enclosing column format, extracts the operator and
  12567. then applies it to the property in the column format's scope."
  12568. (interactive)
  12569. (unless (org-at-property-p)
  12570. (user-error "Not at a property"))
  12571. (let ((prop (match-string-no-properties 2)))
  12572. (org-columns-get-format-and-top-level)
  12573. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12574. (user-error "No operator defined for property %s" prop))
  12575. (org-columns-compute prop)))
  12576. (defvar org-property-allowed-value-functions nil
  12577. "Hook for functions supplying allowed values for a specific property.
  12578. The functions must take a single argument, the name of the property, and
  12579. return a flat list of allowed values. If \":ETC\" is one of
  12580. the values, this means that these values are intended as defaults for
  12581. completion, but that other values should be allowed too.
  12582. The functions must return nil if they are not responsible for this
  12583. property.")
  12584. (defun org-property-get-allowed-values (pom property &optional table)
  12585. "Get allowed values for the property PROPERTY.
  12586. When TABLE is non-nil, return an alist that can directly be used for
  12587. completion."
  12588. (let (vals)
  12589. (cond
  12590. ((equal property "TODO")
  12591. (setq vals (org-with-point-at pom
  12592. (append org-todo-keywords-1 '("")))))
  12593. ((equal property "PRIORITY")
  12594. (let ((n org-lowest-priority))
  12595. (while (>= n org-highest-priority)
  12596. (push (char-to-string n) vals)
  12597. (setq n (1- n)))))
  12598. ((equal property "CATEGORY"))
  12599. ((member property org-special-properties))
  12600. ((setq vals (run-hook-with-args-until-success
  12601. 'org-property-allowed-value-functions property)))
  12602. (t
  12603. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12604. (when (and vals (string-match "\\S-" vals))
  12605. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12606. (setq vals (mapcar (lambda (x)
  12607. (cond ((stringp x) x)
  12608. ((numberp x) (number-to-string x))
  12609. ((symbolp x) (symbol-name x))
  12610. (t "???")))
  12611. vals)))))
  12612. (when (member ":ETC" vals)
  12613. (setq vals (remove ":ETC" vals))
  12614. (org-add-props (car vals) '(org-unrestricted t)))
  12615. (if table (mapcar 'list vals) vals)))
  12616. (defun org-property-previous-allowed-value (&optional _previous)
  12617. "Switch to the next allowed value for this property."
  12618. (interactive)
  12619. (org-property-next-allowed-value t))
  12620. (defun org-property-next-allowed-value (&optional previous)
  12621. "Switch to the next allowed value for this property."
  12622. (interactive)
  12623. (unless (org-at-property-p)
  12624. (user-error "Not at a property"))
  12625. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12626. (key (match-string 2))
  12627. (value (match-string 3))
  12628. (allowed (or (org-property-get-allowed-values (point) key)
  12629. (and (member value '("[ ]" "[-]" "[X]"))
  12630. '("[ ]" "[X]"))))
  12631. (heading (save-match-data (nth 4 (org-heading-components))))
  12632. nval)
  12633. (unless allowed
  12634. (user-error "Allowed values for this property have not been defined"))
  12635. (when previous (setq allowed (reverse allowed)))
  12636. (when (member value allowed)
  12637. (setq nval (car (cdr (member value allowed)))))
  12638. (setq nval (or nval (car allowed)))
  12639. (when (equal nval value)
  12640. (user-error "Only one allowed value for this property"))
  12641. (org-at-property-p)
  12642. (replace-match (concat " :" key ": " nval) t t)
  12643. (org-indent-line)
  12644. (beginning-of-line 1)
  12645. (skip-chars-forward " \t")
  12646. (when (equal prop org-effort-property)
  12647. (org-refresh-property
  12648. '((effort . identity)
  12649. (effort-minutes . org-duration-to-minutes))
  12650. nval)
  12651. (when (string= org-clock-current-task heading)
  12652. (setq org-clock-effort nval)
  12653. (org-clock-update-mode-line)))
  12654. (run-hook-with-args 'org-property-changed-functions key nval)))
  12655. (defun org-find-olp (path &optional this-buffer)
  12656. "Return a marker pointing to the entry at outline path OLP.
  12657. If anything goes wrong, throw an error.
  12658. You can wrap this call to catch the error like this:
  12659. (condition-case msg
  12660. (org-mobile-locate-entry (match-string 4))
  12661. (error (nth 1 msg)))
  12662. The return value will then be either a string with the error message,
  12663. or a marker if everything is OK.
  12664. If THIS-BUFFER is set, the outline path does not contain a file,
  12665. only headings."
  12666. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12667. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12668. (level 1)
  12669. (lmin 1)
  12670. (lmax 1)
  12671. end found flevel)
  12672. (unless buffer (error "File not found :%s" file))
  12673. (with-current-buffer buffer
  12674. (unless (derived-mode-p 'org-mode)
  12675. (error "Buffer %s needs to be in Org mode" buffer))
  12676. (org-with-wide-buffer
  12677. (goto-char (point-min))
  12678. (dolist (heading path)
  12679. (let ((re (format org-complex-heading-regexp-format
  12680. (regexp-quote heading)))
  12681. (cnt 0))
  12682. (while (re-search-forward re end t)
  12683. (setq level (- (match-end 1) (match-beginning 1)))
  12684. (when (and (>= level lmin) (<= level lmax))
  12685. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12686. (when (= cnt 0)
  12687. (error "Heading not found on level %d: %s" lmax heading))
  12688. (when (> cnt 1)
  12689. (error "Heading not unique on level %d: %s" lmax heading))
  12690. (goto-char found)
  12691. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12692. (setq end (save-excursion (org-end-of-subtree t t)))))
  12693. (when (org-at-heading-p)
  12694. (point-marker))))))
  12695. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12696. "Find node HEADING in BUFFER.
  12697. Return a marker to the heading if it was found, or nil if not.
  12698. If POS-ONLY is set, return just the position instead of a marker.
  12699. The heading text must match exact, but it may have a TODO keyword,
  12700. a priority cookie and tags in the standard locations."
  12701. (with-current-buffer (or buffer (current-buffer))
  12702. (org-with-wide-buffer
  12703. (goto-char (point-min))
  12704. (let (case-fold-search)
  12705. (when (re-search-forward
  12706. (format org-complex-heading-regexp-format
  12707. (regexp-quote heading)) nil t)
  12708. (if pos-only
  12709. (match-beginning 0)
  12710. (move-marker (make-marker) (match-beginning 0))))))))
  12711. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12712. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12713. When the target headline is found, return a marker to this location."
  12714. (let ((files (directory-files (or dir default-directory)
  12715. t "\\`[^.#].*\\.org\\'"))
  12716. visiting m buffer)
  12717. (catch 'found
  12718. (dolist (file files)
  12719. (message "trying %s" file)
  12720. (setq visiting (org-find-base-buffer-visiting file))
  12721. (setq buffer (or visiting (find-file-noselect file)))
  12722. (setq m (org-find-exact-headline-in-buffer
  12723. heading buffer))
  12724. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12725. (and m (throw 'found m))))))
  12726. (defun org-find-entry-with-id (ident)
  12727. "Locate the entry that contains the ID property with exact value IDENT.
  12728. IDENT can be a string, a symbol or a number, this function will search for
  12729. the string representation of it.
  12730. Return the position where this entry starts, or nil if there is no such entry."
  12731. (interactive "sID: ")
  12732. (let ((id (cond
  12733. ((stringp ident) ident)
  12734. ((symbolp ident) (symbol-name ident))
  12735. ((numberp ident) (number-to-string ident))
  12736. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12737. (org-with-wide-buffer (org-find-property "ID" id))))
  12738. ;;;; Timestamps
  12739. (defvar org-last-changed-timestamp nil)
  12740. (defvar org-last-inserted-timestamp nil
  12741. "The last time stamp inserted with `org-insert-time-stamp'.")
  12742. (defun org-time-stamp (arg &optional inactive)
  12743. "Prompt for a date/time and insert a time stamp.
  12744. If the user specifies a time like HH:MM or if this command is
  12745. called with at least one prefix argument, the time stamp contains
  12746. the date and the time. Otherwise, only the date is included.
  12747. All parts of a date not specified by the user are filled in from
  12748. the timestamp at point, if any, or the current date/time
  12749. otherwise.
  12750. If there is already a timestamp at the cursor, it is replaced.
  12751. With two universal prefix arguments, insert an active timestamp
  12752. with the current time without prompting the user.
  12753. When called from lisp, the timestamp is inactive if INACTIVE is
  12754. non-nil."
  12755. (interactive "P")
  12756. (let* ((ts (cond
  12757. ((org-at-date-range-p t)
  12758. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12759. ((org-at-timestamp-p 'lax) (match-string 0))))
  12760. ;; Default time is either the timestamp at point or today.
  12761. ;; When entering a range, only the range start is considered.
  12762. (default-time (and ts (org-time-string-to-time ts)))
  12763. (default-input (and ts (org-get-compact-tod ts)))
  12764. (repeater (and ts
  12765. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12766. (match-string 0 ts)))
  12767. org-time-was-given
  12768. org-end-time-was-given
  12769. (time
  12770. (if (equal arg '(16)) (current-time)
  12771. ;; Preserve `this-command' and `last-command'.
  12772. (let ((this-command this-command)
  12773. (last-command last-command))
  12774. (org-read-date
  12775. arg 'totime nil nil default-time default-input
  12776. inactive)))))
  12777. (cond
  12778. ((and ts
  12779. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12780. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12781. (insert "--")
  12782. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12783. (ts
  12784. ;; Make sure we're on a timestamp. When in the middle of a date
  12785. ;; range, move arbitrarily to range end.
  12786. (unless (org-at-timestamp-p 'lax)
  12787. (skip-chars-forward "-")
  12788. (org-at-timestamp-p 'lax))
  12789. (replace-match "")
  12790. (setq org-last-changed-timestamp
  12791. (org-insert-time-stamp
  12792. time (or org-time-was-given arg)
  12793. inactive nil nil (list org-end-time-was-given)))
  12794. (when repeater
  12795. (backward-char)
  12796. (insert " " repeater)
  12797. (setq org-last-changed-timestamp
  12798. (concat (substring org-last-inserted-timestamp 0 -1)
  12799. " " repeater ">")))
  12800. (message "Timestamp updated"))
  12801. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12802. (t (org-insert-time-stamp
  12803. time (or org-time-was-given arg) inactive nil nil
  12804. (list org-end-time-was-given))))))
  12805. ;; FIXME: can we use this for something else, like computing time differences?
  12806. (defun org-get-compact-tod (s)
  12807. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12808. (let* ((t1 (match-string 1 s))
  12809. (h1 (string-to-number (match-string 2 s)))
  12810. (m1 (string-to-number (match-string 3 s)))
  12811. (t2 (and (match-end 4) (match-string 5 s)))
  12812. (h2 (and t2 (string-to-number (match-string 6 s))))
  12813. (m2 (and t2 (string-to-number (match-string 7 s))))
  12814. dh dm)
  12815. (if (not t2)
  12816. t1
  12817. (setq dh (- h2 h1) dm (- m2 m1))
  12818. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12819. (concat t1 "+" (number-to-string dh)
  12820. (and (/= 0 dm) (format ":%02d" dm)))))))
  12821. (defun org-time-stamp-inactive (&optional arg)
  12822. "Insert an inactive time stamp.
  12823. An inactive time stamp is enclosed in square brackets instead of
  12824. angle brackets. It is inactive in the sense that it does not
  12825. trigger agenda entries. So these are more for recording a
  12826. certain time/date.
  12827. If the user specifies a time like HH:MM or if this command is called with
  12828. at least one prefix argument, the time stamp contains the date and the time.
  12829. Otherwise, only the date is included.
  12830. When called with two universal prefix arguments, insert an inactive time stamp
  12831. with the current time without prompting the user."
  12832. (interactive "P")
  12833. (org-time-stamp arg 'inactive))
  12834. (defvar org-date-ovl (make-overlay 1 1))
  12835. (overlay-put org-date-ovl 'face 'org-date-selected)
  12836. (delete-overlay org-date-ovl)
  12837. (defvar org-ans1) ; dynamically scoped parameter
  12838. (defvar org-ans2) ; dynamically scoped parameter
  12839. (defvar org-plain-time-of-day-regexp) ; defined below
  12840. (defvar org-overriding-default-time nil) ; dynamically scoped
  12841. (defvar org-read-date-overlay nil)
  12842. (defvar org-dcst nil) ; dynamically scoped
  12843. (defvar org-read-date-history nil)
  12844. (defvar org-read-date-final-answer nil)
  12845. (defvar org-read-date-analyze-futurep nil)
  12846. (defvar org-read-date-analyze-forced-year nil)
  12847. (defvar org-read-date-inactive)
  12848. (defvar org-def)
  12849. (defvar org-defdecode)
  12850. (defvar org-with-time)
  12851. (defvar calendar-setup) ; Dynamically scoped.
  12852. (defun org-read-date (&optional with-time to-time from-string prompt
  12853. default-time default-input inactive)
  12854. "Read a date, possibly a time, and make things smooth for the user.
  12855. The prompt will suggest to enter an ISO date, but you can also enter anything
  12856. which will at least partially be understood by `parse-time-string'.
  12857. Unrecognized parts of the date will default to the current day, month, year,
  12858. hour and minute. If this command is called to replace a timestamp at point,
  12859. or to enter the second timestamp of a range, the default time is taken
  12860. from the existing stamp. Furthermore, the command prefers the future,
  12861. so if you are giving a date where the year is not given, and the day-month
  12862. combination is already past in the current year, it will assume you
  12863. mean next year. For details, see the manual. A few examples:
  12864. 3-2-5 --> 2003-02-05
  12865. feb 15 --> currentyear-02-15
  12866. 2/15 --> currentyear-02-15
  12867. sep 12 9 --> 2009-09-12
  12868. 12:45 --> today 12:45
  12869. 22 sept 0:34 --> currentyear-09-22 0:34
  12870. 12 --> currentyear-currentmonth-12
  12871. Fri --> nearest Friday after today
  12872. -Tue --> last Tuesday
  12873. etc.
  12874. Furthermore you can specify a relative date by giving, as the *first* thing
  12875. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12876. change in days weeks, months, years.
  12877. With a single plus or minus, the date is relative to today. With a double
  12878. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12879. +4d --> four days from today
  12880. +4 --> same as above
  12881. +2w --> two weeks from today
  12882. ++5 --> five days from default date
  12883. The function understands only English month and weekday abbreviations.
  12884. While prompting, a calendar is popped up - you can also select the
  12885. date with the mouse (button 1). The calendar shows a period of three
  12886. months. To scroll it to other months, use the keys `>' and `<'.
  12887. If you don't like the calendar, turn it off with
  12888. (setq org-read-date-popup-calendar nil)
  12889. With optional argument TO-TIME, the date will immediately be converted
  12890. to an internal time.
  12891. With an optional argument WITH-TIME, the prompt will suggest to
  12892. also insert a time. Note that when WITH-TIME is not set, you can
  12893. still enter a time, and this function will inform the calling routine
  12894. about this change. The calling routine may then choose to change the
  12895. format used to insert the time stamp into the buffer to include the time.
  12896. With optional argument FROM-STRING, read from this string instead from
  12897. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12898. the time/date that is used for everything that is not specified by the
  12899. user."
  12900. (require 'parse-time)
  12901. (let* ((org-with-time with-time)
  12902. (org-time-stamp-rounding-minutes
  12903. (if (equal org-with-time '(16))
  12904. '(0 0)
  12905. org-time-stamp-rounding-minutes))
  12906. (org-dcst org-display-custom-times)
  12907. (ct (org-current-time))
  12908. (org-def (or org-overriding-default-time default-time ct))
  12909. (org-defdecode (decode-time org-def))
  12910. (cur-frame (selected-frame))
  12911. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12912. (calendar-setup
  12913. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12914. (calendar-move-hook nil)
  12915. (calendar-view-diary-initially-flag nil)
  12916. (calendar-view-holidays-initially-flag nil)
  12917. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12918. ;; Rationalize `org-def' and `org-defdecode', if required.
  12919. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12920. (setf (nth 2 org-defdecode) -1)
  12921. (setf (nth 1 org-defdecode) 59)
  12922. (setq org-def (apply #'encode-time org-defdecode))
  12923. (setq org-defdecode (decode-time org-def)))
  12924. (let* ((timestr (format-time-string
  12925. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12926. org-def))
  12927. (prompt (concat (if prompt (concat prompt " ") "")
  12928. (format "Date+time [%s]: " timestr))))
  12929. (cond
  12930. (from-string (setq ans from-string))
  12931. (org-read-date-popup-calendar
  12932. (save-excursion
  12933. (save-window-excursion
  12934. (calendar)
  12935. (when (eq calendar-setup 'calendar-only)
  12936. (setq cal-frame
  12937. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12938. (select-frame cal-frame))
  12939. (org-eval-in-calendar '(setq cursor-type nil) t)
  12940. (unwind-protect
  12941. (progn
  12942. (calendar-forward-day (- (time-to-days org-def)
  12943. (calendar-absolute-from-gregorian
  12944. (calendar-current-date))))
  12945. (org-eval-in-calendar nil t)
  12946. (let* ((old-map (current-local-map))
  12947. (map (copy-keymap calendar-mode-map))
  12948. (minibuffer-local-map
  12949. (copy-keymap org-read-date-minibuffer-local-map)))
  12950. (org-defkey map (kbd "RET") 'org-calendar-select)
  12951. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12952. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12953. (unwind-protect
  12954. (progn
  12955. (use-local-map map)
  12956. (setq org-read-date-inactive inactive)
  12957. (add-hook 'post-command-hook 'org-read-date-display)
  12958. (setq org-ans0
  12959. (read-string prompt
  12960. default-input
  12961. 'org-read-date-history
  12962. nil))
  12963. ;; org-ans0: from prompt
  12964. ;; org-ans1: from mouse click
  12965. ;; org-ans2: from calendar motion
  12966. (setq ans
  12967. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12968. (remove-hook 'post-command-hook 'org-read-date-display)
  12969. (use-local-map old-map)
  12970. (when org-read-date-overlay
  12971. (delete-overlay org-read-date-overlay)
  12972. (setq org-read-date-overlay nil)))))
  12973. (bury-buffer "*Calendar*")
  12974. (when cal-frame
  12975. (delete-frame cal-frame)
  12976. (select-frame-set-input-focus cur-frame))))))
  12977. (t ; Naked prompt only
  12978. (unwind-protect
  12979. (setq ans (read-string prompt default-input
  12980. 'org-read-date-history timestr))
  12981. (when org-read-date-overlay
  12982. (delete-overlay org-read-date-overlay)
  12983. (setq org-read-date-overlay nil))))))
  12984. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12985. (when org-read-date-analyze-forced-year
  12986. (message "Year was forced into %s"
  12987. (if org-read-date-force-compatible-dates
  12988. "compatible range (1970-2037)"
  12989. "range representable on this machine"))
  12990. (ding))
  12991. (setq final (apply #'encode-time final))
  12992. (setq org-read-date-final-answer ans)
  12993. (if to-time
  12994. final
  12995. ;; This round-trip gets rid of 34th of August and stuff like that....
  12996. (setq final (decode-time final))
  12997. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12998. (format "%04d-%02d-%02d %02d:%02d"
  12999. (nth 5 final) (nth 4 final) (nth 3 final)
  13000. (nth 2 final) (nth 1 final))
  13001. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  13002. (defun org-read-date-display ()
  13003. "Display the current date prompt interpretation in the minibuffer."
  13004. (when org-read-date-display-live
  13005. (when org-read-date-overlay
  13006. (delete-overlay org-read-date-overlay))
  13007. (when (minibufferp (current-buffer))
  13008. (save-excursion
  13009. (end-of-line 1)
  13010. (while (not (equal (buffer-substring
  13011. (max (point-min) (- (point) 4)) (point))
  13012. " "))
  13013. (insert " ")))
  13014. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13015. " " (or org-ans1 org-ans2)))
  13016. (org-end-time-was-given nil)
  13017. (f (org-read-date-analyze ans org-def org-defdecode))
  13018. (fmts (if org-dcst
  13019. org-time-stamp-custom-formats
  13020. org-time-stamp-formats))
  13021. (fmt (if (or org-with-time
  13022. (and (boundp 'org-time-was-given) org-time-was-given))
  13023. (cdr fmts)
  13024. (car fmts)))
  13025. (txt (format-time-string fmt (apply #'encode-time f)))
  13026. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13027. (txt (concat "=> " txt)))
  13028. (when (and org-end-time-was-given
  13029. (string-match org-plain-time-of-day-regexp txt))
  13030. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13031. org-end-time-was-given
  13032. (substring txt (match-end 0)))))
  13033. (when org-read-date-analyze-futurep
  13034. (setq txt (concat txt " (=>F)")))
  13035. (setq org-read-date-overlay
  13036. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13037. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13038. (defun org-read-date-analyze (ans def defdecode)
  13039. "Analyze the combined answer of the date prompt."
  13040. ;; FIXME: cleanup and comment
  13041. (let ((org-def def)
  13042. (org-defdecode defdecode)
  13043. (nowdecode (decode-time))
  13044. delta deltan deltaw deltadef year month day
  13045. hour minute second wday pm h2 m2 tl wday1
  13046. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13047. (setq org-read-date-analyze-futurep nil
  13048. org-read-date-analyze-forced-year nil)
  13049. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13050. (setq ans "+0"))
  13051. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13052. (setq ans (replace-match "" t t ans)
  13053. deltan (car delta)
  13054. deltaw (nth 1 delta)
  13055. deltadef (nth 2 delta)))
  13056. ;; Check if there is an iso week date in there. If yes, store the
  13057. ;; info and postpone interpreting it until the rest of the parsing
  13058. ;; is done.
  13059. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13060. (setq iso-year (when (match-end 1)
  13061. (org-small-year-to-year
  13062. (string-to-number (match-string 1 ans))))
  13063. iso-weekday (when (match-end 3)
  13064. (string-to-number (match-string 3 ans)))
  13065. iso-week (string-to-number (match-string 2 ans)))
  13066. (setq ans (replace-match "" t t ans)))
  13067. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13068. (when (string-match
  13069. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13070. (setq year (if (match-end 2)
  13071. (string-to-number (match-string 2 ans))
  13072. (progn (setq kill-year t)
  13073. (string-to-number (format-time-string "%Y"))))
  13074. month (string-to-number (match-string 3 ans))
  13075. day (string-to-number (match-string 4 ans)))
  13076. (setq year (org-small-year-to-year year))
  13077. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13078. t nil ans)))
  13079. ;; Help matching dotted european dates
  13080. (when (string-match
  13081. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13082. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13083. (setq kill-year t)
  13084. (string-to-number (format-time-string "%Y")))
  13085. day (string-to-number (match-string 1 ans))
  13086. month (string-to-number (match-string 2 ans))
  13087. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13088. t nil ans)))
  13089. ;; Help matching american dates, like 5/30 or 5/30/7
  13090. (when (string-match
  13091. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13092. (setq year (if (match-end 4)
  13093. (string-to-number (match-string 4 ans))
  13094. (progn (setq kill-year t)
  13095. (string-to-number (format-time-string "%Y"))))
  13096. month (string-to-number (match-string 1 ans))
  13097. day (string-to-number (match-string 2 ans)))
  13098. (setq year (org-small-year-to-year year))
  13099. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13100. t nil ans)))
  13101. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13102. ;; If there is a time with am/pm, and *no* time without it, we convert
  13103. ;; so that matching will be successful.
  13104. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13105. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13106. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13107. (setq hour (string-to-number (match-string 1 ans))
  13108. minute (if (match-end 3)
  13109. (string-to-number (match-string 3 ans))
  13110. 0)
  13111. pm (equal ?p
  13112. (string-to-char (downcase (match-string 4 ans)))))
  13113. (if (and (= hour 12) (not pm))
  13114. (setq hour 0)
  13115. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13116. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13117. t t ans))))
  13118. ;; Check if a time range is given as a duration
  13119. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13120. (setq hour (string-to-number (match-string 1 ans))
  13121. h2 (+ hour (string-to-number (match-string 3 ans)))
  13122. minute (string-to-number (match-string 2 ans))
  13123. m2 (+ minute (if (match-end 5) (string-to-number
  13124. (match-string 5 ans))0)))
  13125. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13126. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13127. t t ans)))
  13128. ;; Check if there is a time range
  13129. (when (boundp 'org-end-time-was-given)
  13130. (setq org-time-was-given nil)
  13131. (when (and (string-match org-plain-time-of-day-regexp ans)
  13132. (match-end 8))
  13133. (setq org-end-time-was-given (match-string 8 ans))
  13134. (setq ans (concat (substring ans 0 (match-beginning 7))
  13135. (substring ans (match-end 7))))))
  13136. (setq tl (parse-time-string ans)
  13137. day (or (nth 3 tl) (nth 3 org-defdecode))
  13138. month
  13139. (cond ((nth 4 tl))
  13140. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13141. ;; Day was specified. Make sure DAY+MONTH
  13142. ;; combination happens in the future.
  13143. ((nth 3 tl)
  13144. (setq futurep t)
  13145. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13146. (nth 4 nowdecode)))
  13147. (t (nth 4 org-defdecode)))
  13148. year
  13149. (cond ((and (not kill-year) (nth 5 tl)))
  13150. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13151. ;; Month was guessed in the future and is at least
  13152. ;; equal to NOWDECODE's. Fix year accordingly.
  13153. (futurep
  13154. (if (or (> month (nth 4 nowdecode))
  13155. (>= day (nth 3 nowdecode)))
  13156. (nth 5 nowdecode)
  13157. (1+ (nth 5 nowdecode))))
  13158. ;; Month was specified. Make sure MONTH+YEAR
  13159. ;; combination happens in the future.
  13160. ((nth 4 tl)
  13161. (setq futurep t)
  13162. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13163. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13164. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13165. (t (nth 5 nowdecode))))
  13166. (t (nth 5 org-defdecode)))
  13167. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13168. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13169. second (or (nth 0 tl) 0)
  13170. wday (nth 6 tl))
  13171. (when (and (eq org-read-date-prefer-future 'time)
  13172. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13173. (equal day (nth 3 nowdecode))
  13174. (equal month (nth 4 nowdecode))
  13175. (equal year (nth 5 nowdecode))
  13176. (nth 2 tl)
  13177. (or (< (nth 2 tl) (nth 2 nowdecode))
  13178. (and (= (nth 2 tl) (nth 2 nowdecode))
  13179. (nth 1 tl)
  13180. (< (nth 1 tl) (nth 1 nowdecode)))))
  13181. (setq day (1+ day)
  13182. futurep t))
  13183. ;; Special date definitions below
  13184. (cond
  13185. (iso-week
  13186. ;; There was an iso week
  13187. (require 'cal-iso)
  13188. (setq futurep nil)
  13189. (setq year (or iso-year year)
  13190. day (or iso-weekday wday 1)
  13191. wday nil ; to make sure that the trigger below does not match
  13192. iso-date (calendar-gregorian-from-absolute
  13193. (calendar-iso-to-absolute
  13194. (list iso-week day year))))
  13195. ; FIXME: Should we also push ISO weeks into the future?
  13196. ; (when (and org-read-date-prefer-future
  13197. ; (not iso-year)
  13198. ; (< (calendar-absolute-from-gregorian iso-date)
  13199. ; (time-to-days nil)))
  13200. ; (setq year (1+ year)
  13201. ; iso-date (calendar-gregorian-from-absolute
  13202. ; (calendar-iso-to-absolute
  13203. ; (list iso-week day year)))))
  13204. (setq month (car iso-date)
  13205. year (nth 2 iso-date)
  13206. day (nth 1 iso-date)))
  13207. (deltan
  13208. (setq futurep nil)
  13209. (unless deltadef
  13210. (let ((now (decode-time)))
  13211. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13212. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13213. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13214. ((equal deltaw "m") (setq month (+ month deltan)))
  13215. ((equal deltaw "y") (setq year (+ year deltan)))))
  13216. ((and wday (not (nth 3 tl)))
  13217. ;; Weekday was given, but no day, so pick that day in the week
  13218. ;; on or after the derived date.
  13219. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13220. (unless (equal wday wday1)
  13221. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13222. (when (and (boundp 'org-time-was-given)
  13223. (nth 2 tl))
  13224. (setq org-time-was-given t))
  13225. (when (< year 100) (setq year (+ 2000 year)))
  13226. ;; Check of the date is representable
  13227. (if org-read-date-force-compatible-dates
  13228. (progn
  13229. (when (< year 1970)
  13230. (setq year 1970 org-read-date-analyze-forced-year t))
  13231. (when (> year 2037)
  13232. (setq year 2037 org-read-date-analyze-forced-year t)))
  13233. (condition-case nil
  13234. (ignore (encode-time second minute hour day month year))
  13235. (error
  13236. (setq year (nth 5 org-defdecode))
  13237. (setq org-read-date-analyze-forced-year t))))
  13238. (setq org-read-date-analyze-futurep futurep)
  13239. (list second minute hour day month year)))
  13240. (defvar parse-time-weekdays)
  13241. (defun org-read-date-get-relative (s today default)
  13242. "Check string S for special relative date string.
  13243. TODAY and DEFAULT are internal times, for today and for a default.
  13244. Return shift list (N what def-flag)
  13245. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13246. N is the number of WHATs to shift.
  13247. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13248. the DEFAULT date rather than TODAY."
  13249. (require 'parse-time)
  13250. (when (and
  13251. (string-match
  13252. (concat
  13253. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13254. "\\([0-9]+\\)?"
  13255. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13256. "\\([ \t]\\|$\\)") s)
  13257. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13258. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13259. (string-to-char (substring (match-string 1 s) -1))
  13260. ?+))
  13261. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13262. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13263. (what (if (match-end 3) (match-string 3 s) "d"))
  13264. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13265. (date (if rel default today))
  13266. (wday (nth 6 (decode-time date)))
  13267. delta)
  13268. (if wday1
  13269. (progn
  13270. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13271. (when (= delta 0) (setq delta 7))
  13272. (when (= dir ?-)
  13273. (setq delta (- delta 7))
  13274. (when (= delta 0) (setq delta -7)))
  13275. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13276. (list delta "d" rel))
  13277. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13278. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13279. "Turn a user-specified date into the internal representation.
  13280. The internal representation needed by the calendar is (month day year).
  13281. This is a wrapper to handle the brain-dead convention in calendar that
  13282. user function argument order change dependent on argument order."
  13283. (pcase calendar-date-style
  13284. (`american (list arg1 arg2 arg3))
  13285. (`european (list arg2 arg1 arg3))
  13286. (`iso (list arg2 arg3 arg1))))
  13287. (defun org-eval-in-calendar (form &optional keepdate)
  13288. "Eval FORM in the calendar window and return to current window.
  13289. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13290. (let ((sf (selected-frame))
  13291. (sw (selected-window)))
  13292. (select-window (get-buffer-window "*Calendar*" t))
  13293. (eval form)
  13294. (when (and (not keepdate) (calendar-cursor-to-date))
  13295. (let* ((date (calendar-cursor-to-date))
  13296. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13297. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13298. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13299. (select-window sw)
  13300. (select-frame-set-input-focus sf)))
  13301. (defun org-calendar-select ()
  13302. "Return to `org-read-date' with the date currently selected.
  13303. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13304. (interactive)
  13305. (when (calendar-cursor-to-date)
  13306. (let* ((date (calendar-cursor-to-date))
  13307. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13308. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13309. (when (active-minibuffer-window) (exit-minibuffer))))
  13310. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13311. "Insert a date stamp for the date given by the internal TIME.
  13312. See `format-time-string' for the format of TIME.
  13313. WITH-HM means use the stamp format that includes the time of the day.
  13314. INACTIVE means use square brackets instead of angular ones, so that the
  13315. stamp will not contribute to the agenda.
  13316. PRE and POST are optional strings to be inserted before and after the
  13317. stamp.
  13318. The command returns the inserted time stamp."
  13319. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13320. stamp)
  13321. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13322. (insert-before-markers (or pre ""))
  13323. (when (listp extra)
  13324. (setq extra (car extra))
  13325. (if (and (stringp extra)
  13326. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13327. (setq extra (format "-%02d:%02d"
  13328. (string-to-number (match-string 1 extra))
  13329. (string-to-number (match-string 2 extra))))
  13330. (setq extra nil)))
  13331. (when extra
  13332. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13333. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13334. (insert-before-markers (or post ""))
  13335. (setq org-last-inserted-timestamp stamp)))
  13336. (defun org-toggle-time-stamp-overlays ()
  13337. "Toggle the use of custom time stamp formats."
  13338. (interactive)
  13339. (setq org-display-custom-times (not org-display-custom-times))
  13340. (unless org-display-custom-times
  13341. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13342. (while (setq p (next-single-property-change p 'display))
  13343. (when (and (get-text-property p 'display)
  13344. (eq (get-text-property p 'face) 'org-date))
  13345. (remove-text-properties
  13346. p (setq p (next-single-property-change p 'display))
  13347. '(display t))))
  13348. (set-buffer-modified-p bmp)))
  13349. (org-restart-font-lock)
  13350. (setq org-table-may-need-update t)
  13351. (if org-display-custom-times
  13352. (message "Time stamps are overlaid with custom format")
  13353. (message "Time stamp overlays removed")))
  13354. (defun org-display-custom-time (beg end)
  13355. "Overlay modified time stamp format over timestamp between BEG and END."
  13356. (let* ((ts (buffer-substring beg end))
  13357. t1 with-hm tf time str (off 0))
  13358. (save-match-data
  13359. (setq t1 (org-parse-time-string ts t))
  13360. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13361. (setq off (- (match-end 0) (match-beginning 0)))))
  13362. (setq end (- end off))
  13363. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13364. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13365. time (org-fix-decoded-time t1)
  13366. str (org-add-props
  13367. (format-time-string
  13368. (substring tf 1 -1) (apply 'encode-time time))
  13369. nil 'mouse-face 'highlight))
  13370. (put-text-property beg end 'display str)))
  13371. (defun org-fix-decoded-time (time)
  13372. "Set 0 instead of nil for the first 6 elements of time.
  13373. Don't touch the rest."
  13374. (let ((n 0))
  13375. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13376. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13377. "Difference between TIMESTAMP-STRING and now in days.
  13378. If SECONDS is non-nil, return the difference in seconds."
  13379. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13380. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13381. (funcall fdiff nil))))
  13382. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13383. "Is the time in TIMESTAMP-STRING close to the current date?"
  13384. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13385. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13386. (not (org-entry-is-done-p))))
  13387. (defun org-get-wdays (ts &optional delay zero-delay)
  13388. "Get the deadline lead time appropriate for timestring TS.
  13389. When DELAY is non-nil, get the delay time for scheduled items
  13390. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13391. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13392. don't try to find the delay cookie in the scheduled timestamp."
  13393. (let ((tv (if delay org-scheduled-delay-days
  13394. org-deadline-warning-days)))
  13395. (cond
  13396. ((or (and delay (< tv 0))
  13397. (and delay zero-delay (<= tv 0))
  13398. (and (not delay) (<= tv 0)))
  13399. ;; Enforce this value no matter what
  13400. (- tv))
  13401. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13402. ;; lead time is specified.
  13403. (floor (* (string-to-number (match-string 1 ts))
  13404. (cdr (assoc (match-string 2 ts)
  13405. '(("d" . 1) ("w" . 7)
  13406. ("m" . 30.4) ("y" . 365.25)
  13407. ("h" . 0.041667)))))))
  13408. ;; go for the default.
  13409. (t tv))))
  13410. (defun org-calendar-select-mouse (ev)
  13411. "Return to `org-read-date' with the date currently selected.
  13412. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13413. (interactive "e")
  13414. (mouse-set-point ev)
  13415. (when (calendar-cursor-to-date)
  13416. (let* ((date (calendar-cursor-to-date))
  13417. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13418. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13419. (when (active-minibuffer-window) (exit-minibuffer))))
  13420. (defun org-check-deadlines (ndays)
  13421. "Check if there are any deadlines due or past due.
  13422. A deadline is considered due if it happens within `org-deadline-warning-days'
  13423. days from today's date. If the deadline appears in an entry marked DONE,
  13424. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13425. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13426. are shown."
  13427. (interactive "P")
  13428. (let* ((org-warn-days
  13429. (cond
  13430. ((equal ndays '(4)) 100000)
  13431. (ndays (prefix-numeric-value ndays))
  13432. (t (abs org-deadline-warning-days))))
  13433. (case-fold-search nil)
  13434. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13435. (callback
  13436. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13437. (message "%d deadlines past-due or due within %d days"
  13438. (org-occur regexp nil callback)
  13439. org-warn-days)))
  13440. (defsubst org-re-timestamp (type)
  13441. "Return a regexp for timestamp TYPE.
  13442. Allowed values for TYPE are:
  13443. all: all timestamps
  13444. active: only active timestamps (<...>)
  13445. inactive: only inactive timestamps ([...])
  13446. scheduled: only scheduled timestamps
  13447. deadline: only deadline timestamps
  13448. closed: only closed time-stamps
  13449. When TYPE is nil, fall back on returning a regexp that matches
  13450. both scheduled and deadline timestamps."
  13451. (cl-case type
  13452. (all org-ts-regexp-both)
  13453. (active org-ts-regexp)
  13454. (inactive org-ts-regexp-inactive)
  13455. (scheduled org-scheduled-time-regexp)
  13456. (deadline org-deadline-time-regexp)
  13457. (closed org-closed-time-regexp)
  13458. (otherwise
  13459. (concat "\\<"
  13460. (regexp-opt (list org-deadline-string org-scheduled-string))
  13461. " *<\\([^>]+\\)>"))))
  13462. (defun org-check-before-date (d)
  13463. "Check if there are deadlines or scheduled entries before date D."
  13464. (interactive (list (org-read-date)))
  13465. (let* ((case-fold-search nil)
  13466. (regexp (org-re-timestamp org-ts-type))
  13467. (ts-type org-ts-type)
  13468. (callback
  13469. (lambda ()
  13470. (let ((match (match-string 1)))
  13471. (and (if (memq ts-type '(active inactive all))
  13472. (eq (org-element-type (save-excursion
  13473. (backward-char)
  13474. (org-element-context)))
  13475. 'timestamp)
  13476. (org-at-planning-p))
  13477. (time-less-p
  13478. (org-time-string-to-time match)
  13479. (org-time-string-to-time d)))))))
  13480. (message "%d entries before %s"
  13481. (org-occur regexp nil callback)
  13482. d)))
  13483. (defun org-check-after-date (d)
  13484. "Check if there are deadlines or scheduled entries after date D."
  13485. (interactive (list (org-read-date)))
  13486. (let* ((case-fold-search nil)
  13487. (regexp (org-re-timestamp org-ts-type))
  13488. (ts-type org-ts-type)
  13489. (callback
  13490. (lambda ()
  13491. (let ((match (match-string 1)))
  13492. (and (if (memq ts-type '(active inactive all))
  13493. (eq (org-element-type (save-excursion
  13494. (backward-char)
  13495. (org-element-context)))
  13496. 'timestamp)
  13497. (org-at-planning-p))
  13498. (not (time-less-p
  13499. (org-time-string-to-time match)
  13500. (org-time-string-to-time d))))))))
  13501. (message "%d entries after %s"
  13502. (org-occur regexp nil callback)
  13503. d)))
  13504. (defun org-check-dates-range (start-date end-date)
  13505. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13506. (interactive (list (org-read-date nil nil nil "Range starts")
  13507. (org-read-date nil nil nil "Range end")))
  13508. (let ((case-fold-search nil)
  13509. (regexp (org-re-timestamp org-ts-type))
  13510. (callback
  13511. (let ((type org-ts-type))
  13512. (lambda ()
  13513. (let ((match (match-string 1)))
  13514. (and
  13515. (if (memq type '(active inactive all))
  13516. (eq (org-element-type (save-excursion
  13517. (backward-char)
  13518. (org-element-context)))
  13519. 'timestamp)
  13520. (org-at-planning-p))
  13521. (not (time-less-p
  13522. (org-time-string-to-time match)
  13523. (org-time-string-to-time start-date)))
  13524. (time-less-p
  13525. (org-time-string-to-time match)
  13526. (org-time-string-to-time end-date))))))))
  13527. (message "%d entries between %s and %s"
  13528. (org-occur regexp nil callback) start-date end-date)))
  13529. (defun org-evaluate-time-range (&optional to-buffer)
  13530. "Evaluate a time range by computing the difference between start and end.
  13531. Normally the result is just printed in the echo area, but with prefix arg
  13532. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13533. If the time range is actually in a table, the result is inserted into the
  13534. next column.
  13535. For time difference computation, a year is assumed to be exactly 365
  13536. days in order to avoid rounding problems."
  13537. (interactive "P")
  13538. (or
  13539. (org-clock-update-time-maybe)
  13540. (save-excursion
  13541. (unless (org-at-date-range-p t)
  13542. (goto-char (point-at-bol))
  13543. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13544. (unless (org-at-date-range-p t)
  13545. (user-error "Not at a time-stamp range, and none found in current line")))
  13546. (let* ((ts1 (match-string 1))
  13547. (ts2 (match-string 2))
  13548. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13549. (match-end (match-end 0))
  13550. (time1 (org-time-string-to-time ts1))
  13551. (time2 (org-time-string-to-time ts2))
  13552. (diff (abs (float-time (time-subtract time2 time1))))
  13553. (negative (time-less-p time2 time1))
  13554. ;; (ys (floor (* 365 24 60 60)))
  13555. (ds (* 24 60 60))
  13556. (hs (* 60 60))
  13557. (fy "%dy %dd %02d:%02d")
  13558. (fy1 "%dy %dd")
  13559. (fd "%dd %02d:%02d")
  13560. (fd1 "%dd")
  13561. (fh "%02d:%02d")
  13562. y d h m align)
  13563. (if havetime
  13564. (setq ; y (floor diff ys) diff (mod diff ys)
  13565. y 0
  13566. d (floor diff ds) diff (mod diff ds)
  13567. h (floor diff hs) diff (mod diff hs)
  13568. m (floor diff 60))
  13569. (setq ; y (floor diff ys) diff (mod diff ys)
  13570. y 0
  13571. d (round diff ds)
  13572. h 0 m 0))
  13573. (if (not to-buffer)
  13574. (message "%s" (org-make-tdiff-string y d h m))
  13575. (if (org-at-table-p)
  13576. (progn
  13577. (goto-char match-end)
  13578. (setq align t)
  13579. (and (looking-at " *|") (goto-char (match-end 0))))
  13580. (goto-char match-end))
  13581. (when (looking-at
  13582. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13583. (replace-match ""))
  13584. (when negative (insert " -"))
  13585. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13586. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13587. (insert " " (format fh h m))))
  13588. (when align (org-table-align))
  13589. (message "Time difference inserted")))))
  13590. (defun org-make-tdiff-string (y d h m)
  13591. (let ((fmt "")
  13592. (l nil))
  13593. (when (> y 0)
  13594. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13595. (push y l))
  13596. (when (> d 0)
  13597. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13598. (push d l))
  13599. (when (> h 0)
  13600. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13601. (push h l))
  13602. (when (> m 0)
  13603. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13604. (push m l))
  13605. (apply 'format fmt (nreverse l))))
  13606. (defun org-time-string-to-time (s)
  13607. "Convert timestamp string S into internal time."
  13608. (apply #'encode-time (org-parse-time-string s)))
  13609. (defun org-time-string-to-seconds (s)
  13610. "Convert a timestamp string S into a number of seconds."
  13611. (float-time (org-time-string-to-time s)))
  13612. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13613. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13614. "Convert time stamp S to an absolute day number.
  13615. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13616. stamp, get the closest date to DAYNR. If PREFER is
  13617. `past' (respectively `future') return a date past (respectively
  13618. after) or equal to DAYNR.
  13619. POS is the location of time stamp S, as a buffer position in
  13620. BUFFER.
  13621. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13622. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13623. signaled."
  13624. (cond
  13625. ((string-match "\\`%%\\((.*)\\)" s)
  13626. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13627. ;; only able to match individual dates. If it fails, raise an
  13628. ;; error.
  13629. (if (and daynr
  13630. (org-diary-sexp-entry
  13631. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13632. daynr
  13633. (signal 'org-diary-sexp-no-match (list s))))
  13634. (daynr (org-closest-date s daynr prefer))
  13635. (t (time-to-days
  13636. (condition-case errdata
  13637. (org-time-string-to-time s)
  13638. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13639. s
  13640. (if (not (and buffer pos)) ""
  13641. (format-message " at %d in buffer `%s'" pos buffer))
  13642. (cdr errdata))))))))
  13643. (defun org-days-to-iso-week (days)
  13644. "Return the iso week number."
  13645. (require 'cal-iso)
  13646. (car (calendar-iso-from-absolute days)))
  13647. (defun org-small-year-to-year (year)
  13648. "Convert 2-digit years into 4-digit years.
  13649. YEAR is expanded into one of the 30 next years, if possible, or
  13650. into a past one. Any year larger than 99 is returned unchanged."
  13651. (if (>= year 100) year
  13652. (let* ((current (string-to-number (format-time-string "%Y")))
  13653. (century (/ current 100))
  13654. (offset (- year (% current 100))))
  13655. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13656. ((> offset -70) (+ (* century 100) year))
  13657. (t (+ (* (1+ century) 100) year))))))
  13658. (defun org-time-from-absolute (d)
  13659. "Return the time corresponding to date D.
  13660. D may be an absolute day number, or a calendar-type list (month day year)."
  13661. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13662. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13663. (defvar org-agenda-current-date)
  13664. (defun org-calendar-holiday ()
  13665. "List of holidays, for Diary display in Org mode."
  13666. (require 'holidays)
  13667. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13668. (and hl (mapconcat #'identity hl "; "))))
  13669. (defun org-diary-sexp-entry (sexp entry d)
  13670. "Process a SEXP diary ENTRY for date D."
  13671. (require 'diary-lib)
  13672. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13673. ;; dynamically.
  13674. (let* ((sexp `(let ((entry ,entry)
  13675. (date ',d))
  13676. ,(car (read-from-string sexp))))
  13677. (result (if calendar-debug-sexp (eval sexp)
  13678. (condition-case nil
  13679. (eval sexp)
  13680. (error
  13681. (beep)
  13682. (message "Bad sexp at line %d in %s: %s"
  13683. (org-current-line)
  13684. (buffer-file-name) sexp)
  13685. (sleep-for 2))))))
  13686. (cond ((stringp result) (split-string result "; "))
  13687. ((and (consp result)
  13688. (not (consp (cdr result)))
  13689. (stringp (cdr result))) (cdr result))
  13690. ((and (consp result)
  13691. (stringp (car result))) result)
  13692. (result entry))))
  13693. (defun org-diary-to-ical-string (frombuf)
  13694. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13695. This uses the icalendar.el library."
  13696. (let* ((tmpdir temporary-file-directory)
  13697. (tmpfile (make-temp-name
  13698. (expand-file-name "orgics" tmpdir)))
  13699. buf rtn b e)
  13700. (with-current-buffer frombuf
  13701. (icalendar-export-region (point-min) (point-max) tmpfile)
  13702. (setq buf (find-buffer-visiting tmpfile))
  13703. (set-buffer buf)
  13704. (goto-char (point-min))
  13705. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13706. (setq b (match-beginning 0)))
  13707. (goto-char (point-max))
  13708. (when (re-search-backward "^END:VEVENT" nil t)
  13709. (setq e (match-end 0)))
  13710. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13711. (kill-buffer buf)
  13712. (delete-file tmpfile)
  13713. rtn))
  13714. (defun org-closest-date (start current prefer)
  13715. "Return closest date to CURRENT starting from START.
  13716. CURRENT and START are both time stamps.
  13717. When PREFER is `past', return a date that is either CURRENT or
  13718. past. When PREFER is `future', return a date that is either
  13719. CURRENT or future.
  13720. Only time stamps with a repeater are modified. Any other time
  13721. stamp stay unchanged. In any case, return value is an absolute
  13722. day number."
  13723. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13724. ;; No repeater. Do not shift time stamp.
  13725. (time-to-days (org-time-string-to-time start))
  13726. (let ((value (string-to-number (match-string 1 start)))
  13727. (type (match-string 2 start)))
  13728. (if (= 0 value)
  13729. ;; Repeater with a 0-value is considered as void.
  13730. (time-to-days (org-time-string-to-time start))
  13731. (let* ((base (org-date-to-gregorian start))
  13732. (target (org-date-to-gregorian current))
  13733. (sday (calendar-absolute-from-gregorian base))
  13734. (cday (calendar-absolute-from-gregorian target))
  13735. n1 n2)
  13736. ;; If START is already past CURRENT, just return START.
  13737. (if (<= cday sday) sday
  13738. ;; Compute closest date before (N1) and closest date past
  13739. ;; (N2) CURRENT.
  13740. (pcase type
  13741. ("h"
  13742. (let ((missing-hours
  13743. (mod (+ (- (* 24 (- cday sday))
  13744. (nth 2 (org-parse-time-string start)))
  13745. org-extend-today-until)
  13746. value)))
  13747. (setf n1 (if (= missing-hours 0) cday
  13748. (- cday (1+ (/ missing-hours 24)))))
  13749. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13750. ((or "d" "w")
  13751. (let ((value (if (equal type "w") (* 7 value) value)))
  13752. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13753. (setf n2 (+ n1 value))))
  13754. ("m"
  13755. (let* ((add-months
  13756. (lambda (d n)
  13757. ;; Add N months to gregorian date D, i.e.,
  13758. ;; a list (MONTH DAY YEAR). Return a valid
  13759. ;; gregorian date.
  13760. (let ((m (+ (nth 0 d) n)))
  13761. (list (mod m 12)
  13762. (nth 1 d)
  13763. (+ (/ m 12) (nth 2 d))))))
  13764. (months ; Complete months to TARGET.
  13765. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13766. (- (nth 0 target) (nth 0 base))
  13767. ;; If START's day is greater than
  13768. ;; TARGET's, remove incomplete month.
  13769. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13770. value)
  13771. value))
  13772. (before (funcall add-months base months)))
  13773. (setf n1 (calendar-absolute-from-gregorian before))
  13774. (setf n2
  13775. (calendar-absolute-from-gregorian
  13776. (funcall add-months before value)))))
  13777. (_
  13778. (let* ((d (nth 1 base))
  13779. (m (nth 0 base))
  13780. (y (nth 2 base))
  13781. (years ; Complete years to TARGET.
  13782. (* (/ (- (nth 2 target)
  13783. y
  13784. ;; If START's month and day are
  13785. ;; greater than TARGET's, remove
  13786. ;; incomplete year.
  13787. (if (or (> (nth 0 target) m)
  13788. (and (= (nth 0 target) m)
  13789. (> (nth 1 target) d)))
  13790. 0
  13791. 1))
  13792. value)
  13793. value))
  13794. (before (list m d (+ y years))))
  13795. (setf n1 (calendar-absolute-from-gregorian before))
  13796. (setf n2 (calendar-absolute-from-gregorian
  13797. (list m d (+ (nth 2 before) value)))))))
  13798. ;; Handle PREFER parameter, if any.
  13799. (cond
  13800. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13801. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13802. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13803. (defun org-date-to-gregorian (d)
  13804. "Turn any specification of date D into a Gregorian date for the calendar."
  13805. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13806. ((and (listp d) (= (length d) 3)) d)
  13807. ((stringp d)
  13808. (let ((d (org-parse-time-string d)))
  13809. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13810. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13811. (defun org-timestamp-up (&optional arg)
  13812. "Increase the date item at the cursor by one.
  13813. If the cursor is on the year, change the year. If it is on the month,
  13814. the day or the time, change that. If the cursor is on the enclosing
  13815. bracket, change the timestamp type.
  13816. With prefix ARG, change by that many units."
  13817. (interactive "p")
  13818. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13819. (defun org-timestamp-down (&optional arg)
  13820. "Decrease the date item at the cursor by one.
  13821. If the cursor is on the year, change the year. If it is on the month,
  13822. the day or the time, change that. If the cursor is on the enclosing
  13823. bracket, change the timestamp type.
  13824. With prefix ARG, change by that many units."
  13825. (interactive "p")
  13826. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13827. (defun org-timestamp-up-day (&optional arg)
  13828. "Increase the date in the time stamp by one day.
  13829. With prefix ARG, change that many days."
  13830. (interactive "p")
  13831. (if (and (not (org-at-timestamp-p 'lax))
  13832. (org-at-heading-p))
  13833. (org-todo 'up)
  13834. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13835. (defun org-timestamp-down-day (&optional arg)
  13836. "Decrease the date in the time stamp by one day.
  13837. With prefix ARG, change that many days."
  13838. (interactive "p")
  13839. (if (and (not (org-at-timestamp-p 'lax))
  13840. (org-at-heading-p))
  13841. (org-todo 'down)
  13842. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13843. (defun org-at-timestamp-p (&optional extended)
  13844. "Non-nil if point is inside a timestamp.
  13845. By default, the function only consider syntactically valid active
  13846. timestamps. However, the caller may have a broader definition
  13847. for timestamps. As a consequence, optional argument EXTENDED can
  13848. be set to the following values
  13849. `inactive'
  13850. Include also syntactically valid inactive timestamps.
  13851. `agenda'
  13852. Include timestamps allowed in Agenda, i.e., those in
  13853. properties drawers, planning lines and clock lines.
  13854. `lax'
  13855. Ignore context. The function matches any part of the
  13856. document looking like a timestamp. This includes comments,
  13857. example blocks...
  13858. For backward-compatibility with Org 9.0, every other non-nil
  13859. value is equivalent to `inactive'.
  13860. When at a timestamp, return the position of the point as a symbol
  13861. among `bracket', `after', `year', `month', `hour', `minute',
  13862. `day' or a number of character from the last know part of the
  13863. time stamp.
  13864. When matching, the match groups are the following:
  13865. group 1: year
  13866. group 2: month
  13867. group 3: day number
  13868. group 4: day name
  13869. group 5: hours, if any
  13870. group 6: minutes, if any"
  13871. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13872. (pos (point))
  13873. (match?
  13874. (let ((boundaries (org-in-regexp regexp)))
  13875. (save-match-data
  13876. (cond ((null boundaries) nil)
  13877. ((eq extended 'lax) t)
  13878. (t
  13879. (or (and (eq extended 'agenda)
  13880. (or (org-at-planning-p)
  13881. (org-at-property-p)
  13882. (and (bound-and-true-p
  13883. org-agenda-include-inactive-timestamps)
  13884. (org-at-clock-log-p))))
  13885. (eq 'timestamp
  13886. (save-excursion
  13887. (when (= pos (cdr boundaries)) (forward-char -1))
  13888. (org-element-type (org-element-context)))))))))))
  13889. (cond
  13890. ((not match?) nil)
  13891. ((= pos (match-beginning 0)) 'bracket)
  13892. ;; Distinguish location right before the closing bracket from
  13893. ;; right after it.
  13894. ((= pos (1- (match-end 0))) 'bracket)
  13895. ((= pos (match-end 0)) 'after)
  13896. ((org-pos-in-match-range pos 2) 'year)
  13897. ((org-pos-in-match-range pos 3) 'month)
  13898. ((org-pos-in-match-range pos 7) 'hour)
  13899. ((org-pos-in-match-range pos 8) 'minute)
  13900. ((or (org-pos-in-match-range pos 4)
  13901. (org-pos-in-match-range pos 5)) 'day)
  13902. ((and (> pos (or (match-end 8) (match-end 5)))
  13903. (< pos (match-end 0)))
  13904. (- pos (or (match-end 8) (match-end 5))))
  13905. (t 'day))))
  13906. (defun org-toggle-timestamp-type ()
  13907. "Toggle the type (<active> or [inactive]) of a time stamp."
  13908. (interactive)
  13909. (when (org-at-timestamp-p 'lax)
  13910. (let ((beg (match-beginning 0)) (end (match-end 0))
  13911. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13912. (save-excursion
  13913. (goto-char beg)
  13914. (while (re-search-forward "[][<>]" end t)
  13915. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13916. t t)))
  13917. (message "Timestamp is now %sactive"
  13918. (if (equal (char-after beg) ?<) "" "in")))))
  13919. (defun org-at-clock-log-p ()
  13920. "Non-nil if point is on a clock log line."
  13921. (and (org-match-line org-clock-line-re)
  13922. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13923. (defvar org-clock-history) ; defined in org-clock.el
  13924. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13925. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13926. "Change the date in the time stamp at point.
  13927. The date is changed by N times WHAT. WHAT can be `day', `month',
  13928. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13929. position in the timestamp determines what is changed.
  13930. When optional argument UPDOWN is non-nil, minutes are rounded
  13931. according to `org-time-stamp-rounding-minutes'.
  13932. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13933. \"--2d\"."
  13934. (let ((origin (point))
  13935. (timestamp? (org-at-timestamp-p 'lax))
  13936. origin-cat
  13937. with-hm inactive
  13938. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13939. extra rem
  13940. ts time time0 fixnext clrgx)
  13941. (unless timestamp? (user-error "Not at a timestamp"))
  13942. (if (and (not what) (eq timestamp? 'bracket))
  13943. (org-toggle-timestamp-type)
  13944. ;; Point isn't on brackets. Remember the part of the time-stamp
  13945. ;; the point was in. Indeed, size of time-stamps may change,
  13946. ;; but point must be kept in the same category nonetheless.
  13947. (setq origin-cat timestamp?)
  13948. (when (and (not what) (not (eq timestamp? 'day))
  13949. org-display-custom-times
  13950. (get-text-property (point) 'display)
  13951. (not (get-text-property (1- (point)) 'display)))
  13952. (setq timestamp? 'day))
  13953. (setq timestamp? (or what timestamp?)
  13954. inactive (= (char-after (match-beginning 0)) ?\[)
  13955. ts (match-string 0))
  13956. (replace-match "")
  13957. (when (string-match
  13958. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13959. ts)
  13960. (setq extra (match-string 1 ts))
  13961. (when suppress-tmp-delay
  13962. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13963. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13964. (setq with-hm t))
  13965. (setq time0 (org-parse-time-string ts))
  13966. (when (and updown
  13967. (eq timestamp? 'minute)
  13968. (not current-prefix-arg))
  13969. ;; This looks like s-up and s-down. Change by one rounding step.
  13970. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13971. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13972. (setcar (cdr time0) (+ (nth 1 time0)
  13973. (if (> n 0) (- rem) (- dm rem))))))
  13974. (setq time
  13975. (apply #'encode-time
  13976. (or (car time0) 0)
  13977. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13978. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13979. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13980. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13981. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13982. (nthcdr 6 time0)))
  13983. (when (and (memq timestamp? '(hour minute))
  13984. extra
  13985. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13986. (setq extra (org-modify-ts-extra
  13987. extra
  13988. (if (eq timestamp? 'hour) 2 5)
  13989. n dm)))
  13990. (when (integerp timestamp?)
  13991. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13992. (when (eq what 'calendar)
  13993. (let ((cal-date (org-get-date-from-calendar)))
  13994. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13995. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13996. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13997. (setcar time0 (or (car time0) 0))
  13998. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13999. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14000. (setq time (apply 'encode-time time0))))
  14001. ;; Insert the new time-stamp, and ensure point stays in the same
  14002. ;; category as before (i.e. not after the last position in that
  14003. ;; category).
  14004. (let ((pos (point)))
  14005. ;; Stay before inserted string. `save-excursion' is of no use.
  14006. (setq org-last-changed-timestamp
  14007. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14008. (goto-char pos))
  14009. (save-match-data
  14010. (looking-at org-ts-regexp3)
  14011. (goto-char
  14012. (pcase origin-cat
  14013. ;; `day' category ends before `hour' if any, or at the end
  14014. ;; of the day name.
  14015. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14016. (`hour (min (match-end 7) origin))
  14017. (`minute (min (1- (match-end 8)) origin))
  14018. ((pred integerp) (min (1- (match-end 0)) origin))
  14019. ;; Point was right after the time-stamp. However, the
  14020. ;; time-stamp length might have changed, so refer to
  14021. ;; (match-end 0) instead.
  14022. (`after (match-end 0))
  14023. ;; `year' and `month' have both fixed size: point couldn't
  14024. ;; have moved into another part.
  14025. (_ origin))))
  14026. ;; Update clock if on a CLOCK line.
  14027. (org-clock-update-time-maybe)
  14028. ;; Maybe adjust the closest clock in `org-clock-history'
  14029. (when org-clock-adjust-closest
  14030. (if (not (and (org-at-clock-log-p)
  14031. (< 1 (length (delq nil (mapcar 'marker-position
  14032. org-clock-history))))))
  14033. (message "No clock to adjust")
  14034. (cond ((save-excursion ; fix previous clock?
  14035. (re-search-backward org-ts-regexp0 nil t)
  14036. (looking-back (concat org-clock-string " \\[")
  14037. (line-beginning-position)))
  14038. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14039. ((save-excursion ; fix next clock?
  14040. (re-search-backward org-ts-regexp0 nil t)
  14041. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14042. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14043. (save-window-excursion
  14044. ;; Find closest clock to point, adjust the previous/next one in history
  14045. (let* ((p (save-excursion (org-back-to-heading t)))
  14046. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14047. (clfixnth
  14048. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14049. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14050. (if (not clfixpos)
  14051. (message "No clock to adjust")
  14052. (save-excursion
  14053. (org-goto-marker-or-bmk clfixpos)
  14054. (org-show-subtree)
  14055. (when (re-search-forward clrgx nil t)
  14056. (goto-char (match-beginning 1))
  14057. (let (org-clock-adjust-closest)
  14058. (org-timestamp-change n timestamp? updown))
  14059. (message "Clock adjusted in %s for heading: %s"
  14060. (file-name-nondirectory (buffer-file-name))
  14061. (org-get-heading t t)))))))))
  14062. ;; Try to recenter the calendar window, if any.
  14063. (when (and org-calendar-follow-timestamp-change
  14064. (get-buffer-window "*Calendar*" t)
  14065. (memq timestamp? '(day month year)))
  14066. (org-recenter-calendar (time-to-days time))))))
  14067. (defun org-modify-ts-extra (s pos n dm)
  14068. "Change the different parts of the lead-time and repeat fields in timestamp."
  14069. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14070. ng h m new rem)
  14071. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14072. (cond
  14073. ((or (org-pos-in-match-range pos 2)
  14074. (org-pos-in-match-range pos 3))
  14075. (setq m (string-to-number (match-string 3 s))
  14076. h (string-to-number (match-string 2 s)))
  14077. (if (org-pos-in-match-range pos 2)
  14078. (setq h (+ h n))
  14079. (setq n (* dm (with-no-warnings (cl-signum n))))
  14080. (unless (= 0 (setq rem (% m dm)))
  14081. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14082. (setq m (+ m n)))
  14083. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14084. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14085. (setq h (mod h 24))
  14086. (setq ng 1 new (format "-%02d:%02d" h m)))
  14087. ((org-pos-in-match-range pos 6)
  14088. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14089. ((org-pos-in-match-range pos 5)
  14090. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14091. ((org-pos-in-match-range pos 9)
  14092. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14093. ((org-pos-in-match-range pos 8)
  14094. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14095. (when ng
  14096. (setq s (concat
  14097. (substring s 0 (match-beginning ng))
  14098. new
  14099. (substring s (match-end ng))))))
  14100. s))
  14101. (defun org-recenter-calendar (d)
  14102. "If the calendar is visible, recenter it to date D."
  14103. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14104. (when cwin
  14105. (let ((calendar-move-hook nil))
  14106. (with-selected-window cwin
  14107. (calendar-goto-date
  14108. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14109. (defun org-goto-calendar (&optional arg)
  14110. "Go to the Emacs calendar at the current date.
  14111. If there is a time stamp in the current line, go to that date.
  14112. A prefix ARG can be used to force the current date."
  14113. (interactive "P")
  14114. (let ((calendar-move-hook nil)
  14115. (calendar-view-holidays-initially-flag nil)
  14116. (calendar-view-diary-initially-flag nil)
  14117. diff)
  14118. (when (or (org-at-timestamp-p 'lax)
  14119. (org-match-line (concat ".*" org-ts-regexp)))
  14120. (let ((d1 (time-to-days nil))
  14121. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14122. (setq diff (- d2 d1))))
  14123. (calendar)
  14124. (calendar-goto-today)
  14125. (when (and diff (not arg)) (calendar-forward-day diff))))
  14126. (defun org-get-date-from-calendar ()
  14127. "Return a list (month day year) of date at point in calendar."
  14128. (with-current-buffer "*Calendar*"
  14129. (save-match-data
  14130. (calendar-cursor-to-date))))
  14131. (defun org-date-from-calendar ()
  14132. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14133. If there is already a time stamp at the cursor position, update it."
  14134. (interactive)
  14135. (if (org-at-timestamp-p 'lax)
  14136. (org-timestamp-change 0 'calendar)
  14137. (let ((cal-date (org-get-date-from-calendar)))
  14138. (org-insert-time-stamp
  14139. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14140. (defcustom org-image-actual-width t
  14141. "When non-nil, use the actual width of images when inlining them.
  14142. When set to a number, use imagemagick (when available) to set the
  14143. image's width to this value.
  14144. When set to a number in a list, try to get the width from any
  14145. #+ATTR.* keyword if it matches a width specification like
  14146. #+ATTR_HTML: :width 300px
  14147. and fall back on that number if none is found.
  14148. When set to nil, try to get the width from an #+ATTR.* keyword
  14149. and fall back on the original width if none is found.
  14150. When set to any other non-nil value, always use the image width.
  14151. This requires Emacs >= 24.1, built with imagemagick support."
  14152. :group 'org-appearance
  14153. :version "24.4"
  14154. :package-version '(Org . "8.0")
  14155. :type '(choice
  14156. (const :tag "Use the image width" t)
  14157. (integer :tag "Use a number of pixels")
  14158. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14159. (const :tag "Use #+ATTR* or don't resize" nil)))
  14160. (defcustom org-agenda-inhibit-startup nil
  14161. "Inhibit startup when preparing agenda buffers.
  14162. When this variable is t, the initialization of the Org agenda
  14163. buffers is inhibited: e.g. the visibility state is not set, the
  14164. tables are not re-aligned, etc."
  14165. :type 'boolean
  14166. :version "24.3"
  14167. :group 'org-agenda)
  14168. (defcustom org-agenda-ignore-properties nil
  14169. "Avoid updating text properties when building the agenda.
  14170. Properties are used to prepare buffers for effort estimates,
  14171. appointments, statistics and subtree-local categories.
  14172. If you don't use these in the agenda, you can add them to this
  14173. list and agenda building will be a bit faster.
  14174. The value is a list, with zero or more of the symbols `effort', `appt',
  14175. `stats' or `category'."
  14176. :type '(set :greedy t
  14177. (const effort)
  14178. (const appt)
  14179. (const stats)
  14180. (const category))
  14181. :version "26.1"
  14182. :package-version '(Org . "8.3")
  14183. :group 'org-agenda)
  14184. ;;;; Files
  14185. (defun org-save-all-org-buffers ()
  14186. "Save all Org buffers without user confirmation."
  14187. (interactive)
  14188. (message "Saving all Org buffers...")
  14189. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14190. (when (featurep 'org-id) (org-id-locations-save))
  14191. (message "Saving all Org buffers... done"))
  14192. (defun org-revert-all-org-buffers ()
  14193. "Revert all Org buffers.
  14194. Prompt for confirmation when there are unsaved changes.
  14195. Be sure you know what you are doing before letting this function
  14196. overwrite your changes.
  14197. This function is useful in a setup where one tracks Org files
  14198. with a version control system, to revert on one machine after pulling
  14199. changes from another. I believe the procedure must be like this:
  14200. 1. M-x org-save-all-org-buffers
  14201. 2. Pull changes from the other machine, resolve conflicts
  14202. 3. M-x org-revert-all-org-buffers"
  14203. (interactive)
  14204. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14205. (user-error "Abort"))
  14206. (save-excursion
  14207. (save-window-excursion
  14208. (dolist (b (buffer-list))
  14209. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14210. (with-current-buffer b buffer-file-name))
  14211. (pop-to-buffer-same-window b)
  14212. (revert-buffer t 'no-confirm)))
  14213. (when (and (featurep 'org-id) org-id-track-globally)
  14214. (org-id-locations-load)))))
  14215. ;;;; Agenda files
  14216. ;;;###autoload
  14217. (defun org-switchb (&optional arg)
  14218. "Switch between Org buffers.
  14219. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14220. With `\\[universal-argument] \\[universal-argument]' \
  14221. prefix, restrict available buffers to agenda files."
  14222. (interactive "P")
  14223. (let ((blist (org-buffer-list
  14224. (cond ((equal arg '(4)) 'files)
  14225. ((equal arg '(16)) 'agenda)))))
  14226. (pop-to-buffer-same-window
  14227. (completing-read "Org buffer: "
  14228. (mapcar #'list (mapcar #'buffer-name blist))
  14229. nil t))))
  14230. (defun org-buffer-list (&optional predicate exclude-tmp)
  14231. "Return a list of Org buffers.
  14232. PREDICATE can be `export', `files' or `agenda'.
  14233. export restrict the list to Export buffers.
  14234. files restrict the list to buffers visiting Org files.
  14235. agenda restrict the list to buffers visiting agenda files.
  14236. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14237. (let* ((bfn nil)
  14238. (agenda-files (and (eq predicate 'agenda)
  14239. (mapcar 'file-truename (org-agenda-files t))))
  14240. (filter
  14241. (cond
  14242. ((eq predicate 'files)
  14243. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14244. ((eq predicate 'export)
  14245. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14246. ((eq predicate 'agenda)
  14247. (lambda (b)
  14248. (with-current-buffer b
  14249. (and (derived-mode-p 'org-mode)
  14250. (setq bfn (buffer-file-name b))
  14251. (member (file-truename bfn) agenda-files)))))
  14252. (t (lambda (b) (with-current-buffer b
  14253. (or (derived-mode-p 'org-mode)
  14254. (string-match "\\*Org .*Export"
  14255. (buffer-name b)))))))))
  14256. (delq nil
  14257. (mapcar
  14258. (lambda(b)
  14259. (if (and (funcall filter b)
  14260. (or (not exclude-tmp)
  14261. (not (string-match "tmp" (buffer-name b)))))
  14262. b
  14263. nil))
  14264. (buffer-list)))))
  14265. (defun org-agenda-files (&optional unrestricted archives)
  14266. "Get the list of agenda files.
  14267. Optional UNRESTRICTED means return the full list even if a restriction
  14268. is currently in place.
  14269. When ARCHIVES is t, include all archive files that are really being
  14270. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14271. `org-agenda-archives-mode' is t."
  14272. (let ((files
  14273. (cond
  14274. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14275. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14276. ((listp org-agenda-files) org-agenda-files)
  14277. (t (error "Invalid value of `org-agenda-files'")))))
  14278. (setq files (apply 'append
  14279. (mapcar (lambda (f)
  14280. (if (file-directory-p f)
  14281. (directory-files
  14282. f t org-agenda-file-regexp)
  14283. (list f)))
  14284. files)))
  14285. (when org-agenda-skip-unavailable-files
  14286. (setq files (delq nil
  14287. (mapcar (function
  14288. (lambda (file)
  14289. (and (file-readable-p file) file)))
  14290. files))))
  14291. (when (or (eq archives t)
  14292. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14293. (setq files (org-add-archive-files files)))
  14294. files))
  14295. (defun org-agenda-file-p (&optional file)
  14296. "Return non-nil, if FILE is an agenda file.
  14297. If FILE is omitted, use the file associated with the current
  14298. buffer."
  14299. (let ((fname (or file (buffer-file-name))))
  14300. (and fname
  14301. (member (file-truename fname)
  14302. (mapcar #'file-truename (org-agenda-files t))))))
  14303. (defun org-edit-agenda-file-list ()
  14304. "Edit the list of agenda files.
  14305. Depending on setup, this either uses customize to edit the variable
  14306. `org-agenda-files', or it visits the file that is holding the list. In the
  14307. latter case, the buffer is set up in a way that saving it automatically kills
  14308. the buffer and restores the previous window configuration."
  14309. (interactive)
  14310. (if (stringp org-agenda-files)
  14311. (let ((cw (current-window-configuration)))
  14312. (find-file org-agenda-files)
  14313. (setq-local org-window-configuration cw)
  14314. (add-hook 'after-save-hook
  14315. (lambda ()
  14316. (set-window-configuration
  14317. (prog1 org-window-configuration
  14318. (kill-buffer (current-buffer))))
  14319. (org-install-agenda-files-menu)
  14320. (message "New agenda file list installed"))
  14321. nil 'local)
  14322. (message "%s" (substitute-command-keys
  14323. "Edit list and finish with \\[save-buffer]")))
  14324. (customize-variable 'org-agenda-files)))
  14325. (defun org-store-new-agenda-file-list (list)
  14326. "Set new value for the agenda file list and save it correctly."
  14327. (if (stringp org-agenda-files)
  14328. (let ((fe (org-read-agenda-file-list t)) b u)
  14329. (while (setq b (find-buffer-visiting org-agenda-files))
  14330. (kill-buffer b))
  14331. (with-temp-file org-agenda-files
  14332. (insert
  14333. (mapconcat
  14334. (lambda (f) ;; Keep un-expanded entries.
  14335. (if (setq u (assoc f fe))
  14336. (cdr u)
  14337. f))
  14338. list "\n")
  14339. "\n")))
  14340. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14341. (org-insert-mode-line-in-empty-file nil))
  14342. (setq org-agenda-files list)
  14343. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14344. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14345. "Read the list of agenda files from a file.
  14346. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14347. filenames, used by `org-store-new-agenda-file-list' to write back
  14348. un-expanded file names."
  14349. (when (file-directory-p org-agenda-files)
  14350. (error "`org-agenda-files' cannot be a single directory"))
  14351. (when (stringp org-agenda-files)
  14352. (with-temp-buffer
  14353. (insert-file-contents org-agenda-files)
  14354. (mapcar
  14355. (lambda (f)
  14356. (let ((e (expand-file-name (substitute-in-file-name f)
  14357. org-directory)))
  14358. (if pair-with-expansion
  14359. (cons e f)
  14360. e)))
  14361. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14362. ;;;###autoload
  14363. (defun org-cycle-agenda-files ()
  14364. "Cycle through the files in `org-agenda-files'.
  14365. If the current buffer visits an agenda file, find the next one in the list.
  14366. If the current buffer does not, find the first agenda file."
  14367. (interactive)
  14368. (let* ((fs (or (org-agenda-files t)
  14369. (user-error "No agenda files")))
  14370. (files (copy-sequence fs))
  14371. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14372. file)
  14373. (when tcf
  14374. (while (and (setq file (pop files))
  14375. (not (equal (file-truename file) tcf)))))
  14376. (find-file (car (or files fs)))
  14377. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14378. (defun org-agenda-file-to-front (&optional to-end)
  14379. "Move/add the current file to the top of the agenda file list.
  14380. If the file is not present in the list, it is added to the front. If it is
  14381. present, it is moved there. With optional argument TO-END, add/move to the
  14382. end of the list."
  14383. (interactive "P")
  14384. (let ((org-agenda-skip-unavailable-files nil)
  14385. (file-alist (mapcar (lambda (x)
  14386. (cons (file-truename x) x))
  14387. (org-agenda-files t)))
  14388. (ctf (file-truename
  14389. (or buffer-file-name
  14390. (user-error "Please save the current buffer to a file"))))
  14391. x had)
  14392. (setq x (assoc ctf file-alist) had x)
  14393. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14394. (if to-end
  14395. (setq file-alist (append (delq x file-alist) (list x)))
  14396. (setq file-alist (cons x (delq x file-alist))))
  14397. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14398. (org-install-agenda-files-menu)
  14399. (message "File %s to %s of agenda file list"
  14400. (if had "moved" "added") (if to-end "end" "front"))))
  14401. (defun org-remove-file (&optional file)
  14402. "Remove current file from the list of files in variable `org-agenda-files'.
  14403. These are the files which are being checked for agenda entries.
  14404. Optional argument FILE means use this file instead of the current."
  14405. (interactive)
  14406. (let* ((org-agenda-skip-unavailable-files nil)
  14407. (file (or file buffer-file-name
  14408. (user-error "Current buffer does not visit a file")))
  14409. (true-file (file-truename file))
  14410. (afile (abbreviate-file-name file))
  14411. (files (delq nil (mapcar
  14412. (lambda (x)
  14413. (unless (equal true-file
  14414. (file-truename x))
  14415. x))
  14416. (org-agenda-files t)))))
  14417. (if (not (= (length files) (length (org-agenda-files t))))
  14418. (progn
  14419. (org-store-new-agenda-file-list files)
  14420. (org-install-agenda-files-menu)
  14421. (message "Removed from Org Agenda list: %s" afile))
  14422. (message "File was not in list: %s (not removed)" afile))))
  14423. (defun org-file-menu-entry (file)
  14424. (vector file (list 'find-file file) t))
  14425. (defun org-check-agenda-file (file)
  14426. "Make sure FILE exists. If not, ask user what to do."
  14427. (unless (file-exists-p file)
  14428. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14429. (abbreviate-file-name file))
  14430. (let ((r (downcase (read-char-exclusive))))
  14431. (cond
  14432. ((equal r ?r)
  14433. (org-remove-file file)
  14434. (throw 'nextfile t))
  14435. (t (user-error "Abort"))))))
  14436. (defun org-get-agenda-file-buffer (file)
  14437. "Get an agenda buffer visiting FILE.
  14438. If the buffer needs to be created, add it to the list of buffers
  14439. which might be released later."
  14440. (let ((buf (org-find-base-buffer-visiting file)))
  14441. (if buf
  14442. buf ; just return it
  14443. ;; Make a new buffer and remember it
  14444. (setq buf (find-file-noselect file))
  14445. (when buf (push buf org-agenda-new-buffers))
  14446. buf)))
  14447. (defun org-release-buffers (blist)
  14448. "Release all buffers in list, asking the user for confirmation when needed.
  14449. When a buffer is unmodified, it is just killed. When modified, it is saved
  14450. \(if the user agrees) and then killed."
  14451. (let (file)
  14452. (dolist (buf blist)
  14453. (setq file (buffer-file-name buf))
  14454. (when (and (buffer-modified-p buf)
  14455. file
  14456. (y-or-n-p (format "Save file %s? " file)))
  14457. (with-current-buffer buf (save-buffer)))
  14458. (kill-buffer buf))))
  14459. (defun org-agenda-prepare-buffers (files)
  14460. "Create buffers for all agenda files, protect archived trees and comments."
  14461. (interactive)
  14462. (let ((pa '(:org-archived t))
  14463. (pc '(:org-comment t))
  14464. (pall '(:org-archived t :org-comment t))
  14465. (inhibit-read-only t)
  14466. (org-inhibit-startup org-agenda-inhibit-startup)
  14467. (rea (org-make-tag-string (list org-archive-tag)))
  14468. re pos)
  14469. (setq org-tag-alist-for-agenda nil
  14470. org-tag-groups-alist-for-agenda nil)
  14471. (save-excursion
  14472. (save-restriction
  14473. (dolist (file files)
  14474. (catch 'nextfile
  14475. (if (bufferp file)
  14476. (set-buffer file)
  14477. (org-check-agenda-file file)
  14478. (set-buffer (org-get-agenda-file-buffer file)))
  14479. (widen)
  14480. (org-set-regexps-and-options 'tags-only)
  14481. (setq pos (point))
  14482. (or (memq 'category org-agenda-ignore-properties)
  14483. (org-refresh-category-properties))
  14484. (or (memq 'stats org-agenda-ignore-properties)
  14485. (org-refresh-stats-properties))
  14486. (or (memq 'effort org-agenda-ignore-properties)
  14487. (org-refresh-effort-properties))
  14488. (or (memq 'appt org-agenda-ignore-properties)
  14489. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14490. (setq org-todo-keywords-for-agenda
  14491. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14492. (setq org-done-keywords-for-agenda
  14493. (append org-done-keywords-for-agenda org-done-keywords))
  14494. (setq org-todo-keyword-alist-for-agenda
  14495. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14496. (setq org-tag-alist-for-agenda
  14497. (org--tag-add-to-alist
  14498. org-tag-alist-for-agenda
  14499. org-current-tag-alist))
  14500. ;; Merge current file's tag groups into global
  14501. ;; `org-tag-groups-alist-for-agenda'.
  14502. (when org-group-tags
  14503. (dolist (alist org-tag-groups-alist)
  14504. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14505. (if old
  14506. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14507. (push alist org-tag-groups-alist-for-agenda)))))
  14508. (with-silent-modifications
  14509. (save-excursion
  14510. (remove-text-properties (point-min) (point-max) pall)
  14511. (when org-agenda-skip-archived-trees
  14512. (goto-char (point-min))
  14513. (while (re-search-forward rea nil t)
  14514. (when (org-at-heading-p t)
  14515. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14516. (goto-char (point-min))
  14517. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14518. (while (re-search-forward re nil t)
  14519. (when (save-match-data (org-in-commented-heading-p t))
  14520. (add-text-properties
  14521. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14522. (goto-char pos)))))
  14523. (setq org-todo-keywords-for-agenda
  14524. (org-uniquify org-todo-keywords-for-agenda))
  14525. (setq org-todo-keyword-alist-for-agenda
  14526. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14527. ;;;; CDLaTeX minor mode
  14528. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14529. "Keymap for the minor `org-cdlatex-mode'.")
  14530. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14531. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14532. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14533. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14534. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14535. (defvar org-cdlatex-texmathp-advice-is-done nil
  14536. "Flag remembering if we have applied the advice to texmathp already.")
  14537. (define-minor-mode org-cdlatex-mode
  14538. "Toggle the minor `org-cdlatex-mode'.
  14539. This mode supports entering LaTeX environment and math in LaTeX fragments
  14540. in Org mode.
  14541. \\{org-cdlatex-mode-map}"
  14542. nil " OCDL" nil
  14543. (when org-cdlatex-mode
  14544. (require 'cdlatex)
  14545. (run-hooks 'cdlatex-mode-hook)
  14546. (cdlatex-compute-tables))
  14547. (unless org-cdlatex-texmathp-advice-is-done
  14548. (setq org-cdlatex-texmathp-advice-is-done t)
  14549. (defadvice texmathp (around org-math-always-on activate)
  14550. "Always return t in Org buffers.
  14551. This is because we want to insert math symbols without dollars even outside
  14552. the LaTeX math segments. If Org mode thinks that point is actually inside
  14553. an embedded LaTeX fragment, let `texmathp' do its job.
  14554. `\\[org-cdlatex-mode-map]'"
  14555. (interactive)
  14556. (let (p)
  14557. (cond
  14558. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14559. ((eq this-command 'cdlatex-math-symbol)
  14560. (setq ad-return-value t
  14561. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14562. (t
  14563. (let ((p (org-inside-LaTeX-fragment-p)))
  14564. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14565. (setq ad-return-value t
  14566. texmathp-why '("Org mode embedded math" . 0))
  14567. (when p ad-do-it)))))))))
  14568. (defun turn-on-org-cdlatex ()
  14569. "Unconditionally turn on `org-cdlatex-mode'."
  14570. (org-cdlatex-mode 1))
  14571. (defun org-try-cdlatex-tab ()
  14572. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14573. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14574. - inside a LaTeX fragment, or
  14575. - after the first word in a line, where an abbreviation expansion could
  14576. insert a LaTeX environment."
  14577. (when org-cdlatex-mode
  14578. (cond
  14579. ;; Before any word on the line: No expansion possible.
  14580. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14581. ;; Just after first word on the line: Expand it. Make sure it
  14582. ;; cannot happen on headlines, though.
  14583. ((save-excursion
  14584. (skip-chars-backward "a-zA-Z0-9*")
  14585. (skip-chars-backward " \t")
  14586. (and (bolp) (not (org-at-heading-p))))
  14587. (cdlatex-tab) t)
  14588. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14589. (defun org-cdlatex-underscore-caret (&optional _arg)
  14590. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14591. Revert to the normal definition outside of these fragments."
  14592. (interactive "P")
  14593. (if (org-inside-LaTeX-fragment-p)
  14594. (call-interactively 'cdlatex-sub-superscript)
  14595. (let (org-cdlatex-mode)
  14596. (call-interactively (key-binding (vector last-input-event))))))
  14597. (defun org-cdlatex-math-modify (&optional _arg)
  14598. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14599. Revert to the normal definition outside of these fragments."
  14600. (interactive "P")
  14601. (if (org-inside-LaTeX-fragment-p)
  14602. (call-interactively 'cdlatex-math-modify)
  14603. (let (org-cdlatex-mode)
  14604. (call-interactively (key-binding (vector last-input-event))))))
  14605. (defun org-cdlatex-environment-indent (&optional environment item)
  14606. "Execute `cdlatex-environment' and indent the inserted environment.
  14607. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14608. The inserted environment is indented to current indentation
  14609. unless point is at the beginning of the line, in which the
  14610. environment remains unintended."
  14611. (interactive)
  14612. ;; cdlatex-environment always return nil. Therefore, capture output
  14613. ;; first and determine if an environment was selected.
  14614. (let* ((beg (point-marker))
  14615. (end (copy-marker (point) t))
  14616. (inserted (progn
  14617. (ignore-errors (cdlatex-environment environment item))
  14618. (< beg end)))
  14619. ;; Figure out how many lines to move forward after the
  14620. ;; environment has been inserted.
  14621. (lines (when inserted
  14622. (save-excursion
  14623. (- (cl-loop while (< beg (point))
  14624. with x = 0
  14625. do (forward-line -1)
  14626. (cl-incf x)
  14627. finally return x)
  14628. (if (progn (goto-char beg)
  14629. (and (progn (skip-chars-forward " \t") (eolp))
  14630. (progn (skip-chars-backward " \t") (bolp))))
  14631. 1 0)))))
  14632. (env (org-trim (delete-and-extract-region beg end))))
  14633. (when inserted
  14634. ;; Get indentation of next line unless at column 0.
  14635. (let ((ind (if (bolp) 0
  14636. (save-excursion
  14637. (org-return-indent)
  14638. (prog1 (current-indentation)
  14639. (when (progn (skip-chars-forward " \t") (eolp))
  14640. (delete-region beg (point)))))))
  14641. (bol (progn (skip-chars-backward " \t") (bolp))))
  14642. ;; Insert a newline before environment unless at column zero
  14643. ;; to "escape" the current line. Insert a newline if
  14644. ;; something is one the same line as \end{ENVIRONMENT}.
  14645. (insert
  14646. (concat (unless bol "\n") env
  14647. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14648. (unless (zerop ind)
  14649. (save-excursion
  14650. (goto-char beg)
  14651. (while (< (point) end)
  14652. (unless (eolp) (indent-line-to ind))
  14653. (forward-line))))
  14654. (goto-char beg)
  14655. (forward-line lines)
  14656. (indent-line-to ind)))
  14657. (set-marker beg nil)
  14658. (set-marker end nil)))
  14659. ;;;; LaTeX fragments
  14660. (defun org-inside-LaTeX-fragment-p ()
  14661. "Test if point is inside a LaTeX fragment.
  14662. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14663. sequence appearing also before point.
  14664. Even though the matchers for math are configurable, this function assumes
  14665. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14666. delimiters are skipped when they have been removed by customization.
  14667. The return value is nil, or a cons cell with the delimiter and the
  14668. position of this delimiter.
  14669. This function does a reasonably good job, but can locally be fooled by
  14670. for example currency specifications. For example it will assume being in
  14671. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14672. fragments that are properly closed, but during editing, we have to live
  14673. with the uncertainty caused by missing closing delimiters. This function
  14674. looks only before point, not after."
  14675. (catch 'exit
  14676. (let ((pos (point))
  14677. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14678. (lim (progn
  14679. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14680. 'move)
  14681. (point)))
  14682. dd-on str (start 0) m re)
  14683. (goto-char pos)
  14684. (when dodollar
  14685. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14686. re (nth 1 (assoc "$" org-latex-regexps)))
  14687. (while (string-match re str start)
  14688. (cond
  14689. ((= (match-end 0) (length str))
  14690. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14691. ((= (match-end 0) (- (length str) 5))
  14692. (throw 'exit nil))
  14693. (t (setq start (match-end 0))))))
  14694. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14695. (goto-char pos)
  14696. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14697. (and (match-beginning 2) (throw 'exit nil))
  14698. ;; count $$
  14699. (while (re-search-backward "\\$\\$" lim t)
  14700. (setq dd-on (not dd-on)))
  14701. (goto-char pos)
  14702. (when dd-on (cons "$$" m))))))
  14703. (defun org-inside-latex-macro-p ()
  14704. "Is point inside a LaTeX macro or its arguments?"
  14705. (save-match-data
  14706. (org-in-regexp
  14707. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14708. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14709. "Build an overlay between BEG and END using IMAGE file.
  14710. Argument IMAGETYPE is the extension of the displayed image,
  14711. as a string. It defaults to \"png\"."
  14712. (let ((ov (make-overlay beg end))
  14713. (imagetype (or (intern imagetype) 'png)))
  14714. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14715. (overlay-put ov 'evaporate t)
  14716. (overlay-put ov
  14717. 'modification-hooks
  14718. (list (lambda (o _flag _beg _end &optional _l)
  14719. (delete-overlay o))))
  14720. (overlay-put ov
  14721. 'display
  14722. (list 'image :type imagetype :file image :ascent 'center))))
  14723. (defun org-clear-latex-preview (&optional beg end)
  14724. "Remove all overlays with LaTeX fragment images in current buffer.
  14725. When optional arguments BEG and END are non-nil, remove all
  14726. overlays between them instead. Return a non-nil value when some
  14727. overlays were removed, nil otherwise."
  14728. (let ((overlays
  14729. (cl-remove-if-not
  14730. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14731. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14732. (mapc #'delete-overlay overlays)
  14733. overlays))
  14734. (defun org--latex-preview-region (beg end)
  14735. "Preview LaTeX fragments between BEG and END.
  14736. BEG and END are buffer positions."
  14737. (let ((file (buffer-file-name (buffer-base-buffer))))
  14738. (save-excursion
  14739. (org-format-latex
  14740. (concat org-preview-latex-image-directory "org-ltximg")
  14741. beg end
  14742. ;; Emacs cannot overlay images from remote hosts. Create it in
  14743. ;; `temporary-file-directory' instead.
  14744. (if (or (not file) (file-remote-p file))
  14745. temporary-file-directory
  14746. default-directory)
  14747. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14748. (defun org-latex-preview (&optional arg)
  14749. "Toggle preview of the LaTeX fragment at point.
  14750. If the cursor is on a LaTeX fragment, create the image and
  14751. overlay it over the source code, if there is none. Remove it
  14752. otherwise. If there is no fragment at point, display images for
  14753. all fragments in the current section.
  14754. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14755. for all fragments
  14756. in the current section.
  14757. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14758. argument ARG, display image for all
  14759. fragments in the buffer.
  14760. With a `\\[universal-argument] \\[universal-argument] \
  14761. \\[universal-argument]' prefix argument ARG, clear image for all
  14762. fragments in the buffer."
  14763. (interactive "P")
  14764. (cond
  14765. ((not (display-graphic-p)) nil)
  14766. ;; Clear whole buffer.
  14767. ((equal arg '(64))
  14768. (org-clear-latex-preview (point-min) (point-max))
  14769. (message "LaTeX previews removed from buffer"))
  14770. ;; Preview whole buffer.
  14771. ((equal arg '(16))
  14772. (message "Creating LaTeX previews in buffer...")
  14773. (org--latex-preview-region (point-min) (point-max))
  14774. (message "Creating LaTeX previews in buffer... done."))
  14775. ;; Clear current section.
  14776. ((equal arg '(4))
  14777. (org-clear-latex-preview
  14778. (if (org-before-first-heading-p) (point-min)
  14779. (save-excursion
  14780. (org-with-limited-levels (org-back-to-heading t) (point))))
  14781. (org-with-limited-levels (org-entry-end-position))))
  14782. ;; Toggle preview on LaTeX code at point.
  14783. ((let ((datum (org-element-context)))
  14784. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14785. (let ((beg (org-element-property :begin datum))
  14786. (end (org-element-property :end datum)))
  14787. (if (org-clear-latex-preview beg end)
  14788. (message "LaTeX preview removed")
  14789. (message "Creating LaTeX preview...")
  14790. (org--latex-preview-region beg end)
  14791. (message "Creating LaTeX preview... done."))
  14792. t))))
  14793. ;; Preview current section.
  14794. (t
  14795. (let ((beg (if (org-before-first-heading-p) (point-min)
  14796. (save-excursion
  14797. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14798. (end (org-with-limited-levels (org-entry-end-position))))
  14799. (message "Creating LaTeX previews in section...")
  14800. (org--latex-preview-region beg end)
  14801. (message "Creating LaTeX previews in section... done.")))))
  14802. (defun org-format-latex
  14803. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14804. "Replace LaTeX fragments with links to an image.
  14805. The function takes care of creating the replacement image.
  14806. Only consider fragments between BEG and END when those are
  14807. provided.
  14808. When optional argument OVERLAYS is non-nil, display the image on
  14809. top of the fragment instead of replacing it.
  14810. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14811. Some of the options can be changed using the variable
  14812. `org-format-latex-options', which see."
  14813. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14814. (unless (eq processing-type 'verbatim)
  14815. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14816. (cnt 0)
  14817. checkdir-flag)
  14818. (goto-char (or beg (point-min)))
  14819. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14820. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14821. (overlay-recenter (or end (point-max))))
  14822. (while (re-search-forward math-regexp end t)
  14823. (unless (and overlays
  14824. (eq (get-char-property (point) 'org-overlay-type)
  14825. 'org-latex-overlay))
  14826. (let* ((context (org-element-context))
  14827. (type (org-element-type context)))
  14828. (when (memq type '(latex-environment latex-fragment))
  14829. (let ((block-type (eq type 'latex-environment))
  14830. (value (org-element-property :value context))
  14831. (beg (org-element-property :begin context))
  14832. (end (save-excursion
  14833. (goto-char (org-element-property :end context))
  14834. (skip-chars-backward " \r\t\n")
  14835. (point))))
  14836. (cond
  14837. ((eq processing-type 'mathjax)
  14838. ;; Prepare for MathJax processing.
  14839. (if (not (string-match "\\`\\$\\$?" value))
  14840. (goto-char end)
  14841. (delete-region beg end)
  14842. (if (string= (match-string 0 value) "$$")
  14843. (insert "\\[" (substring value 2 -2) "\\]")
  14844. (insert "\\(" (substring value 1 -1) "\\)"))))
  14845. ((assq processing-type org-preview-latex-process-alist)
  14846. ;; Process to an image.
  14847. (cl-incf cnt)
  14848. (goto-char beg)
  14849. (let* ((processing-info
  14850. (cdr (assq processing-type org-preview-latex-process-alist)))
  14851. (face (face-at-point))
  14852. ;; Get the colors from the face at point.
  14853. (fg
  14854. (let ((color (plist-get org-format-latex-options
  14855. :foreground)))
  14856. (if (and forbuffer (eq color 'auto))
  14857. (face-attribute face :foreground nil 'default)
  14858. color)))
  14859. (bg
  14860. (let ((color (plist-get org-format-latex-options
  14861. :background)))
  14862. (if (and forbuffer (eq color 'auto))
  14863. (face-attribute face :background nil 'default)
  14864. color)))
  14865. (hash (sha1 (prin1-to-string
  14866. (list org-format-latex-header
  14867. org-latex-default-packages-alist
  14868. org-latex-packages-alist
  14869. org-format-latex-options
  14870. forbuffer value fg bg))))
  14871. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14872. (absprefix (expand-file-name prefix dir))
  14873. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14874. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14875. (sep (and block-type "\n\n"))
  14876. (link (concat sep "[[file:" linkfile "]]" sep))
  14877. (options
  14878. (org-combine-plists
  14879. org-format-latex-options
  14880. `(:foreground ,fg :background ,bg))))
  14881. (when msg (message msg cnt))
  14882. (unless checkdir-flag ; Ensure the directory exists.
  14883. (setq checkdir-flag t)
  14884. (let ((todir (file-name-directory absprefix)))
  14885. (unless (file-directory-p todir)
  14886. (make-directory todir t))))
  14887. (unless (file-exists-p movefile)
  14888. (org-create-formula-image
  14889. value movefile options forbuffer processing-type))
  14890. (if overlays
  14891. (progn
  14892. (dolist (o (overlays-in beg end))
  14893. (when (eq (overlay-get o 'org-overlay-type)
  14894. 'org-latex-overlay)
  14895. (delete-overlay o)))
  14896. (org--make-preview-overlay beg end movefile imagetype)
  14897. (goto-char end))
  14898. (delete-region beg end)
  14899. (insert
  14900. (org-add-props link
  14901. (list 'org-latex-src
  14902. (replace-regexp-in-string "\"" "" value)
  14903. 'org-latex-src-embed-type
  14904. (if block-type 'paragraph 'character)))))))
  14905. ((eq processing-type 'mathml)
  14906. ;; Process to MathML.
  14907. (unless (org-format-latex-mathml-available-p)
  14908. (user-error "LaTeX to MathML converter not configured"))
  14909. (cl-incf cnt)
  14910. (when msg (message msg cnt))
  14911. (goto-char beg)
  14912. (delete-region beg end)
  14913. (insert (org-format-latex-as-mathml
  14914. value block-type prefix dir)))
  14915. (t
  14916. (error "Unknown conversion process %s for LaTeX fragments"
  14917. processing-type)))))))))))
  14918. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14919. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14920. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14921. successful, return the portion between \"<math...> </math>\"
  14922. elements otherwise return nil. When MATHML-FILE is specified,
  14923. write the results in to that file. When invoked as an
  14924. interactive command, prompt for LATEX-FRAG, with initial value
  14925. set to the current active region and echo the results for user
  14926. inspection."
  14927. (interactive (list (let ((frag (when (org-region-active-p)
  14928. (buffer-substring-no-properties
  14929. (region-beginning) (region-end)))))
  14930. (read-string "LaTeX Fragment: " frag nil frag))))
  14931. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14932. (let* ((tmp-in-file
  14933. (let ((file (file-relative-name
  14934. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14935. (write-region latex-frag nil file)
  14936. file))
  14937. (tmp-out-file (file-relative-name
  14938. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14939. (cmd (format-spec
  14940. org-latex-to-mathml-convert-command
  14941. `((?j . ,(and org-latex-to-mathml-jar-file
  14942. (shell-quote-argument
  14943. (expand-file-name
  14944. org-latex-to-mathml-jar-file))))
  14945. (?I . ,(shell-quote-argument tmp-in-file))
  14946. (?i . ,latex-frag)
  14947. (?o . ,(shell-quote-argument tmp-out-file)))))
  14948. mathml shell-command-output)
  14949. (when (called-interactively-p 'any)
  14950. (unless (org-format-latex-mathml-available-p)
  14951. (user-error "LaTeX to MathML converter not configured")))
  14952. (message "Running %s" cmd)
  14953. (setq shell-command-output (shell-command-to-string cmd))
  14954. (setq mathml
  14955. (when (file-readable-p tmp-out-file)
  14956. (with-current-buffer (find-file-noselect tmp-out-file t)
  14957. (goto-char (point-min))
  14958. (when (re-search-forward
  14959. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14960. (regexp-quote
  14961. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14962. nil t)
  14963. (prog1 (match-string 0) (kill-buffer))))))
  14964. (cond
  14965. (mathml
  14966. (setq mathml
  14967. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14968. (when mathml-file
  14969. (write-region mathml nil mathml-file))
  14970. (when (called-interactively-p 'any)
  14971. (message mathml)))
  14972. ((message "LaTeX to MathML conversion failed")
  14973. (message shell-command-output)))
  14974. (delete-file tmp-in-file)
  14975. (when (file-exists-p tmp-out-file)
  14976. (delete-file tmp-out-file))
  14977. mathml))
  14978. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14979. prefix &optional dir)
  14980. "Use `org-create-math-formula' but check local cache first."
  14981. (let* ((absprefix (expand-file-name prefix dir))
  14982. (print-length nil) (print-level nil)
  14983. (formula-id (concat
  14984. "formula-"
  14985. (sha1
  14986. (prin1-to-string
  14987. (list latex-frag
  14988. org-latex-to-mathml-convert-command)))))
  14989. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14990. (formula-cache-dir (file-name-directory formula-cache)))
  14991. (unless (file-directory-p formula-cache-dir)
  14992. (make-directory formula-cache-dir t))
  14993. (unless (file-exists-p formula-cache)
  14994. (org-create-math-formula latex-frag formula-cache))
  14995. (if (file-exists-p formula-cache)
  14996. ;; Successful conversion. Return the link to MathML file.
  14997. (org-add-props
  14998. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14999. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15000. 'org-latex-src-embed-type (if latex-frag-type
  15001. 'paragraph 'character)))
  15002. ;; Failed conversion. Return the LaTeX fragment verbatim
  15003. latex-frag)))
  15004. (defun org--get-display-dpi ()
  15005. "Get the DPI of the display.
  15006. The function assumes that the display has the same pixel width in
  15007. the horizontal and vertical directions."
  15008. (if (display-graphic-p)
  15009. (round (/ (display-pixel-height)
  15010. (/ (display-mm-height) 25.4)))
  15011. (error "Attempt to calculate the dpi of a non-graphic display")))
  15012. (defun org-create-formula-image
  15013. (string tofile options buffer &optional processing-type)
  15014. "Create an image from LaTeX source using external processes.
  15015. The LaTeX STRING is saved to a temporary LaTeX file, then
  15016. converted to an image file by process PROCESSING-TYPE defined in
  15017. `org-preview-latex-process-alist'. A nil value defaults to
  15018. `org-preview-latex-default-process'.
  15019. The generated image file is eventually moved to TOFILE.
  15020. The OPTIONS argument controls the size, foreground color and
  15021. background color of the generated image.
  15022. When BUFFER non-nil, this function is used for LaTeX previewing.
  15023. Otherwise, it is used to deal with LaTeX snippets showed in
  15024. a HTML file."
  15025. (let* ((processing-type (or processing-type
  15026. org-preview-latex-default-process))
  15027. (processing-info
  15028. (cdr (assq processing-type org-preview-latex-process-alist)))
  15029. (programs (plist-get processing-info :programs))
  15030. (error-message (or (plist-get processing-info :message) ""))
  15031. (image-input-type (plist-get processing-info :image-input-type))
  15032. (image-output-type (plist-get processing-info :image-output-type))
  15033. (post-clean (or (plist-get processing-info :post-clean)
  15034. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15035. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15036. (latex-header
  15037. (or (plist-get processing-info :latex-header)
  15038. (org-latex-make-preamble
  15039. (org-export-get-environment (org-export-get-backend 'latex))
  15040. org-format-latex-header
  15041. 'snippet)))
  15042. (latex-compiler (plist-get processing-info :latex-compiler))
  15043. (image-converter (plist-get processing-info :image-converter))
  15044. (tmpdir temporary-file-directory)
  15045. (texfilebase (make-temp-name
  15046. (expand-file-name "orgtex" tmpdir)))
  15047. (texfile (concat texfilebase ".tex"))
  15048. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15049. '(1.0 . 1.0)))
  15050. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15051. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15052. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15053. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15054. "Black"))
  15055. (bg (or (plist-get options (if buffer :background :html-background))
  15056. "Transparent"))
  15057. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15058. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15059. (dolist (program programs)
  15060. (org-check-external-command program error-message))
  15061. (if (eq fg 'default)
  15062. (setq fg (org-latex-color :foreground))
  15063. (setq fg (org-latex-color-format fg)))
  15064. (if (eq bg 'default)
  15065. (setq bg (org-latex-color :background))
  15066. (setq bg (org-latex-color-format
  15067. (if (string= bg "Transparent") "white" bg))))
  15068. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15069. (if (string-suffix-p string "\n")
  15070. (aset string (1- (length string)) ?%)
  15071. (setq string (concat string "%")))
  15072. (with-temp-file texfile
  15073. (insert latex-header)
  15074. (insert "\n\\begin{document}\n"
  15075. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15076. "\\definecolor{bg}{rgb}{" bg "}%\n"
  15077. "\n\\pagecolor{bg}%\n"
  15078. "\n{\\color{fg}\n"
  15079. string
  15080. "\n}\n"
  15081. "\n\\end{document}\n"))
  15082. (let* ((err-msg (format "Please adjust `%s' part of \
  15083. `org-preview-latex-process-alist'."
  15084. processing-type))
  15085. (image-input-file
  15086. (org-compile-file
  15087. texfile latex-compiler image-input-type err-msg log-buf))
  15088. (image-output-file
  15089. (org-compile-file
  15090. image-input-file image-converter image-output-type err-msg log-buf
  15091. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15092. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15093. (copy-file image-output-file tofile 'replace)
  15094. (dolist (e post-clean)
  15095. (when (file-exists-p (concat texfilebase e))
  15096. (delete-file (concat texfilebase e))))
  15097. image-output-file)))
  15098. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15099. "Fill a LaTeX header template TPL.
  15100. In the template, the following place holders will be recognized:
  15101. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15102. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15103. [PACKAGES] \\usepackage statements for PKG
  15104. [NO-PACKAGES] do not include PKG
  15105. [EXTRA] the string EXTRA
  15106. [NO-EXTRA] do not include EXTRA
  15107. For backward compatibility, if both the positive and the negative place
  15108. holder is missing, the positive one (without the \"NO-\") will be
  15109. assumed to be present at the end of the template.
  15110. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15111. EXTRA is a string.
  15112. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15113. (let (rpl (end ""))
  15114. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15115. (setq rpl (if (or (match-end 1) (not def-pkg))
  15116. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15117. tpl (replace-match rpl t t tpl))
  15118. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15119. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15120. (setq rpl (if (or (match-end 1) (not pkg))
  15121. "" (org-latex-packages-to-string pkg snippets-p t))
  15122. tpl (replace-match rpl t t tpl))
  15123. (when pkg (setq end
  15124. (concat end "\n"
  15125. (org-latex-packages-to-string pkg snippets-p)))))
  15126. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15127. (setq rpl (if (or (match-end 1) (not extra))
  15128. "" (concat extra "\n"))
  15129. tpl (replace-match rpl t t tpl))
  15130. (when (and extra (string-match "\\S-" extra))
  15131. (setq end (concat end "\n" extra))))
  15132. (if (string-match "\\S-" end)
  15133. (concat tpl "\n" end)
  15134. tpl)))
  15135. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15136. "Turn an alist of packages into a string with the \\usepackage macros."
  15137. (setq pkg (mapconcat (lambda(p)
  15138. (cond
  15139. ((stringp p) p)
  15140. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15141. (format "%% Package %s omitted" (cadr p)))
  15142. ((equal "" (car p))
  15143. (format "\\usepackage{%s}" (cadr p)))
  15144. (t
  15145. (format "\\usepackage[%s]{%s}"
  15146. (car p) (cadr p)))))
  15147. pkg
  15148. "\n"))
  15149. (if newline (concat pkg "\n") pkg))
  15150. (defun org-dvipng-color (attr)
  15151. "Return a RGB color specification for dvipng."
  15152. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15153. (defun org-dvipng-color-format (color-name)
  15154. "Convert COLOR-NAME to a RGB color value for dvipng."
  15155. (apply #'format "rgb %s %s %s"
  15156. (mapcar 'org-normalize-color
  15157. (color-values color-name))))
  15158. (defun org-latex-color (attr)
  15159. "Return a RGB color for the LaTeX color package."
  15160. (org-latex-color-format (face-attribute 'default attr nil)))
  15161. (defun org-latex-color-format (color-name)
  15162. "Convert COLOR-NAME to a RGB color value."
  15163. (apply #'format "%s,%s,%s"
  15164. (mapcar 'org-normalize-color
  15165. (color-values color-name))))
  15166. (defun org-normalize-color (value)
  15167. "Return string to be used as color value for an RGB component."
  15168. (format "%g" (/ value 65535.0)))
  15169. ;; Image display
  15170. (defvar-local org-inline-image-overlays nil)
  15171. (defun org-toggle-inline-images (&optional include-linked)
  15172. "Toggle the display of inline images.
  15173. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15174. (interactive "P")
  15175. (if org-inline-image-overlays
  15176. (progn
  15177. (org-remove-inline-images)
  15178. (when (called-interactively-p 'interactive)
  15179. (message "Inline image display turned off")))
  15180. (org-display-inline-images include-linked)
  15181. (when (called-interactively-p 'interactive)
  15182. (message (if org-inline-image-overlays
  15183. (format "%d images displayed inline"
  15184. (length org-inline-image-overlays))
  15185. "No images to display inline")))))
  15186. (defun org-redisplay-inline-images ()
  15187. "Refresh the display of inline images."
  15188. (interactive)
  15189. (if (not org-inline-image-overlays)
  15190. (org-toggle-inline-images)
  15191. (org-toggle-inline-images)
  15192. (org-toggle-inline-images)))
  15193. ;; For without-x builds.
  15194. (declare-function image-refresh "image" (spec &optional frame))
  15195. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15196. "Display inline images.
  15197. An inline image is a link which follows either of these
  15198. conventions:
  15199. 1. Its path is a file with an extension matching return value
  15200. from `image-file-name-regexp' and it has no contents.
  15201. 2. Its description consists in a single link of the previous
  15202. type. In this case, that link must be a well-formed plain
  15203. or angle link, i.e., it must have an explicit \"file\" type.
  15204. Equip each image with the key-map `image-map'.
  15205. When optional argument INCLUDE-LINKED is non-nil, also links with
  15206. a text description part will be inlined. This can be nice for
  15207. a quick look at those images, but it does not reflect what
  15208. exported files will look like.
  15209. When optional argument REFRESH is non-nil, refresh existing
  15210. images between BEG and END. This will create new image displays
  15211. only if necessary.
  15212. BEG and END define the considered part. They default to the
  15213. buffer boundaries with possible narrowing."
  15214. (interactive "P")
  15215. (when (display-graphic-p)
  15216. (unless refresh
  15217. (org-remove-inline-images)
  15218. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15219. (let ((end (or end (point-max))))
  15220. (org-with-point-at (or beg (point-min))
  15221. (let* ((case-fold-search t)
  15222. (file-extension-re (image-file-name-regexp))
  15223. (link-abbrevs (mapcar #'car
  15224. (append org-link-abbrev-alist-local
  15225. org-link-abbrev-alist)))
  15226. ;; Check absolute, relative file names and explicit
  15227. ;; "file:" links. Also check link abbreviations since
  15228. ;; some might expand to "file" links.
  15229. (file-types-re
  15230. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15231. (if (not link-abbrevs) ""
  15232. (concat "\\|" (regexp-opt link-abbrevs))))))
  15233. (while (re-search-forward file-types-re end t)
  15234. (let* ((link (org-element-lineage
  15235. (save-match-data (org-element-context))
  15236. '(link) t))
  15237. (linktype (org-element-property :type link))
  15238. (inner-start (match-beginning 1))
  15239. (path
  15240. (cond
  15241. ;; No link at point; no inline image.
  15242. ((not link) nil)
  15243. ;; File link without a description. Also handle
  15244. ;; INCLUDE-LINKED here since it should have
  15245. ;; precedence over the next case. I.e., if link
  15246. ;; contains filenames in both the path and the
  15247. ;; description, prioritize the path only when
  15248. ;; INCLUDE-LINKED is non-nil.
  15249. ((or (not (org-element-property :contents-begin link))
  15250. include-linked)
  15251. (and (or (equal "file" linktype)
  15252. (equal "attachment" linktype))
  15253. (org-element-property :path link)))
  15254. ;; Link with a description. Check if description
  15255. ;; is a filename. Even if Org doesn't have syntax
  15256. ;; for those -- clickable image -- constructs, fake
  15257. ;; them, as in `org-export-insert-image-links'.
  15258. ((not inner-start) nil)
  15259. (t
  15260. (org-with-point-at inner-start
  15261. (and (looking-at
  15262. (if (char-equal ?< (char-after inner-start))
  15263. org-link-angle-re
  15264. org-link-plain-re))
  15265. ;; File name must fill the whole
  15266. ;; description.
  15267. (= (org-element-property :contents-end link)
  15268. (match-end 0))
  15269. (match-string 2)))))))
  15270. (when (and path (string-match-p file-extension-re path))
  15271. (let ((file (if (equal "attachment" linktype)
  15272. (progn
  15273. (require 'org-attach)
  15274. (ignore-errors (org-attach-expand path)))
  15275. (expand-file-name path))))
  15276. (when (and file (file-exists-p file))
  15277. (let ((width
  15278. ;; Apply `org-image-actual-width' specifications.
  15279. (cond
  15280. ((eq org-image-actual-width t) nil)
  15281. ((listp org-image-actual-width)
  15282. (or
  15283. ;; First try to find a width among
  15284. ;; attributes associated to the paragraph
  15285. ;; containing link.
  15286. (pcase (org-element-lineage link '(paragraph))
  15287. (`nil nil)
  15288. (p
  15289. (let* ((case-fold-search t)
  15290. (end (org-element-property :post-affiliated p))
  15291. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15292. (when (org-with-point-at
  15293. (org-element-property :begin p)
  15294. (re-search-forward re end t))
  15295. (string-to-number (match-string 1))))))
  15296. ;; Otherwise, fall-back to provided number.
  15297. (car org-image-actual-width)))
  15298. ((numberp org-image-actual-width)
  15299. org-image-actual-width)
  15300. (t nil)))
  15301. (old (get-char-property-and-overlay
  15302. (org-element-property :begin link)
  15303. 'org-image-overlay)))
  15304. (if (and (car-safe old) refresh)
  15305. (image-refresh (overlay-get (cdr old) 'display))
  15306. (let ((image (create-image file
  15307. (and (image-type-available-p 'imagemagick)
  15308. width 'imagemagick)
  15309. nil
  15310. :width width)))
  15311. (when image
  15312. (let ((ov (make-overlay
  15313. (org-element-property :begin link)
  15314. (progn
  15315. (goto-char
  15316. (org-element-property :end link))
  15317. (skip-chars-backward " \t")
  15318. (point)))))
  15319. (overlay-put ov 'display image)
  15320. (overlay-put ov 'face 'default)
  15321. (overlay-put ov 'org-image-overlay t)
  15322. (overlay-put
  15323. ov 'modification-hooks
  15324. (list 'org-display-inline-remove-overlay))
  15325. (when (<= 26 emacs-major-version)
  15326. (cl-assert (boundp 'image-map))
  15327. (overlay-put ov 'keymap image-map))
  15328. (push ov org-inline-image-overlays))))))))))))))))
  15329. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15330. "Remove inline-display overlay if a corresponding region is modified."
  15331. (let ((inhibit-modification-hooks t))
  15332. (when (and ov after)
  15333. (delete ov org-inline-image-overlays)
  15334. (delete-overlay ov))))
  15335. (defun org-remove-inline-images ()
  15336. "Remove inline display of images."
  15337. (interactive)
  15338. (mapc #'delete-overlay org-inline-image-overlays)
  15339. (setq org-inline-image-overlays nil))
  15340. (defvar org-self-insert-command-undo-counter 0)
  15341. (defvar org-speed-command nil)
  15342. (defun org-self-insert-command (N)
  15343. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15344. If the cursor is in a table looking at whitespace, the whitespace is
  15345. overwritten, and the table is not marked as requiring realignment."
  15346. (interactive "p")
  15347. (org-check-before-invisible-edit 'insert)
  15348. (cond
  15349. ((and org-use-speed-commands
  15350. (let ((kv (this-command-keys-vector)))
  15351. (setq org-speed-command
  15352. (run-hook-with-args-until-success
  15353. 'org-speed-command-hook
  15354. (make-string 1 (aref kv (1- (length kv))))))))
  15355. (cond
  15356. ((commandp org-speed-command)
  15357. (setq this-command org-speed-command)
  15358. (call-interactively org-speed-command))
  15359. ((functionp org-speed-command)
  15360. (funcall org-speed-command))
  15361. ((and org-speed-command (listp org-speed-command))
  15362. (eval org-speed-command))
  15363. (t (let (org-use-speed-commands)
  15364. (call-interactively 'org-self-insert-command)))))
  15365. ((and
  15366. (= N 1)
  15367. (not (org-region-active-p))
  15368. (org-at-table-p)
  15369. (progn
  15370. ;; Check if we blank the field, and if that triggers align.
  15371. (and (featurep 'org-table)
  15372. org-table-auto-blank-field
  15373. (memq last-command
  15374. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15375. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15376. ;; Got extra space, this field does not determine
  15377. ;; column width.
  15378. (let (org-table-may-need-update) (org-table-blank-field))
  15379. ;; No extra space, this field may determine column
  15380. ;; width.
  15381. (org-table-blank-field)))
  15382. t)
  15383. (looking-at "[^|\n]* |"))
  15384. ;; There is room for insertion without re-aligning the table.
  15385. (self-insert-command N)
  15386. (org-table-with-shrunk-field
  15387. (save-excursion
  15388. (skip-chars-forward "^|")
  15389. ;; Do not delete last space, which is
  15390. ;; `org-table-separator-space', but the regular space before
  15391. ;; it.
  15392. (delete-region (- (point) 2) (1- (point))))))
  15393. (t
  15394. (setq org-table-may-need-update t)
  15395. (self-insert-command N)
  15396. (org-fix-tags-on-the-fly)
  15397. (when org-self-insert-cluster-for-undo
  15398. (if (not (eq last-command 'org-self-insert-command))
  15399. (setq org-self-insert-command-undo-counter 1)
  15400. (if (>= org-self-insert-command-undo-counter 20)
  15401. (setq org-self-insert-command-undo-counter 1)
  15402. (and (> org-self-insert-command-undo-counter 0)
  15403. buffer-undo-list (listp buffer-undo-list)
  15404. (not (cadr buffer-undo-list)) ; remove nil entry
  15405. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15406. (setq org-self-insert-command-undo-counter
  15407. (1+ org-self-insert-command-undo-counter))))))))
  15408. (defun org-check-before-invisible-edit (kind)
  15409. "Check is editing if kind KIND would be dangerous with invisible text around.
  15410. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15411. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15412. (when (and org-catch-invisible-edits
  15413. (or (not (boundp 'visible-mode)) (not visible-mode))
  15414. (or (get-char-property (point) 'invisible)
  15415. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15416. ;; OK, we need to take a closer look. Do not consider
  15417. ;; invisibility obtained through text properties (e.g., link
  15418. ;; fontification), as it cannot be toggled.
  15419. (let* ((invisible-at-point
  15420. (pcase (get-char-property-and-overlay (point) 'invisible)
  15421. (`(,_ . ,(and (pred overlayp) o)) o)))
  15422. ;; Assume that point cannot land in the middle of an
  15423. ;; overlay, or between two overlays.
  15424. (invisible-before-point
  15425. (and (not invisible-at-point)
  15426. (not (bobp))
  15427. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15428. (`(,_ . ,(and (pred overlayp) o)) o))))
  15429. (border-and-ok-direction
  15430. (or
  15431. ;; Check if we are acting predictably before invisible
  15432. ;; text.
  15433. (and invisible-at-point
  15434. (memq kind '(insert delete-backward)))
  15435. ;; Check if we are acting predictably after invisible text
  15436. ;; This works not well, and I have turned it off. It seems
  15437. ;; better to always show and stop after invisible text.
  15438. ;; (and (not invisible-at-point) invisible-before-point
  15439. ;; (memq kind '(insert delete)))
  15440. )))
  15441. (when (or invisible-at-point invisible-before-point)
  15442. (when (eq org-catch-invisible-edits 'error)
  15443. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15444. (if (and org-custom-properties-overlays
  15445. (y-or-n-p "Display invisible properties in this buffer? "))
  15446. (org-toggle-custom-properties-visibility)
  15447. ;; Make the area visible
  15448. (save-excursion
  15449. (when invisible-before-point
  15450. (goto-char
  15451. (previous-single-char-property-change (point) 'invisible)))
  15452. ;; Remove whatever overlay is currently making yet-to-be
  15453. ;; edited text invisible. Also remove nested invisibility
  15454. ;; related overlays.
  15455. (delete-overlay (or invisible-at-point invisible-before-point))
  15456. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15457. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15458. (`(,_ . ,(and (pred overlayp) o))
  15459. (delete-overlay o)
  15460. t)))))
  15461. (cond
  15462. ((eq org-catch-invisible-edits 'show)
  15463. ;; That's it, we do the edit after showing
  15464. (message
  15465. "Unfolding invisible region around point before editing")
  15466. (sit-for 1))
  15467. ((and (eq org-catch-invisible-edits 'smart)
  15468. border-and-ok-direction)
  15469. (message "Unfolding invisible region around point before editing"))
  15470. (t
  15471. ;; Don't do the edit, make the user repeat it in full visibility
  15472. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15473. (defun org-fix-tags-on-the-fly ()
  15474. "Align tags in headline at point.
  15475. Unlike `org-align-tags', this function does nothing if point is
  15476. either not currently on a tagged headline or on a tag."
  15477. (when (and (org-match-line org-tag-line-re)
  15478. (< (point) (match-beginning 1)))
  15479. (org-align-tags)))
  15480. (defun org-delete-backward-char (N)
  15481. "Like `delete-backward-char', insert whitespace at field end in tables.
  15482. When deleting backwards, in tables this function will insert whitespace in
  15483. front of the next \"|\" separator, to keep the table aligned. The table will
  15484. still be marked for re-alignment if the field did fill the entire column,
  15485. because, in this case the deletion might narrow the column."
  15486. (interactive "p")
  15487. (save-match-data
  15488. (org-check-before-invisible-edit 'delete-backward)
  15489. (if (and (= N 1)
  15490. (not overwrite-mode)
  15491. (not (org-region-active-p))
  15492. (not (eq (char-before) ?|))
  15493. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15494. (looking-at-p ".*?|")
  15495. (org-at-table-p))
  15496. (progn (forward-char -1) (org-delete-char 1))
  15497. (backward-delete-char N)
  15498. (org-fix-tags-on-the-fly))))
  15499. (defun org-delete-char (N)
  15500. "Like `delete-char', but insert whitespace at field end in tables.
  15501. When deleting characters, in tables this function will insert whitespace in
  15502. front of the next \"|\" separator, to keep the table aligned. The table will
  15503. still be marked for re-alignment if the field did fill the entire column,
  15504. because, in this case the deletion might narrow the column."
  15505. (interactive "p")
  15506. (save-match-data
  15507. (org-check-before-invisible-edit 'delete)
  15508. (cond
  15509. ((or (/= N 1)
  15510. (eq (char-after) ?|)
  15511. (save-excursion (skip-chars-backward " \t") (bolp))
  15512. (not (org-at-table-p)))
  15513. (delete-char N)
  15514. (org-fix-tags-on-the-fly))
  15515. ((looking-at ".\\(.*?\\)|")
  15516. (let* ((update? org-table-may-need-update)
  15517. (noalign (looking-at-p ".*? |")))
  15518. (delete-char 1)
  15519. (org-table-with-shrunk-field
  15520. (save-excursion
  15521. ;; Last space is `org-table-separator-space', so insert
  15522. ;; a regular one before it instead.
  15523. (goto-char (- (match-end 0) 2))
  15524. (insert " ")))
  15525. ;; If there were two spaces at the end, this field does not
  15526. ;; determine the width of the column.
  15527. (when noalign (setq org-table-may-need-update update?))))
  15528. (t
  15529. (delete-char N)))))
  15530. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15531. (put 'org-self-insert-command 'delete-selection
  15532. (lambda ()
  15533. (not (run-hook-with-args-until-success
  15534. 'self-insert-uses-region-functions))))
  15535. (put 'orgtbl-self-insert-command 'delete-selection
  15536. (lambda ()
  15537. (not (run-hook-with-args-until-success
  15538. 'self-insert-uses-region-functions))))
  15539. (put 'org-delete-char 'delete-selection 'supersede)
  15540. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15541. (put 'org-yank 'delete-selection 'yank)
  15542. ;; Make `flyspell-mode' delay after some commands
  15543. (put 'org-self-insert-command 'flyspell-delayed t)
  15544. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15545. (put 'org-delete-char 'flyspell-delayed t)
  15546. (put 'org-delete-backward-char 'flyspell-delayed t)
  15547. ;; Make pabbrev-mode expand after Org mode commands
  15548. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15549. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15550. (defun org-transpose-words ()
  15551. "Transpose words for Org.
  15552. This uses the `org-mode-transpose-word-syntax-table' syntax
  15553. table, which interprets characters in `org-emphasis-alist' as
  15554. word constituents."
  15555. (interactive)
  15556. (with-syntax-table org-mode-transpose-word-syntax-table
  15557. (call-interactively 'transpose-words)))
  15558. (defvar org-ctrl-c-ctrl-c-hook nil
  15559. "Hook for functions attaching themselves to `C-c C-c'.
  15560. This can be used to add additional functionality to the C-c C-c
  15561. key which executes context-dependent commands. This hook is run
  15562. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15563. run after the last test.
  15564. Each function will be called with no arguments. The function
  15565. must check if the context is appropriate for it to act. If yes,
  15566. it should do its thing and then return a non-nil value. If the
  15567. context is wrong, just do nothing and return nil.")
  15568. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15569. "Hook for functions attaching themselves to `C-c C-c'.
  15570. This can be used to add additional functionality to the C-c C-c
  15571. key which executes context-dependent commands. This hook is run
  15572. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15573. before the first test.
  15574. Each function will be called with no arguments. The function
  15575. must check if the context is appropriate for it to act. If yes,
  15576. it should do its thing and then return a non-nil value. If the
  15577. context is wrong, just do nothing and return nil.")
  15578. (defvar org-tab-first-hook nil
  15579. "Hook for functions to attach themselves to TAB.
  15580. See `org-ctrl-c-ctrl-c-hook' for more information.
  15581. This hook runs as the first action when TAB is pressed, even before
  15582. `org-cycle' messes around with the `outline-regexp' to cater for
  15583. inline tasks and plain list item folding.
  15584. If any function in this hook returns t, any other actions that
  15585. would have been caused by TAB (such as table field motion or visibility
  15586. cycling) will not occur.")
  15587. (defvar org-tab-after-check-for-table-hook nil
  15588. "Hook for functions to attach themselves to TAB.
  15589. See `org-ctrl-c-ctrl-c-hook' for more information.
  15590. This hook runs after it has been established that the cursor is not in a
  15591. table, but before checking if the cursor is in a headline or if global cycling
  15592. should be done.
  15593. If any function in this hook returns t, not other actions like visibility
  15594. cycling will be done.")
  15595. (defvar org-tab-after-check-for-cycling-hook nil
  15596. "Hook for functions to attach themselves to TAB.
  15597. See `org-ctrl-c-ctrl-c-hook' for more information.
  15598. This hook runs after it has been established that not table field motion and
  15599. not visibility should be done because of current context. This is probably
  15600. the place where a package like yasnippets can hook in.")
  15601. (defvar org-tab-before-tab-emulation-hook nil
  15602. "Hook for functions to attach themselves to TAB.
  15603. See `org-ctrl-c-ctrl-c-hook' for more information.
  15604. This hook runs after every other options for TAB have been exhausted, but
  15605. before indentation and \t insertion takes place.")
  15606. (defvar org-metaleft-hook nil
  15607. "Hook for functions attaching themselves to `M-left'.
  15608. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15609. (defvar org-metaright-hook nil
  15610. "Hook for functions attaching themselves to `M-right'.
  15611. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15612. (defvar org-metaup-hook nil
  15613. "Hook for functions attaching themselves to `M-up'.
  15614. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15615. (defvar org-metadown-hook nil
  15616. "Hook for functions attaching themselves to `M-down'.
  15617. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15618. (defvar org-shiftmetaleft-hook nil
  15619. "Hook for functions attaching themselves to `M-S-left'.
  15620. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15621. (defvar org-shiftmetaright-hook nil
  15622. "Hook for functions attaching themselves to `M-S-right'.
  15623. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15624. (defvar org-shiftmetaup-hook nil
  15625. "Hook for functions attaching themselves to `M-S-up'.
  15626. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15627. (defvar org-shiftmetadown-hook nil
  15628. "Hook for functions attaching themselves to `M-S-down'.
  15629. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15630. (defvar org-metareturn-hook nil
  15631. "Hook for functions attaching themselves to `M-RET'.
  15632. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15633. (defvar org-shiftup-hook nil
  15634. "Hook for functions attaching themselves to `S-up'.
  15635. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15636. (defvar org-shiftup-final-hook nil
  15637. "Hook for functions attaching themselves to `S-up'.
  15638. This one runs after all other options except shift-select have been excluded.
  15639. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15640. (defvar org-shiftdown-hook nil
  15641. "Hook for functions attaching themselves to `S-down'.
  15642. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15643. (defvar org-shiftdown-final-hook nil
  15644. "Hook for functions attaching themselves to `S-down'.
  15645. This one runs after all other options except shift-select have been excluded.
  15646. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15647. (defvar org-shiftleft-hook nil
  15648. "Hook for functions attaching themselves to `S-left'.
  15649. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15650. (defvar org-shiftleft-final-hook nil
  15651. "Hook for functions attaching themselves to `S-left'.
  15652. This one runs after all other options except shift-select have been excluded.
  15653. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15654. (defvar org-shiftright-hook nil
  15655. "Hook for functions attaching themselves to `S-right'.
  15656. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15657. (defvar org-shiftright-final-hook nil
  15658. "Hook for functions attaching themselves to `S-right'.
  15659. This one runs after all other options except shift-select have been excluded.
  15660. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15661. (defun org-modifier-cursor-error ()
  15662. "Throw an error, a modified cursor command was applied in wrong context."
  15663. (user-error "This command is active in special context like tables, headlines or items"))
  15664. (defun org-shiftselect-error ()
  15665. "Throw an error because Shift-Cursor command was applied in wrong context."
  15666. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15667. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15668. (user-error "This command works only in special context like headlines or timestamps")))
  15669. (defun org-call-for-shift-select (cmd)
  15670. (let ((this-command-keys-shift-translated t))
  15671. (call-interactively cmd)))
  15672. (defun org-shifttab (&optional arg)
  15673. "Global visibility cycling or move to previous table field.
  15674. Call `org-table-previous-field' within a table.
  15675. When ARG is nil, cycle globally through visibility states.
  15676. When ARG is a numeric prefix, show contents of this level."
  15677. (interactive "P")
  15678. (cond
  15679. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15680. ((integerp arg)
  15681. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15682. (message "Content view to level: %d" arg)
  15683. (org-content (prefix-numeric-value arg2))
  15684. (org-cycle-show-empty-lines t)
  15685. (setq org-cycle-global-status 'overview)))
  15686. (t (call-interactively 'org-global-cycle))))
  15687. (defun org-shiftmetaleft ()
  15688. "Promote subtree or delete table column.
  15689. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15690. `org-table-delete-column', depending on context. See the
  15691. individual commands for more information."
  15692. (interactive)
  15693. (cond
  15694. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15695. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15696. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15697. ((if (not (org-region-active-p)) (org-at-item-p)
  15698. (save-excursion (goto-char (region-beginning))
  15699. (org-at-item-p)))
  15700. (call-interactively 'org-outdent-item-tree))
  15701. (t (org-modifier-cursor-error))))
  15702. (defun org-shiftmetaright ()
  15703. "Demote subtree or insert table column.
  15704. Calls `org-demote-subtree', `org-indent-item-tree', or
  15705. `org-table-insert-column', depending on context. See the
  15706. individual commands for more information."
  15707. (interactive)
  15708. (cond
  15709. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15710. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15711. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15712. ((if (not (org-region-active-p)) (org-at-item-p)
  15713. (save-excursion (goto-char (region-beginning))
  15714. (org-at-item-p)))
  15715. (call-interactively 'org-indent-item-tree))
  15716. (t (org-modifier-cursor-error))))
  15717. (defun org-shiftmetaup (&optional _arg)
  15718. "Drag the line at point up.
  15719. In a table, kill the current row.
  15720. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15721. but also adjust the previous clocked item in the clock history.
  15722. Everywhere else, drag the line at point up."
  15723. (interactive "P")
  15724. (cond
  15725. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15726. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15727. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15728. (call-interactively 'org-timestamp-up)))
  15729. (t (call-interactively 'org-drag-line-backward))))
  15730. (defun org-shiftmetadown (&optional _arg)
  15731. "Drag the line at point down.
  15732. In a table, insert an empty row at the current line.
  15733. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15734. but also adjust the previous clocked item in the clock history.
  15735. Everywhere else, drag the line at point down."
  15736. (interactive "P")
  15737. (cond
  15738. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15739. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15740. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15741. (call-interactively 'org-timestamp-down)))
  15742. (t (call-interactively 'org-drag-line-forward))))
  15743. (defsubst org-hidden-tree-error ()
  15744. (user-error
  15745. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15746. (defun org-metaleft (&optional _arg)
  15747. "Promote heading, list item at point or move table column left.
  15748. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15749. depending on context. With no specific context, calls the Emacs
  15750. default `backward-word'. See the individual commands for more
  15751. information.
  15752. This function runs the hook `org-metaleft-hook' as a first step,
  15753. and returns at first non-nil value."
  15754. (interactive "P")
  15755. (cond
  15756. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15757. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15758. ((org-with-limited-levels
  15759. (or (org-at-heading-p)
  15760. (and (org-region-active-p)
  15761. (save-excursion
  15762. (goto-char (region-beginning))
  15763. (org-at-heading-p)))))
  15764. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15765. (call-interactively 'org-do-promote))
  15766. ;; At an inline task.
  15767. ((org-at-heading-p)
  15768. (call-interactively 'org-inlinetask-promote))
  15769. ((or (org-at-item-p)
  15770. (and (org-region-active-p)
  15771. (save-excursion
  15772. (goto-char (region-beginning))
  15773. (org-at-item-p))))
  15774. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15775. (call-interactively 'org-outdent-item))
  15776. (t (call-interactively 'backward-word))))
  15777. (defun org-metaright (&optional _arg)
  15778. "Demote heading, list item at point or move table column right.
  15779. In front of a drawer or a block keyword, indent it correctly.
  15780. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15781. `org-indent-drawer' or `org-indent-block' depending on context.
  15782. With no specific context, calls the Emacs default `forward-word'.
  15783. See the individual commands for more information.
  15784. This function runs the hook `org-metaright-hook' as a first step,
  15785. and returns at first non-nil value."
  15786. (interactive "P")
  15787. (cond
  15788. ((run-hook-with-args-until-success 'org-metaright-hook))
  15789. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15790. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15791. ((org-at-block-p) (call-interactively 'org-indent-block))
  15792. ((org-with-limited-levels
  15793. (or (org-at-heading-p)
  15794. (and (org-region-active-p)
  15795. (save-excursion
  15796. (goto-char (region-beginning))
  15797. (org-at-heading-p)))))
  15798. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15799. (call-interactively 'org-do-demote))
  15800. ;; At an inline task.
  15801. ((org-at-heading-p)
  15802. (call-interactively 'org-inlinetask-demote))
  15803. ((or (org-at-item-p)
  15804. (and (org-region-active-p)
  15805. (save-excursion
  15806. (goto-char (region-beginning))
  15807. (org-at-item-p))))
  15808. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15809. (call-interactively 'org-indent-item))
  15810. (t (call-interactively 'forward-word))))
  15811. (defun org-check-for-hidden (what)
  15812. "Check if there are hidden headlines/items in the current visual line.
  15813. WHAT can be either `headlines' or `items'. If the current line is
  15814. an outline or item heading and it has a folded subtree below it,
  15815. this function returns t, nil otherwise."
  15816. (let ((re (cond
  15817. ((eq what 'headlines) org-outline-regexp-bol)
  15818. ((eq what 'items) (org-item-beginning-re))
  15819. (t (error "This should not happen"))))
  15820. beg end)
  15821. (save-excursion
  15822. (catch 'exit
  15823. (unless (org-region-active-p)
  15824. (setq beg (point-at-bol))
  15825. (beginning-of-line 2)
  15826. (while (and (not (eobp)) ;; this is like `next-line'
  15827. (get-char-property (1- (point)) 'invisible))
  15828. (beginning-of-line 2))
  15829. (setq end (point))
  15830. (goto-char beg)
  15831. (goto-char (point-at-eol))
  15832. (setq end (max end (point)))
  15833. (while (re-search-forward re end t)
  15834. (when (get-char-property (match-beginning 0) 'invisible)
  15835. (throw 'exit t))))
  15836. nil))))
  15837. (defun org-metaup (&optional _arg)
  15838. "Move subtree up or move table row up.
  15839. Calls `org-move-subtree-up' or `org-table-move-row' or
  15840. `org-move-item-up', depending on context. See the individual commands
  15841. for more information."
  15842. (interactive "P")
  15843. (cond
  15844. ((run-hook-with-args-until-success 'org-metaup-hook))
  15845. ((org-region-active-p)
  15846. (let* ((a (save-excursion
  15847. (goto-char (min (region-beginning) (region-end)))
  15848. (line-beginning-position)))
  15849. (b (save-excursion
  15850. (goto-char (max (region-beginning) (region-end)))
  15851. (if (bolp) (1- (point)) (line-end-position))))
  15852. (c (save-excursion
  15853. (goto-char a)
  15854. (move-beginning-of-line 0)
  15855. (point)))
  15856. (d (save-excursion
  15857. (goto-char a)
  15858. (move-end-of-line 0)
  15859. (point))))
  15860. (transpose-regions a b c d)
  15861. (goto-char c)))
  15862. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15863. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15864. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15865. (t (org-drag-element-backward))))
  15866. (defun org-metadown (&optional _arg)
  15867. "Move subtree down or move table row down.
  15868. Calls `org-move-subtree-down' or `org-table-move-row' or
  15869. `org-move-item-down', depending on context. See the individual
  15870. commands for more information."
  15871. (interactive "P")
  15872. (cond
  15873. ((run-hook-with-args-until-success 'org-metadown-hook))
  15874. ((org-region-active-p)
  15875. (let* ((a (save-excursion
  15876. (goto-char (min (region-beginning) (region-end)))
  15877. (line-beginning-position)))
  15878. (b (save-excursion
  15879. (goto-char (max (region-beginning) (region-end)))
  15880. (if (bolp) (1- (point)) (line-end-position))))
  15881. (c (save-excursion
  15882. (goto-char b)
  15883. (move-beginning-of-line (if (bolp) 1 2))
  15884. (point)))
  15885. (d (save-excursion
  15886. (goto-char b)
  15887. (move-end-of-line (if (bolp) 1 2))
  15888. (point))))
  15889. (transpose-regions a b c d)
  15890. (goto-char d)))
  15891. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15892. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15893. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15894. (t (org-drag-element-forward))))
  15895. (defun org-shiftup (&optional arg)
  15896. "Act on current element according to context.
  15897. Call `org-timestamp-up' or `org-priority-up', or
  15898. `org-previous-item', or `org-table-move-cell-up'. See the
  15899. individual commands for more information."
  15900. (interactive "P")
  15901. (cond
  15902. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15903. ((and org-support-shift-select (org-region-active-p))
  15904. (org-call-for-shift-select 'previous-line))
  15905. ((org-at-timestamp-p 'lax)
  15906. (call-interactively (if org-edit-timestamp-down-means-later
  15907. 'org-timestamp-down 'org-timestamp-up)))
  15908. ((and (not (eq org-support-shift-select 'always))
  15909. org-enable-priority-commands
  15910. (org-at-heading-p))
  15911. (call-interactively 'org-priority-up))
  15912. ((and (not org-support-shift-select) (org-at-item-p))
  15913. (call-interactively 'org-previous-item))
  15914. ((org-clocktable-try-shift 'up arg))
  15915. ((and (not (eq org-support-shift-select 'always))
  15916. (org-at-table-p))
  15917. (org-table-move-cell-up))
  15918. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15919. (org-support-shift-select
  15920. (org-call-for-shift-select 'previous-line))
  15921. (t (org-shiftselect-error))))
  15922. (defun org-shiftdown (&optional arg)
  15923. "Act on current element according to context.
  15924. Call `org-timestamp-down' or `org-priority-down', or
  15925. `org-next-item', or `org-table-move-cell-down'. See the
  15926. individual commands for more information."
  15927. (interactive "P")
  15928. (cond
  15929. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15930. ((and org-support-shift-select (org-region-active-p))
  15931. (org-call-for-shift-select 'next-line))
  15932. ((org-at-timestamp-p 'lax)
  15933. (call-interactively (if org-edit-timestamp-down-means-later
  15934. 'org-timestamp-up 'org-timestamp-down)))
  15935. ((and (not (eq org-support-shift-select 'always))
  15936. org-enable-priority-commands
  15937. (org-at-heading-p))
  15938. (call-interactively 'org-priority-down))
  15939. ((and (not org-support-shift-select) (org-at-item-p))
  15940. (call-interactively 'org-next-item))
  15941. ((org-clocktable-try-shift 'down arg))
  15942. ((and (not (eq org-support-shift-select 'always))
  15943. (org-at-table-p))
  15944. (org-table-move-cell-down))
  15945. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15946. (org-support-shift-select
  15947. (org-call-for-shift-select 'next-line))
  15948. (t (org-shiftselect-error))))
  15949. (defun org-shiftright (&optional arg)
  15950. "Act on the current element according to context.
  15951. This does one of the following:
  15952. - switch a timestamp at point one day into the future
  15953. - on a headline, switch to the next TODO keyword
  15954. - on an item, switch entire list to the next bullet type
  15955. - on a property line, switch to the next allowed value
  15956. - on a clocktable definition line, move time block into the future
  15957. - in a table, move a single cell right"
  15958. (interactive "P")
  15959. (cond
  15960. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15961. ((and org-support-shift-select (org-region-active-p))
  15962. (org-call-for-shift-select 'forward-char))
  15963. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15964. ((and (not (eq org-support-shift-select 'always))
  15965. (org-at-heading-p))
  15966. (let ((org-inhibit-logging
  15967. (not org-treat-S-cursor-todo-selection-as-state-change))
  15968. (org-inhibit-blocking
  15969. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15970. (org-call-with-arg 'org-todo 'right)))
  15971. ((or (and org-support-shift-select
  15972. (not (eq org-support-shift-select 'always))
  15973. (org-at-item-bullet-p))
  15974. (and (not org-support-shift-select) (org-at-item-p)))
  15975. (org-call-with-arg 'org-cycle-list-bullet nil))
  15976. ((and (not (eq org-support-shift-select 'always))
  15977. (org-at-property-p))
  15978. (call-interactively 'org-property-next-allowed-value))
  15979. ((org-clocktable-try-shift 'right arg))
  15980. ((and (not (eq org-support-shift-select 'always))
  15981. (org-at-table-p))
  15982. (org-table-move-cell-right))
  15983. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15984. (org-support-shift-select
  15985. (org-call-for-shift-select 'forward-char))
  15986. (t (org-shiftselect-error))))
  15987. (defun org-shiftleft (&optional arg)
  15988. "Act on current element according to context.
  15989. This does one of the following:
  15990. - switch a timestamp at point one day into the past
  15991. - on a headline, switch to the previous TODO keyword.
  15992. - on an item, switch entire list to the previous bullet type
  15993. - on a property line, switch to the previous allowed value
  15994. - on a clocktable definition line, move time block into the past
  15995. - in a table, move a single cell left"
  15996. (interactive "P")
  15997. (cond
  15998. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15999. ((and org-support-shift-select (org-region-active-p))
  16000. (org-call-for-shift-select 'backward-char))
  16001. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16002. ((and (not (eq org-support-shift-select 'always))
  16003. (org-at-heading-p))
  16004. (let ((org-inhibit-logging
  16005. (not org-treat-S-cursor-todo-selection-as-state-change))
  16006. (org-inhibit-blocking
  16007. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16008. (org-call-with-arg 'org-todo 'left)))
  16009. ((or (and org-support-shift-select
  16010. (not (eq org-support-shift-select 'always))
  16011. (org-at-item-bullet-p))
  16012. (and (not org-support-shift-select) (org-at-item-p)))
  16013. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16014. ((and (not (eq org-support-shift-select 'always))
  16015. (org-at-property-p))
  16016. (call-interactively 'org-property-previous-allowed-value))
  16017. ((org-clocktable-try-shift 'left arg))
  16018. ((and (not (eq org-support-shift-select 'always))
  16019. (org-at-table-p))
  16020. (org-table-move-cell-left))
  16021. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16022. (org-support-shift-select
  16023. (org-call-for-shift-select 'backward-char))
  16024. (t (org-shiftselect-error))))
  16025. (defun org-shiftcontrolright ()
  16026. "Switch to next TODO set."
  16027. (interactive)
  16028. (cond
  16029. ((and org-support-shift-select (org-region-active-p))
  16030. (org-call-for-shift-select 'forward-word))
  16031. ((and (not (eq org-support-shift-select 'always))
  16032. (org-at-heading-p))
  16033. (org-call-with-arg 'org-todo 'nextset))
  16034. (org-support-shift-select
  16035. (org-call-for-shift-select 'forward-word))
  16036. (t (org-shiftselect-error))))
  16037. (defun org-shiftcontrolleft ()
  16038. "Switch to previous TODO set."
  16039. (interactive)
  16040. (cond
  16041. ((and org-support-shift-select (org-region-active-p))
  16042. (org-call-for-shift-select 'backward-word))
  16043. ((and (not (eq org-support-shift-select 'always))
  16044. (org-at-heading-p))
  16045. (org-call-with-arg 'org-todo 'previousset))
  16046. (org-support-shift-select
  16047. (org-call-for-shift-select 'backward-word))
  16048. (t (org-shiftselect-error))))
  16049. (defun org-shiftcontrolup (&optional n)
  16050. "Change timestamps synchronously up in CLOCK log lines.
  16051. Optional argument N tells to change by that many units."
  16052. (interactive "P")
  16053. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16054. (let (org-support-shift-select)
  16055. (org-clock-timestamps-up n))
  16056. (user-error "Not at a clock log")))
  16057. (defun org-shiftcontroldown (&optional n)
  16058. "Change timestamps synchronously down in CLOCK log lines.
  16059. Optional argument N tells to change by that many units."
  16060. (interactive "P")
  16061. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16062. (let (org-support-shift-select)
  16063. (org-clock-timestamps-down n))
  16064. (user-error "Not at a clock log")))
  16065. (defun org-increase-number-at-point (&optional inc)
  16066. "Increment the number at point.
  16067. With an optional prefix numeric argument INC, increment using
  16068. this numeric value."
  16069. (interactive "p")
  16070. (if (not (number-at-point))
  16071. (user-error "Not on a number")
  16072. (unless inc (setq inc 1))
  16073. (let ((pos (point))
  16074. (beg (skip-chars-backward "-+^/*0-9eE."))
  16075. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16076. (setq nap (buffer-substring-no-properties
  16077. (+ pos beg) (+ pos beg end)))
  16078. (delete-region (+ pos beg) (+ pos beg end))
  16079. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16080. (when (org-at-table-p)
  16081. (org-table-align)
  16082. (org-table-end-of-field 1))))
  16083. (defun org-decrease-number-at-point (&optional inc)
  16084. "Decrement the number at point.
  16085. With an optional prefix numeric argument INC, decrement using
  16086. this numeric value."
  16087. (interactive "p")
  16088. (org-increase-number-at-point (- (or inc 1))))
  16089. (defun org-ctrl-c-ret ()
  16090. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16091. (interactive)
  16092. (cond
  16093. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16094. (t (call-interactively 'org-insert-heading))))
  16095. (defun org-copy-visible (beg end)
  16096. "Copy the visible parts of the region."
  16097. (interactive "r")
  16098. (let ((result ""))
  16099. (while (/= beg end)
  16100. (when (get-char-property beg 'invisible)
  16101. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16102. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16103. (setq result (concat result (buffer-substring beg next)))
  16104. (setq beg next)))
  16105. (setq deactivate-mark t)
  16106. (kill-new result)
  16107. (message "Visible strings have been copied to the kill ring.")))
  16108. (defun org-copy-special ()
  16109. "Copy region in table or copy current subtree.
  16110. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16111. context. See the individual commands for more information."
  16112. (interactive)
  16113. (call-interactively
  16114. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16115. (defun org-cut-special ()
  16116. "Cut region in table or cut current subtree.
  16117. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16118. context. See the individual commands for more information."
  16119. (interactive)
  16120. (call-interactively
  16121. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16122. (defun org-paste-special (arg)
  16123. "Paste rectangular region into table, or past subtree relative to level.
  16124. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16125. See the individual commands for more information."
  16126. (interactive "P")
  16127. (if (org-at-table-p)
  16128. (org-table-paste-rectangle)
  16129. (org-paste-subtree arg)))
  16130. (defun org-edit-special (&optional arg)
  16131. "Call a special editor for the element at point.
  16132. When at a table, call the formula editor with `org-table-edit-formulas'.
  16133. When in a source code block, call `org-edit-src-code'.
  16134. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16135. When in an export block, call `org-edit-export-block'.
  16136. When in a LaTeX environment, call `org-edit-latex-environment'.
  16137. When at an #+INCLUDE keyword, visit the included file.
  16138. When at a footnote reference, call `org-edit-footnote-reference'.
  16139. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16140. When at an active timestamp, call `org-time-stamp'.
  16141. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16142. On a link, call `ffap' to visit the link at point.
  16143. Otherwise, return a user error."
  16144. (interactive "P")
  16145. (let ((element (org-element-at-point)))
  16146. (barf-if-buffer-read-only)
  16147. (pcase (org-element-type element)
  16148. (`src-block
  16149. (if (not arg) (org-edit-src-code)
  16150. (let* ((info (org-babel-get-src-block-info))
  16151. (lang (nth 0 info))
  16152. (params (nth 2 info))
  16153. (session (cdr (assq :session params))))
  16154. (if (not session) (org-edit-src-code)
  16155. ;; At a source block with a session and function called
  16156. ;; with an ARG: switch to the buffer related to the
  16157. ;; inferior process.
  16158. (switch-to-buffer
  16159. (funcall (intern (concat "org-babel-prep-session:" lang))
  16160. session params))))))
  16161. (`keyword
  16162. (unless (member (org-element-property :key element)
  16163. '("INCLUDE" "SETUPFILE"))
  16164. (user-error "No special environment to edit here"))
  16165. (let ((value (org-element-property :value element)))
  16166. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16167. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16168. (or (match-string 1 value)
  16169. (match-string 0 value)))))
  16170. (when (org-file-url-p file)
  16171. (user-error "Files located with a URL cannot be edited"))
  16172. (org-link-open-from-string
  16173. (format "[[%s]]" (expand-file-name file))))))
  16174. (`table
  16175. (if (eq (org-element-property :type element) 'table.el)
  16176. (org-edit-table.el)
  16177. (call-interactively 'org-table-edit-formulas)))
  16178. ;; Only Org tables contain `table-row' type elements.
  16179. (`table-row (call-interactively 'org-table-edit-formulas))
  16180. (`example-block (org-edit-src-code))
  16181. (`export-block (org-edit-export-block))
  16182. (`fixed-width (org-edit-fixed-width-region))
  16183. (`latex-environment (org-edit-latex-environment))
  16184. (`planning
  16185. (let ((proplist (cadr element)))
  16186. (mapc #'call-interactively
  16187. (remq nil
  16188. (list
  16189. (when (plist-get proplist :deadline) #'org-deadline)
  16190. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16191. (_
  16192. ;; No notable element at point. Though, we may be at a link or
  16193. ;; a footnote reference, which are objects. Thus, scan deeper.
  16194. (let ((context (org-element-context element)))
  16195. (pcase (org-element-type context)
  16196. (`footnote-reference (org-edit-footnote-reference))
  16197. (`inline-src-block (org-edit-inline-src-code))
  16198. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16199. (call-interactively #'org-time-stamp-inactive)
  16200. (call-interactively #'org-time-stamp)))
  16201. (`link (call-interactively #'ffap))
  16202. (_ (user-error "No special environment to edit here"))))))))
  16203. (defun org-ctrl-c-ctrl-c (&optional arg)
  16204. "Set tags in headline, or update according to changed information at point.
  16205. This command does many different things, depending on context:
  16206. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16207. this is what we do.
  16208. - If the cursor is on a statistics cookie, update it.
  16209. - If the cursor is in a headline, prompt for tags and insert them
  16210. into the current line, aligned to `org-tags-column'. When called
  16211. with prefix arg, realign all tags in the current buffer.
  16212. - If the cursor is in one of the special #+KEYWORD lines, this
  16213. triggers scanning the buffer for these lines and updating the
  16214. information.
  16215. - If the cursor is inside a table, realign the table. This command
  16216. works even if the automatic table editor has been turned off.
  16217. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16218. the entire table.
  16219. - If the cursor is at a footnote reference or definition, jump to
  16220. the corresponding definition or references, respectively.
  16221. - If the cursor is a the beginning of a dynamic block, update it.
  16222. - If the current buffer is a capture buffer, close note and file it.
  16223. - If the cursor is on a <<<target>>>, update radio targets and
  16224. corresponding links in this buffer.
  16225. - If the cursor is on a numbered item in a plain list, renumber the
  16226. ordered list.
  16227. - If the cursor is on a checkbox, toggle it.
  16228. - If the cursor is on a code block, evaluate it. The variable
  16229. `org-confirm-babel-evaluate' can be used to control prompting
  16230. before code block evaluation, by default every code block
  16231. evaluation requires confirmation. Code block evaluation can be
  16232. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16233. (interactive "P")
  16234. (cond
  16235. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16236. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16237. (org-remove-occur-highlights)
  16238. (message "Temporary highlights/overlays removed from current buffer"))
  16239. ((and (local-variable-p 'org-finish-function)
  16240. (fboundp org-finish-function))
  16241. (funcall org-finish-function))
  16242. ((org-babel-hash-at-point))
  16243. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16244. (t
  16245. (let* ((context
  16246. (org-element-lineage
  16247. (org-element-context)
  16248. ;; Limit to supported contexts.
  16249. '(babel-call clock dynamic-block footnote-definition
  16250. footnote-reference inline-babel-call inline-src-block
  16251. inlinetask item keyword node-property paragraph
  16252. plain-list planning property-drawer radio-target
  16253. src-block statistics-cookie table table-cell table-row
  16254. timestamp)
  16255. t))
  16256. (type (org-element-type context)))
  16257. ;; For convenience: at the first line of a paragraph on the same
  16258. ;; line as an item, apply function on that item instead.
  16259. (when (eq type 'paragraph)
  16260. (let ((parent (org-element-property :parent context)))
  16261. (when (and (eq (org-element-type parent) 'item)
  16262. (= (line-beginning-position)
  16263. (org-element-property :begin parent)))
  16264. (setq context parent)
  16265. (setq type 'item))))
  16266. ;; Act according to type of element or object at point.
  16267. ;;
  16268. ;; Do nothing on a blank line, except if it is contained in
  16269. ;; a source block. Hence, we first check if point is in such
  16270. ;; a block and then if it is at a blank line.
  16271. (pcase type
  16272. ((or `inline-src-block `src-block)
  16273. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16274. (org-babel-eval-wipe-error-buffer)
  16275. (org-babel-execute-src-block
  16276. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16277. ((guard (org-match-line "[ \t]*$"))
  16278. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16279. (user-error
  16280. (substitute-command-keys
  16281. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16282. ((or `babel-call `inline-babel-call)
  16283. (let ((info (org-babel-lob-get-info context)))
  16284. (when info (org-babel-execute-src-block nil info))))
  16285. (`clock (org-clock-update-time-maybe))
  16286. (`dynamic-block
  16287. (save-excursion
  16288. (goto-char (org-element-property :post-affiliated context))
  16289. (org-update-dblock)))
  16290. (`footnote-definition
  16291. (goto-char (org-element-property :post-affiliated context))
  16292. (call-interactively 'org-footnote-action))
  16293. (`footnote-reference (call-interactively #'org-footnote-action))
  16294. ((or `headline `inlinetask)
  16295. (save-excursion (goto-char (org-element-property :begin context))
  16296. (call-interactively #'org-set-tags-command)))
  16297. (`item
  16298. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16299. ;; unconditionally, whereas `C-u' will toggle its presence.
  16300. ;; Without a universal argument, if the item has a checkbox,
  16301. ;; toggle it. Otherwise repair the list.
  16302. (let* ((box (org-element-property :checkbox context))
  16303. (struct (org-element-property :structure context))
  16304. (old-struct (copy-tree struct))
  16305. (parents (org-list-parents-alist struct))
  16306. (prevs (org-list-prevs-alist struct))
  16307. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16308. (org-list-set-checkbox
  16309. (org-element-property :begin context) struct
  16310. (cond ((equal arg '(16)) "[-]")
  16311. ((and (not box) (equal arg '(4))) "[ ]")
  16312. ((or (not box) (equal arg '(4))) nil)
  16313. ((eq box 'on) "[ ]")
  16314. (t "[X]")))
  16315. ;; Mimic `org-list-write-struct' but with grabbing a return
  16316. ;; value from `org-list-struct-fix-box'.
  16317. (org-list-struct-fix-ind struct parents 2)
  16318. (org-list-struct-fix-item-end struct)
  16319. (org-list-struct-fix-bul struct prevs)
  16320. (org-list-struct-fix-ind struct parents)
  16321. (let ((block-item
  16322. (org-list-struct-fix-box struct parents prevs orderedp)))
  16323. (if (and box (equal struct old-struct))
  16324. (if (equal arg '(16))
  16325. (message "Checkboxes already reset")
  16326. (user-error "Cannot toggle this checkbox: %s"
  16327. (if (eq box 'on)
  16328. "all subitems checked"
  16329. "unchecked subitems")))
  16330. (org-list-struct-apply-struct struct old-struct)
  16331. (org-update-checkbox-count-maybe))
  16332. (when block-item
  16333. (message "Checkboxes were removed due to empty box at line %d"
  16334. (org-current-line block-item))))))
  16335. (`keyword
  16336. (let ((org-inhibit-startup-visibility-stuff t)
  16337. (org-startup-align-all-tables nil))
  16338. (when (boundp 'org-table-coordinate-overlays)
  16339. (mapc #'delete-overlay org-table-coordinate-overlays)
  16340. (setq org-table-coordinate-overlays nil))
  16341. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16342. (message "Local setup has been refreshed"))
  16343. (`plain-list
  16344. ;; At a plain list, with a double C-u argument, set
  16345. ;; checkboxes of each item to "[-]", whereas a single one
  16346. ;; will toggle their presence according to the state of the
  16347. ;; first item in the list. Without an argument, repair the
  16348. ;; list.
  16349. (let* ((begin (org-element-property :contents-begin context))
  16350. (struct (org-element-property :structure context))
  16351. (old-struct (copy-tree struct))
  16352. (first-box (save-excursion
  16353. (goto-char begin)
  16354. (looking-at org-list-full-item-re)
  16355. (match-string-no-properties 3)))
  16356. (new-box (cond ((equal arg '(16)) "[-]")
  16357. ((equal arg '(4)) (unless first-box "[ ]"))
  16358. ((equal first-box "[X]") "[ ]")
  16359. (t "[X]"))))
  16360. (cond
  16361. (arg
  16362. (dolist (pos
  16363. (org-list-get-all-items
  16364. begin struct (org-list-prevs-alist struct)))
  16365. (org-list-set-checkbox pos struct new-box)))
  16366. ((and first-box (eq (point) begin))
  16367. ;; For convenience, when point is at bol on the first
  16368. ;; item of the list and no argument is provided, simply
  16369. ;; toggle checkbox of that item, if any.
  16370. (org-list-set-checkbox begin struct new-box)))
  16371. (when (equal
  16372. (org-list-write-struct
  16373. struct (org-list-parents-alist struct) old-struct)
  16374. old-struct)
  16375. (message "Cannot update this checkbox"))
  16376. (org-update-checkbox-count-maybe)))
  16377. ((or `property-drawer `node-property)
  16378. (call-interactively #'org-property-action))
  16379. (`radio-target
  16380. (call-interactively #'org-update-radio-target-regexp))
  16381. (`statistics-cookie
  16382. (call-interactively #'org-update-statistics-cookies))
  16383. ((or `table `table-cell `table-row)
  16384. ;; At a table, recalculate every field and align it. Also
  16385. ;; send the table if necessary. If the table has
  16386. ;; a `table.el' type, just give up. At a table row or cell,
  16387. ;; maybe recalculate line but always align table.
  16388. (if (eq (org-element-property :type context) 'table.el)
  16389. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16390. Use `\\[org-edit-special]' to edit table.el tables"))
  16391. (if (or (eq type 'table)
  16392. ;; Check if point is at a TBLFM line.
  16393. (and (eq type 'table-row)
  16394. (= (point) (org-element-property :end context))))
  16395. (save-excursion
  16396. (if (org-at-TBLFM-p)
  16397. (progn (require 'org-table)
  16398. (org-table-calc-current-TBLFM))
  16399. (goto-char (org-element-property :contents-begin context))
  16400. (org-call-with-arg 'org-table-recalculate (or arg t))
  16401. (orgtbl-send-table 'maybe)))
  16402. (org-table-maybe-eval-formula)
  16403. (cond (arg (call-interactively #'org-table-recalculate))
  16404. ((org-table-maybe-recalculate-line))
  16405. (t (org-table-align))))))
  16406. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16407. (org-timestamp-change 0 'day))
  16408. ((and `nil (guard (org-at-heading-p)))
  16409. ;; When point is on an unsupported object type, we can miss
  16410. ;; the fact that it also is at a heading. Handle it here.
  16411. (call-interactively #'org-set-tags-command))
  16412. ((guard
  16413. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16414. (_
  16415. (user-error
  16416. (substitute-command-keys
  16417. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16418. (defun org-mode-restart ()
  16419. (interactive)
  16420. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16421. (funcall major-mode)
  16422. (hack-local-variables)
  16423. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16424. (org-indent-mode -1))
  16425. (org-reset-file-cache))
  16426. (message "%s restarted" major-mode))
  16427. (defun org-flag-above-first-heading (&optional arg)
  16428. "Hide from bob up to the first heading.
  16429. Move point to the beginning of first heading or end of buffer."
  16430. (goto-char (point-min))
  16431. (unless (org-at-heading-p)
  16432. (outline-next-heading))
  16433. (unless (bobp)
  16434. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16435. (defun org-show-branches-buffer ()
  16436. "Show all branches in the buffer."
  16437. (org-flag-above-first-heading)
  16438. (outline-hide-sublevels 1)
  16439. (unless (eobp)
  16440. (outline-show-branches)
  16441. (while (outline-get-next-sibling)
  16442. (outline-show-branches)))
  16443. (goto-char (point-min)))
  16444. (defun org-kill-note-or-show-branches ()
  16445. "Abort storing current note, or show just branches."
  16446. (interactive)
  16447. (cond (org-finish-function
  16448. (let ((org-note-abort t)) (funcall org-finish-function)))
  16449. ((org-before-first-heading-p)
  16450. (org-show-branches-buffer)
  16451. (org-hide-archived-subtrees (point-min) (point-max)))
  16452. (t
  16453. (let ((beg (progn (org-back-to-heading) (point)))
  16454. (end (save-excursion (org-end-of-subtree t t) (point))))
  16455. (outline-hide-subtree)
  16456. (outline-show-branches)
  16457. (org-hide-archived-subtrees beg end)))))
  16458. (defun org-delete-indentation (&optional arg)
  16459. "Join current line to previous and fix whitespace at join.
  16460. If previous line is a headline add to headline title. Otherwise
  16461. the function calls `delete-indentation'.
  16462. With a non-nil optional argument, join it to the following one."
  16463. (interactive "*P")
  16464. (if (save-excursion
  16465. (beginning-of-line (if arg 1 0))
  16466. (let ((case-fold-search nil))
  16467. (looking-at org-complex-heading-regexp)))
  16468. ;; At headline.
  16469. (let ((tags-column (when (match-beginning 5)
  16470. (save-excursion (goto-char (match-beginning 5))
  16471. (current-column))))
  16472. (string (concat " " (progn (when arg (forward-line 1))
  16473. (org-trim (delete-and-extract-region
  16474. (line-beginning-position)
  16475. (line-end-position)))))))
  16476. (unless (bobp) (delete-region (point) (1- (point))))
  16477. (goto-char (or (match-end 4)
  16478. (match-beginning 5)
  16479. (match-end 0)))
  16480. (skip-chars-backward " \t")
  16481. (save-excursion (insert string))
  16482. ;; Adjust alignment of tags.
  16483. (cond
  16484. ((not tags-column)) ;no tags
  16485. (org-auto-align-tags (org-align-tags))
  16486. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16487. (delete-indentation arg)))
  16488. (defun org-open-line (n)
  16489. "Insert a new row in tables, call `open-line' elsewhere.
  16490. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16491. As a special case, when a document starts with a table, allow to
  16492. call `open-line' on the very first character."
  16493. (interactive "*p")
  16494. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16495. (org-table-insert-row)
  16496. (open-line n)))
  16497. (defun org-return (&optional indent)
  16498. "Goto next table row or insert a newline.
  16499. Calls `org-table-next-row' or `newline', depending on context.
  16500. When optional INDENT argument is non-nil, call
  16501. `newline-and-indent' instead of `newline'.
  16502. When `org-return-follows-link' is non-nil and point is on
  16503. a timestamp or a link, call `org-open-at-point'. However, it
  16504. will not happen if point is in a table or on a \"dead\"
  16505. object (e.g., within a comment). In these case, you need to use
  16506. `org-open-at-point' directly."
  16507. (interactive)
  16508. (let ((context (if org-return-follows-link (org-element-context)
  16509. (org-element-at-point))))
  16510. (cond
  16511. ;; In a table, call `org-table-next-row'. However, before first
  16512. ;; column or after last one, split the table.
  16513. ((or (and (eq 'table (org-element-type context))
  16514. (not (eq 'table.el (org-element-property :type context)))
  16515. (>= (point) (org-element-property :contents-begin context))
  16516. (< (point) (org-element-property :contents-end context)))
  16517. (org-element-lineage context '(table-row table-cell) t))
  16518. (if (or (looking-at-p "[ \t]*$")
  16519. (save-excursion (skip-chars-backward " \t") (bolp)))
  16520. (insert "\n")
  16521. (org-table-justify-field-maybe)
  16522. (call-interactively #'org-table-next-row)))
  16523. ;; On a link or a timestamp, call `org-open-at-point' if
  16524. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16525. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16526. ((and org-return-follows-link
  16527. (or (and (eq 'link (org-element-type context))
  16528. ;; Ensure point is not on the white spaces after
  16529. ;; the link.
  16530. (let ((origin (point)))
  16531. (org-with-point-at (org-element-property :end context)
  16532. (skip-chars-backward " \t")
  16533. (> (point) origin))))
  16534. (org-in-regexp org-ts-regexp-both nil t)
  16535. (org-in-regexp org-tsr-regexp-both nil t)
  16536. (org-in-regexp org-link-any-re nil t)))
  16537. (call-interactively #'org-open-at-point))
  16538. ;; Insert newline in heading, but preserve tags.
  16539. ((and (not (bolp))
  16540. (let ((case-fold-search nil))
  16541. (org-match-line org-complex-heading-regexp)))
  16542. ;; At headline. Split line. However, if point is on keyword,
  16543. ;; priority cookie or tags, do not break any of them: add
  16544. ;; a newline after the headline instead.
  16545. (let ((tags-column (and (match-beginning 5)
  16546. (save-excursion (goto-char (match-beginning 5))
  16547. (current-column))))
  16548. (string
  16549. (when (and (match-end 4) (org-point-in-group (point) 4))
  16550. (delete-and-extract-region (point) (match-end 4)))))
  16551. ;; Adjust tag alignment.
  16552. (cond
  16553. ((not (and tags-column string)))
  16554. (org-auto-align-tags (org-align-tags))
  16555. (t (org--align-tags-here tags-column))) ;preserve tags column
  16556. (end-of-line)
  16557. (org-show-entry)
  16558. (if indent (newline-and-indent) (newline))
  16559. (when string (save-excursion (insert (org-trim string))))))
  16560. ;; In a list, make sure indenting keeps trailing text within.
  16561. ((and indent
  16562. (not (eolp))
  16563. (org-element-lineage context '(item)))
  16564. (let ((trailing-data
  16565. (delete-and-extract-region (point) (line-end-position))))
  16566. (newline-and-indent)
  16567. (save-excursion (insert trailing-data))))
  16568. (t
  16569. ;; Do not auto-fill when point is in an Org property drawer.
  16570. (let ((auto-fill-function (and (not (org-at-property-p))
  16571. auto-fill-function)))
  16572. (if indent
  16573. (newline-and-indent)
  16574. (newline)))))))
  16575. (defun org-return-indent ()
  16576. "Goto next table row or insert a newline and indent.
  16577. Calls `org-table-next-row' or `newline-and-indent', depending on
  16578. context. See the individual commands for more information."
  16579. (interactive)
  16580. (org-return t))
  16581. (defun org-ctrl-c-tab (&optional arg)
  16582. "Toggle columns width in a table, or show children.
  16583. Call `org-table-toggle-column-width' if point is in a table.
  16584. Otherwise, call `org-show-children'. ARG is the level to hide."
  16585. (interactive "p")
  16586. (if (org-at-table-p)
  16587. (call-interactively #'org-table-toggle-column-width)
  16588. (if (org-before-first-heading-p)
  16589. (progn
  16590. (org-flag-above-first-heading)
  16591. (outline-hide-sublevels (or arg 1))
  16592. (goto-char (point-min)))
  16593. (outline-hide-subtree)
  16594. (org-show-children arg))))
  16595. (defun org-ctrl-c-star ()
  16596. "Compute table, or change heading status of lines.
  16597. Calls `org-table-recalculate' or `org-toggle-heading',
  16598. depending on context."
  16599. (interactive)
  16600. (cond
  16601. ((org-at-table-p)
  16602. (call-interactively 'org-table-recalculate))
  16603. (t
  16604. ;; Convert all lines in region to list items
  16605. (call-interactively 'org-toggle-heading))))
  16606. (defun org-ctrl-c-minus ()
  16607. "Insert separator line in table or modify bullet status of line.
  16608. Also turns a plain line or a region of lines into list items.
  16609. Calls `org-table-insert-hline', `org-toggle-item', or
  16610. `org-cycle-list-bullet', depending on context."
  16611. (interactive)
  16612. (cond
  16613. ((org-at-table-p)
  16614. (call-interactively 'org-table-insert-hline))
  16615. ((org-region-active-p)
  16616. (call-interactively 'org-toggle-item))
  16617. ((org-in-item-p)
  16618. (call-interactively 'org-cycle-list-bullet))
  16619. (t
  16620. (call-interactively 'org-toggle-item))))
  16621. (defun org-toggle-heading (&optional nstars)
  16622. "Convert headings to normal text, or items or text to headings.
  16623. If there is no active region, only convert the current line.
  16624. With a `\\[universal-argument]' prefix, convert the whole list at
  16625. point into heading.
  16626. In a region:
  16627. - If the first non blank line is a headline, remove the stars
  16628. from all headlines in the region.
  16629. - If it is a normal line, turn each and every normal line (i.e.,
  16630. not an heading or an item) in the region into headings. If you
  16631. want to convert only the first line of this region, use one
  16632. universal prefix argument.
  16633. - If it is a plain list item, turn all plain list items into headings.
  16634. When converting a line into a heading, the number of stars is chosen
  16635. such that the lines become children of the current entry. However,
  16636. when a numeric prefix argument is given, its value determines the
  16637. number of stars to add."
  16638. (interactive "P")
  16639. (let ((skip-blanks
  16640. (function
  16641. ;; Return beginning of first non-blank line, starting from
  16642. ;; line at POS.
  16643. (lambda (pos)
  16644. (save-excursion
  16645. (goto-char pos)
  16646. (while (org-at-comment-p) (forward-line))
  16647. (skip-chars-forward " \r\t\n")
  16648. (point-at-bol)))))
  16649. beg end toggled)
  16650. ;; Determine boundaries of changes. If a universal prefix has
  16651. ;; been given, put the list in a region. If region ends at a bol,
  16652. ;; do not consider the last line to be in the region.
  16653. (when (and current-prefix-arg (org-at-item-p))
  16654. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16655. (org-mark-element))
  16656. (if (org-region-active-p)
  16657. (setq beg (funcall skip-blanks (region-beginning))
  16658. end (copy-marker (save-excursion
  16659. (goto-char (region-end))
  16660. (if (bolp) (point) (point-at-eol)))))
  16661. (setq beg (funcall skip-blanks (point-at-bol))
  16662. end (copy-marker (point-at-eol))))
  16663. ;; Ensure inline tasks don't count as headings.
  16664. (org-with-limited-levels
  16665. (save-excursion
  16666. (goto-char beg)
  16667. (cond
  16668. ;; Case 1. Started at an heading: de-star headings.
  16669. ((org-at-heading-p)
  16670. (while (< (point) end)
  16671. (when (org-at-heading-p t)
  16672. (looking-at org-outline-regexp) (replace-match "")
  16673. (setq toggled t))
  16674. (forward-line)))
  16675. ;; Case 2. Started at an item: change items into headlines.
  16676. ;; One star will be added by `org-list-to-subtree'.
  16677. ((org-at-item-p)
  16678. (while (< (point) end)
  16679. (when (org-at-item-p)
  16680. ;; Pay attention to cases when region ends before list.
  16681. (let* ((struct (org-list-struct))
  16682. (list-end
  16683. (min (org-list-get-bottom-point struct) (1+ end))))
  16684. (save-restriction
  16685. (narrow-to-region (point) list-end)
  16686. (insert (org-list-to-subtree
  16687. (org-list-to-lisp t)
  16688. (pcase (org-current-level)
  16689. (`nil 1)
  16690. (l (1+ (org-reduced-level l)))))
  16691. "\n")))
  16692. (setq toggled t))
  16693. (forward-line)))
  16694. ;; Case 3. Started at normal text: make every line an heading,
  16695. ;; skipping headlines and items.
  16696. (t (let* ((stars
  16697. (make-string
  16698. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16699. (add-stars
  16700. (cond (nstars "") ; stars from prefix only
  16701. ((equal stars "") "*") ; before first heading
  16702. (org-odd-levels-only "**") ; inside heading, odd
  16703. (t "*"))) ; inside heading, oddeven
  16704. (rpl (concat stars add-stars " "))
  16705. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16706. (while (< (point) (if (equal nstars '(4)) lend end))
  16707. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16708. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16709. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16710. (forward-line)))))))
  16711. (unless toggled (message "Cannot toggle heading from here"))))
  16712. (defun org-meta-return (&optional arg)
  16713. "Insert a new heading or wrap a region in a table.
  16714. Calls `org-insert-heading', `org-insert-item' or
  16715. `org-table-wrap-region', depending on context. When called with
  16716. an argument, unconditionally call `org-insert-heading'."
  16717. (interactive "P")
  16718. (org-check-before-invisible-edit 'insert)
  16719. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16720. (call-interactively (cond (arg #'org-insert-heading)
  16721. ((org-at-table-p) #'org-table-wrap-region)
  16722. ((org-in-item-p) #'org-insert-item)
  16723. (t #'org-insert-heading)))))
  16724. ;;; Menu entries
  16725. (defsubst org-in-subtree-not-table-p ()
  16726. "Are we in a subtree and not in a table?"
  16727. (and (not (org-before-first-heading-p))
  16728. (not (org-at-table-p))))
  16729. ;; Define the Org mode menus
  16730. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16731. '("Tbl"
  16732. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16733. ["Next Field" org-cycle (org-at-table-p)]
  16734. ["Previous Field" org-shifttab (org-at-table-p)]
  16735. ["Next Row" org-return (org-at-table-p)]
  16736. "--"
  16737. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16738. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16739. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16740. "--"
  16741. ("Column"
  16742. ["Move Column Left" org-metaleft (org-at-table-p)]
  16743. ["Move Column Right" org-metaright (org-at-table-p)]
  16744. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16745. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16746. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16747. ("Row"
  16748. ["Move Row Up" org-metaup (org-at-table-p)]
  16749. ["Move Row Down" org-metadown (org-at-table-p)]
  16750. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16751. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16752. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16753. "--"
  16754. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16755. ("Rectangle"
  16756. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16757. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16758. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16759. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16760. "--"
  16761. ("Calculate"
  16762. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16763. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16764. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16765. "--"
  16766. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16767. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16768. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16769. "--"
  16770. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16771. "--"
  16772. ["Sum Column/Rectangle" org-table-sum
  16773. (or (org-at-table-p) (org-region-active-p))]
  16774. ["Which Column?" org-table-current-column (org-at-table-p)])
  16775. ["Debug Formulas"
  16776. org-table-toggle-formula-debugger
  16777. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16778. ["Show Col/Row Numbers"
  16779. org-table-toggle-coordinate-overlays
  16780. :style toggle
  16781. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16782. "--"
  16783. ["Create" org-table-create (not (org-at-table-p))]
  16784. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16785. ["Import from File" org-table-import (not (org-at-table-p))]
  16786. ["Export to File" org-table-export (org-at-table-p)]
  16787. "--"
  16788. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16789. "--"
  16790. ("Plot"
  16791. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16792. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16793. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16794. '("Org"
  16795. ("Show/Hide"
  16796. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16797. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16798. ["Sparse Tree..." org-sparse-tree t]
  16799. ["Reveal Context" org-reveal t]
  16800. ["Show All" org-show-all t]
  16801. "--"
  16802. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16803. "--"
  16804. ["New Heading" org-insert-heading t]
  16805. ("Navigate Headings"
  16806. ["Up" outline-up-heading t]
  16807. ["Next" outline-next-visible-heading t]
  16808. ["Previous" outline-previous-visible-heading t]
  16809. ["Next Same Level" outline-forward-same-level t]
  16810. ["Previous Same Level" outline-backward-same-level t]
  16811. "--"
  16812. ["Jump" org-goto t])
  16813. ("Edit Structure"
  16814. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16815. "--"
  16816. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16817. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16818. "--"
  16819. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16820. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16821. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16822. "--"
  16823. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16824. "--"
  16825. ["Copy visible text" org-copy-visible t]
  16826. "--"
  16827. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16828. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16829. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16830. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16831. "--"
  16832. ["Sort Region/Children" org-sort t]
  16833. "--"
  16834. ["Convert to odd levels" org-convert-to-odd-levels t]
  16835. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16836. ("Editing"
  16837. ["Emphasis..." org-emphasize t]
  16838. ["Edit Source Example" org-edit-special t]
  16839. "--"
  16840. ["Footnote new/jump" org-footnote-action t]
  16841. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16842. ("Archive"
  16843. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16844. "--"
  16845. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16846. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16847. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16848. )
  16849. "--"
  16850. ("Hyperlinks"
  16851. ["Store Link (Global)" org-store-link t]
  16852. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16853. ["Insert Link" org-insert-link t]
  16854. ["Follow Link" org-open-at-point t]
  16855. "--"
  16856. ["Next link" org-next-link t]
  16857. ["Previous link" org-previous-link t]
  16858. "--"
  16859. ["Descriptive Links"
  16860. org-toggle-link-display
  16861. :style radio
  16862. :selected org-descriptive-links
  16863. ]
  16864. ["Literal Links"
  16865. org-toggle-link-display
  16866. :style radio
  16867. :selected (not org-descriptive-links)])
  16868. "--"
  16869. ("TODO Lists"
  16870. ["TODO/DONE/-" org-todo t]
  16871. ("Select keyword"
  16872. ["Next keyword" org-shiftright (org-at-heading-p)]
  16873. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16874. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16875. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16876. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16877. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16878. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16879. "--"
  16880. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16881. :selected org-enforce-todo-dependencies :style toggle :active t]
  16882. "Settings for tree at point"
  16883. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16884. :selected (org-entry-get nil "ORDERED")
  16885. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16886. ["Do Children parallel" org-toggle-ordered-property :style radio
  16887. :selected (not (org-entry-get nil "ORDERED"))
  16888. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16889. "--"
  16890. ["Set Priority" org-priority t]
  16891. ["Priority Up" org-shiftup t]
  16892. ["Priority Down" org-shiftdown t]
  16893. "--"
  16894. ["Get news from all feeds" org-feed-update-all t]
  16895. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16896. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16897. ("TAGS and Properties"
  16898. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16899. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16900. "--"
  16901. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16902. ["Column view of properties" org-columns t]
  16903. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16904. ("Dates and Scheduling"
  16905. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16906. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16907. ("Change Date"
  16908. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16909. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16910. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16911. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16912. ["Compute Time Range" org-evaluate-time-range t]
  16913. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16914. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16915. "--"
  16916. ["Custom time format" org-toggle-time-stamp-overlays
  16917. :style radio :selected org-display-custom-times]
  16918. "--"
  16919. ["Goto Calendar" org-goto-calendar t]
  16920. ["Date from Calendar" org-date-from-calendar t]
  16921. "--"
  16922. ["Start/Restart Timer" org-timer-start t]
  16923. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16924. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16925. ["Insert Timer String" org-timer t]
  16926. ["Insert Timer Item" org-timer-item t])
  16927. ("Logging work"
  16928. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16929. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16930. ["Clock out" org-clock-out t]
  16931. ["Clock cancel" org-clock-cancel t]
  16932. "--"
  16933. ["Mark as default task" org-clock-mark-default-task t]
  16934. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16935. ["Goto running clock" org-clock-goto t]
  16936. "--"
  16937. ["Display times" org-clock-display t]
  16938. ["Create clock table" org-clock-report t]
  16939. "--"
  16940. ["Record DONE time"
  16941. (progn (setq org-log-done (not org-log-done))
  16942. (message "Switching to %s will %s record a timestamp"
  16943. (car org-done-keywords)
  16944. (if org-log-done "automatically" "not")))
  16945. :style toggle :selected org-log-done])
  16946. "--"
  16947. ["Agenda Command..." org-agenda t]
  16948. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16949. ("File List for Agenda")
  16950. ("Special views current file"
  16951. ["TODO Tree" org-show-todo-tree t]
  16952. ["Check Deadlines" org-check-deadlines t]
  16953. ["Tags/Property tree" org-match-sparse-tree t])
  16954. "--"
  16955. ["Export/Publish..." org-export-dispatch t]
  16956. ("LaTeX"
  16957. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16958. :style toggle :selected org-cdlatex-mode]
  16959. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16960. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16961. ["Modify math symbol" org-cdlatex-math-modify
  16962. (org-inside-LaTeX-fragment-p)]
  16963. ["Insert citation" org-reftex-citation t])
  16964. "--"
  16965. ("MobileOrg"
  16966. ["Push Files and Views" org-mobile-push t]
  16967. ["Get Captured and Flagged" org-mobile-pull t]
  16968. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16969. "--"
  16970. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16971. "--"
  16972. ("Documentation"
  16973. ["Show Version" org-version t]
  16974. ["Info Documentation" org-info t]
  16975. ["Browse Org News" org-browse-news t])
  16976. ("Customize"
  16977. ["Browse Org Group" org-customize t]
  16978. "--"
  16979. ["Expand This Menu" org-create-customize-menu
  16980. (fboundp 'customize-menu-create)])
  16981. ["Send bug report" org-submit-bug-report t]
  16982. "--"
  16983. ("Refresh/Reload"
  16984. ["Refresh setup current buffer" org-mode-restart t]
  16985. ["Reload Org (after update)" org-reload t]
  16986. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16987. (defun org-info (&optional node)
  16988. "Read documentation for Org in the info system.
  16989. With optional NODE, go directly to that node."
  16990. (interactive)
  16991. (info (format "(org)%s" (or node ""))))
  16992. (defun org-browse-news ()
  16993. "Browse the news for the latest major release."
  16994. (interactive)
  16995. (browse-url "https://orgmode.org/Changes.html"))
  16996. ;;;###autoload
  16997. (defun org-submit-bug-report ()
  16998. "Submit a bug report on Org via mail.
  16999. Don't hesitate to report any problems or inaccurate documentation.
  17000. If you don't have setup sending mail from (X)Emacs, please copy the
  17001. output buffer into your mail program, as it gives us important
  17002. information about your Org version and configuration."
  17003. (interactive)
  17004. (require 'reporter)
  17005. (defvar reporter-prompt-for-summary-p)
  17006. (org-load-modules-maybe)
  17007. (org-require-autoloaded-modules)
  17008. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17009. (reporter-submit-bug-report
  17010. "emacs-orgmode@gnu.org"
  17011. (org-version nil 'full)
  17012. (let (list)
  17013. (save-window-excursion
  17014. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17015. (delete-other-windows)
  17016. (erase-buffer)
  17017. (insert "You are about to submit a bug report to the Org mailing list.
  17018. We would like to add your full Org and Outline configuration to the
  17019. bug report. This greatly simplifies the work of the maintainer and
  17020. other experts on the mailing list.
  17021. HOWEVER, some variables you have customized may contain private
  17022. information. The names of customers, colleagues, or friends, might
  17023. appear in the form of file names, tags, todo states, or search strings.
  17024. If you answer yes to the prompt, you might want to check and remove
  17025. such private information before sending the email.")
  17026. (add-text-properties (point-min) (point-max) '(face org-warning))
  17027. (when (yes-or-no-p "Include your Org configuration ")
  17028. (mapatoms
  17029. (lambda (v)
  17030. (and (boundp v)
  17031. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17032. (or (and (symbol-value v)
  17033. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17034. (and
  17035. (get v 'custom-type) (get v 'standard-value)
  17036. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17037. (push v list)))))
  17038. (kill-buffer (get-buffer "*Warn about privacy*"))
  17039. list))
  17040. nil nil
  17041. "Remember to cover the basics, that is, what you expected to happen and
  17042. what in fact did happen. You don't know how to make a good report? See
  17043. https://orgmode.org/manual/Feedback.html#Feedback
  17044. Your bug report will be posted to the Org mailing list.
  17045. ------------------------------------------------------------------------")
  17046. (save-excursion
  17047. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17048. (replace-match "\\1Bug: \\3 [\\2]")))))
  17049. (defun org-install-agenda-files-menu ()
  17050. (let ((bl (buffer-list)))
  17051. (save-excursion
  17052. (while bl
  17053. (set-buffer (pop bl))
  17054. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17055. (when (derived-mode-p 'org-mode)
  17056. (easy-menu-change
  17057. '("Org") "File List for Agenda"
  17058. (append
  17059. (list
  17060. ["Edit File List" (org-edit-agenda-file-list) t]
  17061. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17062. ["Remove Current File from List" org-remove-file t]
  17063. ["Cycle through agenda files" org-cycle-agenda-files t]
  17064. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17065. "--")
  17066. (mapcar 'org-file-menu-entry
  17067. ;; Prevent initialization from failing.
  17068. (ignore-errors (org-agenda-files t)))))))))
  17069. ;;;; Documentation
  17070. (defun org-require-autoloaded-modules ()
  17071. (interactive)
  17072. (mapc #'require
  17073. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17074. org-table org-timer)))
  17075. ;;;###autoload
  17076. (defun org-reload (&optional uncompiled)
  17077. "Reload all Org Lisp files.
  17078. With prefix arg UNCOMPILED, load the uncompiled versions."
  17079. (interactive "P")
  17080. (require 'loadhist)
  17081. (let* ((org-dir (org-find-library-dir "org"))
  17082. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17083. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17084. (remove-re (format "\\`%s\\'"
  17085. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17086. (feats (delete-dups
  17087. (mapcar 'file-name-sans-extension
  17088. (mapcar 'file-name-nondirectory
  17089. (delq nil
  17090. (mapcar 'feature-file
  17091. features))))))
  17092. (lfeat (append
  17093. (sort
  17094. (setq feats
  17095. (delq nil (mapcar
  17096. (lambda (f)
  17097. (if (and (string-match feature-re f)
  17098. (not (string-match remove-re f)))
  17099. f nil))
  17100. feats)))
  17101. 'string-lessp)
  17102. (list "org-version" "org")))
  17103. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17104. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17105. load-uncore load-misses)
  17106. (setq load-misses
  17107. (delq 't
  17108. (mapcar (lambda (f)
  17109. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17110. (and (string= org-dir contrib-dir)
  17111. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17112. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17113. (push f load-uncore)
  17114. 't)
  17115. f))
  17116. lfeat)))
  17117. (when load-uncore
  17118. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17119. (if (> (length load-uncore) 1) "s were" " was")
  17120. (reverse load-uncore)))
  17121. (if load-misses
  17122. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17123. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17124. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17125. ;;;###autoload
  17126. (defun org-customize ()
  17127. "Call the customize function with org as argument."
  17128. (interactive)
  17129. (org-load-modules-maybe)
  17130. (org-require-autoloaded-modules)
  17131. (customize-browse 'org))
  17132. (defun org-create-customize-menu ()
  17133. "Create a full customization menu for Org mode, insert it into the menu."
  17134. (interactive)
  17135. (org-load-modules-maybe)
  17136. (org-require-autoloaded-modules)
  17137. (if (fboundp 'customize-menu-create)
  17138. (progn
  17139. (easy-menu-change
  17140. '("Org") "Customize"
  17141. `(["Browse Org group" org-customize t]
  17142. "--"
  17143. ,(customize-menu-create 'org)
  17144. ["Set" Custom-set t]
  17145. ["Save" Custom-save t]
  17146. ["Reset to Current" Custom-reset-current t]
  17147. ["Reset to Saved" Custom-reset-saved t]
  17148. ["Reset to Standard Settings" Custom-reset-standard t]))
  17149. (message "\"Org\"-menu now contains full customization menu"))
  17150. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17151. ;;;; Miscellaneous stuff
  17152. ;;; Generally useful functions
  17153. (defun org-in-clocktable-p ()
  17154. "Check if the cursor is in a clocktable."
  17155. (let ((pos (point)) start)
  17156. (save-excursion
  17157. (end-of-line 1)
  17158. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17159. (setq start (match-beginning 0))
  17160. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17161. (>= (match-end 0) pos)
  17162. start))))
  17163. (defun org-in-verbatim-emphasis ()
  17164. (save-match-data
  17165. (and (org-in-regexp org-verbatim-re 2)
  17166. (>= (point) (match-beginning 3))
  17167. (<= (point) (match-end 4)))))
  17168. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17169. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17170. (if (and marker (marker-buffer marker)
  17171. (buffer-live-p (marker-buffer marker)))
  17172. (progn
  17173. (pop-to-buffer-same-window (marker-buffer marker))
  17174. (when (or (> marker (point-max)) (< marker (point-min)))
  17175. (widen))
  17176. (goto-char marker)
  17177. (org-show-context 'org-goto))
  17178. (if bookmark
  17179. (bookmark-jump bookmark)
  17180. (error "Cannot find location"))))
  17181. (defun org-quote-csv-field (s)
  17182. "Quote field for inclusion in CSV material."
  17183. (if (string-match "[\",]" s)
  17184. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17185. s))
  17186. (defun org-force-self-insert (N)
  17187. "Needed to enforce self-insert under remapping."
  17188. (interactive "p")
  17189. (self-insert-command N))
  17190. (defun org-quote-vert (s)
  17191. "Replace \"|\" with \"\\vert\"."
  17192. (while (string-match "|" s)
  17193. (setq s (replace-match "\\vert" t t s)))
  17194. s)
  17195. (defun org-uuidgen-p (s)
  17196. "Is S an ID created by UUIDGEN?"
  17197. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17198. (defun org-in-src-block-p (&optional inside)
  17199. "Whether point is in a code source block.
  17200. When INSIDE is non-nil, don't consider we are within a source
  17201. block when point is at #+BEGIN_SRC or #+END_SRC."
  17202. (let ((case-fold-search t))
  17203. (or (and (eq (get-char-property (point) 'src-block) t))
  17204. (and (not inside)
  17205. (save-match-data
  17206. (save-excursion
  17207. (beginning-of-line)
  17208. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17209. (defun org-context ()
  17210. "Return a list of contexts of the current cursor position.
  17211. If several contexts apply, all are returned.
  17212. Each context entry is a list with a symbol naming the context, and
  17213. two positions indicating start and end of the context. Possible
  17214. contexts are:
  17215. :headline anywhere in a headline
  17216. :headline-stars on the leading stars in a headline
  17217. :todo-keyword on a TODO keyword (including DONE) in a headline
  17218. :tags on the TAGS in a headline
  17219. :priority on the priority cookie in a headline
  17220. :item on the first line of a plain list item
  17221. :item-bullet on the bullet/number of a plain list item
  17222. :checkbox on the checkbox in a plain list item
  17223. :table in an Org table
  17224. :table-special on a special filed in a table
  17225. :table-table in a table.el table
  17226. :clocktable in a clocktable
  17227. :src-block in a source block
  17228. :link on a hyperlink
  17229. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17230. :latex-fragment on a LaTeX fragment
  17231. :latex-preview on a LaTeX fragment with overlaid preview image
  17232. This function expects the position to be visible because it uses font-lock
  17233. faces as a help to recognize the following contexts: :table-special, :link,
  17234. and :keyword."
  17235. (let* ((f (get-text-property (point) 'face))
  17236. (faces (if (listp f) f (list f)))
  17237. (case-fold-search t)
  17238. (p (point)) clist o)
  17239. ;; First the large context
  17240. (cond
  17241. ((org-at-heading-p t)
  17242. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17243. (when (progn
  17244. (beginning-of-line 1)
  17245. (looking-at org-todo-line-tags-regexp))
  17246. (push (org-point-in-group p 1 :headline-stars) clist)
  17247. (push (org-point-in-group p 2 :todo-keyword) clist)
  17248. (push (org-point-in-group p 4 :tags) clist))
  17249. (goto-char p)
  17250. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17251. (when (looking-at "\\[#[A-Z0-9]\\]")
  17252. (push (org-point-in-group p 0 :priority) clist)))
  17253. ((org-at-item-p)
  17254. (push (org-point-in-group p 2 :item-bullet) clist)
  17255. (push (list :item (point-at-bol)
  17256. (save-excursion (org-end-of-item) (point)))
  17257. clist)
  17258. (and (org-at-item-checkbox-p)
  17259. (push (org-point-in-group p 0 :checkbox) clist)))
  17260. ((org-at-table-p)
  17261. (push (list :table (org-table-begin) (org-table-end)) clist)
  17262. (when (memq 'org-formula faces)
  17263. (push (list :table-special
  17264. (previous-single-property-change p 'face)
  17265. (next-single-property-change p 'face)) clist)))
  17266. ((org-at-table-p 'any)
  17267. (push (list :table-table) clist)))
  17268. (goto-char p)
  17269. (let ((case-fold-search t))
  17270. ;; New the "medium" contexts: clocktables, source blocks
  17271. (cond ((org-in-clocktable-p)
  17272. (push (list :clocktable
  17273. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17274. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17275. (match-beginning 1))
  17276. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17277. (match-end 0))) clist))
  17278. ((org-in-src-block-p)
  17279. (push (list :src-block
  17280. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17281. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17282. (match-beginning 1))
  17283. (and (search-forward "#+END_SRC" nil t)
  17284. (match-beginning 0))) clist))))
  17285. (goto-char p)
  17286. ;; Now the small context
  17287. (cond
  17288. ((org-at-timestamp-p)
  17289. (push (org-point-in-group p 0 :timestamp) clist))
  17290. ((memq 'org-link faces)
  17291. (push (list :link
  17292. (previous-single-property-change p 'face)
  17293. (next-single-property-change p 'face)) clist))
  17294. ((memq 'org-special-keyword faces)
  17295. (push (list :keyword
  17296. (previous-single-property-change p 'face)
  17297. (next-single-property-change p 'face)) clist))
  17298. ((setq o (cl-some
  17299. (lambda (o)
  17300. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17301. o))
  17302. (overlays-at (point))))
  17303. (push (list :latex-fragment
  17304. (overlay-start o) (overlay-end o)) clist)
  17305. (push (list :latex-preview
  17306. (overlay-start o) (overlay-end o)) clist))
  17307. ((org-inside-LaTeX-fragment-p)
  17308. ;; FIXME: positions wrong.
  17309. (push (list :latex-fragment (point) (point)) clist)))
  17310. (setq clist (nreverse (delq nil clist)))
  17311. clist))
  17312. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17313. "Non-nil when point is between matches of START-RE and END-RE.
  17314. Also return a non-nil value when point is on one of the matches.
  17315. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17316. buffer positions. Default values are the positions of headlines
  17317. surrounding the point.
  17318. The functions returns a cons cell whose car (resp. cdr) is the
  17319. position before START-RE (resp. after END-RE)."
  17320. (save-match-data
  17321. (let ((pos (point))
  17322. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17323. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17324. beg end)
  17325. (save-excursion
  17326. ;; Point is on a block when on START-RE or if START-RE can be
  17327. ;; found before it...
  17328. (and (or (org-in-regexp start-re)
  17329. (re-search-backward start-re limit-up t))
  17330. (setq beg (match-beginning 0))
  17331. ;; ... and END-RE after it...
  17332. (goto-char (match-end 0))
  17333. (re-search-forward end-re limit-down t)
  17334. (> (setq end (match-end 0)) pos)
  17335. ;; ... without another START-RE in-between.
  17336. (goto-char (match-beginning 0))
  17337. (not (re-search-backward start-re (1+ beg) t))
  17338. ;; Return value.
  17339. (cons beg end))))))
  17340. (defun org-in-block-p (names)
  17341. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17342. NAMES is a list of strings containing names of blocks.
  17343. Return first block name matched, or nil. Beware that in case of
  17344. nested blocks, the returned name may not belong to the closest
  17345. block from point."
  17346. (save-match-data
  17347. (catch 'exit
  17348. (let ((case-fold-search t)
  17349. (lim-up (save-excursion (outline-previous-heading)))
  17350. (lim-down (save-excursion (outline-next-heading))))
  17351. (dolist (name names)
  17352. (let ((n (regexp-quote name)))
  17353. (when (org-between-regexps-p
  17354. (concat "^[ \t]*#\\+begin_" n)
  17355. (concat "^[ \t]*#\\+end_" n)
  17356. lim-up lim-down)
  17357. (throw 'exit n)))))
  17358. nil)))
  17359. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17360. "Call `multi-occur' with buffers for all agenda files."
  17361. (interactive "sOrg-files matching: ")
  17362. (let* ((files (org-agenda-files))
  17363. (tnames (mapcar #'file-truename files))
  17364. (extra org-agenda-text-search-extra-files))
  17365. (when (eq (car extra) 'agenda-archives)
  17366. (setq extra (cdr extra))
  17367. (setq files (org-add-archive-files files)))
  17368. (dolist (f extra)
  17369. (unless (member (file-truename f) tnames)
  17370. (unless (member f files) (setq files (append files (list f))))
  17371. (setq tnames (append tnames (list (file-truename f))))))
  17372. (multi-occur
  17373. (mapcar (lambda (x)
  17374. (with-current-buffer
  17375. ;; FIXME: Why not just (find-file-noselect x)?
  17376. ;; Is it to avoid the "revert buffer" prompt?
  17377. (or (get-file-buffer x) (find-file-noselect x))
  17378. (widen)
  17379. (current-buffer)))
  17380. files)
  17381. regexp)))
  17382. (add-hook 'occur-mode-find-occurrence-hook
  17383. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17384. (defun org-occur-link-in-agenda-files ()
  17385. "Create a link and search for it in the agendas.
  17386. The link is not stored in `org-stored-links', it is just created
  17387. for the search purpose."
  17388. (interactive)
  17389. (let ((link (condition-case nil
  17390. (org-store-link nil)
  17391. (error "Unable to create a link to here"))))
  17392. (org-occur-in-agenda-files (regexp-quote link))))
  17393. (defun org-back-over-empty-lines ()
  17394. "Move backwards over whitespace, to the beginning of the first empty line.
  17395. Returns the number of empty lines passed."
  17396. (let ((pos (point)))
  17397. (if (cdr (assq 'heading org-blank-before-new-entry))
  17398. (skip-chars-backward " \t\n\r")
  17399. (unless (eobp)
  17400. (forward-line -1)))
  17401. (beginning-of-line 2)
  17402. (goto-char (min (point) pos))
  17403. (count-lines (point) pos)))
  17404. ;;; TODO: Only called once, from ox-odt which should probably use
  17405. ;;; org-export-inline-image-p or something.
  17406. (defun org-file-image-p (file)
  17407. "Return non-nil if FILE is an image."
  17408. (save-match-data
  17409. (string-match (image-file-name-regexp) file)))
  17410. (defun org-get-cursor-date (&optional with-time)
  17411. "Return the date at cursor in as a time.
  17412. This works in the calendar and in the agenda, anywhere else it just
  17413. returns the current time.
  17414. If WITH-TIME is non-nil, returns the time of the event at point (in
  17415. the agenda) or the current time of the day; otherwise returns the
  17416. earliest time on the cursor date that Org treats as that date
  17417. (bearing in mind `org-extend-today-until')."
  17418. (let (date day defd tp hod mod)
  17419. (when with-time
  17420. (setq tp (get-text-property (point) 'time))
  17421. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17422. (setq hod (string-to-number (match-string 1 tp))
  17423. mod (string-to-number (match-string 2 tp))))
  17424. (or tp (let ((now (decode-time)))
  17425. (setq hod (nth 2 now)
  17426. mod (nth 1 now)))))
  17427. (cond
  17428. ((eq major-mode 'calendar-mode)
  17429. (setq date (calendar-cursor-to-date)
  17430. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17431. (nth 1 date) (nth 0 date) (nth 2 date))))
  17432. ((eq major-mode 'org-agenda-mode)
  17433. (setq day (get-text-property (point) 'day))
  17434. (when day
  17435. (setq date (calendar-gregorian-from-absolute day)
  17436. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17437. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17438. (or defd (current-time))))
  17439. (defun org-mark-subtree (&optional up)
  17440. "Mark the current subtree.
  17441. This puts point at the start of the current subtree, and mark at
  17442. the end. If a numeric prefix UP is given, move up into the
  17443. hierarchy of headlines by UP levels before marking the subtree."
  17444. (interactive "P")
  17445. (org-with-limited-levels
  17446. (cond ((org-at-heading-p) (beginning-of-line))
  17447. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17448. (t (outline-previous-visible-heading 1))))
  17449. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17450. (if (called-interactively-p 'any)
  17451. (call-interactively 'org-mark-element)
  17452. (org-mark-element)))
  17453. ;;; Indentation
  17454. (defvar org-element-greater-elements)
  17455. (defun org--get-expected-indentation (element contentsp)
  17456. "Expected indentation column for current line, according to ELEMENT.
  17457. ELEMENT is an element containing point. CONTENTSP is non-nil
  17458. when indentation is to be computed according to contents of
  17459. ELEMENT."
  17460. (let ((type (org-element-type element))
  17461. (start (org-element-property :begin element))
  17462. (post-affiliated (org-element-property :post-affiliated element)))
  17463. (org-with-wide-buffer
  17464. (cond
  17465. (contentsp
  17466. (cl-case type
  17467. ((diary-sexp footnote-definition) 0)
  17468. ((headline inlinetask nil)
  17469. (if (not org-adapt-indentation) 0
  17470. (let ((level (org-current-level)))
  17471. (if level (1+ level) 0))))
  17472. ((item plain-list) (org-list-item-body-column post-affiliated))
  17473. (t
  17474. (goto-char start)
  17475. (current-indentation))))
  17476. ((memq type '(headline inlinetask nil))
  17477. (if (org-match-line "[ \t]*$")
  17478. (org--get-expected-indentation element t)
  17479. 0))
  17480. ((memq type '(diary-sexp footnote-definition)) 0)
  17481. ;; First paragraph of a footnote definition or an item.
  17482. ;; Indent like parent.
  17483. ((< (line-beginning-position) start)
  17484. (org--get-expected-indentation
  17485. (org-element-property :parent element) t))
  17486. ;; At first line: indent according to previous sibling, if any,
  17487. ;; ignoring footnote definitions and inline tasks, or parent's
  17488. ;; contents.
  17489. ((= (line-beginning-position) start)
  17490. (catch 'exit
  17491. (while t
  17492. (if (= (point-min) start) (throw 'exit 0)
  17493. (goto-char (1- start))
  17494. (let* ((previous (org-element-at-point))
  17495. (parent previous))
  17496. (while (and parent (<= (org-element-property :end parent) start))
  17497. (setq previous parent
  17498. parent (org-element-property :parent parent)))
  17499. (cond
  17500. ((not previous) (throw 'exit 0))
  17501. ((> (org-element-property :end previous) start)
  17502. (throw 'exit (org--get-expected-indentation previous t)))
  17503. ((memq (org-element-type previous)
  17504. '(footnote-definition inlinetask))
  17505. (setq start (org-element-property :begin previous)))
  17506. (t (goto-char (org-element-property :begin previous))
  17507. (throw 'exit
  17508. (if (bolp) (current-indentation)
  17509. ;; At first paragraph in an item or
  17510. ;; a footnote definition.
  17511. (org--get-expected-indentation
  17512. (org-element-property :parent previous) t))))))))))
  17513. ;; Otherwise, move to the first non-blank line above.
  17514. (t
  17515. (beginning-of-line)
  17516. (let ((pos (point)))
  17517. (skip-chars-backward " \r\t\n")
  17518. (cond
  17519. ;; Two blank lines end a footnote definition or a plain
  17520. ;; list. When we indent an empty line after them, the
  17521. ;; containing list or footnote definition is over, so it
  17522. ;; qualifies as a previous sibling. Therefore, we indent
  17523. ;; like its first line.
  17524. ((and (memq type '(footnote-definition plain-list))
  17525. (> (count-lines (point) pos) 2))
  17526. (goto-char start)
  17527. (current-indentation))
  17528. ;; Line above is the first one of a paragraph at the
  17529. ;; beginning of an item or a footnote definition. Indent
  17530. ;; like parent.
  17531. ((< (line-beginning-position) start)
  17532. (org--get-expected-indentation
  17533. (org-element-property :parent element) t))
  17534. ;; Line above is the beginning of an element, i.e., point
  17535. ;; was originally on the blank lines between element's start
  17536. ;; and contents.
  17537. ((= (line-beginning-position) post-affiliated)
  17538. (org--get-expected-indentation element t))
  17539. ;; POS is after contents in a greater element. Indent like
  17540. ;; the beginning of the element.
  17541. ((and (memq type org-element-greater-elements)
  17542. (let ((cend (org-element-property :contents-end element)))
  17543. (and cend (<= cend pos))))
  17544. ;; As a special case, if point is at the end of a footnote
  17545. ;; definition or an item, indent like the very last element
  17546. ;; within. If that last element is an item, indent like
  17547. ;; its contents.
  17548. (if (memq type '(footnote-definition item plain-list))
  17549. (let ((last (org-element-at-point)))
  17550. (goto-char pos)
  17551. (org--get-expected-indentation
  17552. last (eq (org-element-type last) 'item)))
  17553. (goto-char start)
  17554. (current-indentation)))
  17555. ;; In any other case, indent like the current line.
  17556. (t (current-indentation)))))))))
  17557. (defun org--align-node-property ()
  17558. "Align node property at point.
  17559. Alignment is done according to `org-property-format', which see."
  17560. (when (save-excursion
  17561. (beginning-of-line)
  17562. (looking-at org-property-re))
  17563. (replace-match
  17564. (concat (match-string 4)
  17565. (org-trim
  17566. (format org-property-format (match-string 1) (match-string 3))))
  17567. t t)))
  17568. (defun org-indent-line ()
  17569. "Indent line depending on context.
  17570. Indentation is done according to the following rules:
  17571. - Footnote definitions, diary sexps, headlines and inline tasks
  17572. have to start at column 0.
  17573. - On the very first line of an element, consider, in order, the
  17574. next rules until one matches:
  17575. 1. If there's a sibling element before, ignoring footnote
  17576. definitions and inline tasks, indent like its first line.
  17577. 2. If element has a parent, indent like its contents. More
  17578. precisely, if parent is an item, indent after the bullet.
  17579. Else, indent like parent's first line.
  17580. 3. Otherwise, indent relatively to current level, if
  17581. `org-adapt-indentation' is non-nil, or to left margin.
  17582. - On a blank line at the end of an element, indent according to
  17583. the type of the element. More precisely
  17584. 1. If element is a plain list, an item, or a footnote
  17585. definition, indent like the very last element within.
  17586. 2. If element is a paragraph, indent like its last non blank
  17587. line.
  17588. 3. Otherwise, indent like its very first line.
  17589. - In the code part of a source block, use language major mode
  17590. to indent current line if `org-src-tab-acts-natively' is
  17591. non-nil. If it is nil, do nothing.
  17592. - Otherwise, indent like the first non-blank line above.
  17593. The function doesn't indent an item as it could break the whole
  17594. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17595. `\\[org-shiftmetaright]'.
  17596. Also align node properties according to `org-property-format'."
  17597. (interactive)
  17598. (cond
  17599. ((org-at-heading-p) 'noindent)
  17600. (t
  17601. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17602. (type (org-element-type element)))
  17603. (cond ((and (memq type '(plain-list item))
  17604. (= (line-beginning-position)
  17605. (org-element-property :post-affiliated element)))
  17606. 'noindent)
  17607. ((and (eq type 'latex-environment)
  17608. (>= (point) (org-element-property :post-affiliated element))
  17609. (< (point) (org-with-wide-buffer
  17610. (goto-char (org-element-property :end element))
  17611. (skip-chars-backward " \r\t\n")
  17612. (line-beginning-position 2))))
  17613. 'noindent)
  17614. ((and (eq type 'src-block)
  17615. org-src-tab-acts-natively
  17616. (> (line-beginning-position)
  17617. (org-element-property :post-affiliated element))
  17618. (< (line-beginning-position)
  17619. (org-with-wide-buffer
  17620. (goto-char (org-element-property :end element))
  17621. (skip-chars-backward " \r\t\n")
  17622. (line-beginning-position))))
  17623. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17624. (t
  17625. (let ((column (org--get-expected-indentation element nil)))
  17626. ;; Preserve current column.
  17627. (if (<= (current-column) (current-indentation))
  17628. (indent-line-to column)
  17629. (save-excursion (indent-line-to column))))
  17630. ;; Align node property. Also preserve current column.
  17631. (when (eq type 'node-property)
  17632. (let ((column (current-column)))
  17633. (org--align-node-property)
  17634. (org-move-to-column column)))))))))
  17635. (defun org-indent-region (start end)
  17636. "Indent each non-blank line in the region.
  17637. Called from a program, START and END specify the region to
  17638. indent. The function will not indent contents of example blocks,
  17639. verse blocks and export blocks as leading white spaces are
  17640. assumed to be significant there."
  17641. (interactive "r")
  17642. (save-excursion
  17643. (goto-char start)
  17644. (skip-chars-forward " \r\t\n")
  17645. (unless (eobp) (beginning-of-line))
  17646. (let ((indent-to
  17647. (lambda (ind pos)
  17648. ;; Set IND as indentation for all lines between point and
  17649. ;; POS. Blank lines are ignored. Leave point after POS
  17650. ;; once done.
  17651. (let ((limit (copy-marker pos)))
  17652. (while (< (point) limit)
  17653. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17654. (forward-line))
  17655. (set-marker limit nil))))
  17656. (end (copy-marker end)))
  17657. (while (< (point) end)
  17658. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17659. (let* ((element (org-element-at-point))
  17660. (type (org-element-type element))
  17661. (element-end (copy-marker (org-element-property :end element)))
  17662. (ind (org--get-expected-indentation element nil)))
  17663. (cond
  17664. ;; Element indented as a single block. Example blocks
  17665. ;; preserving indentation are a special case since the
  17666. ;; "contents" must not be indented whereas the block
  17667. ;; boundaries can.
  17668. ((or (memq type '(export-block latex-environment))
  17669. (and (eq type 'example-block)
  17670. (not
  17671. (or org-src-preserve-indentation
  17672. (org-element-property :preserve-indent element)))))
  17673. (let ((offset (- ind (current-indentation))))
  17674. (unless (zerop offset)
  17675. (indent-rigidly (org-element-property :begin element)
  17676. (org-element-property :end element)
  17677. offset)))
  17678. (goto-char element-end))
  17679. ;; Elements indented line wise. Be sure to exclude
  17680. ;; example blocks (preserving indentation) and source
  17681. ;; blocks from this category as they are treated
  17682. ;; specially later.
  17683. ((or (memq type '(paragraph table table-row))
  17684. (not (or (org-element-property :contents-begin element)
  17685. (memq type '(example-block src-block)))))
  17686. (when (eq type 'node-property)
  17687. (org--align-node-property)
  17688. (beginning-of-line))
  17689. (funcall indent-to ind (min element-end end)))
  17690. ;; Elements consisting of three parts: before the
  17691. ;; contents, the contents, and after the contents. The
  17692. ;; contents are treated specially, according to the
  17693. ;; element type, or not indented at all. Other parts are
  17694. ;; indented as a single block.
  17695. (t
  17696. (let* ((post (copy-marker
  17697. (org-element-property :post-affiliated element)))
  17698. (cbeg
  17699. (copy-marker
  17700. (cond
  17701. ((not (org-element-property :contents-begin element))
  17702. ;; Fake contents for source blocks.
  17703. (org-with-wide-buffer
  17704. (goto-char post)
  17705. (line-beginning-position 2)))
  17706. ((memq type '(footnote-definition item plain-list))
  17707. ;; Contents in these elements could start on
  17708. ;; the same line as the beginning of the
  17709. ;; element. Make sure we start indenting
  17710. ;; from the second line.
  17711. (org-with-wide-buffer
  17712. (goto-char post)
  17713. (end-of-line)
  17714. (skip-chars-forward " \r\t\n")
  17715. (if (eobp) (point) (line-beginning-position))))
  17716. (t (org-element-property :contents-begin element)))))
  17717. (cend (copy-marker
  17718. (or (org-element-property :contents-end element)
  17719. ;; Fake contents for source blocks.
  17720. (org-with-wide-buffer
  17721. (goto-char element-end)
  17722. (skip-chars-backward " \r\t\n")
  17723. (line-beginning-position)))
  17724. t)))
  17725. ;; Do not change items indentation individually as it
  17726. ;; might break the list as a whole. On the other
  17727. ;; hand, when at a plain list, indent it as a whole.
  17728. (cond ((eq type 'plain-list)
  17729. (let ((offset (- ind (current-indentation))))
  17730. (unless (zerop offset)
  17731. (indent-rigidly (org-element-property :begin element)
  17732. (org-element-property :end element)
  17733. offset))
  17734. (goto-char cbeg)))
  17735. ((eq type 'item) (goto-char cbeg))
  17736. (t (funcall indent-to ind (min cbeg end))))
  17737. (when (< (point) end)
  17738. (cl-case type
  17739. ((example-block verse-block))
  17740. (src-block
  17741. ;; In a source block, indent source code
  17742. ;; according to language major mode, but only if
  17743. ;; `org-src-tab-acts-natively' is non-nil.
  17744. (when (and (< (point) end) org-src-tab-acts-natively)
  17745. (ignore-errors
  17746. (org-babel-do-in-edit-buffer
  17747. (indent-region (point-min) (point-max))))))
  17748. (t (org-indent-region (point) (min cend end))))
  17749. (goto-char (min cend end))
  17750. (when (< (point) end)
  17751. (funcall indent-to ind (min element-end end))))
  17752. (set-marker post nil)
  17753. (set-marker cbeg nil)
  17754. (set-marker cend nil))))
  17755. (set-marker element-end nil))))
  17756. (set-marker end nil))))
  17757. (defun org-indent-drawer ()
  17758. "Indent the drawer at point."
  17759. (interactive)
  17760. (unless (save-excursion
  17761. (beginning-of-line)
  17762. (looking-at-p org-drawer-regexp))
  17763. (user-error "Not at a drawer"))
  17764. (let ((element (org-element-at-point)))
  17765. (unless (memq (org-element-type element) '(drawer property-drawer))
  17766. (user-error "Not at a drawer"))
  17767. (org-with-wide-buffer
  17768. (org-indent-region (org-element-property :begin element)
  17769. (org-element-property :end element))))
  17770. (message "Drawer at point indented"))
  17771. (defun org-indent-block ()
  17772. "Indent the block at point."
  17773. (interactive)
  17774. (unless (save-excursion
  17775. (beginning-of-line)
  17776. (let ((case-fold-search t))
  17777. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17778. (user-error "Not at a block"))
  17779. (let ((element (org-element-at-point)))
  17780. (unless (memq (org-element-type element)
  17781. '(comment-block center-block dynamic-block example-block
  17782. export-block quote-block special-block
  17783. src-block verse-block))
  17784. (user-error "Not at a block"))
  17785. (org-with-wide-buffer
  17786. (org-indent-region (org-element-property :begin element)
  17787. (org-element-property :end element))))
  17788. (message "Block at point indented"))
  17789. ;;; Filling
  17790. ;; We use our own fill-paragraph and auto-fill functions.
  17791. ;; `org-fill-paragraph' relies on adaptive filling and context
  17792. ;; checking. Appropriate `fill-prefix' is computed with
  17793. ;; `org-adaptive-fill-function'.
  17794. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17795. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17796. ;; `org-adaptive-fill-function' value. Internally,
  17797. ;; `org-comment-line-break-function' breaks the line.
  17798. ;; `org-setup-filling' installs filling and auto-filling related
  17799. ;; variables during `org-mode' initialization.
  17800. (defun org-setup-filling ()
  17801. (require 'org-element)
  17802. ;; Prevent auto-fill from inserting unwanted new items.
  17803. (when (boundp 'fill-nobreak-predicate)
  17804. (setq-local
  17805. fill-nobreak-predicate
  17806. (org-uniquify
  17807. (append fill-nobreak-predicate
  17808. '(org-fill-line-break-nobreak-p
  17809. org-fill-n-macro-as-item-nobreak-p
  17810. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17811. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17812. (setq-local paragraph-start paragraph-ending)
  17813. (setq-local paragraph-separate paragraph-ending))
  17814. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17815. (setq-local auto-fill-inhibit-regexp nil)
  17816. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17817. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17818. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17819. (defun org-fill-line-break-nobreak-p ()
  17820. "Non-nil when a new line at point would create an Org line break."
  17821. (save-excursion
  17822. (skip-chars-backward " \t")
  17823. (skip-chars-backward "\\\\")
  17824. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17825. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17826. "Non-nil when a new line at point would split a timestamp."
  17827. (and (org-at-timestamp-p 'lax)
  17828. (not (looking-at org-ts-regexp-both))))
  17829. (defun org-fill-n-macro-as-item-nobreak-p ()
  17830. "Non-nil when a new line at point would create a new list."
  17831. ;; During export, a "n" macro followed by a dot or a closing
  17832. ;; parenthesis can end up being parsed as a new list item.
  17833. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17834. (defun org-adaptive-fill-function ()
  17835. "Compute a fill prefix for the current line.
  17836. Return fill prefix, as a string, or nil if current line isn't
  17837. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17838. matches in paragraphs or comments, use it."
  17839. (org-with-wide-buffer
  17840. (unless (org-at-heading-p)
  17841. (let* ((p (line-beginning-position))
  17842. (element (save-excursion
  17843. (beginning-of-line)
  17844. (org-element-at-point)))
  17845. (type (org-element-type element))
  17846. (post-affiliated (org-element-property :post-affiliated element)))
  17847. (unless (< p post-affiliated)
  17848. (cl-case type
  17849. (comment
  17850. (save-excursion
  17851. (beginning-of-line)
  17852. (looking-at "[ \t]*")
  17853. (concat (match-string 0) "# ")))
  17854. (footnote-definition "")
  17855. ((item plain-list)
  17856. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17857. (paragraph
  17858. ;; Fill prefix is usually the same as the current line,
  17859. ;; unless the paragraph is at the beginning of an item.
  17860. (let ((parent (org-element-property :parent element)))
  17861. (save-excursion
  17862. (beginning-of-line)
  17863. (cond ((eq (org-element-type parent) 'item)
  17864. (make-string (org-list-item-body-column
  17865. (org-element-property :begin parent))
  17866. ?\s))
  17867. ((and adaptive-fill-regexp
  17868. ;; Locally disable
  17869. ;; `adaptive-fill-function' to let
  17870. ;; `fill-context-prefix' handle
  17871. ;; `adaptive-fill-regexp' variable.
  17872. (let (adaptive-fill-function)
  17873. (fill-context-prefix
  17874. post-affiliated
  17875. (org-element-property :end element)))))
  17876. ((looking-at "[ \t]+") (match-string 0))
  17877. (t "")))))
  17878. (comment-block
  17879. ;; Only fill contents if P is within block boundaries.
  17880. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17881. (forward-line)
  17882. (point)))
  17883. (cend (save-excursion
  17884. (goto-char (org-element-property :end element))
  17885. (skip-chars-backward " \r\t\n")
  17886. (line-beginning-position))))
  17887. (when (and (>= p cbeg) (< p cend))
  17888. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17889. (match-string 0)
  17890. ""))))))))))
  17891. (defun org-fill-element (&optional justify)
  17892. "Fill element at point, when applicable.
  17893. This function only applies to comment blocks, comments, example
  17894. blocks and paragraphs. Also, as a special case, re-align table
  17895. when point is at one.
  17896. If JUSTIFY is non-nil (interactively, with prefix argument),
  17897. justify as well. If `sentence-end-double-space' is non-nil, then
  17898. period followed by one space does not end a sentence, so don't
  17899. break a line there. The variable `fill-column' controls the
  17900. width for filling.
  17901. For convenience, when point is at a plain list, an item or
  17902. a footnote definition, try to fill the first paragraph within."
  17903. (with-syntax-table org-mode-transpose-word-syntax-table
  17904. ;; Move to end of line in order to get the first paragraph within
  17905. ;; a plain list or a footnote definition.
  17906. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17907. ;; First check if point is in a blank line at the beginning of
  17908. ;; the buffer. In that case, ignore filling.
  17909. (cl-case (org-element-type element)
  17910. ;; Use major mode filling function is source blocks.
  17911. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17912. ;; Align Org tables, leave table.el tables as-is.
  17913. (table-row (org-table-align) t)
  17914. (table
  17915. (when (eq (org-element-property :type element) 'org)
  17916. (save-excursion
  17917. (goto-char (org-element-property :post-affiliated element))
  17918. (org-table-align)))
  17919. t)
  17920. (paragraph
  17921. ;; Paragraphs may contain `line-break' type objects.
  17922. (let ((beg (max (point-min)
  17923. (org-element-property :contents-begin element)))
  17924. (end (min (point-max)
  17925. (org-element-property :contents-end element))))
  17926. ;; Do nothing if point is at an affiliated keyword.
  17927. (if (< (line-end-position) beg) t
  17928. ;; Fill paragraph, taking line breaks into account.
  17929. (save-excursion
  17930. (goto-char beg)
  17931. (let ((cuts (list beg)))
  17932. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17933. (when (eq 'line-break
  17934. (org-element-type
  17935. (save-excursion (backward-char)
  17936. (org-element-context))))
  17937. (push (point) cuts)))
  17938. (dolist (c (delq end cuts))
  17939. (fill-region-as-paragraph c end justify)
  17940. (setq end c))))
  17941. t)))
  17942. ;; Contents of `comment-block' type elements should be
  17943. ;; filled as plain text, but only if point is within block
  17944. ;; markers.
  17945. (comment-block
  17946. (let* ((case-fold-search t)
  17947. (beg (save-excursion
  17948. (goto-char (org-element-property :begin element))
  17949. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17950. (forward-line)
  17951. (point)))
  17952. (end (save-excursion
  17953. (goto-char (org-element-property :end element))
  17954. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17955. (line-beginning-position))))
  17956. (if (or (< (point) beg) (> (point) end)) t
  17957. (fill-region-as-paragraph
  17958. (save-excursion (end-of-line)
  17959. (re-search-backward "^[ \t]*$" beg 'move)
  17960. (line-beginning-position))
  17961. (save-excursion (beginning-of-line)
  17962. (re-search-forward "^[ \t]*$" end 'move)
  17963. (line-beginning-position))
  17964. justify))))
  17965. ;; Fill comments.
  17966. (comment
  17967. (let ((begin (org-element-property :post-affiliated element))
  17968. (end (org-element-property :end element)))
  17969. (when (and (>= (point) begin) (<= (point) end))
  17970. (let ((begin (save-excursion
  17971. (end-of-line)
  17972. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17973. (progn (forward-line) (point))
  17974. begin)))
  17975. (end (save-excursion
  17976. (end-of-line)
  17977. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17978. (1- (line-beginning-position))
  17979. (skip-chars-backward " \r\t\n")
  17980. (line-end-position)))))
  17981. ;; Do not fill comments when at a blank line.
  17982. (when (> end begin)
  17983. (let ((fill-prefix
  17984. (save-excursion
  17985. (beginning-of-line)
  17986. (looking-at "[ \t]*#")
  17987. (let ((comment-prefix (match-string 0)))
  17988. (goto-char (match-end 0))
  17989. (if (looking-at adaptive-fill-regexp)
  17990. (concat comment-prefix (match-string 0))
  17991. (concat comment-prefix " "))))))
  17992. (save-excursion
  17993. (fill-region-as-paragraph begin end justify))))))
  17994. t))
  17995. ;; Ignore every other element.
  17996. (otherwise t)))))
  17997. (defun org-fill-paragraph (&optional justify region)
  17998. "Fill element at point, when applicable.
  17999. This function only applies to comment blocks, comments, example
  18000. blocks and paragraphs. Also, as a special case, re-align table
  18001. when point is at one.
  18002. For convenience, when point is at a plain list, an item or
  18003. a footnote definition, try to fill the first paragraph within.
  18004. If JUSTIFY is non-nil (interactively, with prefix argument),
  18005. justify as well. If `sentence-end-double-space' is non-nil, then
  18006. period followed by one space does not end a sentence, so don't
  18007. break a line there. The variable `fill-column' controls the
  18008. width for filling.
  18009. The REGION argument is non-nil if called interactively; in that
  18010. case, if Transient Mark mode is enabled and the mark is active,
  18011. fill each of the elements in the active region, instead of just
  18012. filling the current element."
  18013. (interactive (progn
  18014. (barf-if-buffer-read-only)
  18015. (list (when current-prefix-arg 'full) t)))
  18016. (let ((hash (and (not (buffer-modified-p))
  18017. (org-buffer-hash))))
  18018. (cond
  18019. ((and region transient-mark-mode mark-active
  18020. (not (eq (region-beginning) (region-end))))
  18021. (let ((origin (point-marker))
  18022. (start (region-beginning)))
  18023. (unwind-protect
  18024. (progn
  18025. (goto-char (region-end))
  18026. (while (> (point) start)
  18027. (org-backward-paragraph)
  18028. (org-fill-element justify)))
  18029. (goto-char origin)
  18030. (set-marker origin nil))))
  18031. (t (org-fill-element justify)))
  18032. ;; If we didn't change anything in the buffer (and the buffer was
  18033. ;; previously unmodified), then flip the modification status back
  18034. ;; to "unchanged".
  18035. (when (and hash (equal hash (org-buffer-hash)))
  18036. (set-buffer-modified-p nil))))
  18037. (defun org-auto-fill-function ()
  18038. "Auto-fill function."
  18039. ;; Check if auto-filling is meaningful.
  18040. (let ((fc (current-fill-column)))
  18041. (when (and fc (> (current-column) fc))
  18042. (let* ((fill-prefix (org-adaptive-fill-function))
  18043. ;; Enforce empty fill prefix, if required. Otherwise, it
  18044. ;; will be computed again.
  18045. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18046. (when fill-prefix (do-auto-fill))))))
  18047. (defun org-comment-line-break-function (&optional soft)
  18048. "Break line at point and indent, continuing comment if within one.
  18049. The inserted newline is marked hard if variable
  18050. `use-hard-newlines' is true, unless optional argument SOFT is
  18051. non-nil."
  18052. (if soft (insert-and-inherit ?\n) (newline 1))
  18053. (save-excursion (forward-char -1) (delete-horizontal-space))
  18054. (delete-horizontal-space)
  18055. (indent-to-left-margin)
  18056. (insert-before-markers-and-inherit fill-prefix))
  18057. ;;; Fixed Width Areas
  18058. (defun org-toggle-fixed-width ()
  18059. "Toggle fixed-width markup.
  18060. Add or remove fixed-width markup on current line, whenever it
  18061. makes sense. Return an error otherwise.
  18062. If a region is active and if it contains only fixed-width areas
  18063. or blank lines, remove all fixed-width markup in it. If the
  18064. region contains anything else, convert all non-fixed-width lines
  18065. to fixed-width ones.
  18066. Blank lines at the end of the region are ignored unless the
  18067. region only contains such lines."
  18068. (interactive)
  18069. (if (not (org-region-active-p))
  18070. ;; No region:
  18071. ;;
  18072. ;; Remove fixed width marker only in a fixed-with element.
  18073. ;;
  18074. ;; Add fixed width maker in paragraphs, in blank lines after
  18075. ;; elements or at the beginning of a headline or an inlinetask,
  18076. ;; and before any one-line elements (e.g., a clock).
  18077. (progn
  18078. (beginning-of-line)
  18079. (let* ((element (org-element-at-point))
  18080. (type (org-element-type element)))
  18081. (cond
  18082. ((and (eq type 'fixed-width)
  18083. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18084. (replace-match
  18085. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18086. ((and (memq type '(babel-call clock comment diary-sexp headline
  18087. horizontal-rule keyword paragraph
  18088. planning))
  18089. (<= (org-element-property :post-affiliated element) (point)))
  18090. (skip-chars-forward " \t")
  18091. (insert ": "))
  18092. ((and (looking-at-p "[ \t]*$")
  18093. (or (eq type 'inlinetask)
  18094. (save-excursion
  18095. (skip-chars-forward " \r\t\n")
  18096. (<= (org-element-property :end element) (point)))))
  18097. (delete-region (point) (line-end-position))
  18098. (org-indent-line)
  18099. (insert ": "))
  18100. (t (user-error "Cannot insert a fixed-width line here")))))
  18101. ;; Region active.
  18102. (let* ((begin (save-excursion
  18103. (goto-char (region-beginning))
  18104. (line-beginning-position)))
  18105. (end (copy-marker
  18106. (save-excursion
  18107. (goto-char (region-end))
  18108. (unless (eolp) (beginning-of-line))
  18109. (if (save-excursion (re-search-backward "\\S-" begin t))
  18110. (progn (skip-chars-backward " \r\t\n") (point))
  18111. (point)))))
  18112. (all-fixed-width-p
  18113. (catch 'not-all-p
  18114. (save-excursion
  18115. (goto-char begin)
  18116. (skip-chars-forward " \r\t\n")
  18117. (when (eobp) (throw 'not-all-p nil))
  18118. (while (< (point) end)
  18119. (let ((element (org-element-at-point)))
  18120. (if (eq (org-element-type element) 'fixed-width)
  18121. (goto-char (org-element-property :end element))
  18122. (throw 'not-all-p nil))))
  18123. t))))
  18124. (if all-fixed-width-p
  18125. (save-excursion
  18126. (goto-char begin)
  18127. (while (< (point) end)
  18128. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18129. (replace-match
  18130. "" nil nil nil
  18131. (if (= (line-end-position) (match-end 0)) 0 1)))
  18132. (forward-line)))
  18133. (let ((min-ind (point-max)))
  18134. ;; Find minimum indentation across all lines.
  18135. (save-excursion
  18136. (goto-char begin)
  18137. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18138. (setq min-ind 0)
  18139. (catch 'zerop
  18140. (while (< (point) end)
  18141. (unless (looking-at-p "[ \t]*$")
  18142. (let ((ind (current-indentation)))
  18143. (setq min-ind (min min-ind ind))
  18144. (when (zerop ind) (throw 'zerop t))))
  18145. (forward-line)))))
  18146. ;; Loop over all lines and add fixed-width markup everywhere
  18147. ;; but in fixed-width lines.
  18148. (save-excursion
  18149. (goto-char begin)
  18150. (while (< (point) end)
  18151. (cond
  18152. ((org-at-heading-p)
  18153. (insert ": ")
  18154. (forward-line)
  18155. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18156. (insert ":")
  18157. (forward-line)))
  18158. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18159. (let* ((element (org-element-at-point))
  18160. (element-end (org-element-property :end element)))
  18161. (if (eq (org-element-type element) 'fixed-width)
  18162. (progn (goto-char element-end)
  18163. (skip-chars-backward " \r\t\n")
  18164. (forward-line))
  18165. (let ((limit (min end element-end)))
  18166. (while (< (point) limit)
  18167. (org-move-to-column min-ind t)
  18168. (insert ": ")
  18169. (forward-line))))))
  18170. (t
  18171. (org-move-to-column min-ind t)
  18172. (insert ": ")
  18173. (forward-line)))))))
  18174. (set-marker end nil))))
  18175. ;;; Blocks
  18176. (defun org-block-map (function &optional start end)
  18177. "Call FUNCTION at the head of all source blocks in the current buffer.
  18178. Optional arguments START and END can be used to limit the range."
  18179. (let ((start (or start (point-min)))
  18180. (end (or end (point-max))))
  18181. (save-excursion
  18182. (goto-char start)
  18183. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18184. (save-excursion
  18185. (save-match-data
  18186. (goto-char (match-beginning 0))
  18187. (funcall function)))))))
  18188. (defun org-next-block (arg &optional backward block-regexp)
  18189. "Jump to the next block.
  18190. With a prefix argument ARG, jump forward ARG many blocks.
  18191. When BACKWARD is non-nil, jump to the previous block.
  18192. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18193. Match data is set according to this regexp when the function
  18194. returns.
  18195. Return point at beginning of the opening line of found block.
  18196. Throw an error if no block is found."
  18197. (interactive "p")
  18198. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18199. (case-fold-search t)
  18200. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18201. (count (or arg 1))
  18202. (origin (point))
  18203. last-element)
  18204. (if backward (beginning-of-line) (end-of-line))
  18205. (while (and (> count 0) (funcall search-fn re nil t))
  18206. (let ((element (save-excursion
  18207. (goto-char (match-beginning 0))
  18208. (save-match-data (org-element-at-point)))))
  18209. (when (and (memq (org-element-type element)
  18210. '(center-block comment-block dynamic-block
  18211. example-block export-block quote-block
  18212. special-block src-block verse-block))
  18213. (<= (match-beginning 0)
  18214. (org-element-property :post-affiliated element)))
  18215. (setq last-element element)
  18216. (cl-decf count))))
  18217. (if (= count 0)
  18218. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18219. (save-match-data (org-show-context)))
  18220. (goto-char origin)
  18221. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18222. (defun org-previous-block (arg &optional block-regexp)
  18223. "Jump to the previous block.
  18224. With a prefix argument ARG, jump backward ARG many source blocks.
  18225. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18226. (interactive "p")
  18227. (org-next-block arg t block-regexp))
  18228. ;;; Comments
  18229. ;; Org comments syntax is quite complex. It requires the entire line
  18230. ;; to be just a comment. Also, even with the right syntax at the
  18231. ;; beginning of line, some elements (e.g., verse-block or
  18232. ;; example-block) don't accept comments. Usual Emacs comment commands
  18233. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18234. ;; Org still relies on `comment-dwim', but cannot trust
  18235. ;; `comment-only-p'. So, `comment-region-function' and
  18236. ;; `uncomment-region-function' both point
  18237. ;; to`org-comment-or-uncomment-region'. Eventually,
  18238. ;; `org-insert-comment' takes care of insertion of comments at the
  18239. ;; beginning of line.
  18240. ;; `org-setup-comments-handling' install comments related variables
  18241. ;; during `org-mode' initialization.
  18242. (defun org-setup-comments-handling ()
  18243. (interactive)
  18244. (setq-local comment-use-syntax nil)
  18245. (setq-local comment-start "# ")
  18246. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18247. (setq-local comment-insert-comment-function 'org-insert-comment)
  18248. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18249. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18250. (defun org-insert-comment ()
  18251. "Insert an empty comment above current line.
  18252. If the line is empty, insert comment at its beginning. When
  18253. point is within a source block, comment according to the related
  18254. major mode."
  18255. (if (let ((element (org-element-at-point)))
  18256. (and (eq (org-element-type element) 'src-block)
  18257. (< (save-excursion
  18258. (goto-char (org-element-property :post-affiliated element))
  18259. (line-end-position))
  18260. (point))
  18261. (> (save-excursion
  18262. (goto-char (org-element-property :end element))
  18263. (skip-chars-backward " \r\t\n")
  18264. (line-beginning-position))
  18265. (point))))
  18266. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18267. (beginning-of-line)
  18268. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18269. (open-line 1))
  18270. (org-indent-line)
  18271. (insert "# ")))
  18272. (defvar comment-empty-lines) ; From newcomment.el.
  18273. (defun org-comment-or-uncomment-region (beg end &rest _)
  18274. "Comment or uncomment each non-blank line in the region.
  18275. Uncomment each non-blank line between BEG and END if it only
  18276. contains commented lines. Otherwise, comment them. If region is
  18277. strictly within a source block, use appropriate comment syntax."
  18278. (if (let ((element (org-element-at-point)))
  18279. (and (eq (org-element-type element) 'src-block)
  18280. (< (save-excursion
  18281. (goto-char (org-element-property :post-affiliated element))
  18282. (line-end-position))
  18283. beg)
  18284. (>= (save-excursion
  18285. (goto-char (org-element-property :end element))
  18286. (skip-chars-backward " \r\t\n")
  18287. (line-beginning-position))
  18288. end)))
  18289. ;; Translate region boundaries for the Org buffer to the source
  18290. ;; buffer.
  18291. (let ((offset (- end beg)))
  18292. (save-excursion
  18293. (goto-char beg)
  18294. (org-babel-do-in-edit-buffer
  18295. (comment-or-uncomment-region (point) (+ offset (point))))))
  18296. (save-restriction
  18297. ;; Restrict region
  18298. (narrow-to-region (save-excursion (goto-char beg)
  18299. (skip-chars-forward " \r\t\n" end)
  18300. (line-beginning-position))
  18301. (save-excursion (goto-char end)
  18302. (skip-chars-backward " \r\t\n" beg)
  18303. (line-end-position)))
  18304. (let ((uncommentp
  18305. ;; UNCOMMENTP is non-nil when every non blank line between
  18306. ;; BEG and END is a comment.
  18307. (save-excursion
  18308. (goto-char (point-min))
  18309. (while (and (not (eobp))
  18310. (let ((element (org-element-at-point)))
  18311. (and (eq (org-element-type element) 'comment)
  18312. (goto-char (min (point-max)
  18313. (org-element-property
  18314. :end element)))))))
  18315. (eobp))))
  18316. (if uncommentp
  18317. ;; Only blank lines and comments in region: uncomment it.
  18318. (save-excursion
  18319. (goto-char (point-min))
  18320. (while (not (eobp))
  18321. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18322. (replace-match "" nil nil nil 1))
  18323. (forward-line)))
  18324. ;; Comment each line in region.
  18325. (let ((min-indent (point-max)))
  18326. ;; First find the minimum indentation across all lines.
  18327. (save-excursion
  18328. (goto-char (point-min))
  18329. (while (and (not (eobp)) (not (zerop min-indent)))
  18330. (unless (looking-at "[ \t]*$")
  18331. (setq min-indent (min min-indent (current-indentation))))
  18332. (forward-line)))
  18333. ;; Then loop over all lines.
  18334. (save-excursion
  18335. (goto-char (point-min))
  18336. (while (not (eobp))
  18337. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18338. ;; Don't get fooled by invisible text (e.g. link path)
  18339. ;; when moving to column MIN-INDENT.
  18340. (let ((buffer-invisibility-spec nil))
  18341. (org-move-to-column min-indent t))
  18342. (insert comment-start))
  18343. (forward-line)))))))))
  18344. (defun org-comment-dwim (_arg)
  18345. "Call the comment command you mean.
  18346. Call `org-toggle-comment' if on a heading, otherwise call
  18347. `comment-dwim', within a source edit buffer if needed."
  18348. (interactive "*P")
  18349. (cond ((org-at-heading-p)
  18350. (call-interactively #'org-toggle-comment))
  18351. ((org-in-src-block-p)
  18352. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18353. (t (call-interactively #'comment-dwim))))
  18354. ;;; Timestamps API
  18355. ;; This section contains tools to operate on, or create, timestamp
  18356. ;; objects, as returned by, e.g. `org-element-context'.
  18357. (defun org-timestamp-from-string (s)
  18358. "Convert Org timestamp S, as a string, into a timestamp object.
  18359. Return nil if S is not a valid timestamp string."
  18360. (when (org-string-nw-p s)
  18361. (with-temp-buffer
  18362. (save-excursion (insert s))
  18363. (org-element-timestamp-parser))))
  18364. (defun org-timestamp-from-time (time &optional with-time inactive)
  18365. "Convert a time value into a timestamp object.
  18366. TIME is an Emacs internal time representation, as returned, e.g.,
  18367. by `current-time'.
  18368. When optional argument WITH-TIME is non-nil, return a timestamp
  18369. object with a time part, i.e., with hours and minutes.
  18370. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18371. return an active timestamp."
  18372. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18373. (org-element-create 'timestamp
  18374. (list :type (if inactive 'inactive 'active)
  18375. :year-start year
  18376. :month-start month
  18377. :day-start day
  18378. :hour-start (and with-time hour)
  18379. :minute-start (and with-time minute)))))
  18380. (defun org-timestamp-to-time (timestamp &optional end)
  18381. "Convert TIMESTAMP object into an Emacs internal time value.
  18382. Use end of date range or time range when END is non-nil.
  18383. Otherwise, use its start."
  18384. (apply #'encode-time 0
  18385. (mapcar
  18386. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18387. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18388. '(:minute-start :hour-start :day-start :month-start
  18389. :year-start)))))
  18390. (defun org-timestamp-has-time-p (timestamp)
  18391. "Non-nil when TIMESTAMP has a time specified."
  18392. (org-element-property :hour-start timestamp))
  18393. (defun org-timestamp-format (timestamp format &optional end utc)
  18394. "Format a TIMESTAMP object into a string.
  18395. FORMAT is a format specifier to be passed to
  18396. `format-time-string'.
  18397. When optional argument END is non-nil, use end of date-range or
  18398. time-range, if possible.
  18399. When optional argument UTC is non-nil, time is be expressed as
  18400. Universal Time."
  18401. (format-time-string format (org-timestamp-to-time timestamp end)
  18402. (and utc t)))
  18403. (defun org-timestamp-split-range (timestamp &optional end)
  18404. "Extract a TIMESTAMP object from a date or time range.
  18405. END, when non-nil, means extract the end of the range.
  18406. Otherwise, extract its start.
  18407. Return a new timestamp object."
  18408. (let ((type (org-element-property :type timestamp)))
  18409. (if (memq type '(active inactive diary)) timestamp
  18410. (let ((split-ts (org-element-copy timestamp)))
  18411. ;; Set new type.
  18412. (org-element-put-property
  18413. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18414. ;; Copy start properties over end properties if END is
  18415. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18416. (let ((p-alist '((:minute-start . :minute-end)
  18417. (:hour-start . :hour-end)
  18418. (:day-start . :day-end)
  18419. (:month-start . :month-end)
  18420. (:year-start . :year-end))))
  18421. (dolist (p-cell p-alist)
  18422. (org-element-put-property
  18423. split-ts
  18424. (funcall (if end #'car #'cdr) p-cell)
  18425. (org-element-property
  18426. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18427. ;; Eventually refresh `:raw-value'.
  18428. (org-element-put-property split-ts :raw-value nil)
  18429. (org-element-put-property
  18430. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18431. (defun org-timestamp-translate (timestamp &optional boundary)
  18432. "Translate TIMESTAMP object to custom format.
  18433. Format string is defined in `org-time-stamp-custom-formats',
  18434. which see.
  18435. When optional argument BOUNDARY is non-nil, it is either the
  18436. symbol `start' or `end'. In this case, only translate the
  18437. starting or ending part of TIMESTAMP if it is a date or time
  18438. range. Otherwise, translate both parts.
  18439. Return timestamp as-is if `org-display-custom-times' is nil or if
  18440. it has a `diary' type."
  18441. (let ((type (org-element-property :type timestamp)))
  18442. (if (or (not org-display-custom-times) (eq type 'diary))
  18443. (org-element-interpret-data timestamp)
  18444. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18445. org-time-stamp-custom-formats)))
  18446. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18447. (concat (org-timestamp-format timestamp fmt)
  18448. "--"
  18449. (org-timestamp-format timestamp fmt t))
  18450. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18451. ;;; Other stuff
  18452. (defvar reftex-docstruct-symbol)
  18453. (defvar org--rds)
  18454. (defun org-reftex-citation ()
  18455. "Use reftex-citation to insert a citation into the buffer.
  18456. This looks for a line like
  18457. #+BIBLIOGRAPHY: foo plain option:-d
  18458. and derives from it that foo.bib is the bibliography file relevant
  18459. for this document. It then installs the necessary environment for RefTeX
  18460. to work in this buffer and calls `reftex-citation' to insert a citation
  18461. into the buffer.
  18462. Export of such citations to both LaTeX and HTML is handled by the contributed
  18463. package ox-bibtex by Taru Karttunen."
  18464. (interactive)
  18465. (let ((reftex-docstruct-symbol 'org--rds)
  18466. org--rds bib)
  18467. (org-with-wide-buffer
  18468. (let ((case-fold-search t)
  18469. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18470. (if (not (save-excursion
  18471. (or (re-search-forward re nil t)
  18472. (re-search-backward re nil t))))
  18473. (user-error "No bibliography defined in file")
  18474. (setq bib (concat (match-string 1) ".bib")
  18475. org--rds (list (list 'bib bib))))))
  18476. (call-interactively 'reftex-citation)))
  18477. ;;;; Functions extending outline functionality
  18478. (defun org-beginning-of-line (&optional n)
  18479. "Go to the beginning of the current visible line.
  18480. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18481. symbol `reversed', on the first attempt move to where the
  18482. headline text starts, and only move to beginning of line when the
  18483. cursor is already before the start of the text of the headline.
  18484. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18485. start of the text on the second attempt.
  18486. With argument N not nil or 1, move forward N - 1 lines first."
  18487. (interactive "^p")
  18488. (let ((origin (point))
  18489. (special (pcase org-special-ctrl-a/e
  18490. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18491. deactivate-mark)
  18492. ;; First move to a visible line.
  18493. (if (bound-and-true-p visual-line-mode)
  18494. (beginning-of-visual-line n)
  18495. (move-beginning-of-line n)
  18496. ;; `move-beginning-of-line' may leave point after invisible
  18497. ;; characters if line starts with such of these (e.g., with
  18498. ;; a link at column 0). Really move to the beginning of the
  18499. ;; current visible line.
  18500. (beginning-of-line))
  18501. (cond
  18502. ;; No special behavior. Point is already at the beginning of
  18503. ;; a line, logical or visual.
  18504. ((not special))
  18505. ;; `beginning-of-visual-line' left point before logical beginning
  18506. ;; of line: point is at the beginning of a visual line. Bail
  18507. ;; out.
  18508. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18509. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18510. ;; At a headline, special position is before the title, but
  18511. ;; after any TODO keyword or priority cookie.
  18512. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18513. (line-end-position)))
  18514. (bol (point)))
  18515. (if (eq special 'reversed)
  18516. (when (and (= origin bol) (eq last-command this-command))
  18517. (goto-char refpos))
  18518. (when (or (> origin refpos) (= origin bol))
  18519. (goto-char refpos)))))
  18520. ((and (looking-at org-list-full-item-re)
  18521. (memq (org-element-type (save-match-data (org-element-at-point)))
  18522. '(item plain-list)))
  18523. ;; Set special position at first white space character after
  18524. ;; bullet, and check-box, if any.
  18525. (let ((after-bullet
  18526. (let ((box (match-end 3)))
  18527. (cond ((not box) (match-end 1))
  18528. ((eq (char-after box) ?\s) (1+ box))
  18529. (t box)))))
  18530. (if (eq special 'reversed)
  18531. (when (and (= (point) origin) (eq last-command this-command))
  18532. (goto-char after-bullet))
  18533. (when (or (> origin after-bullet) (= (point) origin))
  18534. (goto-char after-bullet)))))
  18535. ;; No special context. Point is already at beginning of line.
  18536. (t nil))))
  18537. (defun org-end-of-line (&optional n)
  18538. "Go to the end of the line, but before ellipsis, if any.
  18539. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18540. symbol `reversed', ignore tags on the first attempt, and only
  18541. move to after the tags when the cursor is already beyond the end
  18542. of the headline.
  18543. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18544. on the second attempt.
  18545. With argument N not nil or 1, move forward N - 1 lines first."
  18546. (interactive "^p")
  18547. (let ((origin (point))
  18548. (special (pcase org-special-ctrl-a/e
  18549. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18550. deactivate-mark)
  18551. ;; First move to a visible line.
  18552. (if (bound-and-true-p visual-line-mode)
  18553. (beginning-of-visual-line n)
  18554. (move-beginning-of-line n))
  18555. (cond
  18556. ;; At a headline, with tags.
  18557. ((and special
  18558. (save-excursion
  18559. (beginning-of-line)
  18560. (let ((case-fold-search nil))
  18561. (looking-at org-complex-heading-regexp)))
  18562. (match-end 5))
  18563. (let ((tags (save-excursion
  18564. (goto-char (match-beginning 5))
  18565. (skip-chars-backward " \t")
  18566. (point)))
  18567. (visual-end (and (bound-and-true-p visual-line-mode)
  18568. (save-excursion
  18569. (end-of-visual-line)
  18570. (point)))))
  18571. ;; If `end-of-visual-line' brings us before end of line or
  18572. ;; even tags, i.e., the headline spans over multiple visual
  18573. ;; lines, move there.
  18574. (cond ((and visual-end
  18575. (< visual-end tags)
  18576. (<= origin visual-end))
  18577. (goto-char visual-end))
  18578. ((eq special 'reversed)
  18579. (if (and (= origin (line-end-position))
  18580. (eq this-command last-command))
  18581. (goto-char tags)
  18582. (end-of-line)))
  18583. (t
  18584. (if (or (< origin tags) (= origin (line-end-position)))
  18585. (goto-char tags)
  18586. (end-of-line))))))
  18587. ((bound-and-true-p visual-line-mode)
  18588. (let ((bol (line-beginning-position)))
  18589. (end-of-visual-line)
  18590. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18591. ;; end of a line, backtrack and use `end-of-line' instead.
  18592. (when (/= bol (line-beginning-position))
  18593. (goto-char bol)
  18594. (end-of-line))))
  18595. (t (end-of-line)))))
  18596. (defun org-backward-sentence (&optional _arg)
  18597. "Go to beginning of sentence, or beginning of table field.
  18598. This will call `backward-sentence' or `org-table-beginning-of-field',
  18599. depending on context."
  18600. (interactive)
  18601. (let* ((element (org-element-at-point))
  18602. (contents-begin (org-element-property :contents-begin element))
  18603. (table (org-element-lineage element '(table) t)))
  18604. (if (and table
  18605. (> (point) contents-begin)
  18606. (<= (point) (org-element-property :contents-end table)))
  18607. (call-interactively #'org-table-beginning-of-field)
  18608. (save-restriction
  18609. (when (and contents-begin
  18610. (< (point-min) contents-begin)
  18611. (> (point) contents-begin))
  18612. (narrow-to-region contents-begin
  18613. (org-element-property :contents-end element)))
  18614. (call-interactively #'backward-sentence)))))
  18615. (defun org-forward-sentence (&optional _arg)
  18616. "Go to end of sentence, or end of table field.
  18617. This will call `forward-sentence' or `org-table-end-of-field',
  18618. depending on context."
  18619. (interactive)
  18620. (if (and (org-at-heading-p)
  18621. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18622. (save-restriction
  18623. (narrow-to-region (line-beginning-position) (line-end-position))
  18624. (call-interactively #'forward-sentence))
  18625. (let* ((element (org-element-at-point))
  18626. (contents-end (org-element-property :contents-end element))
  18627. (table (org-element-lineage element '(table) t)))
  18628. (if (and table
  18629. (>= (point) (org-element-property :contents-begin table))
  18630. (< (point) contents-end))
  18631. (call-interactively #'org-table-end-of-field)
  18632. (save-restriction
  18633. (when (and contents-end
  18634. (> (point-max) contents-end)
  18635. ;; Skip blank lines between elements.
  18636. (< (org-element-property :end element)
  18637. (save-excursion (goto-char contents-end)
  18638. (skip-chars-forward " \r\t\n"))))
  18639. (narrow-to-region (org-element-property :contents-begin element)
  18640. contents-end))
  18641. ;; End of heading is considered as the end of a sentence.
  18642. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18643. (call-interactively #'forward-sentence)))))))
  18644. (defun org-kill-line (&optional _arg)
  18645. "Kill line, to tags or end of line."
  18646. (interactive)
  18647. (cond
  18648. ((or (not org-special-ctrl-k)
  18649. (bolp)
  18650. (not (org-at-heading-p)))
  18651. (when (and (get-char-property (line-end-position) 'invisible)
  18652. org-ctrl-k-protect-subtree
  18653. (or (eq org-ctrl-k-protect-subtree 'error)
  18654. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18655. (user-error
  18656. (substitute-command-keys
  18657. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18658. (call-interactively
  18659. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18660. ((org-match-line org-tag-line-re)
  18661. (let ((end (save-excursion
  18662. (goto-char (match-beginning 1))
  18663. (skip-chars-backward " \t")
  18664. (point))))
  18665. (if (<= end (point)) ;on tags part
  18666. (kill-region (point) (line-end-position))
  18667. (kill-region (point) end)))
  18668. ;; Only align tags when we are still on a heading:
  18669. (if (org-at-heading-p) (org-align-tags)))
  18670. (t (kill-region (point) (line-end-position)))))
  18671. (defun org-yank (&optional arg)
  18672. "Yank. If the kill is a subtree, treat it specially.
  18673. This command will look at the current kill and check if is a single
  18674. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18675. cursor is at the beginning of a line or after the stars of a currently
  18676. empty headline, then the yank is handled specially. How exactly depends
  18677. on the value of the following variables.
  18678. `org-yank-folded-subtrees'
  18679. By default, this variable is non-nil, which results in
  18680. subtree(s) being folded after insertion, except if doing so
  18681. would swallow text after the yanked text.
  18682. `org-yank-adjusted-subtrees'
  18683. When non-nil (the default value is nil), the subtree will be
  18684. promoted or demoted in order to fit into the local outline tree
  18685. structure, which means that the level will be adjusted so that it
  18686. becomes the smaller one of the two *visible* surrounding headings.
  18687. Any prefix to this command will cause `yank' to be called directly with
  18688. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18689. will just
  18690. plainly yank the text as it is.
  18691. \[1] The test checks if the first non-white line is a heading
  18692. and if there are no other headings with fewer stars."
  18693. (interactive "P")
  18694. (org-yank-generic 'yank arg))
  18695. (defun org-yank-generic (command arg)
  18696. "Perform some yank-like command.
  18697. This function implements the behavior described in the `org-yank'
  18698. documentation. However, it has been generalized to work for any
  18699. interactive command with similar behavior."
  18700. ;; pretend to be command COMMAND
  18701. (setq this-command command)
  18702. (if arg
  18703. (call-interactively command)
  18704. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18705. (and (org-kill-is-subtree-p)
  18706. (or (bolp)
  18707. (and (looking-at "[ \t]*$")
  18708. (string-match
  18709. "\\`\\*+\\'"
  18710. (buffer-substring (point-at-bol) (point)))))))
  18711. swallowp)
  18712. (cond
  18713. ((and subtreep org-yank-folded-subtrees)
  18714. (let ((beg (point))
  18715. end)
  18716. (if (and subtreep org-yank-adjusted-subtrees)
  18717. (org-paste-subtree nil nil 'for-yank)
  18718. (call-interactively command))
  18719. (setq end (point))
  18720. (goto-char beg)
  18721. (when (and (bolp) subtreep
  18722. (not (setq swallowp
  18723. (org-yank-folding-would-swallow-text beg end))))
  18724. (org-with-limited-levels
  18725. (or (looking-at org-outline-regexp)
  18726. (re-search-forward org-outline-regexp-bol end t))
  18727. (while (and (< (point) end) (looking-at org-outline-regexp))
  18728. (org-flag-subtree t)
  18729. (org-cycle-show-empty-lines 'folded)
  18730. (condition-case nil
  18731. (outline-forward-same-level 1)
  18732. (error (goto-char end))))))
  18733. (when swallowp
  18734. (message
  18735. "Inserted text not folded because that would swallow text"))
  18736. (goto-char end)
  18737. (skip-chars-forward " \t\n\r")
  18738. (beginning-of-line 1)
  18739. (push-mark beg 'nomsg)))
  18740. ((and subtreep org-yank-adjusted-subtrees)
  18741. (let ((beg (point-at-bol)))
  18742. (org-paste-subtree nil nil 'for-yank)
  18743. (push-mark beg 'nomsg)))
  18744. (t
  18745. (call-interactively command))))))
  18746. (defun org-yank-folding-would-swallow-text (beg end)
  18747. "Would hide-subtree at BEG swallow any text after END?"
  18748. (let (level)
  18749. (org-with-limited-levels
  18750. (save-excursion
  18751. (goto-char beg)
  18752. (when (or (looking-at org-outline-regexp)
  18753. (re-search-forward org-outline-regexp-bol end t))
  18754. (setq level (org-outline-level)))
  18755. (goto-char end)
  18756. (skip-chars-forward " \t\r\n\v\f")
  18757. (not (or (eobp)
  18758. (and (bolp) (looking-at-p org-outline-regexp)
  18759. (<= (org-outline-level) level))))))))
  18760. (defun org-back-to-heading (&optional invisible-ok)
  18761. "Call `outline-back-to-heading', but provide a better error message."
  18762. (condition-case nil
  18763. (outline-back-to-heading invisible-ok)
  18764. (error (error "Before first headline at position %d in buffer %s"
  18765. (point) (current-buffer)))))
  18766. (defun org-before-first-heading-p ()
  18767. "Before first heading?"
  18768. (org-with-limited-levels
  18769. (save-excursion
  18770. (end-of-line)
  18771. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18772. (defun org-at-heading-p (&optional _)
  18773. "Non-nil when on a headline."
  18774. (outline-on-heading-p t))
  18775. (defun org-in-commented-heading-p (&optional no-inheritance)
  18776. "Non-nil if point is under a commented heading.
  18777. This function also checks ancestors of the current headline,
  18778. unless optional argument NO-INHERITANCE is non-nil."
  18779. (cond
  18780. ((org-before-first-heading-p) nil)
  18781. ((let ((headline (nth 4 (org-heading-components))))
  18782. (and headline
  18783. (let ((case-fold-search nil))
  18784. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18785. headline)))))
  18786. (no-inheritance nil)
  18787. (t
  18788. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18789. (defun org-at-comment-p nil
  18790. "Return t if cursor is in a commented line."
  18791. (save-excursion
  18792. (save-match-data
  18793. (beginning-of-line)
  18794. (looking-at "^[ \t]*# "))))
  18795. (defun org-at-drawer-p nil
  18796. "Return t if cursor is at a drawer keyword."
  18797. (save-excursion
  18798. (move-beginning-of-line 1)
  18799. (looking-at org-drawer-regexp)))
  18800. (defun org-at-block-p nil
  18801. "Return t if cursor is at a block keyword."
  18802. (save-excursion
  18803. (move-beginning-of-line 1)
  18804. (looking-at org-block-regexp)))
  18805. (defun org-point-at-end-of-empty-headline ()
  18806. "If point is at the end of an empty headline, return t, else nil.
  18807. If the heading only contains a TODO keyword, it is still still considered
  18808. empty."
  18809. (let ((case-fold-search nil))
  18810. (and (looking-at "[ \t]*$")
  18811. org-todo-line-regexp
  18812. (save-excursion
  18813. (beginning-of-line)
  18814. (looking-at org-todo-line-regexp)
  18815. (string= (match-string 3) "")))))
  18816. (defun org-at-heading-or-item-p ()
  18817. (or (org-at-heading-p) (org-at-item-p)))
  18818. (defun org-up-heading-all (arg)
  18819. "Move to the heading line of which the present line is a subheading.
  18820. This function considers both visible and invisible heading lines.
  18821. With argument, move up ARG levels."
  18822. (outline-up-heading arg t))
  18823. (defun org-up-heading-safe ()
  18824. "Move to the heading line of which the present line is a subheading.
  18825. This version will not throw an error. It will return the level of the
  18826. headline found, or nil if no higher level is found.
  18827. Also, this function will be a lot faster than `outline-up-heading',
  18828. because it relies on stars being the outline starters. This can really
  18829. make a significant difference in outlines with very many siblings."
  18830. (when (ignore-errors (org-back-to-heading t))
  18831. (let ((level-up (1- (funcall outline-level))))
  18832. (and (> level-up 0)
  18833. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18834. (funcall outline-level)))))
  18835. (defun org-first-sibling-p ()
  18836. "Is this heading the first child of its parents?"
  18837. (interactive)
  18838. (let ((re org-outline-regexp-bol)
  18839. level l)
  18840. (unless (org-at-heading-p t)
  18841. (user-error "Not at a heading"))
  18842. (setq level (funcall outline-level))
  18843. (save-excursion
  18844. (if (not (re-search-backward re nil t))
  18845. t
  18846. (setq l (funcall outline-level))
  18847. (< l level)))))
  18848. (defun org-goto-sibling (&optional previous)
  18849. "Goto the next sibling, even if it is invisible.
  18850. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18851. when a sibling was found. When none is found, return nil and don't
  18852. move point."
  18853. (let ((fun (if previous 're-search-backward 're-search-forward))
  18854. (pos (point))
  18855. (re org-outline-regexp-bol)
  18856. level l)
  18857. (when (ignore-errors (org-back-to-heading t))
  18858. (setq level (funcall outline-level))
  18859. (catch 'exit
  18860. (or previous (forward-char 1))
  18861. (while (funcall fun re nil t)
  18862. (setq l (funcall outline-level))
  18863. (when (< l level) (goto-char pos) (throw 'exit nil))
  18864. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18865. (goto-char pos)
  18866. nil))))
  18867. (defun org-show-siblings ()
  18868. "Show all siblings of the current headline."
  18869. (save-excursion
  18870. (while (org-goto-sibling) (org-flag-heading nil)))
  18871. (save-excursion
  18872. (while (org-goto-sibling 'previous)
  18873. (org-flag-heading nil))))
  18874. (defun org-goto-first-child ()
  18875. "Goto the first child, even if it is invisible.
  18876. Return t when a child was found. Otherwise don't move point and
  18877. return nil."
  18878. (let (level (pos (point)) (re org-outline-regexp-bol))
  18879. (when (ignore-errors (org-back-to-heading t))
  18880. (setq level (outline-level))
  18881. (forward-char 1)
  18882. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18883. (progn (goto-char (match-beginning 0)) t)
  18884. (goto-char pos) nil))))
  18885. (defun org-show-hidden-entry ()
  18886. "Show an entry where even the heading is hidden."
  18887. (save-excursion
  18888. (org-show-entry)))
  18889. (defun org-flag-heading (flag &optional entry)
  18890. "Flag the current heading. FLAG non-nil means make invisible.
  18891. When ENTRY is non-nil, show the entire entry."
  18892. (save-excursion
  18893. (org-back-to-heading t)
  18894. ;; Check if we should show the entire entry
  18895. (if (not entry)
  18896. (org-flag-region
  18897. (line-end-position 0) (line-end-position) flag 'outline)
  18898. (org-show-entry)
  18899. (save-excursion
  18900. (and (outline-next-heading)
  18901. (org-flag-heading nil))))))
  18902. (defun org-get-next-sibling ()
  18903. "Move to next heading of the same level, and return point.
  18904. If there is no such heading, return nil.
  18905. This is like outline-next-sibling, but invisible headings are ok."
  18906. (let ((level (funcall outline-level)))
  18907. (outline-next-heading)
  18908. (while (and (not (eobp)) (> (funcall outline-level) level))
  18909. (outline-next-heading))
  18910. (unless (or (eobp) (< (funcall outline-level) level))
  18911. (point))))
  18912. (defun org-get-last-sibling ()
  18913. "Move to previous heading of the same level, and return point.
  18914. If there is no such heading, return nil."
  18915. (let ((opoint (point))
  18916. (level (funcall outline-level)))
  18917. (outline-previous-heading)
  18918. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18919. (while (and (> (funcall outline-level) level)
  18920. (not (bobp)))
  18921. (outline-previous-heading))
  18922. (unless (< (funcall outline-level) level)
  18923. (point)))))
  18924. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18925. "Goto to the end of a subtree."
  18926. ;; This contains an exact copy of the original function, but it uses
  18927. ;; `org-back-to-heading', to make it work also in invisible
  18928. ;; trees. And is uses an invisible-ok argument.
  18929. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18930. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18931. ;; with many children and grandchildren etc, this can be much faster
  18932. ;; than the outline version.
  18933. (org-back-to-heading invisible-ok)
  18934. (let ((first t)
  18935. (level (funcall outline-level)))
  18936. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18937. ;; A true heading (not a plain list item), in Org
  18938. ;; This means we can easily find the end by looking
  18939. ;; only for the right number of stars. Using a regexp to do
  18940. ;; this is so much faster than using a Lisp loop.
  18941. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18942. (forward-char 1)
  18943. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18944. ;; something else, do it the slow way
  18945. (while (and (not (eobp))
  18946. (or first (> (funcall outline-level) level)))
  18947. (setq first nil)
  18948. (outline-next-heading)))
  18949. (unless to-heading
  18950. (when (memq (preceding-char) '(?\n ?\^M))
  18951. ;; Go to end of line before heading
  18952. (forward-char -1)
  18953. (when (memq (preceding-char) '(?\n ?\^M))
  18954. ;; leave blank line before heading
  18955. (forward-char -1)))))
  18956. (point))
  18957. (defun org-end-of-meta-data (&optional full)
  18958. "Skip planning line and properties drawer in current entry.
  18959. When optional argument FULL is non-nil, also skip empty lines,
  18960. clocking lines and regular drawers at the beginning of the
  18961. entry."
  18962. (org-back-to-heading t)
  18963. (forward-line)
  18964. (when (looking-at-p org-planning-line-re) (forward-line))
  18965. (when (looking-at org-property-drawer-re)
  18966. (goto-char (match-end 0))
  18967. (forward-line))
  18968. (when (and full (not (org-at-heading-p)))
  18969. (catch 'exit
  18970. (let ((end (save-excursion (outline-next-heading) (point)))
  18971. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18972. (while (not (eobp))
  18973. (cond ((looking-at-p org-drawer-regexp)
  18974. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18975. (forward-line)
  18976. (throw 'exit t)))
  18977. ((looking-at-p re) (forward-line))
  18978. (t (throw 'exit t))))))))
  18979. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18980. "Move forward to the ARG'th subheading at same level as this one.
  18981. Stop at the first and last subheadings of a superior heading.
  18982. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18983. non-nil it will also look at invisible ones."
  18984. (interactive "p")
  18985. (let ((backward? (and arg (< arg 0))))
  18986. (if (org-before-first-heading-p)
  18987. (if backward? (goto-char (point-min)) (outline-next-heading))
  18988. (org-back-to-heading invisible-ok)
  18989. (unless backward? (end-of-line)) ;do not match current headline
  18990. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18991. (f (if backward? #'re-search-backward #'re-search-forward))
  18992. (count (if arg (abs arg) 1))
  18993. (result (point)))
  18994. (while (and (> count 0)
  18995. (funcall f org-outline-regexp-bol nil 'move))
  18996. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18997. (cond ((< l level) (setq count 0))
  18998. ((and (= l level)
  18999. (or invisible-ok
  19000. (not (org-invisible-p
  19001. (line-beginning-position)))))
  19002. (cl-decf count)
  19003. (when (= l level) (setq result (point)))))))
  19004. (goto-char result))
  19005. (beginning-of-line))))
  19006. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19007. "Move backward to the ARG'th subheading at same level as this one.
  19008. Stop at the first and last subheadings of a superior heading."
  19009. (interactive "p")
  19010. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19011. (defun org-next-visible-heading (arg)
  19012. "Move to the next visible heading.
  19013. This function wraps `outline-next-visible-heading' with
  19014. `org-with-limited-levels' in order to skip over inline tasks and
  19015. respect customization of `org-odd-levels-only'."
  19016. (interactive "p")
  19017. (org-with-limited-levels
  19018. (outline-next-visible-heading arg)))
  19019. (defun org-previous-visible-heading (arg)
  19020. "Move to the previous visible heading.
  19021. This function wraps `outline-previous-visible-heading' with
  19022. `org-with-limited-levels' in order to skip over inline tasks and
  19023. respect customization of `org-odd-levels-only'."
  19024. (interactive "p")
  19025. (org-with-limited-levels
  19026. (outline-previous-visible-heading arg)))
  19027. (defun org-forward-paragraph ()
  19028. "Move forward to beginning of next paragraph or equivalent.
  19029. The function moves point to the beginning of the next visible
  19030. structural element, which can be a paragraph, a table, a list
  19031. item, etc. It also provides some special moves for convenience:
  19032. - On an affiliated keyword, jump to the beginning of the
  19033. relative element.
  19034. - On an item or a footnote definition, move to the second
  19035. element inside, if any.
  19036. - On a table or a property drawer, jump after it.
  19037. - On a verse or source block, stop after blank lines."
  19038. (interactive)
  19039. (unless (eobp)
  19040. (let* ((deactivate-mark nil)
  19041. (element (org-element-at-point))
  19042. (type (org-element-type element))
  19043. (post-affiliated (org-element-property :post-affiliated element))
  19044. (contents-begin (org-element-property :contents-begin element))
  19045. (contents-end (org-element-property :contents-end element))
  19046. (end (let ((end (org-element-property :end element)) (parent element))
  19047. (while (and (setq parent (org-element-property :parent parent))
  19048. (= (org-element-property :contents-end parent) end))
  19049. (setq end (org-element-property :end parent)))
  19050. end)))
  19051. (cond ((not element)
  19052. (skip-chars-forward " \r\t\n")
  19053. (or (eobp) (beginning-of-line)))
  19054. ;; On affiliated keywords, move to element's beginning.
  19055. ((< (point) post-affiliated)
  19056. (goto-char post-affiliated))
  19057. ;; At a table row, move to the end of the table. Similarly,
  19058. ;; at a node property, move to the end of the property
  19059. ;; drawer.
  19060. ((memq type '(node-property table-row))
  19061. (goto-char (org-element-property
  19062. :end (org-element-property :parent element))))
  19063. ((memq type '(property-drawer table)) (goto-char end))
  19064. ;; Consider blank lines as separators in verse and source
  19065. ;; blocks to ease editing.
  19066. ((memq type '(src-block verse-block))
  19067. (when (eq type 'src-block)
  19068. (setq contents-end
  19069. (save-excursion (goto-char end)
  19070. (skip-chars-backward " \r\t\n")
  19071. (line-beginning-position))))
  19072. (beginning-of-line)
  19073. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19074. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19075. (goto-char end)
  19076. (skip-chars-forward " \r\t\n")
  19077. (if (= (point) contents-end) (goto-char end)
  19078. (beginning-of-line))))
  19079. ;; With no contents, just skip element.
  19080. ((not contents-begin) (goto-char end))
  19081. ;; If contents are invisible, skip the element altogether.
  19082. ((org-invisible-p (line-end-position))
  19083. (cl-case type
  19084. (headline
  19085. (org-with-limited-levels (outline-next-visible-heading 1)))
  19086. ;; At a plain list, make sure we move to the next item
  19087. ;; instead of skipping the whole list.
  19088. (plain-list (forward-char)
  19089. (org-forward-paragraph))
  19090. (otherwise (goto-char end))))
  19091. ((>= (point) contents-end) (goto-char end))
  19092. ((>= (point) contents-begin)
  19093. ;; This can only happen on paragraphs and plain lists.
  19094. (cl-case type
  19095. (paragraph (goto-char end))
  19096. ;; At a plain list, try to move to second element in
  19097. ;; first item, if possible.
  19098. (plain-list (end-of-line)
  19099. (org-forward-paragraph))))
  19100. ;; When contents start on the middle of a line (e.g. in
  19101. ;; items and footnote definitions), try to reach first
  19102. ;; element starting after current line.
  19103. ((> (line-end-position) contents-begin)
  19104. (end-of-line)
  19105. (org-forward-paragraph))
  19106. (t (goto-char contents-begin))))))
  19107. (defun org-backward-paragraph ()
  19108. "Move backward to start of previous paragraph or equivalent.
  19109. The function moves point to the beginning of the current
  19110. structural element, which can be a paragraph, a table, a list
  19111. item, etc., or to the beginning of the previous visible one if
  19112. point is already there. It also provides some special moves for
  19113. convenience:
  19114. - On an affiliated keyword, jump to the first one.
  19115. - On a table or a property drawer, move to its beginning.
  19116. - On comment, example, export, src and verse blocks, stop
  19117. before blank lines."
  19118. (interactive)
  19119. (unless (bobp)
  19120. (let* ((deactivate-mark nil)
  19121. (element (org-element-at-point))
  19122. (type (org-element-type element))
  19123. (contents-end (org-element-property :contents-end element))
  19124. (post-affiliated (org-element-property :post-affiliated element))
  19125. (begin (org-element-property :begin element))
  19126. (special? ;blocks handled specially
  19127. (memq type '(comment-block example-block export-block src-block
  19128. verse-block)))
  19129. (contents-begin
  19130. (if special?
  19131. ;; These types have no proper contents. Fake line
  19132. ;; below the block opening line as contents beginning.
  19133. (save-excursion (goto-char begin) (line-beginning-position 2))
  19134. (org-element-property :contents-begin element))))
  19135. (cond
  19136. ((not element) (goto-char (point-min)))
  19137. ((= (point) begin)
  19138. (backward-char)
  19139. (org-backward-paragraph))
  19140. ((<= (point) post-affiliated) (goto-char begin))
  19141. ;; Special behavior: on a table or a property drawer, move to
  19142. ;; its beginning.
  19143. ((memq type '(node-property table-row))
  19144. (goto-char (org-element-property
  19145. :post-affiliated (org-element-property :parent element))))
  19146. (special?
  19147. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19148. ;; Inside a verse block, see blank lines as paragraph
  19149. ;; separators.
  19150. (let ((origin (point)))
  19151. (skip-chars-backward " \r\t\n" contents-begin)
  19152. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19153. (skip-chars-forward " \r\t\n" origin)
  19154. (if (= (point) origin) (goto-char contents-begin)
  19155. (beginning-of-line))))))
  19156. ((eq type 'paragraph) (goto-char contents-begin)
  19157. ;; When at first paragraph in an item or a footnote definition,
  19158. ;; move directly to beginning of line.
  19159. (let ((parent-contents
  19160. (org-element-property
  19161. :contents-begin (org-element-property :parent element))))
  19162. (when (and parent-contents (= parent-contents contents-begin))
  19163. (beginning-of-line))))
  19164. ;; At the end of a greater element, move to the beginning of
  19165. ;; the last element within.
  19166. ((and contents-end (>= (point) contents-end))
  19167. (goto-char (1- contents-end))
  19168. (org-backward-paragraph))
  19169. (t (goto-char (or post-affiliated begin))))
  19170. ;; Ensure we never leave point invisible.
  19171. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19172. (defun org-forward-element ()
  19173. "Move forward by one element.
  19174. Move to the next element at the same level, when possible."
  19175. (interactive)
  19176. (cond ((eobp) (user-error "Cannot move further down"))
  19177. ((org-with-limited-levels (org-at-heading-p))
  19178. (let ((origin (point)))
  19179. (goto-char (org-end-of-subtree nil t))
  19180. (unless (org-with-limited-levels (org-at-heading-p))
  19181. (goto-char origin)
  19182. (user-error "Cannot move further down"))))
  19183. (t
  19184. (let* ((elem (org-element-at-point))
  19185. (end (org-element-property :end elem))
  19186. (parent (org-element-property :parent elem)))
  19187. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19188. (goto-char (org-element-property :end parent)))
  19189. ((integer-or-marker-p end) (goto-char end))
  19190. (t (message "No element at point")))))))
  19191. (defun org-backward-element ()
  19192. "Move backward by one element.
  19193. Move to the previous element at the same level, when possible."
  19194. (interactive)
  19195. (cond ((bobp) (user-error "Cannot move further up"))
  19196. ((org-with-limited-levels (org-at-heading-p))
  19197. ;; At a headline, move to the previous one, if any, or stay
  19198. ;; here.
  19199. (let ((origin (point)))
  19200. (org-with-limited-levels (org-backward-heading-same-level 1))
  19201. ;; When current headline has no sibling above, move to its
  19202. ;; parent.
  19203. (when (= (point) origin)
  19204. (or (org-with-limited-levels (org-up-heading-safe))
  19205. (progn (goto-char origin)
  19206. (user-error "Cannot move further up"))))))
  19207. (t
  19208. (let* ((elem (org-element-at-point))
  19209. (beg (org-element-property :begin elem)))
  19210. (cond
  19211. ;; Move to beginning of current element if point isn't
  19212. ;; there already.
  19213. ((null beg) (message "No element at point"))
  19214. ((/= (point) beg) (goto-char beg))
  19215. (t (goto-char beg)
  19216. (skip-chars-backward " \r\t\n")
  19217. (unless (bobp)
  19218. (let ((prev (org-element-at-point)))
  19219. (goto-char (org-element-property :begin prev))
  19220. (while (and (setq prev (org-element-property :parent prev))
  19221. (<= (org-element-property :end prev) beg))
  19222. (goto-char (org-element-property :begin prev)))))))))))
  19223. (defun org-up-element ()
  19224. "Move to upper element."
  19225. (interactive)
  19226. (if (org-with-limited-levels (org-at-heading-p))
  19227. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19228. (let* ((elem (org-element-at-point))
  19229. (parent (org-element-property :parent elem)))
  19230. (if parent (goto-char (org-element-property :begin parent))
  19231. (if (org-with-limited-levels (org-before-first-heading-p))
  19232. (user-error "No surrounding element")
  19233. (org-with-limited-levels (org-back-to-heading)))))))
  19234. (defun org-down-element ()
  19235. "Move to inner element."
  19236. (interactive)
  19237. (let ((element (org-element-at-point)))
  19238. (cond
  19239. ((memq (org-element-type element) '(plain-list table))
  19240. (goto-char (org-element-property :contents-begin element))
  19241. (forward-char))
  19242. ((memq (org-element-type element) org-element-greater-elements)
  19243. ;; If contents are hidden, first disclose them.
  19244. (when (org-invisible-p (line-end-position)) (org-cycle))
  19245. (goto-char (or (org-element-property :contents-begin element)
  19246. (user-error "No content for this element"))))
  19247. (t (user-error "No inner element")))))
  19248. (defun org-drag-element-backward ()
  19249. "Move backward element at point."
  19250. (interactive)
  19251. (let ((elem (or (org-element-at-point)
  19252. (user-error "No element at point"))))
  19253. (if (eq (org-element-type elem) 'headline)
  19254. ;; Preserve point when moving a whole tree, even if point was
  19255. ;; on blank lines below the headline.
  19256. (let ((offset (skip-chars-backward " \t\n")))
  19257. (unwind-protect (org-move-subtree-up)
  19258. (forward-char (- offset))))
  19259. (let ((prev-elem
  19260. (save-excursion
  19261. (goto-char (org-element-property :begin elem))
  19262. (skip-chars-backward " \r\t\n")
  19263. (unless (bobp)
  19264. (let* ((beg (org-element-property :begin elem))
  19265. (prev (org-element-at-point))
  19266. (up prev))
  19267. (while (and (setq up (org-element-property :parent up))
  19268. (<= (org-element-property :end up) beg))
  19269. (setq prev up))
  19270. prev)))))
  19271. ;; Error out if no previous element or previous element is
  19272. ;; a parent of the current one.
  19273. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19274. (user-error "Cannot drag element backward")
  19275. (let ((pos (point)))
  19276. (org-element-swap-A-B prev-elem elem)
  19277. (goto-char (+ (org-element-property :begin prev-elem)
  19278. (- pos (org-element-property :begin elem))))))))))
  19279. (defun org-drag-element-forward ()
  19280. "Move forward element at point."
  19281. (interactive)
  19282. (let* ((pos (point))
  19283. (elem (or (org-element-at-point)
  19284. (user-error "No element at point"))))
  19285. (when (= (point-max) (org-element-property :end elem))
  19286. (user-error "Cannot drag element forward"))
  19287. (goto-char (org-element-property :end elem))
  19288. (let ((next-elem (org-element-at-point)))
  19289. (when (or (org-element-nested-p elem next-elem)
  19290. (and (eq (org-element-type next-elem) 'headline)
  19291. (not (eq (org-element-type elem) 'headline))))
  19292. (goto-char pos)
  19293. (user-error "Cannot drag element forward"))
  19294. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19295. ;; body's length (without final blanks) and by the length of
  19296. ;; blanks between ELEM and NEXT-ELEM.
  19297. (let ((size-next (- (save-excursion
  19298. (goto-char (org-element-property :end next-elem))
  19299. (skip-chars-backward " \r\t\n")
  19300. (forward-line)
  19301. ;; Small correction if buffer doesn't end
  19302. ;; with a newline character.
  19303. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19304. (org-element-property :begin next-elem)))
  19305. (size-blank (- (org-element-property :end elem)
  19306. (save-excursion
  19307. (goto-char (org-element-property :end elem))
  19308. (skip-chars-backward " \r\t\n")
  19309. (forward-line)
  19310. (point)))))
  19311. (org-element-swap-A-B elem next-elem)
  19312. (goto-char (+ pos size-next size-blank))))))
  19313. (defun org-drag-line-forward (arg)
  19314. "Drag the line at point ARG lines forward."
  19315. (interactive "p")
  19316. (dotimes (_ (abs arg))
  19317. (let ((c (current-column)))
  19318. (if (< 0 arg)
  19319. (progn
  19320. (beginning-of-line 2)
  19321. (transpose-lines 1)
  19322. (beginning-of-line 0))
  19323. (transpose-lines 1)
  19324. (beginning-of-line -1))
  19325. (org-move-to-column c))))
  19326. (defun org-drag-line-backward (arg)
  19327. "Drag the line at point ARG lines backward."
  19328. (interactive "p")
  19329. (org-drag-line-forward (- arg)))
  19330. (defun org-mark-element ()
  19331. "Put point at beginning of this element, mark at end.
  19332. Interactively, if this command is repeated or (in Transient Mark
  19333. mode) if the mark is active, it marks the next element after the
  19334. ones already marked."
  19335. (interactive)
  19336. (let (deactivate-mark)
  19337. (if (and (called-interactively-p 'any)
  19338. (or (and (eq last-command this-command) (mark t))
  19339. (and transient-mark-mode mark-active)))
  19340. (set-mark
  19341. (save-excursion
  19342. (goto-char (mark))
  19343. (goto-char (org-element-property :end (org-element-at-point)))
  19344. (point)))
  19345. (let ((element (org-element-at-point)))
  19346. (end-of-line)
  19347. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19348. (goto-char (org-element-property :begin element))))))
  19349. (defun org-narrow-to-element ()
  19350. "Narrow buffer to current element."
  19351. (interactive)
  19352. (let ((elem (org-element-at-point)))
  19353. (cond
  19354. ((eq (car elem) 'headline)
  19355. (narrow-to-region
  19356. (org-element-property :begin elem)
  19357. (org-element-property :end elem)))
  19358. ((memq (car elem) org-element-greater-elements)
  19359. (narrow-to-region
  19360. (org-element-property :contents-begin elem)
  19361. (org-element-property :contents-end elem)))
  19362. (t
  19363. (narrow-to-region
  19364. (org-element-property :begin elem)
  19365. (org-element-property :end elem))))))
  19366. (defun org-transpose-element ()
  19367. "Transpose current and previous elements, keeping blank lines between.
  19368. Point is moved after both elements."
  19369. (interactive)
  19370. (org-skip-whitespace)
  19371. (let ((end (org-element-property :end (org-element-at-point))))
  19372. (org-drag-element-backward)
  19373. (goto-char end)))
  19374. (defun org-unindent-buffer ()
  19375. "Un-indent the visible part of the buffer.
  19376. Relative indentation (between items, inside blocks, etc.) isn't
  19377. modified."
  19378. (interactive)
  19379. (unless (eq major-mode 'org-mode)
  19380. (user-error "Cannot un-indent a buffer not in Org mode"))
  19381. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19382. (unindent-tree
  19383. (lambda (contents)
  19384. (dolist (element (reverse contents))
  19385. (if (memq (org-element-type element) '(headline section))
  19386. (funcall unindent-tree (org-element-contents element))
  19387. (save-excursion
  19388. (save-restriction
  19389. (narrow-to-region
  19390. (org-element-property :begin element)
  19391. (org-element-property :end element))
  19392. (org-do-remove-indentation))))))))
  19393. (funcall unindent-tree (org-element-contents parse-tree))))
  19394. (defun org-make-options-regexp (kwds &optional extra)
  19395. "Make a regular expression for keyword lines.
  19396. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19397. when non-nil, is a regexp matching keywords names."
  19398. (concat "^[ \t]*#\\+\\("
  19399. (regexp-opt kwds)
  19400. (and extra (concat (and kwds "\\|") extra))
  19401. "\\):[ \t]*\\(.*\\)"))
  19402. ;;; Conveniently switch to Info nodes
  19403. (defun org-info-find-node (&optional nodename)
  19404. "Find Info documentation NODENAME or Org documentation according context.
  19405. Started from `gnus-info-find-node'."
  19406. (interactive)
  19407. (Info-goto-node
  19408. (or nodename
  19409. (let ((default-org-info-node "(org) Top"))
  19410. (cond
  19411. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19412. ((eq 'org-mode major-mode)
  19413. (let* ((context (org-element-at-point))
  19414. (element-info-nodes ; compare to `org-element-all-elements'.
  19415. `((babel-call . "(org) Evaluating Code Blocks")
  19416. (center-block . "(org) Paragraphs")
  19417. (clock . ,default-org-info-node)
  19418. (comment . "(org) Comment Lines")
  19419. (comment-block . "(org) Comment Lines")
  19420. (diary-sexp . ,default-org-info-node)
  19421. (drawer . "(org) Drawers")
  19422. (dynamic-block . "(org) Dynamic Blocks")
  19423. (example-block . "(org) Literal Examples")
  19424. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19425. (fixed-width . ,default-org-info-node)
  19426. (footnote-definition . "(org) Creating Footnotes")
  19427. (headline . "(org) Document Structure")
  19428. (horizontal-rule . "(org) Built-in Table Editor")
  19429. (inlinetask . ,default-org-info-node)
  19430. (item . "(org) Plain Lists")
  19431. (keyword . "(org) Per-file keywords")
  19432. (latex-environment . "(org) LaTeX Export")
  19433. (node-property . "(org) Properties and Columns")
  19434. (paragraph . "(org) Paragraphs")
  19435. (plain-list . "(org) Plain Lists")
  19436. (planning . "(org) Deadlines and Scheduling")
  19437. (property-drawer . "(org) Properties and Columns")
  19438. (quote-block . "(org) Paragraphs")
  19439. (section . ,default-org-info-node)
  19440. (special-block . ,default-org-info-node)
  19441. (src-block . "(org) Working with Source Code")
  19442. (table . "(org) Tables")
  19443. (table-row . "(org) Tables")
  19444. (verse-block . "(org) Paragraphs"))))
  19445. (or (cdr (assoc (car context) element-info-nodes))
  19446. default-org-info-node)))
  19447. (t default-org-info-node))))))
  19448. ;;; Finish up
  19449. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19450. (lambda () (add-hook 'change-major-mode-hook
  19451. 'org-show-all 'append 'local)))
  19452. (provide 'org)
  19453. (run-hooks 'org-load-hook)
  19454. ;;; org.el ends here