org.el 815 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.5.5
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'oc-basic)
  87. (require 'org-table)
  88. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  89. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function cdlatex-math-symbol "ext:cdlatex")
  102. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  103. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  104. (declare-function org-add-archive-files "org-archive" (files))
  105. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  106. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  107. (declare-function org-agenda-redo "org-agenda" (&optional all))
  108. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  109. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  110. (declare-function org-archive-subtree-default "org-archive" ())
  111. (declare-function org-archive-to-archive-sibling "org-archive" ())
  112. (declare-function org-attach "org-attach" ())
  113. (declare-function org-attach-dir "org-attach"
  114. (&optional create-if-not-exists-p no-fs-check))
  115. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  116. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  117. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  118. (declare-function org-clock-auto-clockout "org-clock" ())
  119. (declare-function org-clock-cancel "org-clock" ())
  120. (declare-function org-clock-display "org-clock" (&optional arg))
  121. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  122. (declare-function org-clock-goto "org-clock" (&optional select))
  123. (declare-function org-clock-in "org-clock" (&optional select start-time))
  124. (declare-function org-clock-in-last "org-clock" (&optional arg))
  125. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  126. (declare-function org-clock-out-if-current "org-clock" ())
  127. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  128. (declare-function org-clock-report "org-clock" (&optional arg))
  129. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  130. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  131. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  132. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  133. (declare-function org-clock-update-time-maybe "org-clock" ())
  134. (declare-function org-clocktable-shift "org-clock" (dir n))
  135. (declare-function org-columns-quit "org-colview" ())
  136. (declare-function org-columns-insert-dblock "org-colview" ())
  137. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  138. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  139. (declare-function org-element-at-point "org-element" ())
  140. (declare-function org-element-cache-refresh "org-element" (pos))
  141. (declare-function org-element-cache-reset "org-element" (&optional all))
  142. (declare-function org-element-contents "org-element" (element))
  143. (declare-function org-element-context "org-element" (&optional element))
  144. (declare-function org-element-copy "org-element" (datum))
  145. (declare-function org-element-create "org-element" (type &optional props &rest children))
  146. (declare-function org-element-extract-element "org-element" (element))
  147. (declare-function org-element-insert-before "org-element" (element location))
  148. (declare-function org-element-interpret-data "org-element" (data))
  149. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  150. (declare-function org-element-link-parser "org-element" ())
  151. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  152. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  153. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  154. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  155. (declare-function org-element-property "org-element" (property element))
  156. (declare-function org-element-put-property "org-element" (element property value))
  157. (declare-function org-element-restriction "org-element" (element))
  158. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  159. (declare-function org-element-timestamp-parser "org-element" ())
  160. (declare-function org-element-type "org-element" (element))
  161. (declare-function org-export-dispatch "ox" (&optional arg))
  162. (declare-function org-export-get-backend "ox" (name))
  163. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  164. (declare-function org-feed-goto-inbox "org-feed" (feed))
  165. (declare-function org-feed-update-all "org-feed" ())
  166. (declare-function org-goto "org-goto" (&optional alternative-interface))
  167. (declare-function org-id-find-id-file "org-id" (id))
  168. (declare-function org-id-get-create "org-id" (&optional force))
  169. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  170. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  171. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  172. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  173. (declare-function org-num-mode "org-num" (&optional arg))
  174. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  175. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  176. (declare-function org-timer "org-timer" (&optional restart no-insert))
  177. (declare-function org-timer-item "org-timer" (&optional arg))
  178. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  179. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  180. (declare-function org-timer-start "org-timer" (&optional offset))
  181. (declare-function org-timer-stop "org-timer" ())
  182. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  183. (declare-function org-update-radio-target-regexp "ol" ())
  184. (defvar org-element-paragraph-separate)
  185. (defvar org-element--timestamp-regexp)
  186. (defvar org-indent-indentation-per-level)
  187. (defvar org-radio-target-regexp)
  188. (defvar org-target-link-regexp)
  189. (defvar org-target-regexp)
  190. (defvar org-id-overriding-file-name)
  191. ;; load languages based on value of `org-babel-load-languages'
  192. (defvar org-babel-load-languages)
  193. (defvar crm-separator) ; dynamically scoped param
  194. ;;;###autoload
  195. (defun org-babel-do-load-languages (sym value)
  196. "Load the languages defined in `org-babel-load-languages'."
  197. (set-default sym value)
  198. (dolist (pair org-babel-load-languages)
  199. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  200. (if active
  201. (require (intern (concat "ob-" lang)))
  202. (fmakunbound
  203. (intern (concat "org-babel-execute:" lang)))
  204. (fmakunbound
  205. (intern (concat "org-babel-expand-body:" lang)))))))
  206. ;;;###autoload
  207. (defun org-babel-load-file (file &optional compile)
  208. "Load Emacs Lisp source code blocks in the Org FILE.
  209. This function exports the source code using `org-babel-tangle'
  210. and then loads the resulting file using `load-file'. With
  211. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  212. byte-compiled before it is loaded."
  213. (interactive "fFile to load: \nP")
  214. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  215. ;; Tangle only if the Org file is newer than the Elisp file.
  216. (unless (org-file-newer-than-p
  217. tangled-file
  218. (file-attribute-modification-time
  219. (file-attributes (file-truename file))))
  220. (org-babel-tangle-file file
  221. tangled-file
  222. (rx string-start
  223. (or "emacs-lisp" "elisp")
  224. string-end)))
  225. (if compile
  226. (progn
  227. (byte-compile-file tangled-file)
  228. (load-file (byte-compile-dest-file tangled-file))
  229. (message "Compiled and loaded %s" tangled-file))
  230. (load-file tangled-file)
  231. (message "Loaded %s" tangled-file))))
  232. (defcustom org-babel-load-languages '((emacs-lisp . t))
  233. "Languages which can be evaluated in Org buffers.
  234. \\<org-mode-map>
  235. This list can be used to load support for any of the languages
  236. below. Each language will depend on a different set of system
  237. executables and/or Emacs modes.
  238. When a language is \"loaded\", code blocks in that language can
  239. be evaluated with `org-babel-execute-src-block', which is bound
  240. by default to \\[org-ctrl-c-ctrl-c].
  241. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  242. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  243. default, only Emacs Lisp is loaded, since it has no specific
  244. requirement."
  245. :group 'org-babel
  246. :set 'org-babel-do-load-languages
  247. :version "24.1"
  248. :type '(alist :tag "Babel Languages"
  249. :key-type
  250. (choice
  251. (const :tag "Awk" awk)
  252. (const :tag "C" C)
  253. (const :tag "R" R)
  254. (const :tag "Calc" calc)
  255. (const :tag "Clojure" clojure)
  256. (const :tag "CSS" css)
  257. (const :tag "Ditaa" ditaa)
  258. (const :tag "Dot" dot)
  259. (const :tag "Emacs Lisp" emacs-lisp)
  260. (const :tag "Forth" forth)
  261. (const :tag "Fortran" fortran)
  262. (const :tag "Gnuplot" gnuplot)
  263. (const :tag "Haskell" haskell)
  264. (const :tag "Java" java)
  265. (const :tag "Javascript" js)
  266. (const :tag "LaTeX" latex)
  267. (const :tag "Lilypond" lilypond)
  268. (const :tag "Lisp" lisp)
  269. (const :tag "Makefile" makefile)
  270. (const :tag "Maxima" maxima)
  271. (const :tag "Matlab" matlab)
  272. (const :tag "Ocaml" ocaml)
  273. (const :tag "Octave" octave)
  274. (const :tag "Org" org)
  275. (const :tag "Perl" perl)
  276. (const :tag "Pico Lisp" picolisp)
  277. (const :tag "PlantUML" plantuml)
  278. (const :tag "Python" python)
  279. (const :tag "Ruby" ruby)
  280. (const :tag "Sass" sass)
  281. (const :tag "Scala" scala)
  282. (const :tag "Scheme" scheme)
  283. (const :tag "Screen" screen)
  284. (const :tag "Shell Script" shell)
  285. (const :tag "Sql" sql)
  286. (const :tag "Sqlite" sqlite)
  287. (const :tag "Stan" stan))
  288. :value-type (boolean :tag "Activate" :value t)))
  289. ;;;; Customization variables
  290. (defcustom org-clone-delete-id nil
  291. "Remove ID property of clones of a subtree.
  292. When non-nil, clones of a subtree don't inherit the ID property.
  293. Otherwise they inherit the ID property with a new unique
  294. identifier."
  295. :type 'boolean
  296. :version "24.1"
  297. :group 'org-id)
  298. ;;; Version
  299. (org-check-version)
  300. ;;;###autoload
  301. (defun org-version (&optional here full message)
  302. "Show the Org version.
  303. Interactively, or when MESSAGE is non-nil, show it in echo area.
  304. With prefix argument, or when HERE is non-nil, insert it at point.
  305. In non-interactive uses, a reduced version string is output unless
  306. FULL is given."
  307. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  308. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  309. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  310. (load-suffixes (list ".el"))
  311. (org-install-dir
  312. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  313. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  314. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  315. (let* ((load-suffixes save-load-suffixes)
  316. (release (org-release))
  317. (git-version (org-git-version))
  318. (version (format "Org mode version %s (%s @ %s)"
  319. release
  320. git-version
  321. (if org-install-dir
  322. (if (string= org-dir org-install-dir)
  323. org-install-dir
  324. (concat "mixed installation! "
  325. org-install-dir
  326. " and "
  327. org-dir))
  328. "org-loaddefs.el can not be found!")))
  329. (version1 (if full version release)))
  330. (when here (insert version1))
  331. (when message (message "%s" version1))
  332. version1)))
  333. (defconst org-version (org-version))
  334. ;;; Syntax Constants
  335. ;;;; Comments
  336. (defconst org-comment-regexp
  337. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  338. "Regular expression for comment lines.")
  339. ;;;; Keyword
  340. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  341. "Regular expression for keyword-lines.")
  342. ;;;; Block
  343. (defconst org-block-regexp
  344. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  345. "Regular expression for hiding blocks.")
  346. (defconst org-dblock-start-re
  347. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  348. "Matches the start line of a dynamic block, with parameters.")
  349. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  350. "Matches the end of a dynamic block.")
  351. ;;;; Timestamp
  352. (defconst org-ts--internal-regexp
  353. (rx (seq
  354. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  355. (optional " " (*? nonl))))
  356. "Regular expression matching the innards of a time stamp.")
  357. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  358. "Regular expression for fast time stamp matching.")
  359. (defconst org-ts-regexp-inactive
  360. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  361. "Regular expression for fast inactive time stamp matching.")
  362. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  363. "Regular expression for fast time stamp matching.")
  364. (defconst org-ts-regexp0
  365. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  366. "Regular expression matching time strings for analysis.
  367. This one does not require the space after the date, so it can be used
  368. on a string that terminates immediately after the date.")
  369. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  370. "Regular expression matching time strings for analysis.")
  371. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  372. "Regular expression matching time stamps, with groups.")
  373. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  374. "Regular expression matching time stamps (also [..]), with groups.")
  375. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  376. "Regular expression matching a time stamp range.")
  377. (defconst org-tr-regexp-both
  378. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  379. "Regular expression matching a time stamp range.")
  380. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  381. org-ts-regexp "\\)?")
  382. "Regular expression matching a time stamp or time stamp range.")
  383. (defconst org-tsr-regexp-both
  384. (concat org-ts-regexp-both "\\(--?-?"
  385. org-ts-regexp-both "\\)?")
  386. "Regular expression matching a time stamp or time stamp range.
  387. The time stamps may be either active or inactive.")
  388. (defconst org-repeat-re
  389. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  390. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  391. "Regular expression for specifying repeated events.
  392. After a match, group 1 contains the repeat expression.")
  393. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  394. "Formats for `format-time-string' which are used for time stamps.")
  395. ;;;; Clock and Planning
  396. (defconst org-clock-string "CLOCK:"
  397. "String used as prefix for timestamps clocking work hours on an item.")
  398. (defvar org-closed-string "CLOSED:"
  399. "String used as the prefix for timestamps logging closing a TODO entry.")
  400. (defvar org-deadline-string "DEADLINE:"
  401. "String to mark deadline entries.
  402. \\<org-mode-map>
  403. A deadline is this string, followed by a time stamp. It must be
  404. a word, terminated by a colon. You can insert a schedule keyword
  405. and a timestamp with `\\[org-deadline]'.")
  406. (defvar org-scheduled-string "SCHEDULED:"
  407. "String to mark scheduled TODO entries.
  408. \\<org-mode-map>
  409. A schedule is this string, followed by a time stamp. It must be
  410. a word, terminated by a colon. You can insert a schedule keyword
  411. and a timestamp with `\\[org-schedule]'.")
  412. (defconst org-ds-keyword-length
  413. (+ 2
  414. (apply #'max
  415. (mapcar #'length
  416. (list org-deadline-string org-scheduled-string
  417. org-clock-string org-closed-string))))
  418. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  419. (defconst org-planning-line-re
  420. (concat "^[ \t]*"
  421. (regexp-opt
  422. (list org-closed-string org-deadline-string org-scheduled-string)
  423. t))
  424. "Matches a line with planning info.
  425. Matched keyword is in group 1.")
  426. (defconst org-clock-line-re
  427. (concat "^[ \t]*" org-clock-string)
  428. "Matches a line with clock info.")
  429. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  430. "Matches the DEADLINE keyword.")
  431. (defconst org-deadline-time-regexp
  432. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  433. "Matches the DEADLINE keyword together with a time stamp.")
  434. (defconst org-deadline-time-hour-regexp
  435. (concat "\\<" org-deadline-string
  436. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  437. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  438. (defconst org-deadline-line-regexp
  439. (concat "\\<\\(" org-deadline-string "\\).*")
  440. "Matches the DEADLINE keyword and the rest of the line.")
  441. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  442. "Matches the SCHEDULED keyword.")
  443. (defconst org-scheduled-time-regexp
  444. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  445. "Matches the SCHEDULED keyword together with a time stamp.")
  446. (defconst org-scheduled-time-hour-regexp
  447. (concat "\\<" org-scheduled-string
  448. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  449. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  450. (defconst org-closed-time-regexp
  451. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  452. "Matches the CLOSED keyword together with a time stamp.")
  453. (defconst org-keyword-time-regexp
  454. (concat "\\<"
  455. (regexp-opt
  456. (list org-scheduled-string org-deadline-string org-closed-string
  457. org-clock-string)
  458. t)
  459. " *[[<]\\([^]>]+\\)[]>]")
  460. "Matches any of the 4 keywords, together with the time stamp.")
  461. (defconst org-keyword-time-not-clock-regexp
  462. (concat
  463. "\\<"
  464. (regexp-opt
  465. (list org-scheduled-string org-deadline-string org-closed-string) t)
  466. " *[[<]\\([^]>]+\\)[]>]")
  467. "Matches any of the 3 keywords, together with the time stamp.")
  468. (defconst org-all-time-keywords
  469. (mapcar (lambda (w) (substring w 0 -1))
  470. (list org-scheduled-string org-deadline-string
  471. org-clock-string org-closed-string))
  472. "List of time keywords.")
  473. ;;;; Drawer
  474. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  475. "Matches first or last line of a hidden block.
  476. Group 1 contains drawer's name or \"END\".")
  477. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  478. "Regular expression matching the first line of a property drawer.")
  479. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  480. "Regular expression matching the last line of a property drawer.")
  481. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  482. "Regular expression matching the first line of a clock drawer.")
  483. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  484. "Regular expression matching the last line of a clock drawer.")
  485. (defconst org-logbook-drawer-re
  486. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  487. (*? (0+ nonl) "\n")
  488. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  489. "Matches an entire LOGBOOK drawer.")
  490. (defconst org-property-drawer-re
  491. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  492. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  493. "[ \t]*:END:[ \t]*$")
  494. "Matches an entire property drawer.")
  495. (defconst org-clock-drawer-re
  496. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  497. org-clock-drawer-end-re "\\)\n?")
  498. "Matches an entire clock drawer.")
  499. ;;;; Headline
  500. (defconst org-heading-keyword-regexp-format
  501. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  502. "Printf format for a regexp matching a headline with some keyword.
  503. This regexp will match the headline of any node which has the
  504. exact keyword that is put into the format. The keyword isn't in
  505. any group by default, but the stars and the body are.")
  506. (defconst org-heading-keyword-maybe-regexp-format
  507. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  508. "Printf format for a regexp matching a headline, possibly with some keyword.
  509. This regexp can match any headline with the specified keyword, or
  510. without a keyword. The keyword isn't in any group by default,
  511. but the stars and the body are.")
  512. (defconst org-archive-tag "ARCHIVE"
  513. "The tag that marks a subtree as archived.
  514. An archived subtree does not open during visibility cycling, and does
  515. not contribute to the agenda listings.")
  516. (defconst org-tag-re "[[:alnum:]_@#%]+"
  517. "Regexp matching a single tag.")
  518. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  519. "Regexp matching the tag group at the end of a line, with leading spaces.
  520. Tags are stored in match group 1. Match group 2 stores the tags
  521. without the enclosing colons.")
  522. (defconst org-tag-line-re
  523. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  524. "Regexp matching tags in a headline.
  525. Tags are stored in match group 1. Match group 2 stores the tags
  526. without the enclosing colons.")
  527. (eval-and-compile
  528. (defconst org-comment-string "COMMENT"
  529. "Entries starting with this keyword will never be exported.
  530. \\<org-mode-map>
  531. An entry can be toggled between COMMENT and normal with
  532. `\\[org-toggle-comment]'."))
  533. ;;;; LaTeX Environments and Fragments
  534. (defconst org-latex-regexps
  535. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  536. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  537. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  538. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  539. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  540. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  541. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  542. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  543. "Regular expressions for matching embedded LaTeX.")
  544. ;;;; Node Property
  545. (defconst org-effort-property "Effort"
  546. "The property that is being used to keep track of effort estimates.
  547. Effort estimates given in this property need to be in the format
  548. defined in org-duration.el.")
  549. ;;; The custom variables
  550. (defgroup org nil
  551. "Outline-based notes management and organizer."
  552. :tag "Org"
  553. :group 'outlines
  554. :group 'calendar)
  555. (defcustom org-mode-hook nil
  556. "Mode hook for Org mode, run after the mode was turned on."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-load-hook nil
  560. "Hook that is run after org.el has been loaded."
  561. :group 'org
  562. :type 'hook)
  563. (make-obsolete-variable
  564. 'org-load-hook
  565. "use `with-eval-after-load' instead." "9.5")
  566. (defcustom org-log-buffer-setup-hook nil
  567. "Hook that is run after an Org log buffer is created."
  568. :group 'org
  569. :version "24.1"
  570. :type 'hook)
  571. (defvar org-modules) ; defined below
  572. (defvar org-modules-loaded nil
  573. "Have the modules been loaded already?")
  574. ;;;###autoload
  575. (defun org-load-modules-maybe (&optional force)
  576. "Load all extensions listed in `org-modules'."
  577. (when (or force (not org-modules-loaded))
  578. (dolist (ext org-modules)
  579. (condition-case nil (require ext)
  580. (error (message "Problems while trying to load feature `%s'" ext))))
  581. (setq org-modules-loaded t)))
  582. (defun org-set-modules (var value)
  583. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  584. (set var value)
  585. (when (featurep 'org)
  586. (org-load-modules-maybe 'force)
  587. (org-element-cache-reset 'all)))
  588. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  589. "Modules that should always be loaded together with org.el.
  590. If a description starts with <C>, the file is not part of Emacs and Org mode,
  591. so loading it will require that you have properly installed org-contrib
  592. package from NonGNU Emacs Lisp Package Archive
  593. https://elpa.nongnu.org/nongnu/org-contrib.html
  594. You can also use this system to load external packages (i.e. neither Org
  595. core modules, nor org-contrib modules). Just add symbols
  596. to the end of the list. If the package is called org-xyz.el, then you need
  597. to add the symbol `xyz', and the package must have a call to:
  598. (provide \\='org-xyz)
  599. For export specific modules, see also `org-export-backends'."
  600. :group 'org
  601. :set 'org-set-modules
  602. :package-version '(Org . "9.5")
  603. :type
  604. '(set :greedy t
  605. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  606. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  607. (const :tag " crypt: Encryption of subtrees" org-crypt)
  608. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  609. (const :tag " docview: Links to Docview buffers" ol-docview)
  610. (const :tag " doi: Links to DOI references" ol-doi)
  611. (const :tag " eww: Store link to URL of Eww" ol-eww)
  612. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  613. (const :tag " habit: Track your consistency with habits" org-habit)
  614. (const :tag " id: Global IDs for identifying entries" org-id)
  615. (const :tag " info: Links to Info nodes" ol-info)
  616. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  617. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  618. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  619. (const :tag " mouse: Additional mouse support" org-mouse)
  620. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  621. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  622. (const :tag " tempo: Fast completion for structures" org-tempo)
  623. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  624. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  625. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  626. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  627. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  628. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  629. (const :tag "C collector: Collect properties into tables" org-collector)
  630. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  631. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  632. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  633. (const :tag "C eval: Include command output as text" org-eval)
  634. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  635. (const :tag "C git-link: Links to specific file version" ol-git-link)
  636. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  637. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  638. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  639. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  640. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  641. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  642. (const :tag "C man: Links to man pages in Org mode" ol-man)
  643. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  644. (const :tag "C notify: Notifications for Org mode" org-notify)
  645. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  646. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  647. (const :tag "C registry: A registry for Org links" org-registry)
  648. (const :tag "C screen: Visit screen sessions through links" org-screen)
  649. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  650. (const :tag "C secretary: Team management with Org" org-secretary)
  651. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  652. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  653. (const :tag "C track: Keep up with Org mode development" org-track)
  654. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  655. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  656. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  657. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  658. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  659. (defvar org-export-registered-backends) ; From ox.el.
  660. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  661. (declare-function org-export-backend-name "ox" (backend) t)
  662. (defcustom org-export-backends '(ascii html icalendar latex odt)
  663. "List of export back-ends that should be always available.
  664. If a description starts with <C>, the file is not part of Emacs and Org mode,
  665. so loading it will require that you have properly installed org-contrib
  666. package from NonGNU Emacs Lisp Package Archive
  667. https://elpa.nongnu.org/nongnu/org-contrib.html
  668. Unlike to `org-modules', libraries in this list will not be
  669. loaded along with Org, but only once the export framework is
  670. needed.
  671. This variable needs to be set before org.el is loaded. If you
  672. need to make a change while Emacs is running, use the customize
  673. interface or run the following code, where VAL stands for the new
  674. value of the variable, after updating it:
  675. (progn
  676. (setq org-export-registered-backends
  677. (cl-remove-if-not
  678. (lambda (backend)
  679. (let ((name (org-export-backend-name backend)))
  680. (or (memq name val)
  681. (catch \\='parentp
  682. (dolist (b val)
  683. (and (org-export-derived-backend-p b name)
  684. (throw \\='parentp t)))))))
  685. org-export-registered-backends))
  686. (let ((new-list (mapcar #\\='org-export-backend-name
  687. org-export-registered-backends)))
  688. (dolist (backend val)
  689. (cond
  690. ((not (load (format \"ox-%s\" backend) t t))
  691. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  692. backend))
  693. ((not (memq backend new-list)) (push backend new-list))))
  694. (set-default \\='org-export-backends new-list)))
  695. Adding a back-end to this list will also pull the back-end it
  696. depends on, if any."
  697. :group 'org
  698. :group 'org-export
  699. :version "26.1"
  700. :package-version '(Org . "9.0")
  701. :initialize 'custom-initialize-set
  702. :set (lambda (var val)
  703. (if (not (featurep 'ox)) (set-default var val)
  704. ;; Any back-end not required anymore (not present in VAL and not
  705. ;; a parent of any back-end in the new value) is removed from the
  706. ;; list of registered back-ends.
  707. (setq org-export-registered-backends
  708. (cl-remove-if-not
  709. (lambda (backend)
  710. (let ((name (org-export-backend-name backend)))
  711. (or (memq name val)
  712. (catch 'parentp
  713. (dolist (b val)
  714. (and (org-export-derived-backend-p b name)
  715. (throw 'parentp t)))))))
  716. org-export-registered-backends))
  717. ;; Now build NEW-LIST of both new back-ends and required
  718. ;; parents.
  719. (let ((new-list (mapcar #'org-export-backend-name
  720. org-export-registered-backends)))
  721. (dolist (backend val)
  722. (cond
  723. ((not (load (format "ox-%s" backend) t t))
  724. (message "Problems while trying to load export back-end `%s'"
  725. backend))
  726. ((not (memq backend new-list)) (push backend new-list))))
  727. ;; Set VAR to that list with fixed dependencies.
  728. (set-default var new-list))))
  729. :type '(set :greedy t
  730. (const :tag " ascii Export buffer to ASCII format" ascii)
  731. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  732. (const :tag " html Export buffer to HTML format" html)
  733. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  734. (const :tag " latex Export buffer to LaTeX format" latex)
  735. (const :tag " man Export buffer to MAN format" man)
  736. (const :tag " md Export buffer to Markdown format" md)
  737. (const :tag " odt Export buffer to ODT format" odt)
  738. (const :tag " org Export buffer to Org format" org)
  739. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  740. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  741. (const :tag "C deck Export buffer to deck.js presentations" deck)
  742. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  743. (const :tag "C groff Export buffer to Groff format" groff)
  744. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  745. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  746. (const :tag "C s5 Export buffer to s5 presentations" s5)
  747. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  748. (eval-after-load 'ox
  749. '(dolist (backend org-export-backends)
  750. (condition-case nil (require (intern (format "ox-%s" backend)))
  751. (error (message "Problems while trying to load export back-end `%s'"
  752. backend)))))
  753. (defcustom org-support-shift-select nil
  754. "Non-nil means make shift-cursor commands select text when possible.
  755. \\<org-mode-map>
  756. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  757. start selecting a region, or enlarge regions started in this way.
  758. In Org mode, in special contexts, these same keys are used for
  759. other purposes, important enough to compete with shift selection.
  760. Org tries to balance these needs by supporting `shift-select-mode'
  761. outside these special contexts, under control of this variable.
  762. The default of this variable is nil, to avoid confusing behavior. Shifted
  763. cursor keys will then execute Org commands in the following contexts:
  764. - on a headline, changing TODO state (left/right) and priority (up/down)
  765. - on a time stamp, changing the time
  766. - in a plain list item, changing the bullet type
  767. - in a property definition line, switching between allowed values
  768. - in the BEGIN line of a clock table (changing the time block).
  769. - in a table, moving the cell in the specified direction.
  770. Outside these contexts, the commands will throw an error.
  771. When this variable is t and the cursor is not in a special
  772. context, Org mode will support shift-selection for making and
  773. enlarging regions. To make this more effective, the bullet
  774. cycling will no longer happen anywhere in an item line, but only
  775. if the cursor is exactly on the bullet.
  776. If you set this variable to the symbol `always', then the keys
  777. will not be special in headlines, property lines, item lines, and
  778. table cells, to make shift selection work there as well. If this is
  779. what you want, you can use the following alternative commands:
  780. `\\[org-todo]' and `\\[org-priority]' \
  781. to change TODO state and priority,
  782. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  783. can be used to switch TODO sets,
  784. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  785. and properties can be edited by hand or in column view.
  786. However, when the cursor is on a timestamp, shift-cursor commands
  787. will still edit the time stamp - this is just too good to give up."
  788. :group 'org
  789. :type '(choice
  790. (const :tag "Never" nil)
  791. (const :tag "When outside special context" t)
  792. (const :tag "Everywhere except timestamps" always)))
  793. (defcustom org-loop-over-headlines-in-active-region t
  794. "Shall some commands act upon headlines in the active region?
  795. When set to t, some commands will be performed in all headlines
  796. within the active region.
  797. When set to `start-level', some commands will be performed in all
  798. headlines within the active region, provided that these headlines
  799. are of the same level than the first one.
  800. When set to a string, those commands will be performed on the
  801. matching headlines within the active region. Such string must be
  802. a tags/property/todo match as it is used in the agenda tags view.
  803. The list of commands is: `org-schedule', `org-deadline',
  804. `org-todo', `org-set-tags-command', `org-archive-subtree',
  805. `org-archive-set-tag', `org-toggle-archive-tag' and
  806. `org-archive-to-archive-sibling'. The archiving commands skip
  807. already archived entries.
  808. See `org-agenda-loop-over-headlines-in-active-region' for the
  809. equivalent option for agenda views."
  810. :type '(choice (const :tag "Don't loop" nil)
  811. (const :tag "All headlines in active region" t)
  812. (const :tag "In active region, headlines at the same level than the first one" start-level)
  813. (string :tag "Tags/Property/Todo matcher"))
  814. :package-version '(Org . "9.4")
  815. :group 'org-todo
  816. :group 'org-archive)
  817. (defcustom org-startup-folded 'showeverything
  818. "Non-nil means entering Org mode will switch to OVERVIEW.
  819. This can also be configured on a per-file basis by adding one of
  820. the following lines anywhere in the buffer:
  821. #+STARTUP: fold (or `overview', this is equivalent)
  822. #+STARTUP: nofold (or `showall', this is equivalent)
  823. #+STARTUP: content
  824. #+STARTUP: show<n>levels (<n> = 2..5)
  825. #+STARTUP: showeverything
  826. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  827. to ignore this option when Org opens agenda files for the first
  828. time."
  829. :group 'org-startup
  830. :package-version '(Org . "9.4")
  831. :type '(choice
  832. (const :tag "nofold: show all" nil)
  833. (const :tag "fold: overview" t)
  834. (const :tag "fold: show two levels" show2levels)
  835. (const :tag "fold: show three levels" show3levels)
  836. (const :tag "fold: show four levels" show4evels)
  837. (const :tag "fold: show five levels" show5levels)
  838. (const :tag "content: all headlines" content)
  839. (const :tag "show everything, even drawers" showeverything)))
  840. (defcustom org-startup-truncated t
  841. "Non-nil means entering Org mode will set `truncate-lines'.
  842. This is useful since some lines containing links can be very long and
  843. uninteresting. Also tables look terrible when wrapped.
  844. The variable `org-startup-truncated' allows to configure
  845. truncation for Org mode different to the other modes that use the
  846. variable `truncate-lines' and as a shortcut instead of putting
  847. the variable `truncate-lines' into the `org-mode-hook'. If one
  848. wants to configure truncation for Org mode not statically but
  849. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  850. the variable `truncate-lines' has to be used because in such a
  851. case it is too late to set the variable `org-startup-truncated'."
  852. :group 'org-startup
  853. :type 'boolean)
  854. (defcustom org-startup-indented nil
  855. "Non-nil means turn on `org-indent-mode' on startup.
  856. This can also be configured on a per-file basis by adding one of
  857. the following lines anywhere in the buffer:
  858. #+STARTUP: indent
  859. #+STARTUP: noindent"
  860. :group 'org-structure
  861. :type '(choice
  862. (const :tag "Not" nil)
  863. (const :tag "Globally (slow on startup in large files)" t)))
  864. (defcustom org-startup-numerated nil
  865. "Non-nil means turn on `org-num-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: num
  869. #+STARTUP: nonum"
  870. :group 'org-structure
  871. :package-version '(Org . "9.4")
  872. :type '(choice
  873. (const :tag "Not" nil)
  874. (const :tag "Globally" t)))
  875. (defcustom org-use-sub-superscripts t
  876. "Non-nil means interpret \"_\" and \"^\" for display.
  877. If you want to control how Org exports those characters, see
  878. `org-export-with-sub-superscripts'.
  879. When this option is turned on, you can use TeX-like syntax for
  880. sub- and superscripts within the buffer. Several characters after
  881. \"_\" or \"^\" will be considered as a single item - so grouping
  882. with {} is normally not needed. For example, the following things
  883. will be parsed as single sub- or superscripts:
  884. 10^24 or 10^tau several digits will be considered 1 item.
  885. 10^-12 or 10^-tau a leading sign with digits or a word
  886. x^2-y^3 will be read as x^2 - y^3, because items are
  887. terminated by almost any nonword/nondigit char.
  888. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  889. Still, ambiguity is possible. So when in doubt, use {} to enclose
  890. the sub/superscript. If you set this variable to the symbol `{}',
  891. the braces are *required* in order to trigger interpretations as
  892. sub/superscript. This can be helpful in documents that need \"_\"
  893. frequently in plain text."
  894. :group 'org-startup
  895. :version "24.4"
  896. :package-version '(Org . "8.0")
  897. :type '(choice
  898. (const :tag "Always interpret" t)
  899. (const :tag "Only with braces" {})
  900. (const :tag "Never interpret" nil)))
  901. (defcustom org-startup-with-beamer-mode nil
  902. "Non-nil means turn on `org-beamer-mode' on startup.
  903. This can also be configured on a per-file basis by adding one of
  904. the following lines anywhere in the buffer:
  905. #+STARTUP: beamer"
  906. :group 'org-startup
  907. :version "24.1"
  908. :type 'boolean)
  909. (defcustom org-startup-align-all-tables nil
  910. "Non-nil means align all tables when visiting a file.
  911. This can also be configured on a per-file basis by adding one of
  912. the following lines anywhere in the buffer:
  913. #+STARTUP: align
  914. #+STARTUP: noalign"
  915. :group 'org-startup
  916. :type 'boolean)
  917. (defcustom org-startup-shrink-all-tables nil
  918. "Non-nil means shrink all table columns with a width cookie.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: shrink"
  922. :group 'org-startup
  923. :type 'boolean
  924. :version "27.1"
  925. :package-version '(Org . "9.2")
  926. :safe #'booleanp)
  927. (defcustom org-startup-with-inline-images nil
  928. "Non-nil means show inline images when loading a new Org file.
  929. This can also be configured on a per-file basis by adding one of
  930. the following lines anywhere in the buffer:
  931. #+STARTUP: inlineimages
  932. #+STARTUP: noinlineimages"
  933. :group 'org-startup
  934. :version "24.1"
  935. :type 'boolean)
  936. (defcustom org-startup-with-latex-preview nil
  937. "Non-nil means preview LaTeX fragments when loading a new Org file.
  938. This can also be configured on a per-file basis by adding one of
  939. the following lines anywhere in the buffer:
  940. #+STARTUP: latexpreview
  941. #+STARTUP: nolatexpreview"
  942. :group 'org-startup
  943. :version "24.4"
  944. :package-version '(Org . "8.0")
  945. :type 'boolean)
  946. (defcustom org-insert-mode-line-in-empty-file nil
  947. "Non-nil means insert the first line setting Org mode in empty files.
  948. When the function `org-mode' is called interactively in an empty file, this
  949. normally means that the file name does not automatically trigger Org mode.
  950. To ensure that the file will always be in Org mode in the future, a
  951. line enforcing Org mode will be inserted into the buffer, if this option
  952. has been set."
  953. :group 'org-startup
  954. :type 'boolean)
  955. (defcustom org-ellipsis nil
  956. "The ellipsis to use in the Org mode outline.
  957. When nil, just use the standard three dots. When a non-empty string,
  958. use that string instead.
  959. The change affects only Org mode (which will then use its own display table).
  960. Changing this requires executing `\\[org-mode]' in a buffer to become
  961. effective. It cannot be set as a local variable."
  962. :group 'org-startup
  963. :type '(choice (const :tag "Default" nil)
  964. (string :tag "String" :value "...#")))
  965. (defvar org-display-table nil
  966. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  967. (defcustom org-directory "~/org"
  968. "Directory with Org files.
  969. This is just a default location to look for Org files. There is no need
  970. at all to put your files into this directory. It is used in the
  971. following situations:
  972. 1. When a capture template specifies a target file that is not an
  973. absolute path. The path will then be interpreted relative to
  974. `org-directory'
  975. 2. When the value of variable `org-agenda-files' is a single file, any
  976. relative paths in this file will be taken as relative to
  977. `org-directory'."
  978. :group 'org-refile
  979. :group 'org-capture
  980. :type 'directory)
  981. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  982. "Default target for storing notes.
  983. Used as a fall back file for org-capture.el, for templates that
  984. do not specify a target file."
  985. :group 'org-refile
  986. :group 'org-capture
  987. :type 'file)
  988. (defcustom org-reverse-note-order nil
  989. "Non-nil means store new notes at the beginning of a file or entry.
  990. When nil, new notes will be filed to the end of a file or entry.
  991. This can also be a list with cons cells of regular expressions that
  992. are matched against file names, and values."
  993. :group 'org-capture
  994. :group 'org-refile
  995. :type '(choice
  996. (const :tag "Reverse always" t)
  997. (const :tag "Reverse never" nil)
  998. (repeat :tag "By file name regexp"
  999. (cons regexp boolean))))
  1000. (defgroup org-keywords nil
  1001. "Keywords in Org mode."
  1002. :tag "Org Keywords"
  1003. :group 'org)
  1004. (defcustom org-closed-keep-when-no-todo nil
  1005. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1006. :group 'org-todo
  1007. :group 'org-keywords
  1008. :version "24.4"
  1009. :package-version '(Org . "8.0")
  1010. :type 'boolean)
  1011. (defgroup org-structure nil
  1012. "Options concerning the general structure of Org files."
  1013. :tag "Org Structure"
  1014. :group 'org)
  1015. (defgroup org-reveal-location nil
  1016. "Options about how to make context of a location visible."
  1017. :tag "Org Reveal Location"
  1018. :group 'org-structure)
  1019. (defcustom org-show-context-detail '((agenda . local)
  1020. (bookmark-jump . lineage)
  1021. (isearch . lineage)
  1022. (default . ancestors))
  1023. "Alist between context and visibility span when revealing a location.
  1024. \\<org-mode-map>Some actions may move point into invisible
  1025. locations. As a consequence, Org always exposes a neighborhood
  1026. around point. How much is shown depends on the initial action,
  1027. or context. Valid contexts are
  1028. agenda when exposing an entry from the agenda
  1029. org-goto when using the command `org-goto' (`\\[org-goto]')
  1030. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1031. tags-tree when constructing a sparse tree based on tags matches
  1032. link-search when exposing search matches associated with a link
  1033. mark-goto when exposing the jump goal of a mark
  1034. bookmark-jump when exposing a bookmark location
  1035. isearch when exiting from an incremental search
  1036. default default for all contexts not set explicitly
  1037. Allowed visibility spans are
  1038. minimal show current headline; if point is not on headline,
  1039. also show entry
  1040. local show current headline, entry and next headline
  1041. ancestors show current headline and its direct ancestors; if
  1042. point is not on headline, also show entry
  1043. ancestors-full show current subtree and its direct ancestors
  1044. lineage show current headline, its direct ancestors and all
  1045. their children; if point is not on headline, also show
  1046. entry and first child
  1047. tree show current headline, its direct ancestors and all
  1048. their children; if point is not on headline, also show
  1049. entry and all children
  1050. canonical show current headline, its direct ancestors along with
  1051. their entries and children; if point is not located on
  1052. the headline, also show current entry and all children
  1053. As special cases, a nil or t value means show all contexts in
  1054. `minimal' or `canonical' view, respectively.
  1055. Some views can make displayed information very compact, but also
  1056. make it harder to edit the location of the match. In such
  1057. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1058. more context."
  1059. :group 'org-reveal-location
  1060. :version "26.1"
  1061. :package-version '(Org . "9.0")
  1062. :type '(choice
  1063. (const :tag "Canonical" t)
  1064. (const :tag "Minimal" nil)
  1065. (repeat :greedy t :tag "Individual contexts"
  1066. (cons
  1067. (choice :tag "Context"
  1068. (const agenda)
  1069. (const org-goto)
  1070. (const occur-tree)
  1071. (const tags-tree)
  1072. (const link-search)
  1073. (const mark-goto)
  1074. (const bookmark-jump)
  1075. (const isearch)
  1076. (const default))
  1077. (choice :tag "Detail level"
  1078. (const minimal)
  1079. (const local)
  1080. (const ancestors)
  1081. (const ancestors-full)
  1082. (const lineage)
  1083. (const tree)
  1084. (const canonical))))))
  1085. (defcustom org-indirect-buffer-display 'other-window
  1086. "How should indirect tree buffers be displayed?
  1087. This applies to indirect buffers created with the commands
  1088. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1089. Valid values are:
  1090. current-window Display in the current window
  1091. other-window Just display in another window.
  1092. dedicated-frame Create one new frame, and re-use it each time.
  1093. new-frame Make a new frame each time. Note that in this case
  1094. previously-made indirect buffers are kept, and you need to
  1095. kill these buffers yourself."
  1096. :group 'org-structure
  1097. :group 'org-agenda-windows
  1098. :type '(choice
  1099. (const :tag "In current window" current-window)
  1100. (const :tag "In current frame, other window" other-window)
  1101. (const :tag "Each time a new frame" new-frame)
  1102. (const :tag "One dedicated frame" dedicated-frame)))
  1103. (defconst org-file-apps-gnu
  1104. '((remote . emacs)
  1105. (system . mailcap)
  1106. (t . mailcap))
  1107. "Default file applications on a UNIX or GNU/Linux system.
  1108. See `org-file-apps'.")
  1109. (defconst org-file-apps-macos
  1110. '((remote . emacs)
  1111. (system . "open %s")
  1112. ("ps.gz" . "gv %s")
  1113. ("eps.gz" . "gv %s")
  1114. ("dvi" . "xdvi %s")
  1115. ("fig" . "xfig %s")
  1116. (t . "open %s"))
  1117. "Default file applications on a macOS system.
  1118. The system \"open\" is known as a default, but we use X11 applications
  1119. for some files for which the OS does not have a good default.
  1120. See `org-file-apps'.")
  1121. (defconst org-file-apps-windowsnt
  1122. (list '(remote . emacs)
  1123. (cons 'system (lambda (file _path)
  1124. (with-no-warnings (w32-shell-execute "open" file))))
  1125. (cons t (lambda (file _path)
  1126. (with-no-warnings (w32-shell-execute "open" file)))))
  1127. "Default file applications on a Windows NT system.
  1128. The system \"open\" is used for most files.
  1129. See `org-file-apps'.")
  1130. (defcustom org-file-apps
  1131. '((auto-mode . emacs)
  1132. (directory . emacs)
  1133. ("\\.mm\\'" . default)
  1134. ("\\.x?html?\\'" . default)
  1135. ("\\.pdf\\'" . default))
  1136. "Applications for opening `file:path' items in a document.
  1137. \\<org-mode-map>
  1138. Org mode uses system defaults for different file types, but you
  1139. can use this variable to set the application for a given file
  1140. extension. The entries in this list are cons cells where the car
  1141. identifies files and the cdr the corresponding command.
  1142. Possible values for the file identifier are:
  1143. \"string\" A string as a file identifier can be interpreted in different
  1144. ways, depending on its contents:
  1145. - Alphanumeric characters only:
  1146. Match links with this file extension.
  1147. Example: (\"pdf\" . \"evince %s\")
  1148. to open PDFs with evince.
  1149. - Regular expression: Match links where the
  1150. filename matches the regexp. If you want to
  1151. use groups here, use shy groups.
  1152. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1153. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1154. to open *.html and *.xhtml with firefox.
  1155. - Regular expression which contains (non-shy) groups:
  1156. Match links where the whole link, including \"::\", and
  1157. anything after that, matches the regexp.
  1158. In a custom command string, %1, %2, etc. are replaced with
  1159. the parts of the link that were matched by the groups.
  1160. For backwards compatibility, if a command string is given
  1161. that does not use any of the group matches, this case is
  1162. handled identically to the second one (i.e. match against
  1163. file name only).
  1164. In a custom function, you can access the group matches with
  1165. (match-string n link).
  1166. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1167. \"evince -p %1 %s\")
  1168. to open [[file:document.pdf::5]] with evince at page 5.
  1169. `directory' Matches a directory
  1170. `remote' Matches a remote file, accessible through tramp or efs.
  1171. Remote files most likely should be visited through Emacs
  1172. because external applications cannot handle such paths.
  1173. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1174. so all files Emacs knows how to handle. Using this with
  1175. command `emacs' will open most files in Emacs. Beware that this
  1176. will also open html files inside Emacs, unless you add
  1177. (\"html\" . default) to the list as well.
  1178. `system' The system command to open files, like `open' on Windows
  1179. and macOS, and mailcap under GNU/Linux. This is the command
  1180. that will be selected if you call `org-open-at-point' with a
  1181. double prefix argument (`\\[universal-argument] \
  1182. \\[universal-argument] \\[org-open-at-point]').
  1183. t Default for files not matched by any of the other options.
  1184. Possible values for the command are:
  1185. `emacs' The file will be visited by the current Emacs process.
  1186. `default' Use the default application for this file type, which is the
  1187. association for t in the list, most likely in the system-specific
  1188. part. This can be used to overrule an unwanted setting in the
  1189. system-specific variable.
  1190. `system' Use the system command for opening files, like \"open\".
  1191. This command is specified by the entry whose car is `system'.
  1192. Most likely, the system-specific version of this variable
  1193. does define this command, but you can overrule/replace it
  1194. here.
  1195. `mailcap' Use command specified in the mailcaps.
  1196. string A command to be executed by a shell; %s will be replaced
  1197. by the path to the file.
  1198. function A Lisp function, which will be called with two arguments:
  1199. the file path and the original link string, without the
  1200. \"file:\" prefix.
  1201. For more examples, see the system specific constants
  1202. `org-file-apps-macos'
  1203. `org-file-apps-windowsnt'
  1204. `org-file-apps-gnu'."
  1205. :group 'org
  1206. :package-version '(Org . "9.4")
  1207. :type '(repeat
  1208. (cons (choice :value ""
  1209. (string :tag "Extension")
  1210. (const :tag "System command to open files" system)
  1211. (const :tag "Default for unrecognized files" t)
  1212. (const :tag "Remote file" remote)
  1213. (const :tag "Links to a directory" directory)
  1214. (const :tag "Any files that have Emacs modes"
  1215. auto-mode))
  1216. (choice :value ""
  1217. (const :tag "Visit with Emacs" emacs)
  1218. (const :tag "Use default" default)
  1219. (const :tag "Use the system command" system)
  1220. (string :tag "Command")
  1221. (function :tag "Function")))))
  1222. (defcustom org-open-non-existing-files nil
  1223. "Non-nil means `org-open-file' opens non-existing files.
  1224. When nil, an error is thrown.
  1225. This variable applies only to external applications because they
  1226. might choke on non-existing files. If the link is to a file that
  1227. will be opened in Emacs, the variable is ignored."
  1228. :group 'org
  1229. :type 'boolean
  1230. :safe #'booleanp)
  1231. (defcustom org-open-directory-means-index-dot-org nil
  1232. "When non-nil a link to a directory really means to \"index.org\".
  1233. When nil, following a directory link runs Dired or opens
  1234. a finder/explorer window on that directory."
  1235. :group 'org
  1236. :type 'boolean
  1237. :safe #'booleanp)
  1238. (defcustom org-bookmark-names-plist
  1239. '(:last-capture "org-capture-last-stored"
  1240. :last-refile "org-refile-last-stored"
  1241. :last-capture-marker "org-capture-last-stored-marker")
  1242. "Names for bookmarks automatically set by some Org commands.
  1243. This can provide strings as names for a number of bookmarks Org sets
  1244. automatically. The following keys are currently implemented:
  1245. :last-capture
  1246. :last-capture-marker
  1247. :last-refile
  1248. When a key does not show up in the property list, the corresponding bookmark
  1249. is not set."
  1250. :group 'org-structure
  1251. :type 'plist)
  1252. (defgroup org-cycle nil
  1253. "Options concerning visibility cycling in Org mode."
  1254. :tag "Org Cycle"
  1255. :group 'org-structure)
  1256. (defcustom org-cycle-skip-children-state-if-no-children t
  1257. "Non-nil means skip CHILDREN state in entries that don't have any."
  1258. :group 'org-cycle
  1259. :type 'boolean)
  1260. (defcustom org-cycle-max-level nil
  1261. "Maximum level which should still be subject to visibility cycling.
  1262. Levels higher than this will, for cycling, be treated as text, not a headline.
  1263. When `org-odd-levels-only' is set, a value of N in this variable actually
  1264. means 2N-1 stars as the limiting headline.
  1265. When nil, cycle all levels.
  1266. Note that the limiting level of cycling is also influenced by
  1267. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1268. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1269. than its value."
  1270. :group 'org-cycle
  1271. :type '(choice
  1272. (const :tag "No limit" nil)
  1273. (integer :tag "Maximum level")))
  1274. (defcustom org-hide-block-startup nil
  1275. "Non-nil means entering Org mode will fold all blocks.
  1276. This can also be set in on a per-file basis with
  1277. #+STARTUP: hideblocks
  1278. #+STARTUP: showblocks"
  1279. :group 'org-startup
  1280. :group 'org-cycle
  1281. :type 'boolean)
  1282. (defcustom org-cycle-global-at-bob nil
  1283. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1284. This makes it possible to do global cycling without having to use `S-TAB'
  1285. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1286. line of the buffer
  1287. must not be a headline -- it may be empty or some other text.
  1288. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1289. sure the cursor stays at the beginning of the buffer.
  1290. When this option is nil, don't do anything special at the beginning of
  1291. the buffer."
  1292. :group 'org-cycle
  1293. :type 'boolean)
  1294. (defcustom org-cycle-level-after-item/entry-creation t
  1295. "Non-nil means cycle entry level or item indentation in new empty entries.
  1296. When the cursor is at the end of an empty headline, i.e., with only stars
  1297. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1298. and then all possible ancestor states, before returning to the original state.
  1299. This makes data entry extremely fast: M-RET to create a new headline,
  1300. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1301. When the cursor is at the end of an empty plain list item, one TAB will
  1302. make it a subitem, two or more tabs will back up to make this an item
  1303. higher up in the item hierarchy."
  1304. :group 'org-cycle
  1305. :type 'boolean)
  1306. (defcustom org-cycle-emulate-tab t
  1307. "Where should `org-cycle' emulate TAB.
  1308. nil Never
  1309. white Only in completely white lines
  1310. whitestart Only at the beginning of lines, before the first non-white char
  1311. t Everywhere except in headlines
  1312. exc-hl-bol Everywhere except at the start of a headline
  1313. If TAB is used in a place where it does not emulate TAB, the current subtree
  1314. visibility is cycled."
  1315. :group 'org-cycle
  1316. :type '(choice (const :tag "Never" nil)
  1317. (const :tag "Only in completely white lines" white)
  1318. (const :tag "Before first char in a line" whitestart)
  1319. (const :tag "Everywhere except in headlines" t)
  1320. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1321. (defcustom org-cycle-separator-lines 2
  1322. "Number of empty lines needed to keep an empty line between collapsed trees.
  1323. If you leave an empty line between the end of a subtree and the following
  1324. headline, this empty line is hidden when the subtree is folded.
  1325. Org mode will leave (exactly) one empty line visible if the number of
  1326. empty lines is equal or larger to the number given in this variable.
  1327. So the default 2 means at least 2 empty lines after the end of a subtree
  1328. are needed to produce free space between a collapsed subtree and the
  1329. following headline.
  1330. If the number is negative, and the number of empty lines is at least -N,
  1331. all empty lines are shown.
  1332. Special case: when 0, never leave empty lines in collapsed view."
  1333. :group 'org-cycle
  1334. :type 'integer)
  1335. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1336. (defcustom org-pre-cycle-hook nil
  1337. "Hook that is run before visibility cycling is happening.
  1338. The function(s) in this hook must accept a single argument which indicates
  1339. the new state that will be set right after running this hook. The
  1340. argument is a symbol. Before a global state change, it can have the values
  1341. `overview', `content', or `all'. Before a local state change, it can have
  1342. the values `folded', `children', or `subtree'."
  1343. :group 'org-cycle
  1344. :type 'hook)
  1345. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1346. org-cycle-hide-drawers
  1347. org-cycle-show-empty-lines
  1348. org-optimize-window-after-visibility-change)
  1349. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1350. The function(s) in this hook must accept a single argument which indicates
  1351. the new state that was set by the most recent `org-cycle' command. The
  1352. argument is a symbol. After a global state change, it can have the values
  1353. `overview', `contents', or `all'. After a local state change, it can have
  1354. the values `folded', `children', or `subtree'."
  1355. :group 'org-cycle
  1356. :package-version '(Org . "9.4")
  1357. :type 'hook)
  1358. (defgroup org-edit-structure nil
  1359. "Options concerning structure editing in Org mode."
  1360. :tag "Org Edit Structure"
  1361. :group 'org-structure)
  1362. (defcustom org-odd-levels-only nil
  1363. "Non-nil means skip even levels and only use odd levels for the outline.
  1364. This has the effect that two stars are being added/taken away in
  1365. promotion/demotion commands. It also influences how levels are
  1366. handled by the exporters.
  1367. Changing it requires restart of `font-lock-mode' to become effective
  1368. for fontification also in regions already fontified.
  1369. You may also set this on a per-file basis by adding one of the following
  1370. lines to the buffer:
  1371. #+STARTUP: odd
  1372. #+STARTUP: oddeven"
  1373. :group 'org-edit-structure
  1374. :group 'org-appearance
  1375. :type 'boolean)
  1376. (defcustom org-adapt-indentation nil
  1377. "Non-nil means adapt indentation to outline node level.
  1378. When set to t, Org assumes that you write outlines by indenting
  1379. text in each node to align with the headline, after the stars.
  1380. When this variable is set to `headline-data', Org only adapts the
  1381. indentation of the data lines right below the headline, such as
  1382. planning/clock lines and property/logbook drawers.
  1383. The following issues are influenced by this variable:
  1384. - The indentation is increased by one space in a demotion
  1385. command, and decreased by one in a promotion command. However,
  1386. in the latter case, if shifting some line in the entry body
  1387. would alter document structure (e.g., insert a new headline),
  1388. indentation is not changed at all.
  1389. - Property drawers and planning information is inserted indented
  1390. when this variable is set. When nil, they will not be indented.
  1391. - TAB indents a line relative to current level. The lines below
  1392. a headline will be indented when this variable is set to t.
  1393. Note that this is all about true indentation, by adding and
  1394. removing space characters. See also \"org-indent.el\" which does
  1395. level-dependent indentation in a virtual way, i.e. at display
  1396. time in Emacs."
  1397. :group 'org-edit-structure
  1398. :type '(choice
  1399. (const :tag "Adapt indentation for all lines" t)
  1400. (const :tag "Adapt indentation for headline data lines"
  1401. headline-data)
  1402. (const :tag "Do not adapt indentation at all" nil))
  1403. :safe (lambda (x) (memq x '(t nil headline-data))))
  1404. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1405. (defcustom org-special-ctrl-a/e nil
  1406. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1407. When t, `C-a' will bring back the cursor to the beginning of the
  1408. headline text, i.e. after the stars and after a possible TODO
  1409. keyword. In an item, this will be the position after bullet and
  1410. check-box, if any. When the cursor is already at that position,
  1411. another `C-a' will bring it to the beginning of the line.
  1412. `C-e' will jump to the end of the headline, ignoring the presence
  1413. of tags in the headline. A second `C-e' will then jump to the
  1414. true end of the line, after any tags. This also means that, when
  1415. this variable is non-nil, `C-e' also will never jump beyond the
  1416. end of the heading of a folded section, i.e. not after the
  1417. ellipses.
  1418. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1419. normally, going to the true line boundary first. Only a directly
  1420. following, identical keypress will bring the cursor to the
  1421. special positions.
  1422. This may also be a cons cell where the behavior for `C-a' and
  1423. `C-e' is set separately."
  1424. :group 'org-edit-structure
  1425. :type '(choice
  1426. (const :tag "off" nil)
  1427. (const :tag "on: after stars/bullet and before tags first" t)
  1428. (const :tag "reversed: true line boundary first" reversed)
  1429. (cons :tag "Set C-a and C-e separately"
  1430. (choice :tag "Special C-a"
  1431. (const :tag "off" nil)
  1432. (const :tag "on: after stars/bullet first" t)
  1433. (const :tag "reversed: before stars/bullet first" reversed))
  1434. (choice :tag "Special C-e"
  1435. (const :tag "off" nil)
  1436. (const :tag "on: before tags first" t)
  1437. (const :tag "reversed: after tags first" reversed)))))
  1438. (defcustom org-special-ctrl-k nil
  1439. "Non-nil means `C-k' will behave specially in headlines.
  1440. When nil, `C-k' will call the default `kill-line' command.
  1441. When t, the following will happen while the cursor is in the headline:
  1442. - When at the beginning of a headline, kill the entire subtree.
  1443. - When in the middle of the headline text, kill the text up to the tags.
  1444. - When after the headline text and before the tags, kill all the tags."
  1445. :group 'org-edit-structure
  1446. :type 'boolean)
  1447. (defcustom org-ctrl-k-protect-subtree nil
  1448. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1449. When set to the symbol `error', simply throw an error when `C-k' is
  1450. used to kill (part-of) a headline that has hidden text behind it.
  1451. Any other non-nil value will result in a query to the user, if it is
  1452. OK to kill that hidden subtree. When nil, kill without remorse."
  1453. :group 'org-edit-structure
  1454. :version "24.1"
  1455. :type '(choice
  1456. (const :tag "Do not protect hidden subtrees" nil)
  1457. (const :tag "Protect hidden subtrees with a security query" t)
  1458. (const :tag "Never kill a hidden subtree with C-k" error)))
  1459. (defcustom org-special-ctrl-o t
  1460. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1461. :group 'org-edit-structure
  1462. :type 'boolean)
  1463. (defcustom org-catch-invisible-edits nil
  1464. "Check if in invisible region before inserting or deleting a character.
  1465. Valid values are:
  1466. nil Do not check, so just do invisible edits.
  1467. error Throw an error and do nothing.
  1468. show Make point visible, and do the requested edit.
  1469. show-and-error Make point visible, then throw an error and abort the edit.
  1470. smart Make point visible, and do insertion/deletion if it is
  1471. adjacent to visible text and the change feels predictable.
  1472. Never delete a previously invisible character or add in the
  1473. middle or right after an invisible region. Basically, this
  1474. allows insertion and backward-delete right before ellipses.
  1475. FIXME: maybe in this case we should not even show?"
  1476. :group 'org-edit-structure
  1477. :version "24.1"
  1478. :type '(choice
  1479. (const :tag "Do not check" nil)
  1480. (const :tag "Throw error when trying to edit" error)
  1481. (const :tag "Unhide, but do not do the edit" show-and-error)
  1482. (const :tag "Show invisible part and do the edit" show)
  1483. (const :tag "Be smart and do the right thing" smart)))
  1484. (defcustom org-yank-folded-subtrees t
  1485. "Non-nil means when yanking subtrees, fold them.
  1486. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1487. it starts with a heading and all other headings in it are either children
  1488. or siblings, then fold all the subtrees. However, do this only if no
  1489. text after the yank would be swallowed into a folded tree by this action."
  1490. :group 'org-edit-structure
  1491. :type 'boolean)
  1492. (defcustom org-yank-adjusted-subtrees nil
  1493. "Non-nil means when yanking subtrees, adjust the level.
  1494. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1495. this function for details."
  1496. :group 'org-edit-structure
  1497. :type 'boolean)
  1498. (defcustom org-M-RET-may-split-line '((default . t))
  1499. "Non-nil means M-RET will split the line at the cursor position.
  1500. When nil, it will go to the end of the line before making a
  1501. new line.
  1502. You may also set this option in a different way for different
  1503. contexts. Valid contexts are:
  1504. headline when creating a new headline
  1505. item when creating a new item
  1506. table in a table field
  1507. default the value to be used for all contexts not explicitly
  1508. customized"
  1509. :group 'org-structure
  1510. :group 'org-table
  1511. :type '(choice
  1512. (const :tag "Always" t)
  1513. (const :tag "Never" nil)
  1514. (repeat :greedy t :tag "Individual contexts"
  1515. (cons
  1516. (choice :tag "Context"
  1517. (const headline)
  1518. (const item)
  1519. (const table)
  1520. (const default))
  1521. (boolean)))))
  1522. (defcustom org-insert-heading-respect-content nil
  1523. "Non-nil means insert new headings after the current subtree.
  1524. \\<org-mode-map>
  1525. When nil, the new heading is created directly after the current line.
  1526. The commands `\\[org-insert-heading-respect-content]' and \
  1527. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1528. for the duration of the command."
  1529. :group 'org-structure
  1530. :type 'boolean)
  1531. (defcustom org-blank-before-new-entry '((heading . auto)
  1532. (plain-list-item . auto))
  1533. "Should `org-insert-heading' leave a blank line before new heading/item?
  1534. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1535. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1536. which case Org will look at the surrounding headings/items and try to
  1537. make an intelligent decision whether to insert a blank line or not."
  1538. :group 'org-edit-structure
  1539. :type '(list
  1540. (cons (const heading)
  1541. (choice (const :tag "Never" nil)
  1542. (const :tag "Always" t)
  1543. (const :tag "Auto" auto)))
  1544. (cons (const plain-list-item)
  1545. (choice (const :tag "Never" nil)
  1546. (const :tag "Always" t)
  1547. (const :tag "Auto" auto)))))
  1548. (defcustom org-insert-heading-hook nil
  1549. "Hook being run after inserting a new heading."
  1550. :group 'org-edit-structure
  1551. :type 'hook)
  1552. (defgroup org-sparse-trees nil
  1553. "Options concerning sparse trees in Org mode."
  1554. :tag "Org Sparse Trees"
  1555. :group 'org-structure)
  1556. (defcustom org-highlight-sparse-tree-matches t
  1557. "Non-nil means highlight all matches that define a sparse tree.
  1558. The highlights will automatically disappear the next time the buffer is
  1559. changed by an edit command."
  1560. :group 'org-sparse-trees
  1561. :type 'boolean)
  1562. (defcustom org-remove-highlights-with-change t
  1563. "Non-nil means any change to the buffer will remove temporary highlights.
  1564. \\<org-mode-map>\
  1565. Such highlights are created by `org-occur' and `org-clock-display'.
  1566. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1567. to get rid of the highlights.
  1568. The highlights created by `org-latex-preview' always need
  1569. `\\[org-latex-preview]' to be removed."
  1570. :group 'org-sparse-trees
  1571. :group 'org-time
  1572. :type 'boolean)
  1573. (defcustom org-occur-case-fold-search t
  1574. "Non-nil means `org-occur' should be case-insensitive.
  1575. If set to `smart' the search will be case-insensitive only if it
  1576. doesn't specify any upper case character."
  1577. :group 'org-sparse-trees
  1578. :version "26.1"
  1579. :type '(choice
  1580. (const :tag "Case-sensitive" nil)
  1581. (const :tag "Case-insensitive" t)
  1582. (const :tag "Case-insensitive for lower case searches only" smart)))
  1583. (defcustom org-occur-hook '(org-first-headline-recenter)
  1584. "Hook that is run after `org-occur' has constructed a sparse tree.
  1585. This can be used to recenter the window to show as much of the structure
  1586. as possible."
  1587. :group 'org-sparse-trees
  1588. :type 'hook)
  1589. (defcustom org-self-insert-cluster-for-undo nil
  1590. "Non-nil means cluster self-insert commands for undo when possible.
  1591. If this is set, then, like in the Emacs command loop, 20 consecutive
  1592. characters will be undone together.
  1593. This is configurable, because there is some impact on typing performance."
  1594. :group 'org-table
  1595. :type 'boolean)
  1596. (defvaralias 'org-activate-links 'org-highlight-links)
  1597. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1598. "Types of links that should be highlighted in Org files.
  1599. This is a list of symbols, each one of them leading to the
  1600. highlighting of a certain link type.
  1601. You can still open links that are not highlighted.
  1602. In principle, it does not hurt to turn on highlighting for all
  1603. link types. There may be a small gain when turning off unused
  1604. link types. The types are:
  1605. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1606. angle Links in angular brackets that may contain whitespace like
  1607. <bbdb:Carsten Dominik>.
  1608. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1609. radio Text that is matched by a radio target, see manual for details.
  1610. tag Tag settings in a headline (link to tag search).
  1611. date Time stamps (link to calendar).
  1612. footnote Footnote labels.
  1613. If you set this variable during an Emacs session, use `org-mode-restart'
  1614. in the Org buffer so that the change takes effect."
  1615. :group 'org-appearance
  1616. :type '(set :greedy t
  1617. (const :tag "Double bracket links" bracket)
  1618. (const :tag "Angular bracket links" angle)
  1619. (const :tag "Plain text links" plain)
  1620. (const :tag "Radio target matches" radio)
  1621. (const :tag "Tags" tag)
  1622. (const :tag "Timestamps" date)
  1623. (const :tag "Footnotes" footnote)))
  1624. (defcustom org-mark-ring-length 4
  1625. "Number of different positions to be recorded in the ring.
  1626. Changing this requires a restart of Emacs to work correctly."
  1627. :group 'org-link-follow
  1628. :type 'integer)
  1629. (defgroup org-todo nil
  1630. "Options concerning TODO items in Org mode."
  1631. :tag "Org TODO"
  1632. :group 'org)
  1633. (defgroup org-progress nil
  1634. "Options concerning Progress logging in Org mode."
  1635. :tag "Org Progress"
  1636. :group 'org-time)
  1637. (defvar org-todo-interpretation-widgets
  1638. '((:tag "Sequence (cycling hits every state)" sequence)
  1639. (:tag "Type (cycling directly to DONE)" type))
  1640. "The available interpretation symbols for customizing `org-todo-keywords'.
  1641. Interested libraries should add to this list.")
  1642. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1643. "List of TODO entry keyword sequences and their interpretation.
  1644. \\<org-mode-map>This is a list of sequences.
  1645. Each sequence starts with a symbol, either `sequence' or `type',
  1646. indicating if the keywords should be interpreted as a sequence of
  1647. action steps, or as different types of TODO items. The first
  1648. keywords are states requiring action - these states will select a headline
  1649. for inclusion into the global TODO list Org produces. If one of the
  1650. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1651. signify that no further action is necessary. If \"|\" is not found,
  1652. the last keyword is treated as the only DONE state of the sequence.
  1653. The command `\\[org-todo]' cycles an entry through these states, and one
  1654. additional state where no keyword is present. For details about this
  1655. cycling, see the manual.
  1656. TODO keywords and interpretation can also be set on a per-file basis with
  1657. the special #+SEQ_TODO and #+TYP_TODO lines.
  1658. Each keyword can optionally specify a character for fast state selection
  1659. \(in combination with the variable `org-use-fast-todo-selection')
  1660. and specifiers for state change logging, using the same syntax that
  1661. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1662. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1663. indicates to record a time stamp each time this state is selected.
  1664. Each keyword may also specify if a timestamp or a note should be
  1665. recorded when entering or leaving the state, by adding additional
  1666. characters in the parenthesis after the keyword. This looks like this:
  1667. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1668. record only the time of the state change. With X and Y being either
  1669. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1670. Y when leaving the state if and only if the *target* state does not
  1671. define X. You may omit any of the fast-selection key or X or /Y,
  1672. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1673. For backward compatibility, this variable may also be just a list
  1674. of keywords. In this case the interpretation (sequence or type) will be
  1675. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1676. :group 'org-todo
  1677. :group 'org-keywords
  1678. :type '(choice
  1679. (repeat :tag "Old syntax, just keywords"
  1680. (string :tag "Keyword"))
  1681. (repeat :tag "New syntax"
  1682. (cons
  1683. (choice
  1684. :tag "Interpretation"
  1685. ;;Quick and dirty way to see
  1686. ;;`org-todo-interpretation'. This takes the
  1687. ;;place of item arguments
  1688. :convert-widget
  1689. (lambda (widget)
  1690. (widget-put widget
  1691. :args (mapcar
  1692. (lambda (x)
  1693. (widget-convert
  1694. (cons 'const x)))
  1695. org-todo-interpretation-widgets))
  1696. widget))
  1697. (repeat
  1698. (string :tag "Keyword"))))))
  1699. (defvar-local org-todo-keywords-1 nil
  1700. "All TODO and DONE keywords active in a buffer.")
  1701. (defvar org-todo-keywords-for-agenda nil)
  1702. (defvar org-done-keywords-for-agenda nil)
  1703. (defvar org-todo-keyword-alist-for-agenda nil)
  1704. (defvar org-tag-alist-for-agenda nil
  1705. "Alist of all tags from all agenda files.")
  1706. (defvar org-tag-groups-alist-for-agenda nil
  1707. "Alist of all groups tags from all current agenda files.")
  1708. (defvar-local org-tag-groups-alist nil)
  1709. (defvar org-agenda-contributing-files nil)
  1710. (defvar-local org-current-tag-alist nil
  1711. "Alist of all tag groups in current buffer.
  1712. This variable takes into consideration `org-tag-alist',
  1713. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1714. (defvar-local org-not-done-keywords nil)
  1715. (defvar-local org-done-keywords nil)
  1716. (defvar-local org-todo-heads nil)
  1717. (defvar-local org-todo-sets nil)
  1718. (defvar-local org-todo-log-states nil)
  1719. (defvar-local org-todo-kwd-alist nil)
  1720. (defvar-local org-todo-key-alist nil)
  1721. (defvar-local org-todo-key-trigger nil)
  1722. (defcustom org-todo-interpretation 'sequence
  1723. "Controls how TODO keywords are interpreted.
  1724. This variable is in principle obsolete and is only used for
  1725. backward compatibility, if the interpretation of todo keywords is
  1726. not given already in `org-todo-keywords'. See that variable for
  1727. more information."
  1728. :group 'org-todo
  1729. :group 'org-keywords
  1730. :type '(choice (const sequence)
  1731. (const type)))
  1732. (defcustom org-use-fast-todo-selection 'auto
  1733. "\\<org-mode-map>\
  1734. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1735. This variable describes if and under what circumstances the cycling
  1736. mechanism for TODO keywords will be replaced by a single-key, direct
  1737. selection scheme, where the choices are displayed in a little window.
  1738. When nil, fast selection is never used. This means that the command
  1739. will always switch to the next state.
  1740. When it is the symbol `auto', fast selection is whenever selection
  1741. keys have been defined.
  1742. `expert' is like `auto', but no special window with the keyword
  1743. will be shown, choices will only be listed in the prompt.
  1744. In all cases, the special interface is only used if access keys have
  1745. actually been assigned by the user, i.e. if keywords in the configuration
  1746. are followed by a letter in parenthesis, like TODO(t)."
  1747. :group 'org-todo
  1748. :set (lambda (var val)
  1749. (cond
  1750. ((eq var t) (set var 'auto))
  1751. ((eq var 'prefix) (set var nil))
  1752. (t (set var val))))
  1753. :type '(choice
  1754. (const :tag "Never" nil)
  1755. (const :tag "Automatically, when key letter have been defined" auto)
  1756. (const :tag "Automatically, but don't show the selection window" expert)))
  1757. (defcustom org-provide-todo-statistics t
  1758. "Non-nil means update todo statistics after insert and toggle.
  1759. ALL-HEADLINES means update todo statistics by including headlines
  1760. with no TODO keyword as well, counting them as not done.
  1761. A list of TODO keywords means the same, but skip keywords that are
  1762. not in this list.
  1763. When set to a list of two lists, the first list contains keywords
  1764. to consider as TODO keywords, the second list contains keywords
  1765. to consider as DONE keywords.
  1766. When this is set, todo statistics is updated in the parent of the
  1767. current entry each time a todo state is changed."
  1768. :group 'org-todo
  1769. :type '(choice
  1770. (const :tag "Yes, only for TODO entries" t)
  1771. (const :tag "Yes, including all entries" all-headlines)
  1772. (repeat :tag "Yes, for TODOs in this list"
  1773. (string :tag "TODO keyword"))
  1774. (list :tag "Yes, for TODOs and DONEs in these lists"
  1775. (repeat (string :tag "TODO keyword"))
  1776. (repeat (string :tag "DONE keyword")))
  1777. (other :tag "No TODO statistics" nil)))
  1778. (defcustom org-hierarchical-todo-statistics t
  1779. "Non-nil means TODO statistics covers just direct children.
  1780. When nil, all entries in the subtree are considered.
  1781. This has only an effect if `org-provide-todo-statistics' is set.
  1782. To set this to nil for only a single subtree, use a COOKIE_DATA
  1783. property and include the word \"recursive\" into the value."
  1784. :group 'org-todo
  1785. :type 'boolean)
  1786. (defcustom org-after-todo-state-change-hook nil
  1787. "Hook which is run after the state of a TODO item was changed.
  1788. The new state (a string with a TODO keyword, or nil) is available in the
  1789. Lisp variable `org-state'."
  1790. :group 'org-todo
  1791. :type 'hook)
  1792. (defvar org-blocker-hook nil
  1793. "Hook for functions that are allowed to block a state change.
  1794. Functions in this hook should not modify the buffer.
  1795. Each function gets as its single argument a property list,
  1796. see `org-trigger-hook' for more information about this list.
  1797. If any of the functions in this hook returns nil, the state change
  1798. is blocked.")
  1799. (defvar org-trigger-hook nil
  1800. "Hook for functions that are triggered by a state change.
  1801. Each function gets as its single argument a property list with at
  1802. least the following elements:
  1803. (:type type-of-change :position pos-at-entry-start
  1804. :from old-state :to new-state)
  1805. Depending on the type, more properties may be present.
  1806. This mechanism is currently implemented for:
  1807. TODO state changes
  1808. ------------------
  1809. :type todo-state-change
  1810. :from previous state (keyword as a string), or nil, or a symbol
  1811. `todo' or `done', to indicate the general type of state.
  1812. :to new state, like in :from")
  1813. (defcustom org-enforce-todo-dependencies nil
  1814. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1815. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1816. be blocked if any prior sibling is not yet done.
  1817. Finally, if the parent is blocked because of ordered siblings of its own,
  1818. the child will also be blocked."
  1819. :set (lambda (var val)
  1820. (set var val)
  1821. (if val
  1822. (add-hook 'org-blocker-hook
  1823. 'org-block-todo-from-children-or-siblings-or-parent)
  1824. (remove-hook 'org-blocker-hook
  1825. 'org-block-todo-from-children-or-siblings-or-parent)))
  1826. :group 'org-todo
  1827. :type 'boolean)
  1828. (defcustom org-enforce-todo-checkbox-dependencies nil
  1829. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1830. When this is nil, checkboxes have no influence on switching TODO states.
  1831. When non-nil, you first need to check off all check boxes before the TODO
  1832. entry can be switched to DONE.
  1833. This variable needs to be set before org.el is loaded, and you need to
  1834. restart Emacs after a change to make the change effective. The only way
  1835. to change it while Emacs is running is through the customize interface."
  1836. :set (lambda (var val)
  1837. (set var val)
  1838. (if val
  1839. (add-hook 'org-blocker-hook
  1840. 'org-block-todo-from-checkboxes)
  1841. (remove-hook 'org-blocker-hook
  1842. 'org-block-todo-from-checkboxes)))
  1843. :group 'org-todo
  1844. :type 'boolean)
  1845. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1846. "Non-nil means inserting a TODO heading is treated as state change.
  1847. So when the command `\\[org-insert-todo-heading]' is used, state change
  1848. logging will apply if appropriate. When nil, the new TODO item will
  1849. be inserted directly, and no logging will take place."
  1850. :group 'org-todo
  1851. :type 'boolean)
  1852. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1853. "Non-nil means switching TODO states with S-cursor counts as state change.
  1854. This is the default behavior. However, setting this to nil allows a
  1855. convenient way to select a TODO state and bypass any logging associated
  1856. with that."
  1857. :group 'org-todo
  1858. :type 'boolean)
  1859. (defcustom org-todo-state-tags-triggers nil
  1860. "Tag changes that should be triggered by TODO state changes.
  1861. This is a list. Each entry is
  1862. (state-change (tag . flag) .......)
  1863. State-change can be a string with a state, and empty string to indicate the
  1864. state that has no TODO keyword, or it can be one of the symbols `todo'
  1865. or `done', meaning any not-done or done state, respectively."
  1866. :group 'org-todo
  1867. :group 'org-tags
  1868. :type '(repeat
  1869. (cons (choice :tag "When changing to"
  1870. (const :tag "Not-done state" todo)
  1871. (const :tag "Done state" done)
  1872. (string :tag "State"))
  1873. (repeat
  1874. (cons :tag "Tag action"
  1875. (string :tag "Tag")
  1876. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1877. (defcustom org-log-done nil
  1878. "Information to record when a task moves to the DONE state.
  1879. Possible values are:
  1880. nil Don't add anything, just change the keyword
  1881. time Add a time stamp to the task
  1882. note Prompt for a note and add it with template `org-log-note-headings'
  1883. This option can also be set with on a per-file-basis with
  1884. #+STARTUP: nologdone
  1885. #+STARTUP: logdone
  1886. #+STARTUP: lognotedone
  1887. You can have local logging settings for a subtree by setting the LOGGING
  1888. property to one or more of these keywords."
  1889. :group 'org-todo
  1890. :group 'org-progress
  1891. :type '(choice
  1892. (const :tag "No logging" nil)
  1893. (const :tag "Record CLOSED timestamp" time)
  1894. (const :tag "Record CLOSED timestamp with note." note)))
  1895. ;; Normalize old uses of org-log-done.
  1896. (cond
  1897. ((eq org-log-done t) (setq org-log-done 'time))
  1898. ((and (listp org-log-done) (memq 'done org-log-done))
  1899. (setq org-log-done 'note)))
  1900. (defcustom org-log-reschedule nil
  1901. "Information to record when the scheduling date of a task is modified.
  1902. Possible values are:
  1903. nil Don't add anything, just change the date
  1904. time Add a time stamp to the task
  1905. note Prompt for a note and add it with template `org-log-note-headings'
  1906. This option can also be set with on a per-file-basis with
  1907. #+STARTUP: nologreschedule
  1908. #+STARTUP: logreschedule
  1909. #+STARTUP: lognotereschedule
  1910. You can have local logging settings for a subtree by setting the LOGGING
  1911. property to one or more of these keywords.
  1912. This variable has an effect when calling `org-schedule' or
  1913. `org-agenda-schedule' only."
  1914. :group 'org-todo
  1915. :group 'org-progress
  1916. :type '(choice
  1917. (const :tag "No logging" nil)
  1918. (const :tag "Record timestamp" time)
  1919. (const :tag "Record timestamp with note" note)))
  1920. (defcustom org-log-redeadline nil
  1921. "Information to record when the deadline date of a task is modified.
  1922. Possible values are:
  1923. nil Don't add anything, just change the date
  1924. time Add a time stamp to the task
  1925. note Prompt for a note and add it with template `org-log-note-headings'
  1926. This option can also be set with on a per-file-basis with
  1927. #+STARTUP: nologredeadline
  1928. #+STARTUP: logredeadline
  1929. #+STARTUP: lognoteredeadline
  1930. You can have local logging settings for a subtree by setting the LOGGING
  1931. property to one or more of these keywords.
  1932. This variable has an effect when calling `org-deadline' or
  1933. `org-agenda-deadline' only."
  1934. :group 'org-todo
  1935. :group 'org-progress
  1936. :type '(choice
  1937. (const :tag "No logging" nil)
  1938. (const :tag "Record timestamp" time)
  1939. (const :tag "Record timestamp with note." note)))
  1940. (defcustom org-log-note-clock-out nil
  1941. "Non-nil means record a note when clocking out of an item.
  1942. This can also be configured on a per-file basis by adding one of
  1943. the following lines anywhere in the buffer:
  1944. #+STARTUP: lognoteclock-out
  1945. #+STARTUP: nolognoteclock-out"
  1946. :group 'org-todo
  1947. :group 'org-progress
  1948. :type 'boolean)
  1949. (defcustom org-log-done-with-time t
  1950. "Non-nil means the CLOSED time stamp will contain date and time.
  1951. When nil, only the date will be recorded."
  1952. :group 'org-progress
  1953. :type 'boolean)
  1954. (defcustom org-log-note-headings
  1955. '((done . "CLOSING NOTE %t")
  1956. (state . "State %-12s from %-12S %t")
  1957. (note . "Note taken on %t")
  1958. (reschedule . "Rescheduled from %S on %t")
  1959. (delschedule . "Not scheduled, was %S on %t")
  1960. (redeadline . "New deadline from %S on %t")
  1961. (deldeadline . "Removed deadline, was %S on %t")
  1962. (refile . "Refiled on %t")
  1963. (clock-out . ""))
  1964. "Headings for notes added to entries.
  1965. The value is an alist, with the car being a symbol indicating the
  1966. note context, and the cdr is the heading to be used. The heading
  1967. may also be the empty string. The following placeholders can be
  1968. used:
  1969. %t a time stamp.
  1970. %T an active time stamp instead the default inactive one
  1971. %d a short-format time stamp.
  1972. %D an active short-format time stamp.
  1973. %s the new TODO state or time stamp (inactive), in double quotes.
  1974. %S the old TODO state or time stamp (inactive), in double quotes.
  1975. %u the user name.
  1976. %U full user name.
  1977. In fact, it is not a good idea to change the `state' entry,
  1978. because Agenda Log mode depends on the format of these entries."
  1979. :group 'org-todo
  1980. :group 'org-progress
  1981. :type '(list :greedy t
  1982. (cons (const :tag "Heading when closing an item" done) string)
  1983. (cons (const :tag
  1984. "Heading when changing todo state (todo sequence only)"
  1985. state) string)
  1986. (cons (const :tag "Heading when just taking a note" note) string)
  1987. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1988. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1989. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1990. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1991. (cons (const :tag "Heading when refiling" refile) string)
  1992. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1993. (unless (assq 'note org-log-note-headings)
  1994. (push '(note . "%t") org-log-note-headings))
  1995. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1996. (defcustom org-log-into-drawer nil
  1997. "Non-nil means insert state change notes and time stamps into a drawer.
  1998. When nil, state changes notes will be inserted after the headline and
  1999. any scheduling and clock lines, but not inside a drawer.
  2000. The value of this variable should be the name of the drawer to use.
  2001. LOGBOOK is proposed as the default drawer for this purpose, you can
  2002. also set this to a string to define the drawer of your choice.
  2003. A value of t is also allowed, representing \"LOGBOOK\".
  2004. A value of t or nil can also be set with on a per-file-basis with
  2005. #+STARTUP: logdrawer
  2006. #+STARTUP: nologdrawer
  2007. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2008. will be ignored.
  2009. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2010. a subtree.
  2011. Do not check directly this variable in a Lisp program. Call
  2012. function `org-log-into-drawer' instead."
  2013. :group 'org-todo
  2014. :group 'org-progress
  2015. :type '(choice
  2016. (const :tag "Not into a drawer" nil)
  2017. (const :tag "LOGBOOK" t)
  2018. (string :tag "Other")))
  2019. (defun org-log-into-drawer ()
  2020. "Name of the log drawer, as a string, or nil.
  2021. This is the value of `org-log-into-drawer'. However, if the
  2022. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2023. be used instead of the default value."
  2024. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2025. (cond ((equal p "nil") nil)
  2026. ((equal p "t") "LOGBOOK")
  2027. ((stringp p) p)
  2028. (p "LOGBOOK")
  2029. ((stringp org-log-into-drawer) org-log-into-drawer)
  2030. (org-log-into-drawer "LOGBOOK"))))
  2031. (defcustom org-log-state-notes-insert-after-drawers nil
  2032. "Non-nil means insert state change notes after any drawers in entry.
  2033. Only the drawers that *immediately* follow the headline and the
  2034. deadline/scheduled line are skipped.
  2035. When nil, insert notes right after the heading and perhaps the line
  2036. with deadline/scheduling if present.
  2037. This variable will have no effect if `org-log-into-drawer' is
  2038. set."
  2039. :group 'org-todo
  2040. :group 'org-progress
  2041. :type 'boolean)
  2042. (defcustom org-log-states-order-reversed t
  2043. "Non-nil means the latest state note will be directly after heading.
  2044. When nil, the state change notes will be ordered according to time.
  2045. This option can also be set with on a per-file-basis with
  2046. #+STARTUP: logstatesreversed
  2047. #+STARTUP: nologstatesreversed"
  2048. :group 'org-todo
  2049. :group 'org-progress
  2050. :type 'boolean)
  2051. (defcustom org-todo-repeat-to-state nil
  2052. "The TODO state to which a repeater should return the repeating task.
  2053. By default this is the first task of a TODO sequence or the
  2054. previous state of a TYPE_TODO set. But you can specify to use
  2055. the previous state in a TODO sequence or a string.
  2056. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2057. entry, which has precedence over this option."
  2058. :group 'org-todo
  2059. :version "24.1"
  2060. :type '(choice (const :tag "Use the previous TODO state" t)
  2061. (const :tag "Use the head of the TODO sequence" nil)
  2062. (string :tag "Use a specific TODO state")))
  2063. (defcustom org-log-repeat 'time
  2064. "Non-nil means record moving through the DONE state when triggering repeat.
  2065. An auto-repeating task is immediately switched back to TODO when
  2066. marked DONE. If you are not logging state changes (by adding \"@\"
  2067. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2068. record a closing note, there will be no record of the task moving
  2069. through DONE. This variable forces taking a note anyway.
  2070. nil Don't force a record
  2071. time Record a time stamp
  2072. note Prompt for a note and add it with template `org-log-note-headings'
  2073. This option can also be set with on a per-file-basis with
  2074. #+STARTUP: nologrepeat
  2075. #+STARTUP: logrepeat
  2076. #+STARTUP: lognoterepeat
  2077. You can have local logging settings for a subtree by setting the LOGGING
  2078. property to one or more of these keywords."
  2079. :group 'org-todo
  2080. :group 'org-progress
  2081. :type '(choice
  2082. (const :tag "Don't force a record" nil)
  2083. (const :tag "Force recording the DONE state" time)
  2084. (const :tag "Force recording a note with the DONE state" note)))
  2085. (defcustom org-todo-repeat-hook nil
  2086. "Hook that is run after a task has been repeated."
  2087. :package-version '(Org . "9.2")
  2088. :group 'org-todo
  2089. :type 'hook)
  2090. (defgroup org-priorities nil
  2091. "Priorities in Org mode."
  2092. :tag "Org Priorities"
  2093. :group 'org-todo)
  2094. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2095. (defcustom org-priority-enable-commands t
  2096. "Non-nil means priority commands are active.
  2097. When nil, these commands will be disabled, so that you never accidentally
  2098. set a priority."
  2099. :group 'org-priorities
  2100. :type 'boolean)
  2101. (defvaralias 'org-highest-priority 'org-priority-highest)
  2102. (defcustom org-priority-highest ?A
  2103. "The highest priority of TODO items.
  2104. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2105. The default is the character ?A, which is 65 as a numeric value.
  2106. If you set `org-priority-highest' to a numeric value inferior to
  2107. 65, Org assumes you want to use digits for the priority cookie.
  2108. If you set it to >=65, Org assumes you want to use alphabetical
  2109. characters.
  2110. In both cases, the value of `org-priority-highest' must be
  2111. smaller than `org-priority-lowest': for example, if \"A\" is the
  2112. highest priority, it is smaller than the lowest \"C\" priority:
  2113. 65 < 67."
  2114. :group 'org-priorities
  2115. :type '(choice
  2116. (character :tag "Character")
  2117. (integer :tag "Integer (< 65)")))
  2118. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2119. (defcustom org-priority-lowest ?C
  2120. "The lowest priority of TODO items.
  2121. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2122. The default is the character ?C, which is 67 as a numeric value.
  2123. If you set `org-priority-lowest' to a numeric value inferior to
  2124. 65, Org assumes you want to use digits for the priority cookie.
  2125. If you set it to >=65, Org assumes you want to use alphabetical
  2126. characters.
  2127. In both cases, the value of `org-priority-lowest' must be greater
  2128. than `org-priority-highest': for example, if \"C\" is the lowest
  2129. priority, it is greater than the highest \"A\" priority: 67 >
  2130. 65."
  2131. :group 'org-priorities
  2132. :type '(choice
  2133. (character :tag "Character")
  2134. (integer :tag "Integer (< 65)")))
  2135. (defvaralias 'org-default-priority 'org-priority-default)
  2136. (defcustom org-priority-default ?B
  2137. "The default priority of TODO items.
  2138. This is the priority an item gets if no explicit priority is given.
  2139. When starting to cycle on an empty priority the first step in the cycle
  2140. depends on `org-priority-start-cycle-with-default'. The resulting first
  2141. step priority must not exceed the range from `org-priority-highest' to
  2142. `org-priority-lowest' which means that `org-priority-default' has to be
  2143. in this range exclusive or inclusive to the range boundaries. Else the
  2144. first step refuses to set the default and the second will fall back on
  2145. \(depending on the command used) the highest or lowest priority."
  2146. :group 'org-priorities
  2147. :type '(choice
  2148. (character :tag "Character")
  2149. (integer :tag "Integer (< 65)")))
  2150. (defcustom org-priority-start-cycle-with-default t
  2151. "Non-nil means start with default priority when starting to cycle.
  2152. When this is nil, the first step in the cycle will be (depending on the
  2153. command used) one higher or lower than the default priority.
  2154. See also `org-priority-default'."
  2155. :group 'org-priorities
  2156. :type 'boolean)
  2157. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2158. (defcustom org-priority-get-priority-function nil
  2159. "Function to extract the priority from a string.
  2160. The string is normally the headline. If this is nil, Org
  2161. computes the priority from the priority cookie like [#A] in the
  2162. headline. It returns an integer, increasing by 1000 for each
  2163. priority level.
  2164. The user can set a different function here, which should take a
  2165. string as an argument and return the numeric priority."
  2166. :group 'org-priorities
  2167. :version "24.1"
  2168. :type '(choice
  2169. (const nil)
  2170. (function)))
  2171. (defgroup org-time nil
  2172. "Options concerning time stamps and deadlines in Org mode."
  2173. :tag "Org Time"
  2174. :group 'org)
  2175. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2176. "Number of minutes to round time stamps to.
  2177. \\<org-mode-map>\
  2178. These are two values, the first applies when first creating a time stamp.
  2179. The second applies when changing it with the commands `S-up' and `S-down'.
  2180. When changing the time stamp, this means that it will change in steps
  2181. of N minutes, as given by the second value.
  2182. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2183. numbers should be factors of 60, so for example 5, 10, 15.
  2184. When this is larger than 1, you can still force an exact time stamp by using
  2185. a double prefix argument to a time stamp command like \
  2186. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2187. and by using a prefix arg to `S-up/down' to specify the exact number
  2188. of minutes to shift."
  2189. :group 'org-time
  2190. :get (lambda (var) ; Make sure both elements are there
  2191. (if (integerp (default-value var))
  2192. (list (default-value var) 5)
  2193. (default-value var)))
  2194. :type '(list
  2195. (integer :tag "when inserting times")
  2196. (integer :tag "when modifying times")))
  2197. ;; Normalize old customizations of this variable.
  2198. (when (integerp org-time-stamp-rounding-minutes)
  2199. (setq org-time-stamp-rounding-minutes
  2200. (list org-time-stamp-rounding-minutes
  2201. org-time-stamp-rounding-minutes)))
  2202. (defcustom org-display-custom-times nil
  2203. "Non-nil means overlay custom formats over all time stamps.
  2204. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2205. To turn this on on a per-file basis, insert anywhere in the file:
  2206. #+STARTUP: customtime"
  2207. :group 'org-time
  2208. :set 'set-default
  2209. :type 'sexp)
  2210. (make-variable-buffer-local 'org-display-custom-times)
  2211. (defcustom org-time-stamp-custom-formats
  2212. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2213. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2214. These are overlaid over the default ISO format if the variable
  2215. `org-display-custom-times' is set. Time like %H:%M should be at the
  2216. end of the second format. The custom formats are also honored by export
  2217. commands, if custom time display is turned on at the time of export."
  2218. :group 'org-time
  2219. :type 'sexp)
  2220. (defun org-time-stamp-format (&optional long inactive)
  2221. "Get the right format for a time string."
  2222. (let ((f (if long (cdr org-time-stamp-formats)
  2223. (car org-time-stamp-formats))))
  2224. (if inactive
  2225. (concat "[" (substring f 1 -1) "]")
  2226. f)))
  2227. (defcustom org-deadline-warning-days 14
  2228. "Number of days before expiration during which a deadline becomes active.
  2229. This variable governs the display in sparse trees and in the agenda.
  2230. When 0 or negative, it means use this number (the absolute value of it)
  2231. even if a deadline has a different individual lead time specified.
  2232. Custom commands can set this variable in the options section."
  2233. :group 'org-time
  2234. :group 'org-agenda-daily/weekly
  2235. :type 'integer)
  2236. (defcustom org-scheduled-delay-days 0
  2237. "Number of days before a scheduled item becomes active.
  2238. This variable governs the display in sparse trees and in the agenda.
  2239. The default value (i.e. 0) means: don't delay scheduled item.
  2240. When negative, it means use this number (the absolute value of it)
  2241. even if a scheduled item has a different individual delay time
  2242. specified.
  2243. Custom commands can set this variable in the options section."
  2244. :group 'org-time
  2245. :group 'org-agenda-daily/weekly
  2246. :version "24.4"
  2247. :package-version '(Org . "8.0")
  2248. :type 'integer)
  2249. (defcustom org-read-date-prefer-future t
  2250. "Non-nil means assume future for incomplete date input from user.
  2251. This affects the following situations:
  2252. 1. The user gives a month but not a year.
  2253. For example, if it is April and you enter \"feb 2\", this will be read
  2254. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2255. 2. The user gives a day, but no month.
  2256. For example, if today is the 15th, and you enter \"3\", Org will read
  2257. this as the third of *next* month. However, if you enter \"17\",
  2258. it will be considered as *this* month.
  2259. If you set this variable to the symbol `time', then also the following
  2260. will work:
  2261. 3. If the user gives a time.
  2262. If the time is before now, it will be interpreted as tomorrow.
  2263. Currently none of this works for ISO week specifications.
  2264. When this option is nil, the current day, month and year will always be
  2265. used as defaults.
  2266. See also `org-agenda-jump-prefer-future'."
  2267. :group 'org-time
  2268. :type '(choice
  2269. (const :tag "Never" nil)
  2270. (const :tag "Check month and day" t)
  2271. (const :tag "Check month, day, and time" time)))
  2272. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2273. "Should the agenda jump command prefer the future for incomplete dates?
  2274. The default is to do the same as configured in `org-read-date-prefer-future'.
  2275. But you can also set a deviating value here.
  2276. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2277. :group 'org-agenda
  2278. :group 'org-time
  2279. :version "24.1"
  2280. :type '(choice
  2281. (const :tag "Use org-read-date-prefer-future"
  2282. org-read-date-prefer-future)
  2283. (const :tag "Never" nil)
  2284. (const :tag "Always" t)))
  2285. (defcustom org-read-date-force-compatible-dates t
  2286. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2287. Depending on the system Emacs is running on, certain dates cannot
  2288. be represented with the type used internally to represent time.
  2289. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2290. correctly. Some systems allow for earlier dates, some for later,
  2291. some for both. One way to find out is to insert any date into an
  2292. Org buffer, putting the cursor on the year and hitting S-up and
  2293. S-down to test the range.
  2294. When this variable is set to t, the date/time prompt will not let
  2295. you specify dates outside the 1970-2037 range, so it is certain that
  2296. these dates will work in whatever version of Emacs you are
  2297. running, and also that you can move a file from one Emacs implementation
  2298. to another. Whenever Org is forcing the year for you, it will display
  2299. a message and beep.
  2300. When this variable is nil, Org will check if the date is
  2301. representable in the specific Emacs implementation you are using.
  2302. If not, it will force a year, usually the current year, and beep
  2303. to remind you. Currently this setting is not recommended because
  2304. the likelihood that you will open your Org files in an Emacs that
  2305. has limited date range is not negligible.
  2306. A workaround for this problem is to use diary sexp dates for time
  2307. stamps outside of this range."
  2308. :group 'org-time
  2309. :version "24.1"
  2310. :type 'boolean)
  2311. (defcustom org-read-date-display-live t
  2312. "Non-nil means display current interpretation of date prompt live.
  2313. This display will be in an overlay, in the minibuffer. Note that
  2314. live display is only active when `org-read-date-popup-calendar'
  2315. is non-nil."
  2316. :group 'org-time
  2317. :type 'boolean)
  2318. (defvaralias 'org-popup-calendar-for-date-prompt
  2319. 'org-read-date-popup-calendar)
  2320. (defcustom org-read-date-popup-calendar t
  2321. "Non-nil means pop up a calendar when prompting for a date.
  2322. In the calendar, the date can be selected with mouse-1. However, the
  2323. minibuffer will also be active, and you can simply enter the date as well.
  2324. When nil, only the minibuffer will be available."
  2325. :group 'org-time
  2326. :type 'boolean)
  2327. (defcustom org-extend-today-until 0
  2328. "The hour when your day really ends. Must be an integer.
  2329. This has influence for the following applications:
  2330. - When switching the agenda to \"today\". If it is still earlier than
  2331. the time given here, the day recognized as TODAY is actually yesterday.
  2332. - When a date is read from the user and it is still before the time given
  2333. here, the current date and time will be assumed to be yesterday, 23:59.
  2334. Also, timestamps inserted in capture templates follow this rule.
  2335. IMPORTANT: This is a feature whose implementation is and likely will
  2336. remain incomplete. Really, it is only here because past midnight seems to
  2337. be the favorite working time of John Wiegley :-)"
  2338. :group 'org-time
  2339. :type 'integer)
  2340. (defcustom org-use-effective-time nil
  2341. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2342. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2343. \"effective time\" of any timestamps between midnight and 8am will be
  2344. 23:59 of the previous day."
  2345. :group 'org-time
  2346. :version "24.1"
  2347. :type 'boolean)
  2348. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2349. "When non-nil, use the last clock out time for `org-todo'.
  2350. Note that this option has precedence over the combined use of
  2351. `org-use-effective-time' and `org-extend-today-until'."
  2352. :group 'org-time
  2353. :version "24.4"
  2354. :package-version '(Org . "8.0")
  2355. :type 'boolean)
  2356. (defcustom org-edit-timestamp-down-means-later nil
  2357. "Non-nil means S-down will increase the time in a time stamp.
  2358. When nil, S-up will increase."
  2359. :group 'org-time
  2360. :type 'boolean)
  2361. (defcustom org-calendar-follow-timestamp-change t
  2362. "Non-nil means make the calendar window follow timestamp changes.
  2363. When a timestamp is modified and the calendar window is visible, it will be
  2364. moved to the new date."
  2365. :group 'org-time
  2366. :type 'boolean)
  2367. (defgroup org-tags nil
  2368. "Options concerning tags in Org mode."
  2369. :tag "Org Tags"
  2370. :group 'org)
  2371. (defcustom org-tag-alist nil
  2372. "Default tags available in Org files.
  2373. The value of this variable is an alist. Associations either:
  2374. (TAG)
  2375. (TAG . SELECT)
  2376. (SPECIAL)
  2377. where TAG is a tag as a string, SELECT is character, used to
  2378. select that tag through the fast tag selection interface, and
  2379. SPECIAL is one of the following keywords: `:startgroup',
  2380. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2381. `:newline'. These keywords are used to define a hierarchy of
  2382. tags. See manual for details.
  2383. When this variable is nil, Org mode bases tag input on what is
  2384. already in the buffer. The value can be overridden locally by
  2385. using a TAGS keyword, e.g.,
  2386. #+TAGS: tag1 tag2
  2387. See also `org-tag-persistent-alist' to sidestep this behavior."
  2388. :group 'org-tags
  2389. :type '(repeat
  2390. (choice
  2391. (cons :tag "Tag with key"
  2392. (string :tag "Tag name")
  2393. (character :tag "Access char"))
  2394. (list :tag "Tag" (string :tag "Tag name"))
  2395. (const :tag "Start radio group" (:startgroup))
  2396. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2397. (const :tag "Group tags delimiter" (:grouptags))
  2398. (const :tag "End radio group" (:endgroup))
  2399. (const :tag "End tag group, non distinct" (:endgrouptag))
  2400. (const :tag "New line" (:newline)))))
  2401. (defcustom org-tag-persistent-alist nil
  2402. "Tags always available in Org files.
  2403. The value of this variable is an alist. Associations either:
  2404. (TAG)
  2405. (TAG . SELECT)
  2406. (SPECIAL)
  2407. where TAG is a tag as a string, SELECT is a character, used to
  2408. select that tag through the fast tag selection interface, and
  2409. SPECIAL is one of the following keywords: `:startgroup',
  2410. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2411. `:newline'. These keywords are used to define a hierarchy of
  2412. tags. See manual for details.
  2413. Unlike to `org-tag-alist', tags defined in this variable do not
  2414. depend on a local TAGS keyword. Instead, to disable these tags
  2415. on a per-file basis, insert anywhere in the file:
  2416. #+STARTUP: noptag"
  2417. :group 'org-tags
  2418. :type '(repeat
  2419. (choice
  2420. (cons :tag "Tag with key"
  2421. (string :tag "Tag name")
  2422. (character :tag "Access char"))
  2423. (list :tag "Tag" (string :tag "Tag name"))
  2424. (const :tag "Start radio group" (:startgroup))
  2425. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2426. (const :tag "Group tags delimiter" (:grouptags))
  2427. (const :tag "End radio group" (:endgroup))
  2428. (const :tag "End tag group, non distinct" (:endgrouptag))
  2429. (const :tag "New line" (:newline)))))
  2430. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2431. "If non-nil, always offer completion for all tags of all agenda files.
  2432. Setting this variable locally allows for dynamic generation of tag
  2433. completions in capture buffers.
  2434. (add-hook \\='org-capture-mode-hook
  2435. (lambda ()
  2436. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2437. :group 'org-tags
  2438. :version "24.1"
  2439. :type 'boolean)
  2440. (defvar org-file-tags nil
  2441. "List of tags that can be inherited by all entries in the file.
  2442. The tags will be inherited if the variable `org-use-tag-inheritance'
  2443. says they should be.
  2444. This variable is populated from #+FILETAGS lines.")
  2445. (defcustom org-use-fast-tag-selection 'auto
  2446. "Non-nil means use fast tag selection scheme.
  2447. This is a special interface to select and deselect tags with single keys.
  2448. When nil, fast selection is never used.
  2449. When the symbol `auto', fast selection is used if and only if selection
  2450. characters for tags have been configured, either through the variable
  2451. `org-tag-alist' or through a #+TAGS line in the buffer.
  2452. When t, fast selection is always used and selection keys are assigned
  2453. automatically if necessary."
  2454. :group 'org-tags
  2455. :type '(choice
  2456. (const :tag "Always" t)
  2457. (const :tag "Never" nil)
  2458. (const :tag "When selection characters are configured" auto)))
  2459. (defcustom org-fast-tag-selection-single-key nil
  2460. "Non-nil means fast tag selection exits after first change.
  2461. When nil, you have to press RET to exit it.
  2462. During fast tag selection, you can toggle this flag with `C-c'.
  2463. This variable can also have the value `expert'. In this case, the window
  2464. displaying the tags menu is not even shown, until you press `C-c' again."
  2465. :group 'org-tags
  2466. :type '(choice
  2467. (const :tag "No" nil)
  2468. (const :tag "Yes" t)
  2469. (const :tag "Expert" expert)))
  2470. (defvar org-fast-tag-selection-include-todo nil
  2471. "Non-nil means fast tags selection interface will also offer TODO states.
  2472. This is an undocumented feature, you should not rely on it.")
  2473. (defcustom org-tags-column -77
  2474. "The column to which tags should be indented in a headline.
  2475. If this number is positive, it specifies the column. If it is negative,
  2476. it means that the tags should be flushright to that column. For example,
  2477. -80 works well for a normal 80 character screen.
  2478. When 0, place tags directly after headline text, with only one space in
  2479. between."
  2480. :group 'org-tags
  2481. :type 'integer)
  2482. (defcustom org-auto-align-tags t
  2483. "Non-nil keeps tags aligned when modifying headlines.
  2484. Some operations (i.e. demoting) change the length of a headline and
  2485. therefore shift the tags around. With this option turned on, after
  2486. each such operation the tags are again aligned to `org-tags-column'."
  2487. :group 'org-tags
  2488. :type 'boolean)
  2489. (defcustom org-use-tag-inheritance t
  2490. "Non-nil means tags in levels apply also for sublevels.
  2491. When nil, only the tags directly given in a specific line apply there.
  2492. This may also be a list of tags that should be inherited, or a regexp that
  2493. matches tags that should be inherited. Additional control is possible
  2494. with the variable `org-tags-exclude-from-inheritance' which gives an
  2495. explicit list of tags to be excluded from inheritance, even if the value of
  2496. `org-use-tag-inheritance' would select it for inheritance.
  2497. If this option is t, a match early-on in a tree can lead to a large
  2498. number of matches in the subtree when constructing the agenda or creating
  2499. a sparse tree. If you only want to see the first match in a tree during
  2500. a search, check out the variable `org-tags-match-list-sublevels'."
  2501. :group 'org-tags
  2502. :type '(choice
  2503. (const :tag "Not" nil)
  2504. (const :tag "Always" t)
  2505. (repeat :tag "Specific tags" (string :tag "Tag"))
  2506. (regexp :tag "Tags matched by regexp")))
  2507. (defcustom org-tags-exclude-from-inheritance nil
  2508. "List of tags that should never be inherited.
  2509. This is a way to exclude a few tags from inheritance. For way to do
  2510. the opposite, to actively allow inheritance for selected tags,
  2511. see the variable `org-use-tag-inheritance'."
  2512. :group 'org-tags
  2513. :type '(repeat (string :tag "Tag")))
  2514. (defun org-tag-inherit-p (tag)
  2515. "Check if TAG is one that should be inherited."
  2516. (cond
  2517. ((member tag org-tags-exclude-from-inheritance) nil)
  2518. ((eq org-use-tag-inheritance t) t)
  2519. ((not org-use-tag-inheritance) nil)
  2520. ((stringp org-use-tag-inheritance)
  2521. (string-match org-use-tag-inheritance tag))
  2522. ((listp org-use-tag-inheritance)
  2523. (member tag org-use-tag-inheritance))
  2524. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2525. (defcustom org-tags-match-list-sublevels t
  2526. "Non-nil means list also sublevels of headlines matching a search.
  2527. This variable applies to tags/property searches, and also to stuck
  2528. projects because this search is based on a tags match as well.
  2529. When set to the symbol `indented', sublevels are indented with
  2530. leading dots.
  2531. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2532. the sublevels of a headline matching a tag search often also match
  2533. the same search. Listing all of them can create very long lists.
  2534. Setting this variable to nil causes subtrees of a match to be skipped.
  2535. This variable is semi-obsolete and probably should always be true. It
  2536. is better to limit inheritance to certain tags using the variables
  2537. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2538. :group 'org-tags
  2539. :type '(choice
  2540. (const :tag "No, don't list them" nil)
  2541. (const :tag "Yes, do list them" t)
  2542. (const :tag "List them, indented with leading dots" indented)))
  2543. (defcustom org-tags-sort-function nil
  2544. "When set, tags are sorted using this function as a comparator."
  2545. :group 'org-tags
  2546. :type '(choice
  2547. (const :tag "No sorting" nil)
  2548. (const :tag "Alphabetical" org-string-collate-lessp)
  2549. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2550. (function :tag "Custom function" nil)))
  2551. (defvar org-tags-history nil
  2552. "History of minibuffer reads for tags.")
  2553. (defvar org-last-tags-completion-table nil
  2554. "The last used completion table for tags.")
  2555. (defvar org-after-tags-change-hook nil
  2556. "Hook that is run after the tags in a line have changed.")
  2557. (defgroup org-properties nil
  2558. "Options concerning properties in Org mode."
  2559. :tag "Org Properties"
  2560. :group 'org)
  2561. (defcustom org-property-format "%-10s %s"
  2562. "How property key/value pairs should be formatted by `indent-line'.
  2563. When `indent-line' hits a property definition, it will format the line
  2564. according to this format, mainly to make sure that the values are
  2565. lined-up with respect to each other."
  2566. :group 'org-properties
  2567. :type 'string)
  2568. (defcustom org-properties-postprocess-alist nil
  2569. "Alist of properties and functions to adjust inserted values.
  2570. Elements of this alist must be of the form
  2571. ([string] [function])
  2572. where [string] must be a property name and [function] must be a
  2573. lambda expression: this lambda expression must take one argument,
  2574. the value to adjust, and return the new value as a string.
  2575. For example, this element will allow the property \"Remaining\"
  2576. to be updated wrt the relation between the \"Effort\" property
  2577. and the clock summary:
  2578. ((\"Remaining\" (lambda(value)
  2579. (let ((clocksum (org-clock-sum-current-item))
  2580. (effort (org-duration-to-minutes
  2581. (org-entry-get (point) \"Effort\"))))
  2582. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2583. :group 'org-properties
  2584. :version "24.1"
  2585. :type '(alist :key-type (string :tag "Property")
  2586. :value-type (function :tag "Function")))
  2587. (defcustom org-use-property-inheritance nil
  2588. "Non-nil means properties apply also for sublevels.
  2589. This setting is chiefly used during property searches. Turning it on can
  2590. cause significant overhead when doing a search, which is why it is not
  2591. on by default.
  2592. When nil, only the properties directly given in the current entry count.
  2593. When t, every property is inherited. The value may also be a list of
  2594. properties that should have inheritance, or a regular expression matching
  2595. properties that should be inherited.
  2596. However, note that some special properties use inheritance under special
  2597. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2598. and the properties ending in \"_ALL\" when they are used as descriptor
  2599. for valid values of a property.
  2600. Note for programmers:
  2601. When querying an entry with `org-entry-get', you can control if inheritance
  2602. should be used. By default, `org-entry-get' looks only at the local
  2603. properties. You can request inheritance by setting the inherit argument
  2604. to t (to force inheritance) or to `selective' (to respect the setting
  2605. in this variable)."
  2606. :group 'org-properties
  2607. :type '(choice
  2608. (const :tag "Not" nil)
  2609. (const :tag "Always" t)
  2610. (repeat :tag "Specific properties" (string :tag "Property"))
  2611. (regexp :tag "Properties matched by regexp")))
  2612. (defun org-property-inherit-p (property)
  2613. "Return a non-nil value if PROPERTY should be inherited."
  2614. (cond
  2615. ((eq org-use-property-inheritance t) t)
  2616. ((not org-use-property-inheritance) nil)
  2617. ((stringp org-use-property-inheritance)
  2618. (string-match org-use-property-inheritance property))
  2619. ((listp org-use-property-inheritance)
  2620. (member-ignore-case property org-use-property-inheritance))
  2621. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2622. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2623. "The default column format, if no other format has been defined.
  2624. This variable can be set on the per-file basis by inserting a line
  2625. #+COLUMNS: %25ITEM ....."
  2626. :group 'org-properties
  2627. :type 'string)
  2628. (defcustom org-columns-default-format-for-agenda nil
  2629. "The default column format in an agenda buffer.
  2630. This will be used for column view in the agenda unless a format has
  2631. been set by adding `org-overriding-columns-format' to the local
  2632. settings list of a custom agenda view. When nil, the columns format
  2633. for the first item in the agenda list will be used, or as a fall-back,
  2634. `org-columns-default-format'."
  2635. :group 'org-properties
  2636. :type '(choice
  2637. (const :tag "No default" nil)
  2638. (string :tag "Format string")))
  2639. (defcustom org-columns-ellipses ".."
  2640. "The ellipses to be used when a field in column view is truncated.
  2641. When this is the empty string, as many characters as possible are shown,
  2642. but then there will be no visual indication that the field has been truncated.
  2643. When this is a string of length N, the last N characters of a truncated
  2644. field are replaced by this string. If the column is narrower than the
  2645. ellipses string, only part of the ellipses string will be shown."
  2646. :group 'org-properties
  2647. :type 'string)
  2648. (defconst org-global-properties-fixed
  2649. '(("VISIBILITY_ALL" . "folded children content all")
  2650. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2651. "List of property/value pairs that can be inherited by any entry.
  2652. These are fixed values, for the preset properties. The user variable
  2653. that can be used to add to this list is `org-global-properties'.
  2654. The entries in this list are cons cells where the car is a property
  2655. name and cdr is a string with the value. If the value represents
  2656. multiple items like an \"_ALL\" property, separate the items by
  2657. spaces.")
  2658. (defcustom org-global-properties nil
  2659. "List of property/value pairs that can be inherited by any entry.
  2660. This list will be combined with the constant `org-global-properties-fixed'.
  2661. The entries in this list are cons cells where the car is a property
  2662. name and cdr is a string with the value.
  2663. Buffer local properties are added either by a document property drawer
  2664. :PROPERTIES:
  2665. :NAME: VALUE
  2666. :END:
  2667. or by adding lines like
  2668. #+PROPERTY: NAME VALUE"
  2669. :group 'org-properties
  2670. :type '(repeat
  2671. (cons (string :tag "Property")
  2672. (string :tag "Value"))))
  2673. (defvar-local org-keyword-properties nil
  2674. "List of property/value pairs inherited by any entry.
  2675. Valid for the current buffer. This variable is populated from
  2676. PROPERTY keywords.
  2677. Note that properties are defined also in property drawers.
  2678. Properties defined there take precedence over properties defined
  2679. as keywords.")
  2680. (defgroup org-agenda nil
  2681. "Options concerning agenda views in Org mode."
  2682. :tag "Org Agenda"
  2683. :group 'org)
  2684. (defvar-local org-category nil
  2685. "Variable used by Org files to set a category for agenda display.
  2686. There are multiple ways to set the category. One way is to set
  2687. it in the document property drawer. For example:
  2688. :PROPERTIES:
  2689. :CATEGORY: ELisp
  2690. :END:
  2691. Other ways to define it is as an Emacs file variable, for example
  2692. # -*- mode: org; org-category: \"ELisp\"
  2693. or for the file to contain a special line:
  2694. #+CATEGORY: ELisp
  2695. If the file does not specify a category, then file's base name
  2696. is used instead.")
  2697. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2698. (defcustom org-agenda-files nil
  2699. "The files to be used for agenda display.
  2700. If an entry is a directory, all files in that directory that are matched
  2701. by `org-agenda-file-regexp' will be part of the file list.
  2702. If the value of the variable is not a list but a single file name, then
  2703. the list of agenda files is actually stored and maintained in that file,
  2704. one agenda file per line. In this file paths can be given relative to
  2705. `org-directory'. Tilde expansion and environment variable substitution
  2706. are also made.
  2707. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2708. and removed with `\\[org-remove-file]'."
  2709. :group 'org-agenda
  2710. :type '(choice
  2711. (repeat :tag "List of files and directories" file)
  2712. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2713. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2714. "Regular expression to match files for `org-agenda-files'.
  2715. If any element in the list in that variable contains a directory instead
  2716. of a normal file, all files in that directory that are matched by this
  2717. regular expression will be included."
  2718. :group 'org-agenda
  2719. :type 'regexp)
  2720. (defvaralias 'org-agenda-multi-occur-extra-files
  2721. 'org-agenda-text-search-extra-files)
  2722. (defcustom org-agenda-text-search-extra-files nil
  2723. "List of extra files to be searched by text search commands.
  2724. These files will be searched in addition to the agenda files by the
  2725. commands `org-search-view' (`\\[org-agenda] s') \
  2726. and `org-occur-in-agenda-files'.
  2727. Note that these files will only be searched for text search commands,
  2728. not for the other agenda views like todo lists, tag searches or the weekly
  2729. agenda. This variable is intended to list notes and possibly archive files
  2730. that should also be searched by these two commands.
  2731. In fact, if the first element in the list is the symbol `agenda-archives',
  2732. then all archive files of all agenda files will be added to the search
  2733. scope."
  2734. :group 'org-agenda
  2735. :type '(set :greedy t
  2736. (const :tag "Agenda Archives" agenda-archives)
  2737. (repeat :inline t (file))))
  2738. (defcustom org-agenda-skip-unavailable-files nil
  2739. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2740. A nil value means to remove them, after a query, from the list."
  2741. :group 'org-agenda
  2742. :type 'boolean)
  2743. (defgroup org-latex nil
  2744. "Options for embedding LaTeX code into Org mode."
  2745. :tag "Org LaTeX"
  2746. :group 'org)
  2747. (defcustom org-format-latex-options
  2748. '(:foreground default :background default :scale 1.0
  2749. :html-foreground "Black" :html-background "Transparent"
  2750. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2751. "Options for creating images from LaTeX fragments.
  2752. This is a property list with the following properties:
  2753. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2754. `default' means use the foreground of the default face.
  2755. `auto' means use the foreground from the text face.
  2756. :background the background color, or \"Transparent\".
  2757. `default' means use the background of the default face.
  2758. `auto' means use the background from the text face.
  2759. :scale a scaling factor for the size of the images, to get more pixels
  2760. :html-foreground, :html-background, :html-scale
  2761. the same numbers for HTML export.
  2762. :matchers a list indicating which matchers should be used to
  2763. find LaTeX fragments. Valid members of this list are:
  2764. \"begin\" find environments
  2765. \"$1\" find single characters surrounded by $.$
  2766. \"$\" find math expressions surrounded by $...$
  2767. \"$$\" find math expressions surrounded by $$....$$
  2768. \"\\(\" find math expressions surrounded by \\(...\\)
  2769. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2770. :group 'org-latex
  2771. :type 'plist)
  2772. (defcustom org-format-latex-signal-error t
  2773. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2774. When nil, just push out a message."
  2775. :group 'org-latex
  2776. :version "24.1"
  2777. :type 'boolean)
  2778. (defcustom org-latex-to-mathml-jar-file nil
  2779. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2780. Use this to specify additional executable file say a jar file.
  2781. When using MathToWeb as the converter, specify the full-path to
  2782. your mathtoweb.jar file."
  2783. :group 'org-latex
  2784. :version "24.1"
  2785. :type '(choice
  2786. (const :tag "None" nil)
  2787. (file :tag "JAR file" :must-match t)))
  2788. (defcustom org-latex-to-mathml-convert-command nil
  2789. "Command to convert LaTeX fragments to MathML.
  2790. Replace format-specifiers in the command as noted below and use
  2791. `shell-command' to convert LaTeX to MathML.
  2792. %j: Executable file in fully expanded form as specified by
  2793. `org-latex-to-mathml-jar-file'.
  2794. %I: Input LaTeX file in fully expanded form.
  2795. %i: The latex fragment to be converted.
  2796. %o: Output MathML file.
  2797. This command is used by `org-create-math-formula'.
  2798. When using MathToWeb as the converter, set this option to
  2799. \"java -jar %j -unicode -force -df %o %I\".
  2800. When using LaTeXML set this option to
  2801. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2802. :group 'org-latex
  2803. :version "24.1"
  2804. :type '(choice
  2805. (const :tag "None" nil)
  2806. (string :tag "\nShell command")))
  2807. (defcustom org-latex-to-html-convert-command nil
  2808. "Command to convert LaTeX fragments to HTML.
  2809. This command is very open-ended: the output of the command will
  2810. directly replace the LaTeX fragment in the resulting HTML.
  2811. Replace format-specifiers in the command as noted below and use
  2812. `shell-command' to convert LaTeX to HTML.
  2813. %i: The LaTeX fragment to be converted.
  2814. For example, this could be used with LaTeXML as
  2815. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2816. :group 'org-latex
  2817. :package-version '(Org . "9.4")
  2818. :type '(choice
  2819. (const :tag "None" nil)
  2820. (string :tag "Shell command")))
  2821. (defcustom org-preview-latex-default-process 'dvipng
  2822. "The default process to convert LaTeX fragments to image files.
  2823. All available processes and theirs documents can be found in
  2824. `org-preview-latex-process-alist', which see."
  2825. :group 'org-latex
  2826. :version "26.1"
  2827. :package-version '(Org . "9.0")
  2828. :type 'symbol)
  2829. (defcustom org-preview-latex-process-alist
  2830. '((dvipng
  2831. :programs ("latex" "dvipng")
  2832. :description "dvi > png"
  2833. :message "you need to install the programs: latex and dvipng."
  2834. :image-input-type "dvi"
  2835. :image-output-type "png"
  2836. :image-size-adjust (1.0 . 1.0)
  2837. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2838. :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2839. (dvisvgm
  2840. :programs ("latex" "dvisvgm")
  2841. :description "dvi > svg"
  2842. :message "you need to install the programs: latex and dvisvgm."
  2843. :image-input-type "dvi"
  2844. :image-output-type "svg"
  2845. :image-size-adjust (1.7 . 1.5)
  2846. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2847. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2848. (imagemagick
  2849. :programs ("latex" "convert")
  2850. :description "pdf > png"
  2851. :message "you need to install the programs: latex and imagemagick."
  2852. :image-input-type "pdf"
  2853. :image-output-type "png"
  2854. :image-size-adjust (1.0 . 1.0)
  2855. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2856. :image-converter
  2857. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2858. "Definitions of external processes for LaTeX previewing.
  2859. Org mode can use some external commands to generate TeX snippet's images for
  2860. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2861. `org-create-formula-image' how to call them.
  2862. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2863. PROPERTIES accepts the following attributes:
  2864. :programs list of strings, required programs.
  2865. :description string, describe the process.
  2866. :message string, message it when required programs cannot be found.
  2867. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2868. :image-output-type string, output file type of image converter (e.g., \"png\").
  2869. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2870. image size showed in buffer and the cdr element is for
  2871. HTML file. This option is only useful for process
  2872. developers, users should use variable
  2873. `org-format-latex-options' instead.
  2874. :post-clean list of strings, files matched are to be cleaned up once
  2875. the image is generated. When nil, the files with \".dvi\",
  2876. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2877. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2878. be cleaned up.
  2879. :latex-header list of strings, the LaTeX header of the snippet file.
  2880. When nil, the fallback value is used instead, which is
  2881. controlled by `org-format-latex-header',
  2882. `org-latex-default-packages-alist' and
  2883. `org-latex-packages-alist', which see.
  2884. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2885. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2886. replaced with values defined below.
  2887. :image-converter list of image converter commands strings. Each of them is
  2888. given to the shell and supports any of the following
  2889. place-holders defined below.
  2890. Place-holders used by `:image-converter' and `:latex-compiler':
  2891. %f input file name
  2892. %b base name of input file
  2893. %o base directory of input file
  2894. %O absolute output file name
  2895. Place-holders only used by `:image-converter':
  2896. %D dpi, which is used to adjust image size by some processing commands.
  2897. %S the image size scale ratio, which is used to adjust image size by some
  2898. processing commands."
  2899. :group 'org-latex
  2900. :version "26.1"
  2901. :package-version '(Org . "9.0")
  2902. :type '(alist :tag "LaTeX to image backends"
  2903. :value-type (plist)))
  2904. (defcustom org-preview-latex-image-directory "ltximg/"
  2905. "Path to store latex preview images.
  2906. A relative path here creates many directories relative to the
  2907. processed Org files paths. An absolute path puts all preview
  2908. images at the same place."
  2909. :group 'org-latex
  2910. :version "26.1"
  2911. :package-version '(Org . "9.0")
  2912. :type 'string)
  2913. (defun org-format-latex-mathml-available-p ()
  2914. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2915. (save-match-data
  2916. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2917. org-latex-to-mathml-convert-command)
  2918. (let ((executable (car (split-string
  2919. org-latex-to-mathml-convert-command))))
  2920. (when (executable-find executable)
  2921. (if (string-match
  2922. "%j" org-latex-to-mathml-convert-command)
  2923. (file-readable-p org-latex-to-mathml-jar-file)
  2924. t))))))
  2925. (defcustom org-format-latex-header "\\documentclass{article}
  2926. \\usepackage[usenames]{color}
  2927. \[PACKAGES]
  2928. \[DEFAULT-PACKAGES]
  2929. \\pagestyle{empty} % do not remove
  2930. % The settings below are copied from fullpage.sty
  2931. \\setlength{\\textwidth}{\\paperwidth}
  2932. \\addtolength{\\textwidth}{-3cm}
  2933. \\setlength{\\oddsidemargin}{1.5cm}
  2934. \\addtolength{\\oddsidemargin}{-2.54cm}
  2935. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2936. \\setlength{\\textheight}{\\paperheight}
  2937. \\addtolength{\\textheight}{-\\headheight}
  2938. \\addtolength{\\textheight}{-\\headsep}
  2939. \\addtolength{\\textheight}{-\\footskip}
  2940. \\addtolength{\\textheight}{-3cm}
  2941. \\setlength{\\topmargin}{1.5cm}
  2942. \\addtolength{\\topmargin}{-2.54cm}"
  2943. "The document header used for processing LaTeX fragments.
  2944. It is imperative that this header make sure that no page number
  2945. appears on the page. The package defined in the variables
  2946. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2947. will either replace the placeholder \"[PACKAGES]\" in this
  2948. header, or they will be appended."
  2949. :group 'org-latex
  2950. :type 'string)
  2951. (defun org-set-packages-alist (var val)
  2952. "Set the packages alist and make sure it has 3 elements per entry."
  2953. (set var (mapcar (lambda (x)
  2954. (if (and (consp x) (= (length x) 2))
  2955. (list (car x) (nth 1 x) t)
  2956. x))
  2957. val)))
  2958. (defun org-get-packages-alist (var)
  2959. "Get the packages alist and make sure it has 3 elements per entry."
  2960. (mapcar (lambda (x)
  2961. (if (and (consp x) (= (length x) 2))
  2962. (list (car x) (nth 1 x) t)
  2963. x))
  2964. (default-value var)))
  2965. (defcustom org-latex-default-packages-alist
  2966. '(("AUTO" "inputenc" t ("pdflatex"))
  2967. ("T1" "fontenc" t ("pdflatex"))
  2968. ("" "graphicx" t)
  2969. ("" "longtable" nil)
  2970. ("" "wrapfig" nil)
  2971. ("" "rotating" nil)
  2972. ("normalem" "ulem" t)
  2973. ("" "amsmath" t)
  2974. ("" "amssymb" t)
  2975. ("" "capt-of" nil)
  2976. ("" "hyperref" nil))
  2977. "Alist of default packages to be inserted in the header.
  2978. Change this only if one of the packages here causes an
  2979. incompatibility with another package you are using.
  2980. The packages in this list are needed by one part or another of
  2981. Org mode to function properly:
  2982. - inputenc, fontenc: for basic font and character selection
  2983. - graphicx: for including images
  2984. - longtable: For multipage tables
  2985. - wrapfig: for figure placement
  2986. - rotating: for sideways figures and tables
  2987. - ulem: for underline and strike-through
  2988. - amsmath: for subscript and superscript and math environments
  2989. - amssymb: for various symbols used for interpreting the entities
  2990. in `org-entities'. You can skip some of this package if you don't
  2991. use any of the symbols.
  2992. - capt-of: for captions outside of floats
  2993. - hyperref: for cross references
  2994. Therefore you should not modify this variable unless you know
  2995. what you are doing. The one reason to change it anyway is that
  2996. you might be loading some other package that conflicts with one
  2997. of the default packages. Each element is either a cell or
  2998. a string.
  2999. A cell is of the format
  3000. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3001. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3002. when compiling LaTeX snippets into images for inclusion into
  3003. non-LaTeX output.
  3004. COMPILERS is a list of compilers that should include the package,
  3005. see `org-latex-compiler'. If the document compiler is not in the
  3006. list, and the list is non-nil, the package will not be inserted
  3007. in the final document.
  3008. A string will be inserted as-is in the header of the document."
  3009. :group 'org-latex
  3010. :group 'org-export-latex
  3011. :set 'org-set-packages-alist
  3012. :get 'org-get-packages-alist
  3013. :version "26.1"
  3014. :package-version '(Org . "8.3")
  3015. :type '(repeat
  3016. (choice
  3017. (list :tag "options/package pair"
  3018. (string :tag "options")
  3019. (string :tag "package")
  3020. (boolean :tag "Snippet")
  3021. (choice
  3022. (const :tag "For all compilers" nil)
  3023. (repeat :tag "Allowed compiler" string)))
  3024. (string :tag "A line of LaTeX"))))
  3025. (defcustom org-latex-packages-alist nil
  3026. "Alist of packages to be inserted in every LaTeX header.
  3027. These will be inserted after `org-latex-default-packages-alist'.
  3028. Each element is either a cell or a string.
  3029. A cell is of the format:
  3030. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3031. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3032. needed when turning LaTeX snippets into images for inclusion into
  3033. non-LaTeX output.
  3034. COMPILERS is a list of compilers that should include the package,
  3035. see `org-latex-compiler'. If the document compiler is not in the
  3036. list, and the list is non-nil, the package will not be inserted
  3037. in the final document.
  3038. A string will be inserted as-is in the header of the document.
  3039. Make sure that you only list packages here which:
  3040. - you want in every file;
  3041. - do not conflict with the setup in `org-format-latex-header';
  3042. - do not conflict with the default packages in
  3043. `org-latex-default-packages-alist'."
  3044. :group 'org-latex
  3045. :group 'org-export-latex
  3046. :set 'org-set-packages-alist
  3047. :get 'org-get-packages-alist
  3048. :type '(repeat
  3049. (choice
  3050. (list :tag "options/package pair"
  3051. (string :tag "options")
  3052. (string :tag "package")
  3053. (boolean :tag "Snippet"))
  3054. (string :tag "A line of LaTeX"))))
  3055. (defgroup org-appearance nil
  3056. "Settings for Org mode appearance."
  3057. :tag "Org Appearance"
  3058. :group 'org)
  3059. (defcustom org-level-color-stars-only nil
  3060. "Non-nil means fontify only the stars in each headline.
  3061. When nil, the entire headline is fontified.
  3062. Changing it requires restart of `font-lock-mode' to become effective
  3063. also in regions already fontified."
  3064. :group 'org-appearance
  3065. :type 'boolean)
  3066. (defcustom org-hide-leading-stars nil
  3067. "Non-nil means hide the first N-1 stars in a headline.
  3068. This works by using the face `org-hide' for these stars. This
  3069. face is white for a light background, and black for a dark
  3070. background. You may have to customize the face `org-hide' to
  3071. make this work.
  3072. Changing it requires restart of `font-lock-mode' to become effective
  3073. also in regions already fontified.
  3074. You may also set this on a per-file basis by adding one of the following
  3075. lines to the buffer:
  3076. #+STARTUP: hidestars
  3077. #+STARTUP: showstars"
  3078. :group 'org-appearance
  3079. :type 'boolean)
  3080. (defcustom org-hidden-keywords nil
  3081. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3082. For example, a value \\='(title) for this list makes the document's title
  3083. appear in the buffer without the initial \"#+TITLE:\" part."
  3084. :group 'org-appearance
  3085. :package-version '(Org . "9.5")
  3086. :type '(set (const :tag "#+AUTHOR" author)
  3087. (const :tag "#+DATE" date)
  3088. (const :tag "#+EMAIL" email)
  3089. (const :tag "#+SUBTITLE" subtitle)
  3090. (const :tag "#+TITLE" title)))
  3091. (defcustom org-custom-properties nil
  3092. "List of properties (as strings) with a special meaning.
  3093. The default use of these custom properties is to let the user
  3094. hide them with `org-toggle-custom-properties-visibility'."
  3095. :group 'org-properties
  3096. :group 'org-appearance
  3097. :version "24.3"
  3098. :type '(repeat (string :tag "Property Name")))
  3099. (defcustom org-fontify-todo-headline nil
  3100. "Non-nil means change the face of a headline if it is marked as TODO.
  3101. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3102. When this is non-nil, the headline after the keyword is set to the
  3103. `org-headline-todo' as an additional indication."
  3104. :group 'org-appearance
  3105. :package-version '(Org . "9.4")
  3106. :type 'boolean
  3107. :safe #'booleanp)
  3108. (defcustom org-fontify-done-headline t
  3109. "Non-nil means change the face of a headline if it is marked DONE.
  3110. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3111. When this is non-nil, the headline after the keyword is set to the
  3112. `org-headline-done' as an additional indication."
  3113. :group 'org-appearance
  3114. :package-version '(Org . "9.4")
  3115. :type 'boolean)
  3116. (defcustom org-fontify-emphasized-text t
  3117. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3118. Changing this variable requires a restart of Emacs to take effect."
  3119. :group 'org-appearance
  3120. :type 'boolean)
  3121. (defcustom org-fontify-whole-heading-line nil
  3122. "Non-nil means fontify the whole line for headings.
  3123. This is useful when setting a background color for the
  3124. org-level-* faces."
  3125. :group 'org-appearance
  3126. :type 'boolean)
  3127. (defcustom org-fontify-whole-block-delimiter-line t
  3128. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3129. This is useful when setting a background color for the
  3130. org-block-begin-line and org-block-end-line faces."
  3131. :group 'org-appearance
  3132. :type 'boolean)
  3133. (defcustom org-highlight-latex-and-related nil
  3134. "Non-nil means highlight LaTeX related syntax in the buffer.
  3135. When non-nil, the value should be a list containing any of the
  3136. following symbols:
  3137. `native' Highlight LaTeX snippets and environments natively.
  3138. `latex' Highlight LaTeX snippets and environments.
  3139. `script' Highlight subscript and superscript.
  3140. `entities' Highlight entities."
  3141. :group 'org-appearance
  3142. :version "24.4"
  3143. :package-version '(Org . "8.0")
  3144. :type '(choice
  3145. (const :tag "No highlighting" nil)
  3146. (set :greedy t :tag "Highlight"
  3147. (const :tag "LaTeX snippets and environments (native)" native)
  3148. (const :tag "LaTeX snippets and environments" latex)
  3149. (const :tag "Subscript and superscript" script)
  3150. (const :tag "Entities" entities))))
  3151. (defcustom org-hide-emphasis-markers nil
  3152. "Non-nil mean font-lock should hide the emphasis marker characters."
  3153. :group 'org-appearance
  3154. :type 'boolean
  3155. :safe #'booleanp)
  3156. (defcustom org-hide-macro-markers nil
  3157. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3158. :group 'org-appearance
  3159. :type 'boolean)
  3160. (defcustom org-pretty-entities nil
  3161. "Non-nil means show entities as UTF8 characters.
  3162. When nil, the \\name form remains in the buffer."
  3163. :group 'org-appearance
  3164. :version "24.1"
  3165. :type 'boolean)
  3166. (defcustom org-pretty-entities-include-sub-superscripts t
  3167. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3168. :group 'org-appearance
  3169. :version "24.1"
  3170. :type 'boolean)
  3171. (defvar org-emph-re nil
  3172. "Regular expression for matching emphasis.
  3173. After a match, the match groups contain these elements:
  3174. 0 The match of the full regular expression, including the characters
  3175. before and after the proper match
  3176. 1 The character before the proper match, or empty at beginning of line
  3177. 2 The proper match, including the leading and trailing markers
  3178. 3 The leading marker like * or /, indicating the type of highlighting
  3179. 4 The text between the emphasis markers, not including the markers
  3180. 5 The character after the match, empty at the end of a line")
  3181. (defvar org-verbatim-re nil
  3182. "Regular expression for matching verbatim text.")
  3183. (defvar org-emphasis-regexp-components) ; defined just below
  3184. (defvar org-emphasis-alist) ; defined just below
  3185. (defun org-set-emph-re (var val)
  3186. "Set variable and compute the emphasis regular expression."
  3187. (set var val)
  3188. (when (and (boundp 'org-emphasis-alist)
  3189. (boundp 'org-emphasis-regexp-components)
  3190. org-emphasis-alist org-emphasis-regexp-components)
  3191. (pcase-let*
  3192. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3193. (body (if (<= nl 0) body
  3194. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3195. (template
  3196. (format (concat "\\([%s]\\|^\\)" ;before markers
  3197. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3198. "\\([%s]\\|$\\)") ;after markers
  3199. pre border border body border post)))
  3200. (setq org-emph-re (format template "*/_+"))
  3201. (setq org-verbatim-re (format template "=~")))))
  3202. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3203. ;; set this option proved cumbersome. See this message/thread:
  3204. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3205. (defvar org-emphasis-regexp-components
  3206. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3207. "Components used to build the regular expression for emphasis.
  3208. This is a list with five entries. Terminology: In an emphasis string
  3209. like \" *strong word* \", we call the initial space PREMATCH, the final
  3210. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3211. and \"trong wor\" is the body. The different components in this variable
  3212. specify what is allowed/forbidden in each part:
  3213. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3214. post Chars allowed as postmatch. End of line will be allowed too.
  3215. border The chars *forbidden* as border characters.
  3216. body-regexp A regexp like \".\" to match a body character. Don't use
  3217. non-shy groups here, and don't allow newline here.
  3218. newline The maximum number of newlines allowed in an emphasis exp.
  3219. You need to reload Org or to restart Emacs after setting this.")
  3220. (defcustom org-emphasis-alist
  3221. '(("*" bold)
  3222. ("/" italic)
  3223. ("_" underline)
  3224. ("=" org-verbatim verbatim)
  3225. ("~" org-code verbatim)
  3226. ("+" (:strike-through t)))
  3227. "Alist of characters and faces to emphasize text.
  3228. Text starting and ending with a special character will be emphasized,
  3229. for example *bold*, _underlined_ and /italic/. This variable sets the
  3230. marker characters and the face to be used by font-lock for highlighting
  3231. in Org buffers.
  3232. You need to reload Org or to restart Emacs after customizing this."
  3233. :group 'org-appearance
  3234. :set 'org-set-emph-re
  3235. :version "24.4"
  3236. :package-version '(Org . "8.0")
  3237. :type '(repeat
  3238. (list
  3239. (string :tag "Marker character")
  3240. (choice
  3241. (face :tag "Font-lock-face")
  3242. (plist :tag "Face property list"))
  3243. (option (const verbatim)))))
  3244. (defvar org-protecting-blocks '("src" "example" "export")
  3245. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3246. This is needed for font-lock setup.")
  3247. ;;; Functions and variables from their packages
  3248. ;; Declared here to avoid compiler warnings
  3249. (defvar mark-active)
  3250. ;; Various packages
  3251. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3252. (declare-function calendar-forward-day "cal-move" (arg))
  3253. (declare-function calendar-goto-date "cal-move" (date))
  3254. (declare-function calendar-goto-today "cal-move" ())
  3255. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3256. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3257. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3258. (declare-function cdlatex-tab "ext:cdlatex" ())
  3259. (declare-function dired-get-filename
  3260. "dired"
  3261. (&optional localp no-error-if-not-filep))
  3262. (declare-function iswitchb-read-buffer
  3263. "iswitchb"
  3264. (prompt &optional
  3265. default require-match _predicate start matches-set))
  3266. (declare-function org-agenda-change-all-lines
  3267. "org-agenda"
  3268. (newhead hdmarker &optional fixface just-this))
  3269. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3270. "org-agenda"
  3271. (&optional end))
  3272. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3273. (declare-function org-agenda-format-item
  3274. "org-agenda"
  3275. (extra txt &optional level category tags dotime
  3276. remove-re habitp))
  3277. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3278. (declare-function org-agenda-save-markers-for-cut-and-paste
  3279. "org-agenda"
  3280. (beg end))
  3281. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3282. (declare-function org-agenda-skip "org-agenda" ())
  3283. (declare-function org-attach-expand "org-attach" (file))
  3284. (declare-function org-attach-reveal "org-attach" ())
  3285. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3286. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3287. (declare-function org-indent-mode "org-indent" (&optional arg))
  3288. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3289. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3290. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3291. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3292. (declare-function parse-time-string "parse-time" (string))
  3293. (defvar align-mode-rules-list)
  3294. (defvar calc-embedded-close-formula)
  3295. (defvar calc-embedded-open-formula)
  3296. (defvar calc-embedded-open-mode)
  3297. (defvar font-lock-unfontify-region-function)
  3298. (defvar iswitchb-temp-buflist)
  3299. (defvar org-agenda-tags-todo-honor-ignore-options)
  3300. (defvar remember-data-file)
  3301. (defvar texmathp-why)
  3302. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3303. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3304. (declare-function org-resolve-clocks "org-clock"
  3305. (&optional also-non-dangling-p prompt last-valid))
  3306. (defvar org-clock-start-time)
  3307. (defvar org-clock-marker (make-marker)
  3308. "Marker recording the last clock-in.")
  3309. (defvar org-clock-hd-marker (make-marker)
  3310. "Marker recording the last clock-in, but the headline position.")
  3311. (defvar org-clock-heading ""
  3312. "The heading of the current clock entry.")
  3313. (defun org-clocking-buffer ()
  3314. "Return the buffer where the clock is currently running.
  3315. Return nil if no clock is running."
  3316. (marker-buffer org-clock-marker))
  3317. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3318. (defun org-check-running-clock ()
  3319. "Check if the current buffer contains the running clock.
  3320. If yes, offer to stop it and to save the buffer with the changes."
  3321. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3322. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3323. (buffer-name))))
  3324. (org-clock-out)
  3325. (when (y-or-n-p "Save changed buffer?")
  3326. (save-buffer))))
  3327. (defun org-clocktable-try-shift (dir n)
  3328. "Check if this line starts a clock table, if yes, shift the time block."
  3329. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3330. (org-clocktable-shift dir n)))
  3331. ;;;###autoload
  3332. (defun org-clock-persistence-insinuate ()
  3333. "Set up hooks for clock persistence."
  3334. (require 'org-clock)
  3335. (add-hook 'org-mode-hook 'org-clock-load)
  3336. (add-hook 'kill-emacs-hook 'org-clock-save))
  3337. (defun org-clock-auto-clockout-insinuate ()
  3338. "Set up hook for auto clocking out when Emacs is idle.
  3339. See `org-clock-auto-clockout-timer'.
  3340. This function is meant to be added to the user configuration."
  3341. (require 'org-clock)
  3342. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3343. (defgroup org-archive nil
  3344. "Options concerning archiving in Org mode."
  3345. :tag "Org Archive"
  3346. :group 'org-structure)
  3347. (defcustom org-archive-location "%s_archive::"
  3348. "The location where subtrees should be archived.
  3349. The value of this variable is a string, consisting of two parts,
  3350. separated by a double-colon. The first part is a filename and
  3351. the second part is a headline.
  3352. When the filename is omitted, archiving happens in the same file.
  3353. %s in the filename will be replaced by the current file
  3354. name (without the directory part). Archiving to a different file
  3355. is useful to keep archived entries from contributing to the
  3356. Org Agenda.
  3357. The archived entries will be filed as subtrees of the specified
  3358. headline. When the headline is omitted, the subtrees are simply
  3359. filed away at the end of the file, as top-level entries. Also in
  3360. the heading you can use %s to represent the file name, this can be
  3361. useful when using the same archive for a number of different files.
  3362. Here are a few examples:
  3363. \"%s_archive::\"
  3364. If the current file is Projects.org, archive in file
  3365. Projects.org_archive, as top-level trees. This is the default.
  3366. \"::* Archived Tasks\"
  3367. Archive in the current file, under the top-level headline
  3368. \"* Archived Tasks\".
  3369. \"~/org/archive.org::\"
  3370. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3371. \"~/org/archive.org::* From %s\"
  3372. Archive in file ~/org/archive.org (absolute path), under headlines
  3373. \"From FILENAME\" where file name is the current file name.
  3374. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3375. The \"datetree/\" string is special, signifying to archive
  3376. items to the datetree. Items are placed in either the CLOSED
  3377. date of the item, or the current date if there is no CLOSED date.
  3378. The heading will be a subentry to the current date. There doesn't
  3379. need to be a heading, but there always needs to be a slash after
  3380. datetree. For example, to store archived items directly in the
  3381. datetree, use \"~/org/datetree.org::datetree/\".
  3382. \"basement::** Finished Tasks\"
  3383. Archive in file ./basement (relative path), as level 3 trees
  3384. below the level 2 heading \"** Finished Tasks\".
  3385. You may define it locally by setting an ARCHIVE property. If
  3386. such a property is found in the file or in an entry, and anywhere
  3387. up the hierarchy, it will be used.
  3388. You can also set it for the whole file using the keyword-syntax:
  3389. #+ARCHIVE: basement::** Finished Tasks"
  3390. :group 'org-archive
  3391. :type 'string)
  3392. (defcustom org-agenda-skip-archived-trees t
  3393. "Non-nil means the agenda will skip any items located in archived trees.
  3394. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3395. variable is no longer recommended, you should leave it at the value t.
  3396. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3397. :group 'org-archive
  3398. :group 'org-agenda-skip
  3399. :type 'boolean)
  3400. (defcustom org-columns-skip-archived-trees t
  3401. "Non-nil means ignore archived trees when creating column view."
  3402. :group 'org-archive
  3403. :group 'org-properties
  3404. :type 'boolean)
  3405. (defcustom org-cycle-open-archived-trees nil
  3406. "Non-nil means `org-cycle' will open archived trees.
  3407. An archived tree is a tree marked with the tag ARCHIVE.
  3408. When nil, archived trees will stay folded. You can still open them with
  3409. normal outline commands like `show-all', but not with the cycling commands."
  3410. :group 'org-archive
  3411. :group 'org-cycle
  3412. :type 'boolean)
  3413. (defcustom org-sparse-tree-open-archived-trees nil
  3414. "Non-nil means sparse tree construction shows matches in archived trees.
  3415. When nil, matches in these trees are highlighted, but the trees are kept in
  3416. collapsed state."
  3417. :group 'org-archive
  3418. :group 'org-sparse-trees
  3419. :type 'boolean)
  3420. (defcustom org-sparse-tree-default-date-type nil
  3421. "The default date type when building a sparse tree.
  3422. When this is nil, a date is a scheduled or a deadline timestamp.
  3423. Otherwise, these types are allowed:
  3424. all: all timestamps
  3425. active: only active timestamps (<...>)
  3426. inactive: only inactive timestamps ([...])
  3427. scheduled: only scheduled timestamps
  3428. deadline: only deadline timestamps"
  3429. :type '(choice (const :tag "Scheduled or deadline" nil)
  3430. (const :tag "All timestamps" all)
  3431. (const :tag "Only active timestamps" active)
  3432. (const :tag "Only inactive timestamps" inactive)
  3433. (const :tag "Only scheduled timestamps" scheduled)
  3434. (const :tag "Only deadline timestamps" deadline)
  3435. (const :tag "Only closed timestamps" closed))
  3436. :version "26.1"
  3437. :package-version '(Org . "8.3")
  3438. :group 'org-sparse-trees)
  3439. (defun org-cycle-hide-archived-subtrees (state)
  3440. "Re-hide all archived subtrees after a visibility state change.
  3441. STATE should be one of the symbols listed in the docstring of
  3442. `org-cycle-hook'."
  3443. (when (and (not org-cycle-open-archived-trees)
  3444. (not (memq state '(overview folded))))
  3445. (save-excursion
  3446. (let* ((globalp (memq state '(contents all)))
  3447. (beg (if globalp (point-min) (point)))
  3448. (end (if globalp (point-max) (org-end-of-subtree t))))
  3449. (org-hide-archived-subtrees beg end)
  3450. (goto-char beg)
  3451. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3452. (message "%s" (substitute-command-keys
  3453. "Subtree is archived and stays closed. Use \
  3454. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3455. (defun org-force-cycle-archived ()
  3456. "Cycle subtree even if it is archived."
  3457. (interactive)
  3458. (setq this-command 'org-cycle)
  3459. (let ((org-cycle-open-archived-trees t))
  3460. (call-interactively 'org-cycle)))
  3461. (defun org-hide-archived-subtrees (beg end)
  3462. "Re-hide all archived subtrees after a visibility state change."
  3463. (org-with-wide-buffer
  3464. (let ((case-fold-search nil)
  3465. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3466. (goto-char beg)
  3467. ;; Include headline point is currently on.
  3468. (beginning-of-line)
  3469. (while (and (< (point) end) (re-search-forward re end t))
  3470. (when (member org-archive-tag (org-get-tags nil t))
  3471. (org-flag-subtree t)
  3472. (org-end-of-subtree t))))))
  3473. (defun org-flag-subtree (flag)
  3474. (save-excursion
  3475. (org-back-to-heading t)
  3476. (org-flag-region (line-end-position)
  3477. (progn (org-end-of-subtree t) (point))
  3478. flag
  3479. 'outline)))
  3480. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3481. ;; Declare Column View Code
  3482. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3483. (declare-function org-columns-compute "org-colview" (property))
  3484. ;; Declare ID code
  3485. (declare-function org-id-store-link "org-id")
  3486. (declare-function org-id-locations-load "org-id")
  3487. (declare-function org-id-locations-save "org-id")
  3488. (defvar org-id-track-globally)
  3489. ;;; Variables for pre-computed regular expressions, all buffer local
  3490. (defvar-local org-todo-regexp nil
  3491. "Matches any of the TODO state keywords.
  3492. Since TODO keywords are case-sensitive, `case-fold-search' is
  3493. expected to be bound to nil when matching against this regexp.")
  3494. (defvar-local org-not-done-regexp nil
  3495. "Matches any of the TODO state keywords except the last one.
  3496. Since TODO keywords are case-sensitive, `case-fold-search' is
  3497. expected to be bound to nil when matching against this regexp.")
  3498. (defvar-local org-not-done-heading-regexp nil
  3499. "Matches a TODO headline that is not done.
  3500. Since TODO keywords are case-sensitive, `case-fold-search' is
  3501. expected to be bound to nil when matching against this regexp.")
  3502. (defvar-local org-todo-line-regexp nil
  3503. "Matches a headline and puts TODO state into group 2 if present.
  3504. Since TODO keywords are case-sensitive, `case-fold-search' is
  3505. expected to be bound to nil when matching against this regexp.")
  3506. (defvar-local org-complex-heading-regexp nil
  3507. "Matches a headline and puts everything into groups:
  3508. group 1: Stars
  3509. group 2: The TODO keyword, maybe
  3510. group 3: Priority cookie
  3511. group 4: True headline
  3512. group 5: Tags
  3513. Since TODO keywords are case-sensitive, `case-fold-search' is
  3514. expected to be bound to nil when matching against this regexp.")
  3515. (defvar-local org-complex-heading-regexp-format nil
  3516. "Printf format to make regexp to match an exact headline.
  3517. This regexp will match the headline of any node which has the
  3518. exact headline text that is put into the format, but may have any
  3519. TODO state, priority and tags.")
  3520. (defvar-local org-todo-line-tags-regexp nil
  3521. "Matches a headline and puts TODO state into group 2 if present.
  3522. Also put tags into group 4 if tags are present.")
  3523. (defconst org-plain-time-of-day-regexp
  3524. (concat
  3525. "\\(\\<[012]?[0-9]"
  3526. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3527. "\\(--?"
  3528. "\\(\\<[012]?[0-9]"
  3529. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3530. "\\)?")
  3531. "Regular expression to match a plain time or time range.
  3532. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3533. groups carry important information:
  3534. 0 the full match
  3535. 1 the first time, range or not
  3536. 8 the second time, if it is a range.")
  3537. (defconst org-plain-time-extension-regexp
  3538. (concat
  3539. "\\(\\<[012]?[0-9]"
  3540. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3541. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3542. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3543. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3544. groups carry important information:
  3545. 0 the full match
  3546. 7 hours of duration
  3547. 9 minutes of duration")
  3548. (defconst org-stamp-time-of-day-regexp
  3549. (concat
  3550. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3551. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3552. "\\(--?"
  3553. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3554. "Regular expression to match a timestamp time or time range.
  3555. After a match, the following groups carry important information:
  3556. 0 the full match
  3557. 1 date plus weekday, for back referencing to make sure
  3558. both times are on the same day
  3559. 2 the first time, range or not
  3560. 4 the second time, if it is a range.")
  3561. (defconst org-startup-options
  3562. '(("fold" org-startup-folded t)
  3563. ("overview" org-startup-folded t)
  3564. ("nofold" org-startup-folded nil)
  3565. ("showall" org-startup-folded nil)
  3566. ("show2levels" org-startup-folded show2levels)
  3567. ("show3levels" org-startup-folded show3levels)
  3568. ("show4levels" org-startup-folded show4levels)
  3569. ("show5levels" org-startup-folded show5levels)
  3570. ("showeverything" org-startup-folded showeverything)
  3571. ("content" org-startup-folded content)
  3572. ("indent" org-startup-indented t)
  3573. ("noindent" org-startup-indented nil)
  3574. ("num" org-startup-numerated t)
  3575. ("nonum" org-startup-numerated nil)
  3576. ("hidestars" org-hide-leading-stars t)
  3577. ("showstars" org-hide-leading-stars nil)
  3578. ("odd" org-odd-levels-only t)
  3579. ("oddeven" org-odd-levels-only nil)
  3580. ("align" org-startup-align-all-tables t)
  3581. ("noalign" org-startup-align-all-tables nil)
  3582. ("shrink" org-startup-shrink-all-tables t)
  3583. ("inlineimages" org-startup-with-inline-images t)
  3584. ("noinlineimages" org-startup-with-inline-images nil)
  3585. ("latexpreview" org-startup-with-latex-preview t)
  3586. ("nolatexpreview" org-startup-with-latex-preview nil)
  3587. ("customtime" org-display-custom-times t)
  3588. ("logdone" org-log-done time)
  3589. ("lognotedone" org-log-done note)
  3590. ("nologdone" org-log-done nil)
  3591. ("lognoteclock-out" org-log-note-clock-out t)
  3592. ("nolognoteclock-out" org-log-note-clock-out nil)
  3593. ("logrepeat" org-log-repeat state)
  3594. ("lognoterepeat" org-log-repeat note)
  3595. ("logdrawer" org-log-into-drawer t)
  3596. ("nologdrawer" org-log-into-drawer nil)
  3597. ("logstatesreversed" org-log-states-order-reversed t)
  3598. ("nologstatesreversed" org-log-states-order-reversed nil)
  3599. ("nologrepeat" org-log-repeat nil)
  3600. ("logreschedule" org-log-reschedule time)
  3601. ("lognotereschedule" org-log-reschedule note)
  3602. ("nologreschedule" org-log-reschedule nil)
  3603. ("logredeadline" org-log-redeadline time)
  3604. ("lognoteredeadline" org-log-redeadline note)
  3605. ("nologredeadline" org-log-redeadline nil)
  3606. ("logrefile" org-log-refile time)
  3607. ("lognoterefile" org-log-refile note)
  3608. ("nologrefile" org-log-refile nil)
  3609. ("fninline" org-footnote-define-inline t)
  3610. ("nofninline" org-footnote-define-inline nil)
  3611. ("fnlocal" org-footnote-section nil)
  3612. ("fnauto" org-footnote-auto-label t)
  3613. ("fnprompt" org-footnote-auto-label nil)
  3614. ("fnconfirm" org-footnote-auto-label confirm)
  3615. ("fnplain" org-footnote-auto-label plain)
  3616. ("fnadjust" org-footnote-auto-adjust t)
  3617. ("nofnadjust" org-footnote-auto-adjust nil)
  3618. ("constcgs" constants-unit-system cgs)
  3619. ("constSI" constants-unit-system SI)
  3620. ("noptag" org-tag-persistent-alist nil)
  3621. ("hideblocks" org-hide-block-startup t)
  3622. ("nohideblocks" org-hide-block-startup nil)
  3623. ("beamer" org-startup-with-beamer-mode t)
  3624. ("entitiespretty" org-pretty-entities t)
  3625. ("entitiesplain" org-pretty-entities nil))
  3626. "Variable associated with STARTUP options for Org.
  3627. Each element is a list of three items: the startup options (as written
  3628. in the #+STARTUP line), the corresponding variable, and the value to set
  3629. this variable to if the option is found. An optional fourth element PUSH
  3630. means to push this value onto the list in the variable.")
  3631. (defcustom org-group-tags t
  3632. "When non-nil (the default), use group tags.
  3633. This can be turned on/off through `org-toggle-tags-groups'."
  3634. :group 'org-tags
  3635. :group 'org-startup
  3636. :type 'boolean)
  3637. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3638. (defun org-toggle-tags-groups ()
  3639. "Toggle support for group tags.
  3640. Support for group tags is controlled by the option
  3641. `org-group-tags', which is non-nil by default."
  3642. (interactive)
  3643. (setq org-group-tags (not org-group-tags))
  3644. (cond ((and (derived-mode-p 'org-agenda-mode)
  3645. org-group-tags)
  3646. (org-agenda-redo))
  3647. ((derived-mode-p 'org-mode)
  3648. (let ((org-inhibit-startup t)) (org-mode))))
  3649. (message "Groups tags support has been turned %s"
  3650. (if org-group-tags "on" "off")))
  3651. (defun org--tag-add-to-alist (alist1 alist2)
  3652. "Merge tags from ALIST1 into ALIST2.
  3653. Duplicates tags outside a group are removed. Keywords and order
  3654. are preserved.
  3655. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3656. See `org-tag-alist' for their structure."
  3657. (cond
  3658. ((null alist2) alist1)
  3659. ((null alist1) alist2)
  3660. (t
  3661. (let ((to-add nil)
  3662. (group-flag nil))
  3663. (dolist (tag-pair alist1)
  3664. (pcase tag-pair
  3665. (`(,(or :startgrouptag :startgroup))
  3666. (setq group-flag t)
  3667. (push tag-pair to-add))
  3668. (`(,(or :endgrouptag :endgroup))
  3669. (setq group-flag nil)
  3670. (push tag-pair to-add))
  3671. (`(,(or :grouptags :newline))
  3672. (push tag-pair to-add))
  3673. (`(,tag . ,_)
  3674. ;; Remove duplicates from ALIST1, unless they are in
  3675. ;; a group. Indeed, it makes sense to have a tag appear in
  3676. ;; multiple groups.
  3677. (when (or group-flag (not (assoc tag alist2)))
  3678. (push tag-pair to-add)))
  3679. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3680. ;; Preserve order of ALIST1.
  3681. (append (nreverse to-add) alist2)))))
  3682. (defun org-priority-to-value (s)
  3683. "Convert priority string S to its numeric value."
  3684. (or (save-match-data
  3685. (and (string-match "\\([0-9]+\\)" s)
  3686. (string-to-number (match-string 1 s))))
  3687. (string-to-char s)))
  3688. (defun org-set-regexps-and-options (&optional tags-only)
  3689. "Precompute regular expressions used in the current buffer.
  3690. When optional argument TAGS-ONLY is non-nil, only compute tags
  3691. related expressions."
  3692. (when (derived-mode-p 'org-mode)
  3693. (let ((alist (org-collect-keywords
  3694. (append '("FILETAGS" "TAGS")
  3695. (and (not tags-only)
  3696. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3697. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3698. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3699. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3700. ;; Startup options. Get this early since it does change
  3701. ;; behavior for other options (e.g., tags).
  3702. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3703. (cdr (assoc "STARTUP" alist)))))
  3704. (dolist (option startup)
  3705. (pcase (assoc-string option org-startup-options t)
  3706. (`(,_ ,variable ,value t)
  3707. (unless (listp (symbol-value variable))
  3708. (set (make-local-variable variable) nil))
  3709. (add-to-list variable value))
  3710. (`(,_ ,variable ,value . ,_)
  3711. (set (make-local-variable variable) value))
  3712. (_ nil))))
  3713. (setq-local org-file-tags
  3714. (mapcar #'org-add-prop-inherited
  3715. (cl-mapcan (lambda (value)
  3716. (cl-mapcan
  3717. (lambda (k) (org-split-string k ":"))
  3718. (split-string value)))
  3719. (cdr (assoc "FILETAGS" alist)))))
  3720. (setq org-current-tag-alist
  3721. (org--tag-add-to-alist
  3722. org-tag-persistent-alist
  3723. (let ((tags (cdr (assoc "TAGS" alist))))
  3724. (if tags
  3725. (org-tag-string-to-alist
  3726. (mapconcat #'identity tags "\n"))
  3727. org-tag-alist))))
  3728. (setq org-tag-groups-alist
  3729. (org-tag-alist-to-groups org-current-tag-alist))
  3730. (unless tags-only
  3731. ;; Properties.
  3732. (let ((properties nil))
  3733. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3734. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3735. (setq properties (org--update-property-plist
  3736. (match-string-no-properties 1 value)
  3737. (match-string-no-properties 2 value)
  3738. properties))))
  3739. (setq-local org-keyword-properties properties))
  3740. ;; Archive location.
  3741. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3742. (when archive (setq-local org-archive-location archive)))
  3743. ;; Category.
  3744. (let ((category (cdr (assoc "CATEGORY" alist))))
  3745. (when category
  3746. (setq-local org-category (intern category))
  3747. (setq-local org-keyword-properties
  3748. (org--update-property-plist
  3749. "CATEGORY" category org-keyword-properties))))
  3750. ;; Columns.
  3751. (let ((column (cdr (assoc "COLUMNS" alist))))
  3752. (when column (setq-local org-columns-default-format column)))
  3753. ;; Constants.
  3754. (let ((store nil))
  3755. (dolist (pair (cl-mapcan #'split-string
  3756. (cdr (assoc "CONSTANTS" alist))))
  3757. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3758. (let* ((name (match-string 1 pair))
  3759. (value (match-string 2 pair))
  3760. (old (assoc name store)))
  3761. (if old (setcdr old value)
  3762. (push (cons name value) store)))))
  3763. (setq org-table-formula-constants-local store))
  3764. ;; Link abbreviations.
  3765. (let ((links
  3766. (delq nil
  3767. (mapcar
  3768. (lambda (value)
  3769. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3770. (cons (match-string-no-properties 1 value)
  3771. (match-string-no-properties 2 value))))
  3772. (cdr (assoc "LINK" alist))))))
  3773. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3774. ;; Priorities.
  3775. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3776. (pcase (and value (split-string value))
  3777. (`(,high ,low ,default . ,_)
  3778. (setq-local org-priority-highest (org-priority-to-value high))
  3779. (setq-local org-priority-lowest (org-priority-to-value low))
  3780. (setq-local org-priority-default (org-priority-to-value default)))))
  3781. ;; Scripts.
  3782. (let ((value (cdr (assoc "OPTIONS" alist))))
  3783. (dolist (option value)
  3784. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3785. (setq-local org-use-sub-superscripts
  3786. (read (match-string 1 option))))))
  3787. ;; TODO keywords.
  3788. (setq-local org-todo-kwd-alist nil)
  3789. (setq-local org-todo-key-alist nil)
  3790. (setq-local org-todo-key-trigger nil)
  3791. (setq-local org-todo-keywords-1 nil)
  3792. (setq-local org-done-keywords nil)
  3793. (setq-local org-todo-heads nil)
  3794. (setq-local org-todo-sets nil)
  3795. (setq-local org-todo-log-states nil)
  3796. (let ((todo-sequences
  3797. (or (append (mapcar (lambda (value)
  3798. (cons 'type (split-string value)))
  3799. (cdr (assoc "TYP_TODO" alist)))
  3800. (mapcar (lambda (value)
  3801. (cons 'sequence (split-string value)))
  3802. (append (cdr (assoc "TODO" alist))
  3803. (cdr (assoc "SEQ_TODO" alist)))))
  3804. (let ((d (default-value 'org-todo-keywords)))
  3805. (if (not (stringp (car d))) d
  3806. ;; XXX: Backward compatibility code.
  3807. (list (cons org-todo-interpretation d)))))))
  3808. (dolist (sequence todo-sequences)
  3809. (let* ((sequence (or (run-hook-with-args-until-success
  3810. 'org-todo-setup-filter-hook sequence)
  3811. sequence))
  3812. (sequence-type (car sequence))
  3813. (keywords (cdr sequence))
  3814. (sep (member "|" keywords))
  3815. names alist)
  3816. (dolist (k (remove "|" keywords))
  3817. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3818. k)
  3819. (error "Invalid TODO keyword %s" k))
  3820. (let ((name (match-string 1 k))
  3821. (key (match-string 2 k))
  3822. (log (org-extract-log-state-settings k)))
  3823. (push name names)
  3824. (push (cons name (and key (string-to-char key))) alist)
  3825. (when log (push log org-todo-log-states))))
  3826. (let* ((names (nreverse names))
  3827. (done (if sep (org-remove-keyword-keys (cdr sep))
  3828. (last names)))
  3829. (head (car names))
  3830. (tail (list sequence-type head (car done) (org-last done))))
  3831. (add-to-list 'org-todo-heads head 'append)
  3832. (push names org-todo-sets)
  3833. (setq org-done-keywords (append org-done-keywords done nil))
  3834. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3835. (setq org-todo-key-alist
  3836. (append org-todo-key-alist
  3837. (and alist
  3838. (append '((:startgroup))
  3839. (nreverse alist)
  3840. '((:endgroup))))))
  3841. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3842. (setq org-todo-sets (nreverse org-todo-sets)
  3843. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3844. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3845. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3846. ;; Compute the regular expressions and other local variables.
  3847. ;; Using `org-outline-regexp-bol' would complicate them much,
  3848. ;; because of the fixed white space at the end of that string.
  3849. (unless org-done-keywords
  3850. (setq org-done-keywords
  3851. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3852. (setq org-not-done-keywords
  3853. (org-delete-all org-done-keywords
  3854. (copy-sequence org-todo-keywords-1))
  3855. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3856. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3857. org-not-done-heading-regexp
  3858. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3859. org-todo-line-regexp
  3860. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3861. org-complex-heading-regexp
  3862. (concat "^\\(\\*+\\)"
  3863. "\\(?: +" org-todo-regexp "\\)?"
  3864. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3865. "\\(?: +\\(.*?\\)\\)??"
  3866. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3867. "[ \t]*$")
  3868. org-complex-heading-regexp-format
  3869. (concat "^\\(\\*+\\)"
  3870. "\\(?: +" org-todo-regexp "\\)?"
  3871. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3872. "\\(?: +"
  3873. ;; Stats cookies can be stuck to body.
  3874. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3875. "\\(%s\\)"
  3876. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3877. "\\)"
  3878. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3879. "[ \t]*$")
  3880. org-todo-line-tags-regexp
  3881. (concat "^\\(\\*+\\)"
  3882. "\\(?: +" org-todo-regexp "\\)?"
  3883. "\\(?: +\\(.*?\\)\\)??"
  3884. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3885. "[ \t]*$"))
  3886. (org-compute-latex-and-related-regexp)))))
  3887. (defun org-collect-keywords (keywords &optional unique directory)
  3888. "Return values for KEYWORDS in current buffer, as an alist.
  3889. KEYWORDS is a list of strings. Return value is a list of
  3890. elements with the pattern:
  3891. (NAME . LIST-OF-VALUES)
  3892. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3893. is a list of non-empty values, as strings, in order of appearance
  3894. in the buffer.
  3895. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3896. value, empty or not, appearing in the buffer, as a string.
  3897. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3898. (VALUE . DIRECTORY)
  3899. where VALUE is the regular value, and DIRECTORY is the variable
  3900. `default-directory' for the buffer containing the keyword. This
  3901. is important for values containing relative file names, since the
  3902. function follows SETUPFILE keywords, and may change its working
  3903. directory."
  3904. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3905. (unique (mapcar #'upcase unique))
  3906. (alist (org--collect-keywords-1
  3907. keywords unique directory
  3908. (and buffer-file-name (list buffer-file-name))
  3909. nil)))
  3910. ;; Re-order results.
  3911. (dolist (entry alist)
  3912. (pcase entry
  3913. (`(,_ . ,(and value (pred consp)))
  3914. (setcdr entry (nreverse value)))))
  3915. (nreverse alist)))
  3916. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3917. (org-with-point-at 1
  3918. (let ((case-fold-search t)
  3919. (regexp (org-make-options-regexp keywords)))
  3920. (while (and keywords (re-search-forward regexp nil t))
  3921. (let ((element (org-element-at-point)))
  3922. (when (eq 'keyword (org-element-type element))
  3923. (let ((value (org-element-property :value element)))
  3924. (pcase (org-element-property :key element)
  3925. ("SETUPFILE"
  3926. (when (and (org-string-nw-p value)
  3927. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3928. (let* ((uri (org-strip-quotes value))
  3929. (uri-is-url (org-url-p uri))
  3930. (uri (if uri-is-url
  3931. uri
  3932. (expand-file-name uri))))
  3933. (unless (member uri files)
  3934. (with-temp-buffer
  3935. (unless uri-is-url
  3936. (setq default-directory (file-name-directory uri)))
  3937. (let ((contents (org-file-contents uri :noerror)))
  3938. (when contents
  3939. (insert contents)
  3940. ;; Fake Org mode: `org-element-at-point'
  3941. ;; doesn't need full set-up.
  3942. (let ((major-mode 'org-mode))
  3943. (setq alist
  3944. (org--collect-keywords-1
  3945. keywords unique directory
  3946. (cons uri files)
  3947. alist))))))))))
  3948. (keyword
  3949. (let ((entry (assoc keyword alist))
  3950. (final
  3951. (cond ((not (member keyword directory)) value)
  3952. (buffer-file-name
  3953. (cons value
  3954. (file-name-directory buffer-file-name)))
  3955. (t (cons value default-directory)))))
  3956. (cond ((member keyword unique)
  3957. (push (cons keyword final) alist)
  3958. (setq keywords (remove keyword keywords))
  3959. (setq regexp (org-make-options-regexp keywords)))
  3960. ((null entry) (push (list keyword final) alist))
  3961. (t (push final (cdr entry)))))))))))
  3962. alist)))
  3963. (defun org-tag-string-to-alist (s)
  3964. "Return tag alist associated to string S.
  3965. S is a value for TAGS keyword or produced with
  3966. `org-tag-alist-to-string'. Return value is an alist suitable for
  3967. `org-tag-alist' or `org-tag-persistent-alist'."
  3968. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3969. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3970. "\\(?:(\\(.\\))\\)?\\'"))
  3971. alist group-flag)
  3972. (dolist (tokens lines (cdr (nreverse alist)))
  3973. (push '(:newline) alist)
  3974. (while tokens
  3975. (let ((token (pop tokens)))
  3976. (pcase token
  3977. ("{"
  3978. (push '(:startgroup) alist)
  3979. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3980. ("}"
  3981. (push '(:endgroup) alist)
  3982. (setq group-flag nil))
  3983. ("["
  3984. (push '(:startgrouptag) alist)
  3985. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3986. ("]"
  3987. (push '(:endgrouptag) alist)
  3988. (setq group-flag nil))
  3989. (":"
  3990. (push '(:grouptags) alist))
  3991. ((guard (string-match tag-re token))
  3992. (let ((tag (match-string 1 token))
  3993. (key (and (match-beginning 2)
  3994. (string-to-char (match-string 2 token)))))
  3995. ;; Push all tags in groups, no matter if they already
  3996. ;; appear somewhere else in the list.
  3997. (when (or group-flag (not (assoc tag alist)))
  3998. (push (cons tag key) alist))))))))))
  3999. (defun org-tag-alist-to-string (alist &optional skip-key)
  4000. "Return tag string associated to ALIST.
  4001. ALIST is an alist, as defined in `org-tag-alist' or
  4002. `org-tag-persistent-alist', or produced with
  4003. `org-tag-string-to-alist'.
  4004. Return value is a string suitable as a value for \"TAGS\"
  4005. keyword.
  4006. When optional argument SKIP-KEY is non-nil, skip selection keys
  4007. next to tags."
  4008. (mapconcat (lambda (token)
  4009. (pcase token
  4010. (`(:startgroup) "{")
  4011. (`(:endgroup) "}")
  4012. (`(:startgrouptag) "[")
  4013. (`(:endgrouptag) "]")
  4014. (`(:grouptags) ":")
  4015. (`(:newline) "\\n")
  4016. ((and
  4017. (guard (not skip-key))
  4018. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4019. (format "%s(%c)" tag key))
  4020. (`(,(and tag (pred stringp)) . ,_) tag)
  4021. (_ (user-error "Invalid tag token: %S" token))))
  4022. alist
  4023. " "))
  4024. (defun org-tag-alist-to-groups (alist)
  4025. "Return group alist from tag ALIST.
  4026. ALIST is an alist, as defined in `org-tag-alist' or
  4027. `org-tag-persistent-alist', or produced with
  4028. `org-tag-string-to-alist'. Return value is an alist following
  4029. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4030. a string, summarizing TAGS, as a list of strings."
  4031. (let (groups group-status current-group)
  4032. (dolist (token alist (nreverse groups))
  4033. (pcase token
  4034. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4035. (`(,(or :endgroup :endgrouptag))
  4036. (when (eq group-status 'append)
  4037. (push (nreverse current-group) groups))
  4038. (setq group-status nil current-group nil))
  4039. (`(:grouptags) (setq group-status 'append))
  4040. ((and `(,tag . ,_) (guard group-status))
  4041. (if (eq group-status 'append) (push tag current-group)
  4042. (setq current-group (list tag))))
  4043. (_ nil)))))
  4044. (defvar org--file-cache (make-hash-table :test #'equal)
  4045. "Hash table to store contents of files referenced via a URL.
  4046. This is the cache of file URLs read using `org-file-contents'.")
  4047. (defun org-reset-file-cache ()
  4048. "Reset the cache of files downloaded by `org-file-contents'."
  4049. (clrhash org--file-cache))
  4050. (defun org-file-contents (file &optional noerror nocache)
  4051. "Return the contents of FILE, as a string.
  4052. FILE can be a file name or URL.
  4053. If FILE is a URL, download the contents. If the URL contents are
  4054. already cached in the `org--file-cache' hash table, the download step
  4055. is skipped.
  4056. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4057. from file or URL, and return nil.
  4058. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4059. is available. This option applies only if FILE is a URL."
  4060. (let* ((is-url (org-url-p file))
  4061. (cache (and is-url
  4062. (not nocache)
  4063. (gethash file org--file-cache))))
  4064. (cond
  4065. (cache)
  4066. (is-url
  4067. (with-current-buffer (url-retrieve-synchronously file)
  4068. (goto-char (point-min))
  4069. ;; Move point to after the url-retrieve header.
  4070. (search-forward "\n\n" nil :move)
  4071. ;; Search for the success code only in the url-retrieve header.
  4072. (if (save-excursion
  4073. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4074. ;; Update the cache `org--file-cache' and return contents.
  4075. (puthash file
  4076. (buffer-substring-no-properties (point) (point-max))
  4077. org--file-cache)
  4078. (funcall (if noerror #'message #'user-error)
  4079. "Unable to fetch file from %S"
  4080. file)
  4081. nil)))
  4082. (t
  4083. (with-temp-buffer
  4084. (condition-case nil
  4085. (progn
  4086. (insert-file-contents file)
  4087. (buffer-string))
  4088. (file-error
  4089. (funcall (if noerror #'message #'user-error)
  4090. "Unable to read file %S"
  4091. file)
  4092. nil)))))))
  4093. (defun org-extract-log-state-settings (x)
  4094. "Extract the log state setting from a TODO keyword string.
  4095. This will extract info from a string like \"WAIT(w@/!)\"."
  4096. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4097. (let ((kw (match-string 1 x))
  4098. (log1 (and (match-end 3) (match-string 3 x)))
  4099. (log2 (and (match-end 4) (match-string 4 x))))
  4100. (and (or log1 log2)
  4101. (list kw
  4102. (and log1 (if (equal log1 "!") 'time 'note))
  4103. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4104. (defun org-remove-keyword-keys (list)
  4105. "Remove a pair of parenthesis at the end of each string in LIST."
  4106. (mapcar (lambda (x)
  4107. (if (string-match "(.*)$" x)
  4108. (substring x 0 (match-beginning 0))
  4109. x))
  4110. list))
  4111. (defun org-assign-fast-keys (alist)
  4112. "Assign fast keys to a keyword-key alist.
  4113. Respect keys that are already there."
  4114. (let (new e (alt ?0))
  4115. (while (setq e (pop alist))
  4116. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4117. (cdr e)) ;; Key already assigned.
  4118. (push e new)
  4119. (let ((clist (string-to-list (downcase (car e))))
  4120. (used (append new alist)))
  4121. (when (= (car clist) ?@)
  4122. (pop clist))
  4123. (while (and clist (rassoc (car clist) used))
  4124. (pop clist))
  4125. (unless clist
  4126. (while (rassoc alt used)
  4127. (cl-incf alt)))
  4128. (push (cons (car e) (or (car clist) alt)) new))))
  4129. (nreverse new)))
  4130. ;;; Some variables used in various places
  4131. (defvar org-window-configuration nil
  4132. "Used in various places to store a window configuration.")
  4133. (defvar org-selected-window nil
  4134. "Used in various places to store a window configuration.")
  4135. (defvar org-finish-function nil
  4136. "Function to be called when `C-c C-c' is used.
  4137. This is for getting out of special buffers like capture.")
  4138. (defvar org-last-state)
  4139. ;; Defined somewhere in this file, but used before definition.
  4140. (defvar org-entities) ;; defined in org-entities.el
  4141. (defvar org-struct-menu)
  4142. (defvar org-org-menu)
  4143. (defvar org-tbl-menu)
  4144. ;;;; Define the Org mode
  4145. (defun org-before-change-function (_beg _end)
  4146. "Every change indicates that a table might need an update."
  4147. (setq org-table-may-need-update t))
  4148. (defvar org-mode-map)
  4149. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4150. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4151. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4152. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4153. (defvar bidi-paragraph-direction)
  4154. (defvar buffer-face-mode-face)
  4155. (require 'outline)
  4156. ;; Other stuff we need.
  4157. (require 'time-date)
  4158. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4159. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4160. (require 'easymenu))
  4161. (require 'org-entities)
  4162. (require 'org-faces)
  4163. (require 'org-list)
  4164. (require 'org-pcomplete)
  4165. (require 'org-src)
  4166. (require 'org-footnote)
  4167. (require 'org-macro)
  4168. ;; babel
  4169. (require 'ob)
  4170. ;;;###autoload
  4171. (define-derived-mode org-mode outline-mode "Org"
  4172. "Outline-based notes management and organizer, alias
  4173. \"Carsten's outline-mode for keeping track of everything.\"
  4174. Org mode develops organizational tasks around a NOTES file which
  4175. contains information about projects as plain text. Org mode is
  4176. implemented on top of Outline mode, which is ideal to keep the content
  4177. of large files well structured. It supports ToDo items, deadlines and
  4178. time stamps, which magically appear in the diary listing of the Emacs
  4179. calendar. Tables are easily created with a built-in table editor.
  4180. Plain text URL-like links connect to websites, emails (VM), Usenet
  4181. messages (Gnus), BBDB entries, and any files related to the project.
  4182. For printing and sharing of notes, an Org file (or a part of it)
  4183. can be exported as a structured ASCII or HTML file.
  4184. The following commands are available:
  4185. \\{org-mode-map}"
  4186. (org-load-modules-maybe)
  4187. (org-install-agenda-files-menu)
  4188. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4189. (make-local-variable 'org-link-descriptive)
  4190. (add-to-invisibility-spec '(org-hide-block . t))
  4191. (setq-local outline-regexp org-outline-regexp)
  4192. (setq-local outline-level 'org-outline-level)
  4193. (setq bidi-paragraph-direction 'left-to-right)
  4194. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4195. (unless org-display-table
  4196. (setq org-display-table (make-display-table)))
  4197. (set-display-table-slot
  4198. org-display-table 4
  4199. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4200. org-ellipsis)))
  4201. (setq buffer-display-table org-display-table))
  4202. (org-set-regexps-and-options)
  4203. (org-set-font-lock-defaults)
  4204. (when (and org-tag-faces (not org-tags-special-faces-re))
  4205. ;; tag faces set outside customize.... force initialization.
  4206. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4207. ;; Calc embedded
  4208. (setq-local calc-embedded-open-mode "# ")
  4209. ;; Modify a few syntax entries
  4210. (modify-syntax-entry ?\" "\"")
  4211. (modify-syntax-entry ?\\ "_")
  4212. (modify-syntax-entry ?~ "_")
  4213. (modify-syntax-entry ?< "(>")
  4214. (modify-syntax-entry ?> ")<")
  4215. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4216. ;; Activate before-change-function
  4217. (setq-local org-table-may-need-update t)
  4218. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4219. ;; Check for running clock before killing a buffer
  4220. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4221. ;; Initialize macros templates.
  4222. (org-macro-initialize-templates)
  4223. ;; Initialize radio targets.
  4224. (org-update-radio-target-regexp)
  4225. ;; Indentation.
  4226. (setq-local indent-line-function 'org-indent-line)
  4227. (setq-local indent-region-function 'org-indent-region)
  4228. ;; Filling and auto-filling.
  4229. (org-setup-filling)
  4230. ;; Comments.
  4231. (org-setup-comments-handling)
  4232. ;; Initialize cache.
  4233. (org-element-cache-reset)
  4234. ;; Beginning/end of defun
  4235. (setq-local beginning-of-defun-function 'org-backward-element)
  4236. (setq-local end-of-defun-function
  4237. (lambda ()
  4238. (if (not (org-at-heading-p))
  4239. (org-forward-element)
  4240. (org-forward-element)
  4241. (forward-char -1))))
  4242. ;; Next error for sparse trees
  4243. (setq-local next-error-function 'org-occur-next-match)
  4244. ;; Make commit log messages from Org documents easier.
  4245. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4246. ;; Make sure dependence stuff works reliably, even for users who set it
  4247. ;; too late :-(
  4248. (if org-enforce-todo-dependencies
  4249. (add-hook 'org-blocker-hook
  4250. 'org-block-todo-from-children-or-siblings-or-parent)
  4251. (remove-hook 'org-blocker-hook
  4252. 'org-block-todo-from-children-or-siblings-or-parent))
  4253. (if org-enforce-todo-checkbox-dependencies
  4254. (add-hook 'org-blocker-hook
  4255. 'org-block-todo-from-checkboxes)
  4256. (remove-hook 'org-blocker-hook
  4257. 'org-block-todo-from-checkboxes))
  4258. ;; Align options lines
  4259. (setq-local
  4260. align-mode-rules-list
  4261. '((org-in-buffer-settings
  4262. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4263. (modes . '(org-mode)))))
  4264. ;; Setup the pcomplete hooks
  4265. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4266. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4267. (setq-local pcomplete-default-completion-function #'ignore)
  4268. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4269. (setq-local pcomplete-termination-string "")
  4270. (add-hook 'completion-at-point-functions
  4271. #'pcomplete-completions-at-point nil t)
  4272. (setq-local buffer-face-mode-face 'org-default)
  4273. ;; If empty file that did not turn on Org mode automatically, make
  4274. ;; it to.
  4275. (when (and org-insert-mode-line-in-empty-file
  4276. (called-interactively-p 'any)
  4277. (= (point-min) (point-max)))
  4278. (insert "# -*- mode: org -*-\n\n"))
  4279. (unless org-inhibit-startup
  4280. (org-unmodified
  4281. (when org-startup-with-beamer-mode (org-beamer-mode))
  4282. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4283. (org-table-map-tables
  4284. (cond ((and org-startup-align-all-tables
  4285. org-startup-shrink-all-tables)
  4286. (lambda () (org-table-align) (org-table-shrink)))
  4287. (org-startup-align-all-tables #'org-table-align)
  4288. (t #'org-table-shrink))
  4289. t))
  4290. (when org-startup-with-inline-images (org-display-inline-images))
  4291. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4292. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4293. (when org-startup-truncated (setq truncate-lines t))
  4294. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4295. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4296. ;; Add a custom keymap for `visual-line-mode' so that activating
  4297. ;; this minor mode does not override Org's keybindings.
  4298. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4299. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4300. (newmap (make-sparse-keymap)))
  4301. (set-keymap-parent newmap oldmap)
  4302. (define-key newmap [remap move-beginning-of-line] nil)
  4303. (define-key newmap [remap move-end-of-line] nil)
  4304. (define-key newmap [remap kill-line] nil)
  4305. (make-local-variable 'minor-mode-overriding-map-alist)
  4306. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4307. ;; Activate `org-table-header-line-mode'
  4308. (when org-table-header-line-p
  4309. (org-table-header-line-mode 1))
  4310. ;; Try to set `org-hide' face correctly.
  4311. (let ((foreground (org-find-invisible-foreground)))
  4312. (when foreground
  4313. (set-face-foreground 'org-hide foreground)))
  4314. ;; Set face extension as requested.
  4315. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4316. org-fontify-whole-block-delimiter-line)
  4317. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4318. ;; Update `customize-package-emacs-version-alist'
  4319. (add-to-list 'customize-package-emacs-version-alist
  4320. '(Org ("8.0" . "24.4")
  4321. ("8.1" . "24.4")
  4322. ("8.2" . "24.4")
  4323. ("8.2.7" . "24.4")
  4324. ("8.3" . "26.1")
  4325. ("9.0" . "26.1")
  4326. ("9.1" . "26.1")
  4327. ("9.2" . "27.1")
  4328. ("9.3" . "27.1")
  4329. ("9.4" . "27.2")
  4330. ("9.5" . "28.1")))
  4331. (defvar org-mode-transpose-word-syntax-table
  4332. (let ((st (make-syntax-table text-mode-syntax-table)))
  4333. (dolist (c org-emphasis-alist st)
  4334. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4335. (when (fboundp 'abbrev-table-put)
  4336. (abbrev-table-put org-mode-abbrev-table
  4337. :parents (list text-mode-abbrev-table)))
  4338. (defun org-find-invisible-foreground ()
  4339. (let ((candidates (remove
  4340. "unspecified-bg"
  4341. (nconc
  4342. (list (face-background 'default)
  4343. (face-background 'org-default))
  4344. (mapcar
  4345. (lambda (alist)
  4346. (when (boundp alist)
  4347. (cdr (assq 'background-color (symbol-value alist)))))
  4348. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4349. (list (face-foreground 'org-hide))))))
  4350. (car (remove nil candidates))))
  4351. (defun org-current-time (&optional rounding-minutes past)
  4352. "Current time, possibly rounded to ROUNDING-MINUTES.
  4353. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4354. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4355. the rounding returns a past time."
  4356. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4357. (car org-time-stamp-rounding-minutes)))
  4358. (now (current-time)))
  4359. (if (< r 1)
  4360. now
  4361. (let* ((time (decode-time now))
  4362. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4363. (nthcdr 2 time))))
  4364. (if (or (not past) (org-time-less-p res now))
  4365. res
  4366. (org-time-subtract res (* r 60)))))))
  4367. (defun org-today ()
  4368. "Return today date, considering `org-extend-today-until'."
  4369. (time-to-days
  4370. (org-time-since (* 3600 org-extend-today-until))))
  4371. ;;;; Font-Lock stuff, including the activators
  4372. (defconst org-match-sexp-depth 3
  4373. "Number of stacked braces for sub/superscript matching.")
  4374. (defun org-create-multibrace-regexp (left right n)
  4375. "Create a regular expression which will match a balanced sexp.
  4376. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4377. as single character strings.
  4378. The regexp returned will match the entire expression including the
  4379. delimiters. It will also define a single group which contains the
  4380. match except for the outermost delimiters. The maximum depth of
  4381. stacked delimiters is N. Escaping delimiters is not possible."
  4382. (let* ((nothing (concat "[^" left right "]*?"))
  4383. (or "\\|")
  4384. (re nothing)
  4385. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4386. (while (> n 1)
  4387. (setq n (1- n)
  4388. re (concat re or next)
  4389. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4390. (concat left "\\(" re "\\)" right)))
  4391. (defconst org-match-substring-regexp
  4392. (concat
  4393. "\\(\\S-\\)\\([_^]\\)\\("
  4394. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4395. "\\|"
  4396. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4397. "\\|"
  4398. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4399. "The regular expression matching a sub- or superscript.")
  4400. (defconst org-match-substring-with-braces-regexp
  4401. (concat
  4402. "\\(\\S-\\)\\([_^]\\)"
  4403. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4404. "The regular expression matching a sub- or superscript, forcing braces.")
  4405. (defvar org-emph-face nil)
  4406. (defun org-do-emphasis-faces (limit)
  4407. "Run through the buffer and emphasize strings."
  4408. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4409. (car org-emphasis-regexp-components))))
  4410. (catch :exit
  4411. (while (re-search-forward quick-re limit t)
  4412. (let* ((marker (match-string 2))
  4413. (verbatim? (member marker '("~" "="))))
  4414. (when (save-excursion
  4415. (goto-char (match-beginning 0))
  4416. (and
  4417. ;; Do not match table hlines.
  4418. (not (and (equal marker "+")
  4419. (org-match-line
  4420. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4421. ;; Do not match headline stars. Do not consider
  4422. ;; stars of a headline as closing marker for bold
  4423. ;; markup either.
  4424. (not (and (equal marker "*")
  4425. (save-excursion
  4426. (forward-char)
  4427. (skip-chars-backward "*")
  4428. (looking-at-p org-outline-regexp-bol))))
  4429. ;; Match full emphasis markup regexp.
  4430. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4431. ;; Do not span over paragraph boundaries.
  4432. (not (string-match-p org-element-paragraph-separate
  4433. (match-string 2)))
  4434. ;; Do not span over cells in table rows.
  4435. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4436. (string-match-p "|" (match-string 4))))))
  4437. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4438. (m (if org-hide-emphasis-markers 4 2)))
  4439. (font-lock-prepend-text-property
  4440. (match-beginning m) (match-end m) 'face face)
  4441. (when verbatim?
  4442. (org-remove-flyspell-overlays-in
  4443. (match-beginning 0) (match-end 0))
  4444. (remove-text-properties (match-beginning 2) (match-end 2)
  4445. '(display t invisible t intangible t)))
  4446. (add-text-properties (match-beginning 2) (match-end 2)
  4447. '(font-lock-multiline t org-emphasis t))
  4448. (when (and org-hide-emphasis-markers
  4449. (not (org-at-comment-p)))
  4450. (add-text-properties (match-end 4) (match-beginning 5)
  4451. '(invisible t))
  4452. (add-text-properties (match-beginning 3) (match-end 3)
  4453. '(invisible t)))
  4454. (throw :exit t))))))))
  4455. (defun org-emphasize (&optional char)
  4456. "Insert or change an emphasis, i.e. a font like bold or italic.
  4457. If there is an active region, change that region to a new emphasis.
  4458. If there is no region, just insert the marker characters and position
  4459. the cursor between them.
  4460. CHAR should be the marker character. If it is a space, it means to
  4461. remove the emphasis of the selected region.
  4462. If CHAR is not given (for example in an interactive call) it will be
  4463. prompted for."
  4464. (interactive)
  4465. (let ((erc org-emphasis-regexp-components)
  4466. (string "") beg end move s)
  4467. (if (org-region-active-p)
  4468. (setq beg (region-beginning)
  4469. end (region-end)
  4470. string (buffer-substring beg end))
  4471. (setq move t))
  4472. (unless char
  4473. (message "Emphasis marker or tag: [%s]"
  4474. (mapconcat #'car org-emphasis-alist ""))
  4475. (setq char (read-char-exclusive)))
  4476. (if (equal char ?\s)
  4477. (setq s ""
  4478. move nil)
  4479. (unless (assoc (char-to-string char) org-emphasis-alist)
  4480. (user-error "No such emphasis marker: \"%c\"" char))
  4481. (setq s (char-to-string char)))
  4482. (while (and (> (length string) 1)
  4483. (equal (substring string 0 1) (substring string -1))
  4484. (assoc (substring string 0 1) org-emphasis-alist))
  4485. (setq string (substring string 1 -1)))
  4486. (setq string (concat s string s))
  4487. (when beg (delete-region beg end))
  4488. (unless (or (bolp)
  4489. (string-match (concat "[" (nth 0 erc) "\n]")
  4490. (char-to-string (char-before (point)))))
  4491. (insert " "))
  4492. (unless (or (eobp)
  4493. (string-match (concat "[" (nth 1 erc) "\n]")
  4494. (char-to-string (char-after (point)))))
  4495. (insert " ") (backward-char 1))
  4496. (insert string)
  4497. (and move (backward-char 1))))
  4498. (defconst org-nonsticky-props
  4499. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4500. (defsubst org-rear-nonsticky-at (pos)
  4501. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4502. (defun org-activate-links (limit)
  4503. "Add link properties to links.
  4504. This includes angle, plain, and bracket links."
  4505. (catch :exit
  4506. (while (re-search-forward org-link-any-re limit t)
  4507. (let* ((start (match-beginning 0))
  4508. (end (match-end 0))
  4509. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4510. (visible-end (or (match-end 3) (match-end 2)))
  4511. (style (cond ((eq ?< (char-after start)) 'angle)
  4512. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4513. (t 'plain))))
  4514. (when (and (memq style org-highlight-links)
  4515. ;; Do not span over paragraph boundaries.
  4516. (not (string-match-p org-element-paragraph-separate
  4517. (match-string 0)))
  4518. ;; Do not confuse plain links with tags.
  4519. (not (and (eq style 'plain)
  4520. (let ((face (get-text-property
  4521. (max (1- start) (point-min)) 'face)))
  4522. (if (consp face) (memq 'org-tag face)
  4523. (eq 'org-tag face))))))
  4524. (let* ((link-object (save-excursion
  4525. (goto-char start)
  4526. (save-match-data (org-element-link-parser))))
  4527. (link (org-element-property :raw-link link-object))
  4528. (type (org-element-property :type link-object))
  4529. (path (org-element-property :path link-object))
  4530. (face-property (pcase (org-link-get-parameter type :face)
  4531. ((and (pred functionp) face) (funcall face path))
  4532. ((and (pred facep) face) face)
  4533. ((and (pred consp) face) face) ;anonymous
  4534. (_ 'org-link)))
  4535. (properties ;for link's visible part
  4536. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4537. 'highlight)
  4538. 'keymap (or (org-link-get-parameter type :keymap)
  4539. org-mouse-map)
  4540. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4541. ((and (pred stringp) echo) echo)
  4542. ((and (pred functionp) echo) echo)
  4543. (_ (concat "LINK: " link)))
  4544. 'htmlize-link (pcase (org-link-get-parameter type
  4545. :htmlize-link)
  4546. ((and (pred functionp) f) (funcall f))
  4547. (_ `(:uri ,link)))
  4548. 'font-lock-multiline t)))
  4549. (org-remove-flyspell-overlays-in start end)
  4550. (org-rear-nonsticky-at end)
  4551. (if (not (eq 'bracket style))
  4552. (progn
  4553. (add-face-text-property start end face-property)
  4554. (add-text-properties start end properties))
  4555. ;; Handle invisible parts in bracket links.
  4556. (remove-text-properties start end '(invisible nil))
  4557. (let ((hidden
  4558. (append `(invisible
  4559. ,(or (org-link-get-parameter type :display)
  4560. 'org-link))
  4561. properties)))
  4562. (add-text-properties start visible-start hidden)
  4563. (add-face-text-property start end face-property)
  4564. (add-text-properties visible-start visible-end properties)
  4565. (add-text-properties visible-end end hidden)
  4566. (org-rear-nonsticky-at visible-start)
  4567. (org-rear-nonsticky-at visible-end)))
  4568. (let ((f (org-link-get-parameter type :activate-func)))
  4569. (when (functionp f)
  4570. (funcall f start end path (eq style 'bracket))))
  4571. (throw :exit t))))) ;signal success
  4572. nil))
  4573. (defun org-activate-code (limit)
  4574. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4575. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4576. (remove-text-properties (match-beginning 0) (match-end 0)
  4577. '(display t invisible t intangible t))
  4578. t))
  4579. (defcustom org-src-fontify-natively t
  4580. "When non-nil, fontify code in code blocks.
  4581. See also the `org-block' face."
  4582. :type 'boolean
  4583. :version "26.1"
  4584. :package-version '(Org . "8.3")
  4585. :group 'org-appearance
  4586. :group 'org-babel)
  4587. (defcustom org-allow-promoting-top-level-subtree nil
  4588. "When non-nil, allow promoting a top level subtree.
  4589. The leading star of the top level headline will be replaced
  4590. by a #."
  4591. :type 'boolean
  4592. :version "24.1"
  4593. :group 'org-appearance)
  4594. (defun org-fontify-meta-lines-and-blocks (limit)
  4595. (condition-case nil
  4596. (org-fontify-meta-lines-and-blocks-1 limit)
  4597. (error (message "Org mode fontification error in %S at %d"
  4598. (current-buffer)
  4599. (line-number-at-pos)))))
  4600. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4601. "Fontify #+ lines and blocks."
  4602. (let ((case-fold-search t))
  4603. (when (re-search-forward
  4604. (rx bol (group (zero-or-more (any " \t")) "#"
  4605. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4606. (any " \t")
  4607. eol))
  4608. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4609. (zero-or-more (any " \t"))
  4610. (group (group (zero-or-more (not (any " \t\n"))))
  4611. (zero-or-more (any " \t"))
  4612. (group (zero-or-more any)))))
  4613. limit t)
  4614. (let ((beg (match-beginning 0))
  4615. (end-of-beginline (match-end 0))
  4616. ;; Including \n at end of #+begin line will include \n
  4617. ;; after the end of block content.
  4618. (block-start (match-end 0))
  4619. (block-end nil)
  4620. (lang (match-string 7)) ; The language, if it is a source block.
  4621. (bol-after-beginline (line-beginning-position 2))
  4622. (dc1 (downcase (match-string 2)))
  4623. (dc3 (downcase (match-string 3)))
  4624. (whole-blockline org-fontify-whole-block-delimiter-line)
  4625. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4626. (cond
  4627. ((and (match-end 4) (equal dc3 "+begin"))
  4628. ;; Truly a block
  4629. (setq block-type (downcase (match-string 5))
  4630. ;; Src, example, export, maybe more.
  4631. quoting (member block-type org-protecting-blocks))
  4632. (when (re-search-forward
  4633. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4634. (seq (zero-or-more (any " \t"))
  4635. "#+end"
  4636. ,(match-string 4)
  4637. word-end
  4638. (zero-or-more any)))))
  4639. ;; We look further than LIMIT on purpose.
  4640. nil t)
  4641. ;; We do have a matching #+end line.
  4642. (setq beg-of-endline (match-beginning 0)
  4643. end-of-endline (match-end 0)
  4644. nl-before-endline (1- (match-beginning 0)))
  4645. (setq block-end (match-beginning 0)) ; Include the final newline.
  4646. (when quoting
  4647. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4648. (remove-text-properties beg end-of-endline
  4649. '(display t invisible t intangible t)))
  4650. (add-text-properties
  4651. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4652. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4653. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4654. (cond
  4655. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4656. (save-match-data
  4657. (org-src-font-lock-fontify-block lang block-start block-end))
  4658. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4659. (quoting
  4660. (add-text-properties
  4661. bol-after-beginline beg-of-endline
  4662. (list 'face
  4663. (list :inherit
  4664. (let ((face-name
  4665. (intern (format "org-block-%s" lang))))
  4666. (append (and (facep face-name) (list face-name))
  4667. '(org-block)))))))
  4668. ((not org-fontify-quote-and-verse-blocks))
  4669. ((string= block-type "quote")
  4670. (add-face-text-property
  4671. bol-after-beginline beg-of-endline 'org-quote t))
  4672. ((string= block-type "verse")
  4673. (add-face-text-property
  4674. bol-after-beginline beg-of-endline 'org-verse t)))
  4675. ;; Fontify the #+begin and #+end lines of the blocks
  4676. (add-text-properties
  4677. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4678. '(face org-block-begin-line))
  4679. (unless (eq (char-after beg-of-endline) ?*)
  4680. (add-text-properties
  4681. beg-of-endline
  4682. (if whole-blockline
  4683. (let ((beg-of-next-line (1+ end-of-endline)))
  4684. (min (point-max) beg-of-next-line))
  4685. (min (point-max) end-of-endline))
  4686. '(face org-block-end-line)))
  4687. t))
  4688. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4689. (org-remove-flyspell-overlays-in
  4690. (match-beginning 0)
  4691. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4692. (add-text-properties
  4693. beg (match-end 3)
  4694. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4695. '(font-lock-fontified t invisible t)
  4696. '(font-lock-fontified t face org-document-info-keyword)))
  4697. (add-text-properties
  4698. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4699. (if (string-equal dc1 "+title:")
  4700. '(font-lock-fontified t face org-document-title)
  4701. '(font-lock-fontified t face org-document-info))))
  4702. ((string-prefix-p "+caption" dc1)
  4703. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4704. (remove-text-properties (match-beginning 0) (match-end 0)
  4705. '(display t invisible t intangible t))
  4706. ;; Handle short captions
  4707. (save-excursion
  4708. (beginning-of-line)
  4709. (looking-at (rx (group (zero-or-more (any " \t"))
  4710. "#+caption"
  4711. (optional "[" (zero-or-more any) "]")
  4712. ":")
  4713. (zero-or-more (any " \t")))))
  4714. (add-text-properties (line-beginning-position) (match-end 1)
  4715. '(font-lock-fontified t face org-meta-line))
  4716. (add-text-properties (match-end 0) (line-end-position)
  4717. '(font-lock-fontified t face org-block))
  4718. t)
  4719. ((member dc3 '(" " ""))
  4720. ;; Just a comment, the plus was not there
  4721. (org-remove-flyspell-overlays-in beg (match-end 0))
  4722. (add-text-properties
  4723. beg (match-end 0)
  4724. '(font-lock-fontified t face font-lock-comment-face)))
  4725. (t ;; Just any other in-buffer setting, but not indented
  4726. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4727. (remove-text-properties (match-beginning 0) (match-end 0)
  4728. '(display t invisible t intangible t))
  4729. (add-text-properties beg (match-end 0)
  4730. '(font-lock-fontified t face org-meta-line))
  4731. t))))))
  4732. (defun org-fontify-drawers (limit)
  4733. "Fontify drawers."
  4734. (when (re-search-forward org-drawer-regexp limit t)
  4735. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4736. '(font-lock-fontified t face org-drawer))
  4737. (org-remove-flyspell-overlays-in
  4738. (line-beginning-position) (line-beginning-position 2))
  4739. t))
  4740. (defun org-fontify-macros (limit)
  4741. "Fontify macros."
  4742. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4743. (let ((begin (match-beginning 0))
  4744. (opening-end (match-beginning 1)))
  4745. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4746. (match-string 1))
  4747. (let ((end (match-end 1))
  4748. (closing-start (match-beginning 1)))
  4749. (add-text-properties
  4750. begin end
  4751. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4752. (org-remove-flyspell-overlays-in begin end)
  4753. (when org-hide-macro-markers
  4754. (add-text-properties begin opening-end '(invisible t))
  4755. (add-text-properties closing-start end '(invisible t)))
  4756. t)))))
  4757. (defun org-fontify-extend-region (beg end _old-len)
  4758. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4759. (1+ end) end))
  4760. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4761. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4762. (extend
  4763. (lambda (r1 r2 dir)
  4764. (let ((re (replace-regexp-in-string
  4765. "\\(begin\\|end\\)" r1
  4766. (replace-regexp-in-string
  4767. "[][]" r2
  4768. (match-string-no-properties 0)))))
  4769. (re-search-forward (regexp-quote re) nil t dir)))))
  4770. (goto-char beg)
  4771. (back-to-indentation)
  4772. (save-match-data
  4773. (cond ((looking-at end-re)
  4774. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4775. ((looking-at begin-re)
  4776. (cons beg (or (funcall extend "end" "]" 1) end)))
  4777. (t (cons beg end))))))
  4778. (defun org-activate-footnote-links (limit)
  4779. "Add text properties for footnotes."
  4780. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4781. (when fn
  4782. (let* ((beg (nth 1 fn))
  4783. (end (nth 2 fn))
  4784. (label (car fn))
  4785. (referencep (/= (line-beginning-position) beg)))
  4786. (when (and referencep (nth 3 fn))
  4787. (save-excursion
  4788. (goto-char beg)
  4789. (search-forward (or label "fn:"))
  4790. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4791. (add-text-properties beg end
  4792. (list 'mouse-face 'highlight
  4793. 'keymap org-mouse-map
  4794. 'help-echo
  4795. (if referencep "Footnote reference"
  4796. "Footnote definition")
  4797. 'font-lock-fontified t
  4798. 'font-lock-multiline t
  4799. 'face 'org-footnote))))))
  4800. (defun org-activate-dates (limit)
  4801. "Add text properties for dates."
  4802. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4803. (not (equal (char-before (match-beginning 0)) 91)))
  4804. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4805. (add-text-properties (match-beginning 0) (match-end 0)
  4806. (list 'mouse-face 'highlight
  4807. 'keymap org-mouse-map))
  4808. (org-rear-nonsticky-at (match-end 0))
  4809. (when org-display-custom-times
  4810. ;; If it's a date range, activate custom time for second date.
  4811. (when (match-end 3)
  4812. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4813. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4814. t))
  4815. (defun org-activate-target-links (limit)
  4816. "Add text properties for target matches."
  4817. (when org-target-link-regexp
  4818. (let ((case-fold-search t))
  4819. ;; `org-target-link-regexp' matches one character before the
  4820. ;; actual target.
  4821. (unless (bolp) (forward-char -1))
  4822. (when (re-search-forward org-target-link-regexp limit t)
  4823. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4824. (add-text-properties (match-beginning 1) (match-end 1)
  4825. (list 'mouse-face 'highlight
  4826. 'keymap org-mouse-map
  4827. 'help-echo "Radio target link"
  4828. 'org-linked-text t))
  4829. (org-rear-nonsticky-at (match-end 1))
  4830. t))))
  4831. (defvar org-latex-and-related-regexp nil
  4832. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4833. (defun org-compute-latex-and-related-regexp ()
  4834. "Compute regular expression for LaTeX, entities and sub/superscript.
  4835. Result depends on variable `org-highlight-latex-and-related'."
  4836. (let ((re-sub
  4837. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4838. ((eq org-use-sub-superscripts '{})
  4839. (list org-match-substring-with-braces-regexp))
  4840. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4841. (re-latex
  4842. (when (or (memq 'latex org-highlight-latex-and-related)
  4843. (memq 'native org-highlight-latex-and-related))
  4844. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4845. (delq nil
  4846. (mapcar (lambda (x)
  4847. (and (member (car x) matchers) (nth 1 x)))
  4848. org-latex-regexps)))))
  4849. (re-entities
  4850. (when (memq 'entities org-highlight-latex-and-related)
  4851. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4852. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4853. (setq-local org-latex-and-related-regexp
  4854. (mapconcat #'identity
  4855. (append re-latex re-entities re-sub)
  4856. "\\|"))))
  4857. (defun org-do-latex-and-related (limit)
  4858. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4859. Stop at first highlighted object, if any. Return t if some
  4860. highlighting was done, nil otherwise."
  4861. (when (org-string-nw-p org-latex-and-related-regexp)
  4862. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4863. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4864. (catch 'found
  4865. (while (and (< (point) limit)
  4866. (re-search-forward org-latex-and-related-regexp nil t))
  4867. (cond
  4868. ((>= (match-beginning 0) limit)
  4869. (throw 'found nil))
  4870. ((cl-some (lambda (f)
  4871. (memq f '(org-code org-verbatim underline
  4872. org-special-keyword)))
  4873. (save-excursion
  4874. (goto-char (1+ (match-beginning 0)))
  4875. (face-at-point nil t))))
  4876. ;; Try to limit false positives. In this case, ignore
  4877. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4878. ;; contain an empty line.
  4879. ((save-excursion
  4880. (goto-char (match-beginning 0))
  4881. (and (looking-at-p latex-prefix-re)
  4882. (save-match-data
  4883. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4884. (t
  4885. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4886. '(?_ ?^))
  4887. 1
  4888. 0))
  4889. (start (+ offset (match-beginning 0)))
  4890. (end (match-end 0)))
  4891. (if (memq 'native org-highlight-latex-and-related)
  4892. (org-src-font-lock-fontify-block "latex" start end)
  4893. (font-lock-prepend-text-property start end
  4894. 'face 'org-latex-and-related))
  4895. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4896. '(font-lock-multiline t))
  4897. (throw 'found t)))))
  4898. nil))))
  4899. (defun org-restart-font-lock ()
  4900. "Restart `font-lock-mode', to force refontification."
  4901. (when font-lock-mode
  4902. (font-lock-mode -1)
  4903. (font-lock-mode 1)))
  4904. (defun org-activate-tags (limit)
  4905. (when (re-search-forward org-tag-line-re limit t)
  4906. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4907. (add-text-properties (match-beginning 1) (match-end 1)
  4908. (list 'mouse-face 'highlight
  4909. 'keymap org-mouse-map))
  4910. (org-rear-nonsticky-at (match-end 1))
  4911. t))
  4912. (defun org-outline-level ()
  4913. "Compute the outline level of the heading at point.
  4914. If this is called at a normal headline, the level is the number
  4915. of stars. Use `org-reduced-level' to remove the effect of
  4916. `org-odd-levels'. Unlike to `org-current-level', this function
  4917. takes into consideration inlinetasks."
  4918. (org-with-wide-buffer
  4919. (end-of-line)
  4920. (if (re-search-backward org-outline-regexp-bol nil t)
  4921. (1- (- (match-end 0) (match-beginning 0)))
  4922. 0)))
  4923. (defvar org-font-lock-keywords nil)
  4924. (defsubst org-re-property (property &optional literal allow-null value)
  4925. "Return a regexp matching a PROPERTY line.
  4926. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4927. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4928. non-nil, match properties even without a value.
  4929. Match group 3 is set to the value when it exists. If there is no
  4930. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4931. With optional argument VALUE, match only property lines with
  4932. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4933. unless LITERAL is non-nil."
  4934. (concat
  4935. "^\\(?4:[ \t]*\\)"
  4936. (format "\\(?1::\\(?2:%s\\):\\)"
  4937. (if literal property (regexp-quote property)))
  4938. (cond (value
  4939. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4940. (if literal value (regexp-quote value))))
  4941. (allow-null
  4942. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4943. (t
  4944. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4945. (defconst org-property-re
  4946. (org-re-property "\\S-+" 'literal t)
  4947. "Regular expression matching a property line.
  4948. There are four matching groups:
  4949. 1: :PROPKEY: including the leading and trailing colon,
  4950. 2: PROPKEY without the leading and trailing colon,
  4951. 3: PROPVAL without leading or trailing spaces,
  4952. 4: the indentation of the current line,
  4953. 5: trailing whitespace.")
  4954. (defvar org-font-lock-hook nil
  4955. "Functions to be called for special font lock stuff.")
  4956. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4957. (defvar org-font-lock-set-keywords-hook nil
  4958. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4959. This is called after `org-font-lock-extra-keywords' is defined, but before
  4960. it is installed to be used by font lock. This can be useful if something
  4961. needs to be inserted at a specific position in the font-lock sequence.")
  4962. (defun org-font-lock-hook (limit)
  4963. "Run `org-font-lock-hook' within LIMIT."
  4964. (run-hook-with-args 'org-font-lock-hook limit))
  4965. (defun org-set-font-lock-defaults ()
  4966. "Set font lock defaults for the current buffer."
  4967. (let ((org-font-lock-extra-keywords
  4968. (list
  4969. ;; Call the hook
  4970. '(org-font-lock-hook)
  4971. ;; Headlines
  4972. `(,(if org-fontify-whole-heading-line
  4973. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4974. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4975. (1 (org-get-level-face 1))
  4976. (2 (org-get-level-face 2))
  4977. (3 (org-get-level-face 3)))
  4978. ;; Table lines
  4979. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4980. (1 'org-table t))
  4981. ;; Table internals
  4982. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4983. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4984. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4985. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4986. ;; Properties
  4987. (list org-property-re
  4988. '(1 'org-special-keyword t)
  4989. '(3 'org-property-value t))
  4990. ;; Drawers
  4991. '(org-fontify-drawers)
  4992. ;; Link related fontification.
  4993. '(org-activate-links)
  4994. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4995. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4996. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4997. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4998. ;; Targets.
  4999. (list org-radio-target-regexp '(0 'org-target t))
  5000. (list org-target-regexp '(0 'org-target t))
  5001. ;; Diary sexps.
  5002. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5003. ;; Macro
  5004. '(org-fontify-macros)
  5005. ;; TODO keyword
  5006. (list (format org-heading-keyword-regexp-format
  5007. org-todo-regexp)
  5008. '(2 (org-get-todo-face 2) prepend))
  5009. ;; TODO
  5010. (when org-fontify-todo-headline
  5011. (list (format org-heading-keyword-regexp-format
  5012. (concat
  5013. "\\(?:"
  5014. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5015. "\\)"))
  5016. '(2 'org-headline-todo prepend)))
  5017. ;; DONE
  5018. (when org-fontify-done-headline
  5019. (list (format org-heading-keyword-regexp-format
  5020. (concat
  5021. "\\(?:"
  5022. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5023. "\\)"))
  5024. '(2 'org-headline-done prepend)))
  5025. ;; Priorities
  5026. '(org-font-lock-add-priority-faces)
  5027. ;; Tags
  5028. '(org-font-lock-add-tag-faces)
  5029. ;; Tags groups
  5030. (when (and org-group-tags org-tag-groups-alist)
  5031. (list (concat org-outline-regexp-bol ".+\\(:"
  5032. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5033. ":\\).*$")
  5034. '(1 'org-tag-group prepend)))
  5035. ;; Special keywords
  5036. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5037. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5038. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5039. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5040. ;; Emphasis
  5041. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5042. ;; Checkboxes
  5043. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5044. 1 'org-checkbox prepend)
  5045. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5046. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5047. (0 (org-get-checkbox-statistics-face) prepend)))
  5048. ;; Description list items
  5049. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5050. 1 'org-list-dt prepend)
  5051. ;; Inline export snippets
  5052. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5053. (1 'font-lock-comment-face t)
  5054. (2 'org-tag t)
  5055. (3 'font-lock-comment-face t))
  5056. ;; ARCHIVEd headings
  5057. (list (concat
  5058. org-outline-regexp-bol
  5059. "\\(.*:" org-archive-tag ":.*\\)")
  5060. '(1 'org-archived prepend))
  5061. ;; Specials
  5062. '(org-do-latex-and-related)
  5063. '(org-fontify-entities)
  5064. '(org-raise-scripts)
  5065. ;; Code
  5066. '(org-activate-code (1 'org-code t))
  5067. ;; COMMENT
  5068. (list (format
  5069. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5070. org-todo-regexp
  5071. org-comment-string)
  5072. '(9 'org-special-keyword t))
  5073. ;; Blocks and meta lines
  5074. '(org-fontify-meta-lines-and-blocks)
  5075. ;; Citations
  5076. '(org-cite-activate))))
  5077. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5078. (run-hooks 'org-font-lock-set-keywords-hook)
  5079. ;; Now set the full font-lock-keywords
  5080. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5081. (setq-local font-lock-defaults
  5082. '(org-font-lock-keywords t nil nil backward-paragraph))
  5083. (setq-local font-lock-extend-after-change-region-function
  5084. #'org-fontify-extend-region)
  5085. (kill-local-variable 'font-lock-keywords)
  5086. nil))
  5087. (defun org-toggle-pretty-entities ()
  5088. "Toggle the composition display of entities as UTF8 characters."
  5089. (interactive)
  5090. (setq-local org-pretty-entities (not org-pretty-entities))
  5091. (org-restart-font-lock)
  5092. (if org-pretty-entities
  5093. (message "Entities are now displayed as UTF8 characters")
  5094. (save-restriction
  5095. (widen)
  5096. (decompose-region (point-min) (point-max))
  5097. (message "Entities are now displayed as plain text"))))
  5098. (defvar-local org-custom-properties-overlays nil
  5099. "List of overlays used for custom properties.")
  5100. (defun org-toggle-custom-properties-visibility ()
  5101. "Display or hide properties in `org-custom-properties'."
  5102. (interactive)
  5103. (if org-custom-properties-overlays
  5104. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5105. (setq org-custom-properties-overlays nil))
  5106. (when org-custom-properties
  5107. (org-with-wide-buffer
  5108. (goto-char (point-min))
  5109. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5110. (while (re-search-forward regexp nil t)
  5111. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5112. (when (and end (< (point) end))
  5113. ;; Hide first custom property in current drawer.
  5114. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5115. (overlay-put o 'invisible t)
  5116. (overlay-put o 'org-custom-property t)
  5117. (push o org-custom-properties-overlays))
  5118. ;; Hide additional custom properties in the same drawer.
  5119. (while (re-search-forward regexp end t)
  5120. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5121. (overlay-put o 'invisible t)
  5122. (overlay-put o 'org-custom-property t)
  5123. (push o org-custom-properties-overlays)))))
  5124. ;; Each entry is limited to a single property drawer.
  5125. (outline-next-heading)))))))
  5126. (defun org-fontify-entities (limit)
  5127. "Find an entity to fontify."
  5128. (let (ee)
  5129. (when org-pretty-entities
  5130. (catch 'match
  5131. ;; "\_ "-family is left out on purpose. Only the first one,
  5132. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5133. ;; confusing when adding a second white space character.
  5134. (while (re-search-forward
  5135. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5136. limit t)
  5137. (when (and (not (org-at-comment-p))
  5138. (setq ee (org-entity-get (match-string 1)))
  5139. (= (length (nth 6 ee)) 1))
  5140. (let* ((end (if (equal (match-string 2) "{}")
  5141. (match-end 2)
  5142. (match-end 1))))
  5143. (add-text-properties
  5144. (match-beginning 0) end
  5145. (list 'font-lock-fontified t))
  5146. (compose-region (match-beginning 0) end
  5147. (nth 6 ee) nil)
  5148. (backward-char 1)
  5149. (throw 'match t))))
  5150. nil))))
  5151. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5152. "Fontify string S like in Org mode."
  5153. (with-temp-buffer
  5154. (insert s)
  5155. (let ((org-odd-levels-only odd-levels))
  5156. (org-mode)
  5157. (org-font-lock-ensure)
  5158. (buffer-string))))
  5159. (defun org-get-level-face (n)
  5160. "Get the right face for match N in font-lock matching of headlines."
  5161. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5162. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5163. (org-f (if org-cycle-level-faces
  5164. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5165. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5166. (cond
  5167. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5168. ((eq n 2) org-f)
  5169. (t (unless org-level-color-stars-only org-f)))))
  5170. (defun org-face-from-face-or-color (context inherit face-or-color)
  5171. "Create a face list that inherits INHERIT, but sets the foreground color.
  5172. When FACE-OR-COLOR is not a string, just return it."
  5173. (if (stringp face-or-color)
  5174. (list :inherit inherit
  5175. (cdr (assoc context org-faces-easy-properties))
  5176. face-or-color)
  5177. face-or-color))
  5178. (defun org-get-todo-face (kwd)
  5179. "Get the right face for a TODO keyword KWD.
  5180. If KWD is a number, get the corresponding match group."
  5181. (when (numberp kwd) (setq kwd (match-string kwd)))
  5182. (or (org-face-from-face-or-color
  5183. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5184. (and (member kwd org-done-keywords) 'org-done)
  5185. 'org-todo))
  5186. (defun org-get-priority-face (priority)
  5187. "Get the right face for PRIORITY.
  5188. PRIORITY is a character."
  5189. (or (org-face-from-face-or-color
  5190. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5191. 'org-priority))
  5192. (defun org-get-tag-face (tag)
  5193. "Get the right face for TAG.
  5194. If TAG is a number, get the corresponding match group."
  5195. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5196. (or (org-face-from-face-or-color
  5197. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5198. 'org-tag)))
  5199. (defvar org-priority-regexp) ; defined later in the file
  5200. (defun org-font-lock-add-priority-faces (limit)
  5201. "Add the special priority faces."
  5202. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5203. (let ((beg (match-beginning 1))
  5204. (end (1+ (match-end 2))))
  5205. (add-face-text-property
  5206. beg end
  5207. (org-get-priority-face (string-to-char (match-string 2))))
  5208. (add-text-properties
  5209. beg end
  5210. (list 'font-lock-fontified t)))))
  5211. (defun org-font-lock-add-tag-faces (limit)
  5212. "Add the special tag faces."
  5213. (when (and org-tag-faces org-tags-special-faces-re)
  5214. (while (re-search-forward org-tags-special-faces-re limit t)
  5215. (add-face-text-property
  5216. (match-beginning 1)
  5217. (match-end 1)
  5218. (org-get-tag-face 1))
  5219. (add-text-properties (match-beginning 1) (match-end 1)
  5220. (list 'font-lock-fontified t))
  5221. (backward-char 1))))
  5222. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5223. "Remove fontification and activation overlays from links."
  5224. (font-lock-default-unfontify-region beg end)
  5225. (let* ((buffer-undo-list t)
  5226. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5227. (inhibit-modification-hooks t)
  5228. deactivate-mark buffer-file-name buffer-file-truename)
  5229. (decompose-region beg end)
  5230. (remove-text-properties beg end
  5231. '(mouse-face t keymap t org-linked-text t
  5232. invisible t intangible t
  5233. org-emphasis t))
  5234. (org-remove-font-lock-display-properties beg end)))
  5235. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5236. ((raise 0.3) (height 0.7))
  5237. ((raise -0.5))
  5238. ((raise 0.5)))
  5239. "Display properties for showing superscripts and subscripts.")
  5240. (defun org-remove-font-lock-display-properties (beg end)
  5241. "Remove specific display properties that have been added by font lock.
  5242. The will remove the raise properties that are used to show superscripts
  5243. and subscripts."
  5244. (let (next prop)
  5245. (while (< beg end)
  5246. (setq next (next-single-property-change beg 'display nil end)
  5247. prop (get-text-property beg 'display))
  5248. (when (member prop org-script-display)
  5249. (put-text-property beg next 'display nil))
  5250. (setq beg next))))
  5251. (defun org-raise-scripts (limit)
  5252. "Add raise properties to sub/superscripts."
  5253. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5254. (re-search-forward
  5255. (if (eq org-use-sub-superscripts t)
  5256. org-match-substring-regexp
  5257. org-match-substring-with-braces-regexp)
  5258. limit t))
  5259. (let* ((pos (point)) table-p comment-p
  5260. (mpos (match-beginning 3))
  5261. (emph-p (get-text-property mpos 'org-emphasis))
  5262. (link-p (get-text-property mpos 'mouse-face))
  5263. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5264. (goto-char (point-at-bol))
  5265. (setq table-p (looking-at-p org-table-dataline-regexp)
  5266. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5267. (goto-char pos)
  5268. ;; Handle a_b^c
  5269. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5270. (unless (or comment-p emph-p link-p keyw-p)
  5271. (put-text-property (match-beginning 3) (match-end 0)
  5272. 'display
  5273. (if (equal (char-after (match-beginning 2)) ?^)
  5274. (nth (if table-p 3 1) org-script-display)
  5275. (nth (if table-p 2 0) org-script-display)))
  5276. (add-text-properties (match-beginning 2) (match-end 2)
  5277. (list 'invisible t))
  5278. (when (and (eq (char-after (match-beginning 3)) ?{)
  5279. (eq (char-before (match-end 3)) ?}))
  5280. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5281. (list 'invisible t))
  5282. (add-text-properties (1- (match-end 3)) (match-end 3)
  5283. (list 'invisible t))))
  5284. t)))
  5285. (defun org-remove-empty-overlays-at (pos)
  5286. "Remove outline overlays that do not contain non-white stuff."
  5287. (dolist (o (overlays-at pos))
  5288. (and (eq 'outline (overlay-get o 'invisible))
  5289. (not (string-match-p
  5290. "\\S-" (buffer-substring (overlay-start o)
  5291. (overlay-end o))))
  5292. (delete-overlay o))))
  5293. (defun org-show-empty-lines-in-parent ()
  5294. "Move to the parent and re-show empty lines before visible headlines."
  5295. (save-excursion
  5296. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5297. (org-cycle-show-empty-lines context))))
  5298. (defun org-files-list ()
  5299. "Return `org-agenda-files' list, plus all open Org files.
  5300. This is useful for operations that need to scan all of a user's
  5301. open and agenda-wise Org files."
  5302. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5303. (dolist (buf (buffer-list))
  5304. (with-current-buffer buf
  5305. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5306. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5307. :test #'equal))))
  5308. files))
  5309. (defsubst org-entry-beginning-position ()
  5310. "Return the beginning position of the current entry."
  5311. (save-excursion (org-back-to-heading t) (point)))
  5312. (defsubst org-entry-end-position ()
  5313. "Return the end position of the current entry."
  5314. (save-excursion (outline-next-heading) (point)))
  5315. (defun org-subtree-end-visible-p ()
  5316. "Is the end of the current subtree visible?"
  5317. (pos-visible-in-window-p
  5318. (save-excursion (org-end-of-subtree t) (point))))
  5319. (defun org-first-headline-recenter ()
  5320. "Move cursor to the first headline and recenter the headline."
  5321. (let ((window (get-buffer-window)))
  5322. (when window
  5323. (goto-char (point-min))
  5324. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5325. (set-window-start window (line-beginning-position))))))
  5326. ;;; Visibility (headlines, blocks, drawers)
  5327. ;;;; Headlines visibility
  5328. (defun org-show-entry ()
  5329. "Show the body directly following its heading.
  5330. Show the heading too, if it is currently invisible."
  5331. (interactive)
  5332. (save-excursion
  5333. (org-back-to-heading-or-point-min t)
  5334. (org-flag-region
  5335. (line-end-position 0)
  5336. (save-excursion
  5337. (if (re-search-forward
  5338. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5339. (match-beginning 1)
  5340. (point-max)))
  5341. nil
  5342. 'outline)
  5343. (org-cycle-hide-drawers 'children)))
  5344. (defun org-hide-entry ()
  5345. "Hide the body directly following its heading."
  5346. (interactive)
  5347. (save-excursion
  5348. (org-back-to-heading-or-point-min t)
  5349. (when (org-at-heading-p) (forward-line))
  5350. (org-flag-region
  5351. (line-end-position 0)
  5352. (save-excursion
  5353. (if (re-search-forward
  5354. (concat "[\r\n]" org-outline-regexp) nil t)
  5355. (line-end-position 0)
  5356. (point-max)))
  5357. t
  5358. 'outline)))
  5359. (defun org-show-children (&optional level)
  5360. "Show all direct subheadings of this heading.
  5361. Prefix arg LEVEL is how many levels below the current level
  5362. should be shown. Default is enough to cause the following
  5363. heading to appear."
  5364. (interactive "p")
  5365. (unless (org-before-first-heading-p)
  5366. (save-excursion
  5367. (org-with-limited-levels (org-back-to-heading t))
  5368. (let* ((current-level (funcall outline-level))
  5369. (max-level (org-get-valid-level
  5370. current-level
  5371. (if level (prefix-numeric-value level) 1)))
  5372. (end (save-excursion (org-end-of-subtree t t)))
  5373. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5374. (past-first-child nil)
  5375. ;; Make sure to skip inlinetasks.
  5376. (re (format regexp-fmt
  5377. current-level
  5378. (cond
  5379. ((not (featurep 'org-inlinetask)) "")
  5380. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5381. 3))
  5382. (t (1- org-inlinetask-min-level))))))
  5383. ;; Display parent heading.
  5384. (org-flag-heading nil)
  5385. (forward-line)
  5386. ;; Display children. First child may be deeper than expected
  5387. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5388. ;; MAX-LEVEL accordingly.
  5389. (while (re-search-forward re end t)
  5390. (unless past-first-child
  5391. (setq re (format regexp-fmt
  5392. current-level
  5393. (max (funcall outline-level) max-level)))
  5394. (setq past-first-child t))
  5395. (org-flag-heading nil))))))
  5396. (defun org-show-subtree ()
  5397. "Show everything after this heading at deeper levels."
  5398. (interactive)
  5399. (org-flag-region
  5400. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5401. ;;;; Blocks and drawers visibility
  5402. (defun org--hide-wrapper-toggle (element category force no-error)
  5403. "Toggle visibility for ELEMENT.
  5404. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5405. either `block' or `drawer'. When FORCE is `off', show the block
  5406. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5407. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5408. Return a non-nil value when toggling is successful."
  5409. (let ((type (org-element-type element)))
  5410. (cond
  5411. ((memq type
  5412. (pcase category
  5413. (`drawer '(drawer property-drawer))
  5414. (`block '(center-block
  5415. comment-block dynamic-block example-block export-block
  5416. quote-block special-block src-block verse-block))
  5417. (_ (error "Unknown category: %S" category))))
  5418. (let* ((post (org-element-property :post-affiliated element))
  5419. (start (save-excursion
  5420. (goto-char post)
  5421. (line-end-position)))
  5422. (end (save-excursion
  5423. (goto-char (org-element-property :end element))
  5424. (skip-chars-backward " \t\n")
  5425. (line-end-position))))
  5426. ;; Do nothing when not before or at the block opening line or
  5427. ;; at the block closing line.
  5428. (unless (let ((eol (line-end-position)))
  5429. (and (> eol start) (/= eol end)))
  5430. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5431. (flag
  5432. (cond ((eq force 'off) nil)
  5433. (force t)
  5434. ((eq spec (get-char-property start 'invisible)) nil)
  5435. (t t))))
  5436. (org-flag-region start end flag spec))
  5437. ;; When the block is hidden away, make sure point is left in
  5438. ;; a visible part of the buffer.
  5439. (when (invisible-p (max (1- (point)) (point-min)))
  5440. (goto-char post))
  5441. ;; Signal success.
  5442. t)))
  5443. (no-error nil)
  5444. (t
  5445. (user-error (if (eq category 'drawer)
  5446. "Not at a drawer"
  5447. "Not at a block"))))))
  5448. (defun org-hide-block-toggle (&optional force no-error element)
  5449. "Toggle the visibility of the current block.
  5450. When optional argument FORCE is `off', make block visible. If it
  5451. is non-nil, hide it unconditionally. Throw an error when not at
  5452. a block, unless NO-ERROR is non-nil. When optional argument
  5453. ELEMENT is provided, consider it instead of the current block.
  5454. Return a non-nil value when toggling is successful."
  5455. (interactive)
  5456. (org--hide-wrapper-toggle
  5457. (or element (org-element-at-point)) 'block force no-error))
  5458. (defun org-hide-drawer-toggle (&optional force no-error element)
  5459. "Toggle the visibility of the current drawer.
  5460. When optional argument FORCE is `off', make drawer visible. If
  5461. it is non-nil, hide it unconditionally. Throw an error when not
  5462. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5463. ELEMENT is provided, consider it instead of the current drawer.
  5464. Return a non-nil value when toggling is successful."
  5465. (interactive)
  5466. (org--hide-wrapper-toggle
  5467. (or element (org-element-at-point)) 'drawer force no-error))
  5468. (defun org-hide-block-all ()
  5469. "Fold all blocks in the current buffer."
  5470. (interactive)
  5471. (org-show-all '(blocks))
  5472. (org-block-map 'org-hide-block-toggle))
  5473. (defun org-hide-drawer-all ()
  5474. "Fold all drawers in the current buffer."
  5475. (let ((begin (point-min))
  5476. (end (point-max)))
  5477. (org--hide-drawers begin end)))
  5478. (defun org-cycle-hide-drawers (state)
  5479. "Re-hide all drawers after a visibility state change.
  5480. STATE should be one of the symbols listed in the docstring of
  5481. `org-cycle-hook'."
  5482. (when (derived-mode-p 'org-mode)
  5483. (cond ((not (memq state '(overview folded contents)))
  5484. (let* ((global? (eq state 'all))
  5485. (beg (if global? (point-min) (line-beginning-position)))
  5486. (end (cond (global? (point-max))
  5487. ((eq state 'children) (org-entry-end-position))
  5488. (t (save-excursion (org-end-of-subtree t t))))))
  5489. (org--hide-drawers beg end)))
  5490. ((memq state '(overview contents))
  5491. ;; Hide drawers before first heading.
  5492. (let ((beg (point-min))
  5493. (end (save-excursion
  5494. (goto-char (point-min))
  5495. (if (org-before-first-heading-p)
  5496. (org-entry-end-position)
  5497. (point-min)))))
  5498. (when (< beg end)
  5499. (org--hide-drawers beg end)))))))
  5500. (defun org--hide-drawers (begin end)
  5501. "Hide all drawers between BEGIN and END."
  5502. (save-excursion
  5503. (goto-char begin)
  5504. (while (re-search-forward org-drawer-regexp end t)
  5505. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5506. 'invisible))
  5507. (o (cdr-safe pair)))
  5508. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5509. (pcase (get-char-property-and-overlay (point) 'invisible)
  5510. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5511. (_
  5512. (let* ((drawer (org-element-at-point))
  5513. (type (org-element-type drawer)))
  5514. (when (memq type '(drawer property-drawer))
  5515. (org-hide-drawer-toggle t nil drawer)
  5516. ;; Make sure to skip drawer entirely or we might flag it
  5517. ;; another time when matching its ending line with
  5518. ;; `org-drawer-regexp'.
  5519. (goto-char (org-element-property :end drawer)))))))))))
  5520. ;;;; Visibility cycling
  5521. (defvar-local org-cycle-global-status nil)
  5522. (put 'org-cycle-global-status 'org-state t)
  5523. (defvar-local org-cycle-subtree-status nil)
  5524. (put 'org-cycle-subtree-status 'org-state t)
  5525. (defun org-show-all (&optional types)
  5526. "Show all contents in the visible part of the buffer.
  5527. By default, the function expands headings, blocks and drawers.
  5528. When optional argument TYPE is a list of symbols among `blocks',
  5529. `drawers' and `headings', to only expand one specific type."
  5530. (interactive)
  5531. (let ((types (or types '(blocks drawers headings))))
  5532. (when (memq 'blocks types)
  5533. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5534. (cond
  5535. ;; Fast path. Since headings and drawers share the same
  5536. ;; invisible spec, clear everything in one go.
  5537. ((and (memq 'headings types)
  5538. (memq 'drawers types))
  5539. (org-flag-region (point-min) (point-max) nil 'outline))
  5540. ((memq 'headings types)
  5541. (org-flag-region (point-min) (point-max) nil 'outline)
  5542. (org-cycle-hide-drawers 'all))
  5543. ((memq 'drawers types)
  5544. (save-excursion
  5545. (goto-char (point-min))
  5546. (while (re-search-forward org-drawer-regexp nil t)
  5547. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5548. 'invisible))
  5549. (o (cdr-safe pair)))
  5550. (if (overlayp o) (goto-char (overlay-end o))
  5551. (pcase (get-char-property-and-overlay (point) 'invisible)
  5552. (`(outline . ,o)
  5553. (goto-char (overlay-end o))
  5554. (delete-overlay o))
  5555. (_ nil))))))))))
  5556. ;;;###autoload
  5557. (defun org-cycle (&optional arg)
  5558. "TAB-action and visibility cycling for Org mode.
  5559. This is the command invoked in Org mode by the `TAB' key. Its main
  5560. purpose is outline visibility cycling, but it also invokes other actions
  5561. in special contexts.
  5562. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5563. the entire
  5564. buffer through 3 states (global cycling)
  5565. 1. OVERVIEW: Show only top-level headlines.
  5566. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5567. 3. SHOW ALL: Show everything.
  5568. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5569. switch to the startup visibility,
  5570. determined by the variable `org-startup-folded', and by any VISIBILITY
  5571. properties in the buffer.
  5572. With a `\\[universal-argument] \\[universal-argument] \
  5573. \\[universal-argument]' prefix argument, show the entire buffer, including
  5574. any drawers.
  5575. When inside a table, re-align the table and move to the next field.
  5576. When point is at the beginning of a headline, rotate the subtree started
  5577. by this line through 3 different states (local cycling)
  5578. 1. FOLDED: Only the main headline is shown.
  5579. 2. CHILDREN: The main headline and the direct children are shown.
  5580. From this state, you can move to one of the children
  5581. and zoom in further.
  5582. 3. SUBTREE: Show the entire subtree, including body text.
  5583. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5584. When point is at the beginning of an empty headline and the variable
  5585. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5586. of the headline by demoting and promoting it to likely levels. This
  5587. speeds up creation document structure by pressing `TAB' once or several
  5588. times right after creating a new headline.
  5589. When there is a numeric prefix, go up to a heading with level ARG, do
  5590. a `show-subtree' and return to the previous cursor position. If ARG
  5591. is negative, go up that many levels.
  5592. When point is not at the beginning of a headline, execute the global
  5593. binding for `TAB', which is re-indenting the line. See the option
  5594. `org-cycle-emulate-tab' for details.
  5595. As a special case, if point is at the very beginning of the buffer, if
  5596. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5597. is non-nil, this function acts as if called with prefix argument \
  5598. \(`\\[universal-argument] TAB',
  5599. same as `S-TAB') also when called without prefix argument."
  5600. (interactive "P")
  5601. (org-load-modules-maybe)
  5602. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5603. (and org-cycle-level-after-item/entry-creation
  5604. (or (org-cycle-level)
  5605. (org-cycle-item-indentation))))
  5606. (let* ((limit-level
  5607. (or org-cycle-max-level
  5608. (and (boundp 'org-inlinetask-min-level)
  5609. org-inlinetask-min-level
  5610. (1- org-inlinetask-min-level))))
  5611. (nstars
  5612. (and limit-level
  5613. (if org-odd-levels-only
  5614. (1- (* 2 limit-level))
  5615. limit-level)))
  5616. (org-outline-regexp
  5617. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5618. (cond
  5619. ((equal arg '(16))
  5620. (setq last-command 'dummy)
  5621. (org-set-startup-visibility)
  5622. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5623. ((equal arg '(64))
  5624. (org-show-all)
  5625. (org-unlogged-message "Entire buffer visible, including drawers"))
  5626. ((equal arg '(4)) (org-cycle-internal-global))
  5627. ;; Show-subtree, ARG levels up from here.
  5628. ((integerp arg)
  5629. (save-excursion
  5630. (org-back-to-heading)
  5631. (outline-up-heading (if (< arg 0) (- arg)
  5632. (- (funcall outline-level) arg)))
  5633. (org-show-subtree)))
  5634. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5635. ((and org-cycle-global-at-bob
  5636. (bobp)
  5637. (not (looking-at org-outline-regexp)))
  5638. (let ((org-cycle-hook
  5639. (remq 'org-optimize-window-after-visibility-change
  5640. org-cycle-hook)))
  5641. (org-cycle-internal-global)))
  5642. ;; Try CDLaTeX TAB completion.
  5643. ((org-try-cdlatex-tab))
  5644. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5645. ((and (featurep 'org-inlinetask)
  5646. (org-inlinetask-at-task-p)
  5647. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5648. (org-inlinetask-toggle-visibility))
  5649. (t
  5650. (let ((pos (point))
  5651. (element (org-element-at-point)))
  5652. (cond
  5653. ;; Try toggling visibility for block at point.
  5654. ((org-hide-block-toggle nil t element))
  5655. ;; Try toggling visibility for drawer at point.
  5656. ((org-hide-drawer-toggle nil t element))
  5657. ;; Table: enter it or move to the next field.
  5658. ((and (org-match-line "[ \t]*[|+]")
  5659. (org-element-lineage element '(table) t))
  5660. (if (and (eq 'table (org-element-type element))
  5661. (eq 'table.el (org-element-property :type element)))
  5662. (message (substitute-command-keys "\\<org-mode-map>\
  5663. Use `\\[org-edit-special]' to edit table.el tables"))
  5664. (org-table-justify-field-maybe)
  5665. (call-interactively #'org-table-next-field)))
  5666. ((run-hook-with-args-until-success
  5667. 'org-tab-after-check-for-table-hook))
  5668. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5669. ((and (or (and org-cycle-include-plain-lists
  5670. (let ((item (org-element-lineage element
  5671. '(item plain-list)
  5672. t)))
  5673. (and item
  5674. (= (line-beginning-position)
  5675. (org-element-property :post-affiliated
  5676. item)))))
  5677. (org-match-line org-outline-regexp))
  5678. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5679. (org-cycle-internal-local))
  5680. ;; From there: TAB emulation and template completion.
  5681. (buffer-read-only (org-back-to-heading))
  5682. ((run-hook-with-args-until-success
  5683. 'org-tab-after-check-for-cycling-hook))
  5684. ((run-hook-with-args-until-success
  5685. 'org-tab-before-tab-emulation-hook))
  5686. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5687. (or (not (bolp))
  5688. (not (looking-at org-outline-regexp))))
  5689. (call-interactively (global-key-binding (kbd "TAB"))))
  5690. ((or (eq org-cycle-emulate-tab t)
  5691. (and (memq org-cycle-emulate-tab '(white whitestart))
  5692. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5693. (or (and (eq org-cycle-emulate-tab 'white)
  5694. (= (match-end 0) (point-at-eol)))
  5695. (and (eq org-cycle-emulate-tab 'whitestart)
  5696. (>= (match-end 0) pos)))))
  5697. (call-interactively (global-key-binding (kbd "TAB"))))
  5698. (t
  5699. (save-excursion
  5700. (org-back-to-heading)
  5701. (org-cycle))))))))))
  5702. (defun org-cycle-internal-global ()
  5703. "Do the global cycling action."
  5704. ;; Hack to avoid display of messages for .org attachments in Gnus
  5705. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5706. (cond
  5707. ((and (eq last-command this-command)
  5708. (eq org-cycle-global-status 'overview))
  5709. ;; We just created the overview - now do table of contents
  5710. ;; This can be slow in very large buffers, so indicate action
  5711. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5712. (unless ga (org-unlogged-message "CONTENTS..."))
  5713. (org-content)
  5714. (unless ga (org-unlogged-message "CONTENTS...done"))
  5715. (setq org-cycle-global-status 'contents)
  5716. (run-hook-with-args 'org-cycle-hook 'contents))
  5717. ((and (eq last-command this-command)
  5718. (eq org-cycle-global-status 'contents))
  5719. ;; We just showed the table of contents - now show everything
  5720. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5721. (org-show-all '(headings blocks))
  5722. (unless ga (org-unlogged-message "SHOW ALL"))
  5723. (setq org-cycle-global-status 'all)
  5724. (run-hook-with-args 'org-cycle-hook 'all))
  5725. (t
  5726. ;; Default action: go to overview
  5727. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5728. (org-overview)
  5729. (unless ga (org-unlogged-message "OVERVIEW"))
  5730. (setq org-cycle-global-status 'overview)
  5731. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5732. (defvar org-called-with-limited-levels nil
  5733. "Non-nil when `org-with-limited-levels' is currently active.")
  5734. (defun org-cycle-internal-local ()
  5735. "Do the local cycling action."
  5736. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5737. ;; First, determine end of headline (EOH), end of subtree or item
  5738. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5739. (save-excursion
  5740. (if (org-at-item-p)
  5741. (progn
  5742. (beginning-of-line)
  5743. (setq struct (org-list-struct))
  5744. (setq eoh (point-at-eol))
  5745. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5746. (setq has-children (org-list-has-child-p (point) struct)))
  5747. (org-back-to-heading)
  5748. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5749. (setq eos (save-excursion
  5750. (org-end-of-subtree t t)
  5751. (unless (eobp) (forward-char -1))
  5752. (point)))
  5753. (setq has-children
  5754. (or
  5755. (save-excursion
  5756. (let ((level (funcall outline-level)))
  5757. (outline-next-heading)
  5758. (and (org-at-heading-p t)
  5759. (> (funcall outline-level) level))))
  5760. (and (eq org-cycle-include-plain-lists 'integrate)
  5761. (save-excursion
  5762. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5763. ;; Determine end invisible part of buffer (EOL)
  5764. (beginning-of-line 2)
  5765. (while (and (not (eobp)) ;this is like `next-line'
  5766. (get-char-property (1- (point)) 'invisible))
  5767. (goto-char (next-single-char-property-change (point) 'invisible))
  5768. (and (eolp) (beginning-of-line 2)))
  5769. (setq eol (point)))
  5770. ;; Find out what to do next and set `this-command'
  5771. (cond
  5772. ((= eos eoh)
  5773. ;; Nothing is hidden behind this heading
  5774. (unless (org-before-first-heading-p)
  5775. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5776. (org-unlogged-message "EMPTY ENTRY")
  5777. (setq org-cycle-subtree-status nil)
  5778. (save-excursion
  5779. (goto-char eos)
  5780. (outline-next-heading)
  5781. (when (org-invisible-p) (org-flag-heading nil))))
  5782. ((and (or (>= eol eos)
  5783. (not (string-match "\\S-" (buffer-substring eol eos))))
  5784. (or has-children
  5785. (not (setq children-skipped
  5786. org-cycle-skip-children-state-if-no-children))))
  5787. ;; Entire subtree is hidden in one line: children view
  5788. (unless (org-before-first-heading-p)
  5789. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5790. (if (org-at-item-p)
  5791. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5792. (org-show-entry)
  5793. (org-with-limited-levels (org-show-children))
  5794. (org-show-set-visibility 'tree)
  5795. ;; Fold every list in subtree to top-level items.
  5796. (when (eq org-cycle-include-plain-lists 'integrate)
  5797. (save-excursion
  5798. (org-back-to-heading)
  5799. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5800. (beginning-of-line 1)
  5801. (let* ((struct (org-list-struct))
  5802. (prevs (org-list-prevs-alist struct))
  5803. (end (org-list-get-bottom-point struct)))
  5804. (dolist (e (org-list-get-all-items (point) struct prevs))
  5805. (org-list-set-item-visibility e struct 'folded))
  5806. (goto-char (if (< end eos) end eos)))))))
  5807. (org-unlogged-message "CHILDREN")
  5808. (save-excursion
  5809. (goto-char eos)
  5810. (outline-next-heading)
  5811. (when (org-invisible-p) (org-flag-heading nil)))
  5812. (setq org-cycle-subtree-status 'children)
  5813. (unless (org-before-first-heading-p)
  5814. (run-hook-with-args 'org-cycle-hook 'children)))
  5815. ((or children-skipped
  5816. (and (eq last-command this-command)
  5817. (eq org-cycle-subtree-status 'children)))
  5818. ;; We just showed the children, or no children are there,
  5819. ;; now show everything.
  5820. (unless (org-before-first-heading-p)
  5821. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5822. (org-flag-region eoh eos nil 'outline)
  5823. (org-unlogged-message
  5824. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5825. (setq org-cycle-subtree-status 'subtree)
  5826. (unless (org-before-first-heading-p)
  5827. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5828. (t
  5829. ;; Default action: hide the subtree.
  5830. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5831. (org-flag-region eoh eos t 'outline)
  5832. (org-unlogged-message "FOLDED")
  5833. (setq org-cycle-subtree-status 'folded)
  5834. (unless (org-before-first-heading-p)
  5835. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5836. ;;;###autoload
  5837. (defun org-global-cycle (&optional arg)
  5838. "Cycle the global visibility. For details see `org-cycle'.
  5839. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5840. With a numeric prefix, show all headlines up to that level."
  5841. (interactive "P")
  5842. (cond
  5843. ((integerp arg)
  5844. (org-content arg)
  5845. (setq org-cycle-global-status 'contents))
  5846. ((equal arg '(4))
  5847. (org-set-startup-visibility)
  5848. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5849. (t
  5850. (org-cycle '(4)))))
  5851. (defun org-set-startup-visibility ()
  5852. "Set the visibility required by startup options and properties."
  5853. (cond
  5854. ((eq org-startup-folded t)
  5855. (org-overview))
  5856. ((eq org-startup-folded 'content)
  5857. (org-content))
  5858. ((eq org-startup-folded 'show2levels)
  5859. (org-content 2))
  5860. ((eq org-startup-folded 'show3levels)
  5861. (org-content 3))
  5862. ((eq org-startup-folded 'show4levels)
  5863. (org-content 4))
  5864. ((eq org-startup-folded 'show5levels)
  5865. (org-content 5))
  5866. ((or (eq org-startup-folded 'showeverything)
  5867. (eq org-startup-folded nil))
  5868. (org-show-all)))
  5869. (unless (eq org-startup-folded 'showeverything)
  5870. (when org-hide-block-startup (org-hide-block-all))
  5871. (org-set-visibility-according-to-property)
  5872. (org-cycle-hide-archived-subtrees 'all)
  5873. (org-cycle-hide-drawers 'all)
  5874. (org-cycle-show-empty-lines t)))
  5875. (defun org-set-visibility-according-to-property ()
  5876. "Switch subtree visibility according to VISIBILITY property."
  5877. (interactive)
  5878. (let ((regexp (org-re-property "VISIBILITY")))
  5879. (org-with-point-at 1
  5880. (while (re-search-forward regexp nil t)
  5881. (let ((state (match-string 3)))
  5882. (if (not (org-at-property-p)) (outline-next-heading)
  5883. (save-excursion
  5884. (org-back-to-heading t)
  5885. (org-flag-subtree t)
  5886. (org-reveal)
  5887. (pcase state
  5888. ("folded"
  5889. (org-flag-subtree t))
  5890. ("children"
  5891. (org-show-hidden-entry)
  5892. (org-show-children))
  5893. ("content"
  5894. (save-excursion
  5895. (save-restriction
  5896. (org-narrow-to-subtree)
  5897. (org-content))))
  5898. ((or "all" "showall")
  5899. (outline-show-subtree))
  5900. (_ nil)))
  5901. (org-end-of-subtree)))))))
  5902. (defun org-overview ()
  5903. "Switch to overview mode, showing only top-level headlines."
  5904. (interactive)
  5905. (org-show-all '(headings drawers))
  5906. (save-excursion
  5907. (goto-char (point-min))
  5908. (when (re-search-forward org-outline-regexp-bol nil t)
  5909. (let* ((last (line-end-position))
  5910. (level (- (match-end 0) (match-beginning 0) 1))
  5911. (regexp (format "^\\*\\{1,%d\\} " level)))
  5912. (while (re-search-forward regexp nil :move)
  5913. (org-flag-region last (line-end-position 0) t 'outline)
  5914. (setq last (line-end-position))
  5915. (setq level (- (match-end 0) (match-beginning 0) 1))
  5916. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5917. (org-flag-region last (point) t 'outline)))))
  5918. (defun org-content (&optional arg)
  5919. "Show all headlines in the buffer, like a table of contents.
  5920. With numerical argument N, show content up to level N."
  5921. (interactive "p")
  5922. (org-show-all '(headings drawers))
  5923. (save-excursion
  5924. (goto-char (point-max))
  5925. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5926. (format "^\\*\\{1,%d\\} " arg)
  5927. "^\\*+ "))
  5928. (last (point)))
  5929. (while (re-search-backward regexp nil t)
  5930. (org-flag-region (line-end-position) last t 'outline)
  5931. (setq last (line-end-position 0))))))
  5932. (defvar org-scroll-position-to-restore nil
  5933. "Temporarily store scroll position to restore.")
  5934. (defun org-optimize-window-after-visibility-change (state)
  5935. "Adjust the window after a change in outline visibility.
  5936. This function is the default value of the hook `org-cycle-hook'."
  5937. (when (get-buffer-window (current-buffer))
  5938. (let ((repeat (eq last-command this-command)))
  5939. (unless repeat
  5940. (setq org-scroll-position-to-restore nil))
  5941. (cond
  5942. ((eq state 'content) nil)
  5943. ((eq state 'all) nil)
  5944. ((and org-scroll-position-to-restore repeat
  5945. (eq state 'folded))
  5946. (set-window-start nil org-scroll-position-to-restore))
  5947. ((eq state 'folded) nil)
  5948. ((eq state 'children)
  5949. (setq org-scroll-position-to-restore (window-start))
  5950. (or (org-subtree-end-visible-p) (recenter 1)))
  5951. ((eq state 'subtree)
  5952. (unless repeat
  5953. (setq org-scroll-position-to-restore (window-start)))
  5954. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5955. (defun org-clean-visibility-after-subtree-move ()
  5956. "Fix visibility issues after moving a subtree."
  5957. ;; First, find a reasonable region to look at:
  5958. ;; Start two siblings above, end three below
  5959. (let* ((beg (save-excursion
  5960. (and (org-get-previous-sibling)
  5961. (org-get-previous-sibling))
  5962. (point)))
  5963. (end (save-excursion
  5964. (and (org-get-next-sibling)
  5965. (org-get-next-sibling)
  5966. (org-get-next-sibling))
  5967. (if (org-at-heading-p)
  5968. (point-at-eol)
  5969. (point))))
  5970. (level (looking-at "\\*+"))
  5971. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5972. (save-excursion
  5973. (save-restriction
  5974. (narrow-to-region beg end)
  5975. (when re
  5976. ;; Properly fold already folded siblings
  5977. (goto-char (point-min))
  5978. (while (re-search-forward re nil t)
  5979. (when (and (not (org-invisible-p))
  5980. (org-invisible-p (line-end-position)))
  5981. (outline-hide-entry))))
  5982. (org-cycle-hide-drawers 'all)
  5983. (org-cycle-show-empty-lines 'overview)))))
  5984. (defun org-cycle-show-empty-lines (state)
  5985. "Show empty lines above all visible headlines.
  5986. The region to be covered depends on STATE when called through
  5987. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5988. entire buffer covered. Note that an empty line is only shown if there
  5989. are at least `org-cycle-separator-lines' empty lines before the headline."
  5990. (when (/= org-cycle-separator-lines 0)
  5991. (save-excursion
  5992. (let* ((n (abs org-cycle-separator-lines))
  5993. (re (cond
  5994. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5995. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5996. (t (let ((ns (number-to-string (- n 2))))
  5997. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5998. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5999. beg end)
  6000. (cond
  6001. ((memq state '(overview contents t))
  6002. (setq beg (point-min) end (point-max)))
  6003. ((memq state '(children folded))
  6004. (setq beg (point)
  6005. end (progn (org-end-of-subtree t t)
  6006. (line-beginning-position 2)))))
  6007. (when beg
  6008. (goto-char beg)
  6009. (while (re-search-forward re end t)
  6010. (unless (get-char-property (match-end 1) 'invisible)
  6011. (let ((e (match-end 1))
  6012. (b (if (>= org-cycle-separator-lines 0)
  6013. (match-beginning 1)
  6014. (save-excursion
  6015. (goto-char (match-beginning 0))
  6016. (skip-chars-backward " \t\n")
  6017. (line-end-position)))))
  6018. (org-flag-region b e nil 'outline))))))))
  6019. ;; Never hide empty lines at the end of the file.
  6020. (save-excursion
  6021. (goto-char (point-max))
  6022. (outline-previous-heading)
  6023. (outline-end-of-heading)
  6024. (when (and (looking-at "[ \t\n]+")
  6025. (= (match-end 0) (point-max)))
  6026. (org-flag-region (point) (match-end 0) nil 'outline))))
  6027. ;;;; Reveal point location
  6028. (defun org-show-context (&optional key)
  6029. "Make sure point and context are visible.
  6030. Optional argument KEY, when non-nil, is a symbol. See
  6031. `org-show-context-detail' for allowed values and how much is to
  6032. be shown."
  6033. (org-show-set-visibility
  6034. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6035. ((cdr (assq key org-show-context-detail)))
  6036. (t (cdr (assq 'default org-show-context-detail))))))
  6037. (defun org-show-set-visibility (detail)
  6038. "Set visibility around point according to DETAIL.
  6039. DETAIL is either nil, `minimal', `local', `ancestors',
  6040. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6041. `org-show-context-detail' for more information."
  6042. ;; Show current heading and possibly its entry, following headline
  6043. ;; or all children.
  6044. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6045. (org-flag-heading nil)
  6046. (org-show-entry)
  6047. ;; If point is hidden within a drawer or a block, make sure to
  6048. ;; expose it.
  6049. (dolist (o (overlays-at (point)))
  6050. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6051. (delete-overlay o)))
  6052. (unless (org-before-first-heading-p)
  6053. (org-with-limited-levels
  6054. (cl-case detail
  6055. ((tree canonical t) (org-show-children))
  6056. ((nil minimal ancestors ancestors-full))
  6057. (t (save-excursion
  6058. (outline-next-heading)
  6059. (org-flag-heading nil)))))))
  6060. ;; Show whole subtree.
  6061. (when (eq detail 'ancestors-full) (org-show-subtree))
  6062. ;; Show all siblings.
  6063. (when (eq detail 'lineage) (org-show-siblings))
  6064. ;; Show ancestors, possibly with their children.
  6065. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6066. (save-excursion
  6067. (while (org-up-heading-safe)
  6068. (org-flag-heading nil)
  6069. (when (memq detail '(canonical t)) (org-show-entry))
  6070. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6071. (defvar org-reveal-start-hook nil
  6072. "Hook run before revealing a location.")
  6073. (defun org-reveal (&optional siblings)
  6074. "Show current entry, hierarchy above it, and the following headline.
  6075. This can be used to show a consistent set of context around
  6076. locations exposed with `org-show-context'.
  6077. With optional argument SIBLINGS, on each level of the hierarchy all
  6078. siblings are shown. This repairs the tree structure to what it would
  6079. look like when opened with hierarchical calls to `org-cycle'.
  6080. With a \\[universal-argument] \\[universal-argument] prefix, \
  6081. go to the parent and show the entire tree."
  6082. (interactive "P")
  6083. (run-hooks 'org-reveal-start-hook)
  6084. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6085. ((equal siblings '(16))
  6086. (save-excursion
  6087. (when (org-up-heading-safe)
  6088. (org-show-subtree)
  6089. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6090. (t (org-show-set-visibility 'lineage))))
  6091. ;;; Indirect buffer display of subtrees
  6092. (defvar org-indirect-dedicated-frame nil
  6093. "This is the frame being used for indirect tree display.")
  6094. (defvar org-last-indirect-buffer nil)
  6095. (defun org-tree-to-indirect-buffer (&optional arg)
  6096. "Create indirect buffer and narrow it to current subtree.
  6097. With a numerical prefix ARG, go up to this level and then take that tree.
  6098. If ARG is negative, go up that many levels.
  6099. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6100. indirect buffer previously made with this command, to avoid proliferation of
  6101. indirect buffers. However, when you call the command with a \
  6102. `\\[universal-argument]' prefix, or
  6103. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6104. so that you can work with several indirect buffers at the same time. If
  6105. `org-indirect-buffer-display' is `dedicated-frame', the \
  6106. `\\[universal-argument]' prefix also
  6107. requests that a new frame be made for the new buffer, so that the dedicated
  6108. frame is not changed."
  6109. (interactive "P")
  6110. (let ((cbuf (current-buffer))
  6111. (cwin (selected-window))
  6112. (pos (point))
  6113. beg end level heading ibuf)
  6114. (save-excursion
  6115. (org-back-to-heading t)
  6116. (when (numberp arg)
  6117. (setq level (org-outline-level))
  6118. (when (< arg 0) (setq arg (+ level arg)))
  6119. (while (> (setq level (org-outline-level)) arg)
  6120. (org-up-heading-safe)))
  6121. (setq beg (point)
  6122. heading (org-get-heading 'no-tags))
  6123. (org-end-of-subtree t t)
  6124. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  6125. (setq end (point)))
  6126. (when (and (buffer-live-p org-last-indirect-buffer)
  6127. (not (eq org-indirect-buffer-display 'new-frame))
  6128. (not arg))
  6129. (kill-buffer org-last-indirect-buffer))
  6130. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6131. org-last-indirect-buffer ibuf)
  6132. (cond
  6133. ((or (eq org-indirect-buffer-display 'new-frame)
  6134. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6135. (select-frame (make-frame))
  6136. (delete-other-windows)
  6137. (pop-to-buffer-same-window ibuf)
  6138. (org-set-frame-title heading))
  6139. ((eq org-indirect-buffer-display 'dedicated-frame)
  6140. (raise-frame
  6141. (select-frame (or (and org-indirect-dedicated-frame
  6142. (frame-live-p org-indirect-dedicated-frame)
  6143. org-indirect-dedicated-frame)
  6144. (setq org-indirect-dedicated-frame (make-frame)))))
  6145. (delete-other-windows)
  6146. (pop-to-buffer-same-window ibuf)
  6147. (org-set-frame-title (concat "Indirect: " heading)))
  6148. ((eq org-indirect-buffer-display 'current-window)
  6149. (pop-to-buffer-same-window ibuf))
  6150. ((eq org-indirect-buffer-display 'other-window)
  6151. (pop-to-buffer ibuf))
  6152. (t (error "Invalid value")))
  6153. (narrow-to-region beg end)
  6154. (org-show-all '(headings drawers blocks))
  6155. (goto-char pos)
  6156. (run-hook-with-args 'org-cycle-hook 'all)
  6157. (and (window-live-p cwin) (select-window cwin))))
  6158. (defun org-get-indirect-buffer (&optional buffer heading)
  6159. (setq buffer (or buffer (current-buffer)))
  6160. (let ((n 1) (base (buffer-name buffer)) bname)
  6161. (while (buffer-live-p
  6162. (get-buffer
  6163. (setq bname
  6164. (concat base "-"
  6165. (if heading (concat heading "-" (number-to-string n))
  6166. (number-to-string n))))))
  6167. (setq n (1+ n)))
  6168. (condition-case nil
  6169. (make-indirect-buffer buffer bname 'clone)
  6170. (error (make-indirect-buffer buffer bname)))))
  6171. (defun org-set-frame-title (title)
  6172. "Set the title of the current frame to the string TITLE."
  6173. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6174. ;;;; Structure editing
  6175. ;;; Inserting headlines
  6176. (defun org--blank-before-heading-p (&optional parent)
  6177. "Non-nil when an empty line should precede a new heading here.
  6178. When optional argument PARENT is non-nil, consider parent
  6179. headline instead of current one."
  6180. (pcase (assq 'heading org-blank-before-new-entry)
  6181. (`(heading . auto)
  6182. (save-excursion
  6183. (org-with-limited-levels
  6184. (unless (and (org-before-first-heading-p)
  6185. (not (outline-next-heading)))
  6186. (org-back-to-heading t)
  6187. (when parent (org-up-heading-safe))
  6188. (cond ((not (bobp))
  6189. (org-previous-line-empty-p))
  6190. ((outline-next-heading)
  6191. (org-previous-line-empty-p))
  6192. ;; Ignore trailing spaces on last buffer line.
  6193. ((progn (skip-chars-backward " \t") (bolp))
  6194. (org-previous-line-empty-p))
  6195. (t nil))))))
  6196. (`(heading . ,value) value)
  6197. (_ nil)))
  6198. (defun org-insert-heading (&optional arg invisible-ok top)
  6199. "Insert a new heading or an item with the same depth at point.
  6200. If point is at the beginning of a heading, insert a new heading
  6201. or a new headline above the current one. When at the beginning
  6202. of a regular line of text, turn it into a heading.
  6203. If point is in the middle of a line, split it and create a new
  6204. headline with the text in the current line after point (see
  6205. `org-M-RET-may-split-line' on how to modify this behavior). As
  6206. a special case, on a headline, splitting can only happen on the
  6207. title itself. E.g., this excludes breaking stars or tags.
  6208. With a `\\[universal-argument]' prefix, set \
  6209. `org-insert-heading-respect-content' to
  6210. a non-nil value for the duration of the command. This forces the
  6211. insertion of a heading after the current subtree, independently
  6212. on the location of point.
  6213. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6214. insert the heading at the end of the tree
  6215. above the current heading. For example, if point is within a
  6216. 2nd-level heading, then it will insert a 2nd-level heading at
  6217. the end of the 1st-level parent subtree.
  6218. When INVISIBLE-OK is set, stop at invisible headlines when going
  6219. back. This is important for non-interactive uses of the
  6220. command.
  6221. When optional argument TOP is non-nil, insert a level 1 heading,
  6222. unconditionally."
  6223. (interactive "P")
  6224. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6225. (level (org-current-level))
  6226. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6227. (cond
  6228. ((or org-insert-heading-respect-content
  6229. (member arg '((4) (16)))
  6230. (and (not invisible-ok)
  6231. (invisible-p (max (1- (point)) (point-min)))))
  6232. ;; Position point at the location of insertion. Make sure we
  6233. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6234. (org-with-limited-levels
  6235. (if (not level) (outline-next-heading) ;before first headline
  6236. (org-back-to-heading invisible-ok)
  6237. (when (equal arg '(16)) (org-up-heading-safe))
  6238. (org-end-of-subtree)))
  6239. (unless (bolp) (insert "\n"))
  6240. (when (and blank? (save-excursion
  6241. (backward-char)
  6242. (org-before-first-heading-p)))
  6243. (insert "\n")
  6244. (backward-char))
  6245. (when (and (not level) (not (eobp)) (not (bobp)))
  6246. (when (org-at-heading-p) (insert "\n"))
  6247. (backward-char))
  6248. (unless (and blank? (org-previous-line-empty-p))
  6249. (org-N-empty-lines-before-current (if blank? 1 0)))
  6250. (insert stars " ")
  6251. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6252. ;; is visible.
  6253. (unless invisible-ok
  6254. (pcase (get-char-property-and-overlay (point) 'invisible)
  6255. (`(outline . ,o)
  6256. (move-overlay o (overlay-start o) (line-end-position 0)))
  6257. (_ nil))))
  6258. ;; At a headline...
  6259. ((org-at-heading-p)
  6260. (cond ((bolp)
  6261. (when blank? (save-excursion (insert "\n")))
  6262. (save-excursion (insert stars " \n"))
  6263. (unless (and blank? (org-previous-line-empty-p))
  6264. (org-N-empty-lines-before-current (if blank? 1 0)))
  6265. (end-of-line))
  6266. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6267. (org-match-line org-complex-heading-regexp)
  6268. (org-pos-in-match-range (point) 4))
  6269. ;; Grab the text that should moved to the new headline.
  6270. ;; Preserve tags.
  6271. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6272. (if (looking-at "[ \t]*$") (replace-match "")
  6273. (org-align-tags))
  6274. (end-of-line)
  6275. (when blank? (insert "\n"))
  6276. (insert "\n" stars " ")
  6277. (when (org-string-nw-p split) (insert split))))
  6278. (t
  6279. (end-of-line)
  6280. (when blank? (insert "\n"))
  6281. (insert "\n" stars " "))))
  6282. ;; On regular text, turn line into a headline or split, if
  6283. ;; appropriate.
  6284. ((bolp)
  6285. (insert stars " ")
  6286. (unless (and blank? (org-previous-line-empty-p))
  6287. (org-N-empty-lines-before-current (if blank? 1 0))))
  6288. (t
  6289. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6290. (end-of-line))
  6291. (insert "\n" stars " ")
  6292. (unless (and blank? (org-previous-line-empty-p))
  6293. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6294. (run-hooks 'org-insert-heading-hook))
  6295. (defun org-N-empty-lines-before-current (n)
  6296. "Make the number of empty lines before current exactly N.
  6297. So this will delete or add empty lines."
  6298. (let ((column (current-column)))
  6299. (beginning-of-line)
  6300. (unless (bobp)
  6301. (let ((start (save-excursion
  6302. (skip-chars-backward " \r\t\n")
  6303. (line-end-position))))
  6304. (delete-region start (line-end-position 0))))
  6305. (insert (make-string n ?\n))
  6306. (move-to-column column)))
  6307. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6308. "Return the heading of the current entry, without the stars.
  6309. When NO-TAGS is non-nil, don't include tags.
  6310. When NO-TODO is non-nil, don't include TODO keywords.
  6311. When NO-PRIORITY is non-nil, don't include priority cookie.
  6312. When NO-COMMENT is non-nil, don't include COMMENT string.
  6313. Return nil before first heading."
  6314. (unless (org-before-first-heading-p)
  6315. (save-excursion
  6316. (org-back-to-heading t)
  6317. (let ((case-fold-search nil))
  6318. (looking-at org-complex-heading-regexp)
  6319. (let ((todo (and (not no-todo) (match-string 2)))
  6320. (priority (and (not no-priority) (match-string 3)))
  6321. (headline (pcase (match-string 4)
  6322. (`nil "")
  6323. ((and (guard no-comment) h)
  6324. (replace-regexp-in-string
  6325. (eval-when-compile
  6326. (format "\\`%s[ \t]+" org-comment-string))
  6327. "" h))
  6328. (h h)))
  6329. (tags (and (not no-tags) (match-string 5))))
  6330. (mapconcat #'identity
  6331. (delq nil (list todo priority headline tags))
  6332. " "))))))
  6333. (defun org-heading-components ()
  6334. "Return the components of the current heading.
  6335. This is a list with the following elements:
  6336. - the level as an integer
  6337. - the reduced level, different if `org-odd-levels-only' is set.
  6338. - the TODO keyword, or nil
  6339. - the priority character, like ?A, or nil if no priority is given
  6340. - the headline text itself, or the tags string if no headline text
  6341. - the tags string, or nil."
  6342. (save-excursion
  6343. (org-back-to-heading t)
  6344. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6345. (list (length (match-string 1))
  6346. (org-reduced-level (length (match-string 1)))
  6347. (match-string-no-properties 2)
  6348. (and (match-end 3) (aref (match-string 3) 2))
  6349. (match-string-no-properties 4)
  6350. (match-string-no-properties 5)))))
  6351. (defun org-get-entry ()
  6352. "Get the entry text, after heading, entire subtree."
  6353. (save-excursion
  6354. (org-back-to-heading t)
  6355. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6356. (defun org-edit-headline (&optional heading)
  6357. "Edit the current headline.
  6358. Set it to HEADING when provided."
  6359. (interactive)
  6360. (org-with-wide-buffer
  6361. (org-back-to-heading t)
  6362. (let ((case-fold-search nil))
  6363. (when (looking-at org-complex-heading-regexp)
  6364. (let* ((old (match-string-no-properties 4))
  6365. (new (save-match-data
  6366. (org-trim (or heading (read-string "Edit: " old))))))
  6367. (unless (equal old new)
  6368. (if old (replace-match new t t nil 4)
  6369. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6370. (insert " " new))
  6371. (org-align-tags)
  6372. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6373. (defun org-insert-heading-after-current ()
  6374. "Insert a new heading with same level as current, after current subtree."
  6375. (interactive)
  6376. (org-back-to-heading)
  6377. (org-insert-heading)
  6378. (org-move-subtree-down)
  6379. (end-of-line 1))
  6380. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6381. "Insert heading with `org-insert-heading-respect-content' set to t."
  6382. (interactive)
  6383. (org-insert-heading '(4) invisible-ok))
  6384. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6385. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6386. (interactive)
  6387. (org-insert-todo-heading force-state '(4)))
  6388. (defun org-insert-todo-heading (arg &optional force-heading)
  6389. "Insert a new heading with the same level and TODO state as current heading.
  6390. If the heading has no TODO state, or if the state is DONE, use
  6391. the first state (TODO by default). Also with one prefix arg,
  6392. force first state. With two prefix args, force inserting at the
  6393. end of the parent subtree.
  6394. When called at a plain list item, insert a new item with an
  6395. unchecked check box."
  6396. (interactive "P")
  6397. (when (or force-heading (not (org-insert-item 'checkbox)))
  6398. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6399. force-heading))
  6400. (save-excursion
  6401. (org-forward-heading-same-level -1)
  6402. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6403. (let* ((new-mark-x
  6404. (if (or (equal arg '(4))
  6405. (not (match-beginning 2))
  6406. (member (match-string 2) org-done-keywords))
  6407. (car org-todo-keywords-1)
  6408. (match-string 2)))
  6409. (new-mark
  6410. (or
  6411. (run-hook-with-args-until-success
  6412. 'org-todo-get-default-hook new-mark-x nil)
  6413. new-mark-x)))
  6414. (beginning-of-line 1)
  6415. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6416. (if org-treat-insert-todo-heading-as-state-change
  6417. (org-todo new-mark)
  6418. (insert new-mark " "))))
  6419. (when org-provide-todo-statistics
  6420. (org-update-parent-todo-statistics))))
  6421. (defun org-insert-subheading (arg)
  6422. "Insert a new subheading and demote it.
  6423. Works for outline headings and for plain lists alike."
  6424. (interactive "P")
  6425. (org-insert-heading arg)
  6426. (cond
  6427. ((org-at-heading-p) (org-do-demote))
  6428. ((org-at-item-p) (org-indent-item))))
  6429. (defun org-insert-todo-subheading (arg)
  6430. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6431. Works for outline headings and for plain lists alike."
  6432. (interactive "P")
  6433. (org-insert-todo-heading arg)
  6434. (cond
  6435. ((org-at-heading-p) (org-do-demote))
  6436. ((org-at-item-p) (org-indent-item))))
  6437. ;;; Promotion and Demotion
  6438. (defvar org-after-demote-entry-hook nil
  6439. "Hook run after an entry has been demoted.
  6440. The cursor will be at the beginning of the entry.
  6441. When a subtree is being demoted, the hook will be called for each node.")
  6442. (defvar org-after-promote-entry-hook nil
  6443. "Hook run after an entry has been promoted.
  6444. The cursor will be at the beginning of the entry.
  6445. When a subtree is being promoted, the hook will be called for each node.")
  6446. (defun org-promote-subtree ()
  6447. "Promote the entire subtree.
  6448. See also `org-promote'."
  6449. (interactive)
  6450. (save-excursion
  6451. (org-with-limited-levels (org-map-tree 'org-promote)))
  6452. (org-fix-position-after-promote))
  6453. (defun org-demote-subtree ()
  6454. "Demote the entire subtree.
  6455. See `org-demote' and `org-promote'."
  6456. (interactive)
  6457. (save-excursion
  6458. (org-with-limited-levels (org-map-tree 'org-demote)))
  6459. (org-fix-position-after-promote))
  6460. (defun org-do-promote ()
  6461. "Promote the current heading higher up the tree.
  6462. If the region is active in `transient-mark-mode', promote all
  6463. headings in the region."
  6464. (interactive)
  6465. (save-excursion
  6466. (if (org-region-active-p)
  6467. (org-map-region 'org-promote (region-beginning) (region-end))
  6468. (org-promote)))
  6469. (org-fix-position-after-promote))
  6470. (defun org-do-demote ()
  6471. "Demote the current heading lower down the tree.
  6472. If the region is active in `transient-mark-mode', demote all
  6473. headings in the region."
  6474. (interactive)
  6475. (save-excursion
  6476. (if (org-region-active-p)
  6477. (org-map-region 'org-demote (region-beginning) (region-end))
  6478. (org-demote)))
  6479. (org-fix-position-after-promote))
  6480. (defun org-fix-position-after-promote ()
  6481. "Fix cursor position and indentation after demoting/promoting."
  6482. (let ((pos (point)))
  6483. (when (save-excursion
  6484. (beginning-of-line)
  6485. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6486. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6487. (cond ((eobp) (insert " "))
  6488. ((eolp) (insert " "))
  6489. ((equal (char-after) ?\s) (forward-char 1))))))
  6490. (defun org-current-level ()
  6491. "Return the level of the current entry, or nil if before the first headline.
  6492. The level is the number of stars at the beginning of the
  6493. headline. Use `org-reduced-level' to remove the effect of
  6494. `org-odd-levels'. Unlike to `org-outline-level', this function
  6495. ignores inlinetasks."
  6496. (let ((level (org-with-limited-levels (org-outline-level))))
  6497. (and (> level 0) level)))
  6498. (defun org-get-previous-line-level ()
  6499. "Return the outline depth of the last headline before the current line.
  6500. Returns 0 for the first headline in the buffer, and nil if before the
  6501. first headline."
  6502. (and (org-current-level)
  6503. (or (and (/= (line-beginning-position) (point-min))
  6504. (save-excursion (beginning-of-line 0) (org-current-level)))
  6505. 0)))
  6506. (defun org-reduced-level (l)
  6507. "Compute the effective level of a heading.
  6508. This takes into account the setting of `org-odd-levels-only'."
  6509. (cond
  6510. ((zerop l) 0)
  6511. (org-odd-levels-only (1+ (floor (/ l 2))))
  6512. (t l)))
  6513. (defun org-level-increment ()
  6514. "Return the number of stars that will be added or removed at a
  6515. time to headlines when structure editing, based on the value of
  6516. `org-odd-levels-only'."
  6517. (if org-odd-levels-only 2 1))
  6518. (defun org-get-valid-level (level &optional change)
  6519. "Rectify a level change under the influence of `org-odd-levels-only'.
  6520. LEVEL is a current level, CHANGE is by how much the level should
  6521. be modified. Even if CHANGE is nil, LEVEL may be returned
  6522. modified because even level numbers will become the next higher
  6523. odd number. Returns values greater than 0."
  6524. (if org-odd-levels-only
  6525. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6526. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6527. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6528. (max 1 (+ level (or change 0)))))
  6529. (defun org-promote ()
  6530. "Promote the current heading higher up the tree."
  6531. (org-with-wide-buffer
  6532. (org-back-to-heading t)
  6533. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6534. after-change-functions))
  6535. (level (save-match-data (funcall outline-level)))
  6536. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6537. (diff (abs (- level (length up-head) -1))))
  6538. (cond
  6539. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6540. (replace-match "# " nil t))
  6541. ((= level 1)
  6542. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6543. (t (replace-match up-head nil t)))
  6544. (unless (= level 1)
  6545. (when org-auto-align-tags (org-align-tags))
  6546. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6547. (run-hooks 'org-after-promote-entry-hook))))
  6548. (defun org-demote ()
  6549. "Demote the current heading lower down the tree."
  6550. (org-with-wide-buffer
  6551. (org-back-to-heading t)
  6552. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6553. after-change-functions))
  6554. (level (save-match-data (funcall outline-level)))
  6555. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6556. (diff (abs (- level (length down-head) -1))))
  6557. (replace-match down-head nil t)
  6558. (when org-auto-align-tags (org-align-tags))
  6559. (when org-adapt-indentation (org-fixup-indentation diff))
  6560. (run-hooks 'org-after-demote-entry-hook))))
  6561. (defun org-cycle-level ()
  6562. "Cycle the level of an empty headline through possible states.
  6563. This goes first to child, then to parent, level, then up the hierarchy.
  6564. After top level, it switches back to sibling level."
  6565. (interactive)
  6566. (let ((org-adapt-indentation nil))
  6567. (when (org-point-at-end-of-empty-headline)
  6568. (setq this-command 'org-cycle-level) ; Only needed for caching
  6569. (let ((cur-level (org-current-level))
  6570. (prev-level (org-get-previous-line-level)))
  6571. (cond
  6572. ;; If first headline in file, promote to top-level.
  6573. ((= prev-level 0)
  6574. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6575. do (org-do-promote)))
  6576. ;; If same level as prev, demote one.
  6577. ((= prev-level cur-level)
  6578. (org-do-demote))
  6579. ;; If parent is top-level, promote to top level if not already.
  6580. ((= prev-level 1)
  6581. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6582. do (org-do-promote)))
  6583. ;; If top-level, return to prev-level.
  6584. ((= cur-level 1)
  6585. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6586. do (org-do-demote)))
  6587. ;; If less than prev-level, promote one.
  6588. ((< cur-level prev-level)
  6589. (org-do-promote))
  6590. ;; If deeper than prev-level, promote until higher than
  6591. ;; prev-level.
  6592. ((> cur-level prev-level)
  6593. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6594. do (org-do-promote))))
  6595. t))))
  6596. (defun org-map-tree (fun)
  6597. "Call FUN for every heading underneath the current one."
  6598. (org-back-to-heading t)
  6599. (let ((level (funcall outline-level)))
  6600. (save-excursion
  6601. (funcall fun)
  6602. (while (and (progn
  6603. (outline-next-heading)
  6604. (> (funcall outline-level) level))
  6605. (not (eobp)))
  6606. (funcall fun)))))
  6607. (defun org-map-region (fun beg end)
  6608. "Call FUN for every heading between BEG and END."
  6609. (let ((org-ignore-region t))
  6610. (save-excursion
  6611. (setq end (copy-marker end))
  6612. (goto-char beg)
  6613. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6614. (< (point) end))
  6615. (funcall fun))
  6616. (while (and (progn
  6617. (outline-next-heading)
  6618. (< (point) end))
  6619. (not (eobp)))
  6620. (funcall fun)))))
  6621. (defun org-fixup-indentation (diff)
  6622. "Change the indentation in the current entry by DIFF.
  6623. DIFF is an integer. Indentation is done according to the
  6624. following rules:
  6625. - Planning information and property drawers are always indented
  6626. according to the new level of the headline;
  6627. - Footnote definitions and their contents are ignored;
  6628. - Inlinetasks' boundaries are not shifted;
  6629. - Empty lines are ignored;
  6630. - Other lines' indentation are shifted by DIFF columns, unless
  6631. it would introduce a structural change in the document, in
  6632. which case no shifting is done at all.
  6633. Assume point is at a heading or an inlinetask beginning."
  6634. (org-with-wide-buffer
  6635. (narrow-to-region (line-beginning-position)
  6636. (save-excursion
  6637. (if (org-with-limited-levels (org-at-heading-p))
  6638. (org-with-limited-levels (outline-next-heading))
  6639. (org-inlinetask-goto-end))
  6640. (point)))
  6641. (forward-line)
  6642. ;; Indent properly planning info and property drawer.
  6643. (when (looking-at-p org-planning-line-re)
  6644. (org-indent-line)
  6645. (forward-line))
  6646. (when (looking-at org-property-drawer-re)
  6647. (goto-char (match-end 0))
  6648. (forward-line)
  6649. (org-indent-region (match-beginning 0) (match-end 0)))
  6650. (when (looking-at org-logbook-drawer-re)
  6651. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6652. (col (+ (current-indentation) diff)))
  6653. (when (wholenump col)
  6654. (while (< (point) end-marker)
  6655. (if (natnump diff)
  6656. (insert (make-string diff 32))
  6657. (delete-char (abs diff)))
  6658. (forward-line)))))
  6659. (catch 'no-shift
  6660. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6661. (throw 'no-shift nil))
  6662. ;; If DIFF is negative, first check if a shift is possible at all
  6663. ;; (e.g., it doesn't break structure). This can only happen if
  6664. ;; some contents are not properly indented.
  6665. (let ((case-fold-search t))
  6666. (when (< diff 0)
  6667. (let ((diff (- diff))
  6668. (forbidden-re (concat org-outline-regexp
  6669. "\\|"
  6670. (substring org-footnote-definition-re 1))))
  6671. (save-excursion
  6672. (while (not (eobp))
  6673. (cond
  6674. ((looking-at-p "[ \t]*$") (forward-line))
  6675. ((and (looking-at-p org-footnote-definition-re)
  6676. (let ((e (org-element-at-point)))
  6677. (and (eq (org-element-type e) 'footnote-definition)
  6678. (goto-char (org-element-property :end e))))))
  6679. ((looking-at-p org-outline-regexp) (forward-line))
  6680. ;; Give up if shifting would move before column 0 or
  6681. ;; if it would introduce a headline or a footnote
  6682. ;; definition.
  6683. (t
  6684. (skip-chars-forward " \t")
  6685. (let ((ind (current-column)))
  6686. (when (or (< ind diff)
  6687. (and (= ind diff) (looking-at-p forbidden-re)))
  6688. (throw 'no-shift nil)))
  6689. ;; Ignore contents of example blocks and source
  6690. ;; blocks if their indentation is meant to be
  6691. ;; preserved. Jump to block's closing line.
  6692. (beginning-of-line)
  6693. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6694. (let ((e (org-element-at-point)))
  6695. (and (memq (org-element-type e)
  6696. '(example-block src-block))
  6697. (or org-src-preserve-indentation
  6698. (org-element-property :preserve-indent e))
  6699. (goto-char (org-element-property :end e))
  6700. (progn (skip-chars-backward " \r\t\n")
  6701. (beginning-of-line)
  6702. t))))
  6703. (forward-line))))))))
  6704. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6705. ;; by DIFF. Also skip contents of source or example blocks
  6706. ;; when indentation is meant to be preserved.
  6707. (while (not (eobp))
  6708. (cond
  6709. ((and (looking-at-p org-footnote-definition-re)
  6710. (let ((e (org-element-at-point)))
  6711. (and (eq (org-element-type e) 'footnote-definition)
  6712. (goto-char (org-element-property :end e))))))
  6713. ((looking-at-p org-outline-regexp) (forward-line))
  6714. ((looking-at-p "[ \t]*$") (forward-line))
  6715. (t
  6716. (indent-line-to (+ (current-indentation) diff))
  6717. (beginning-of-line)
  6718. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6719. (let ((e (org-element-at-point)))
  6720. (and (memq (org-element-type e)
  6721. '(example-block src-block))
  6722. (or org-src-preserve-indentation
  6723. (org-element-property :preserve-indent e))
  6724. (goto-char (org-element-property :end e))
  6725. (progn (skip-chars-backward " \r\t\n")
  6726. (beginning-of-line)
  6727. t))))
  6728. (forward-line)))))))))
  6729. (defun org-convert-to-odd-levels ()
  6730. "Convert an Org file with all levels allowed to one with odd levels.
  6731. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6732. level 5 etc."
  6733. (interactive)
  6734. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6735. (let ((outline-level 'org-outline-level)
  6736. (org-odd-levels-only nil) n)
  6737. (save-excursion
  6738. (goto-char (point-min))
  6739. (while (re-search-forward "^\\*\\*+ " nil t)
  6740. (setq n (- (length (match-string 0)) 2))
  6741. (while (>= (setq n (1- n)) 0)
  6742. (org-demote))
  6743. (end-of-line 1))))))
  6744. (defun org-convert-to-oddeven-levels ()
  6745. "Convert an Org file with only odd levels to one with odd/even levels.
  6746. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6747. file contains a section with an even level, conversion would
  6748. destroy the structure of the file. An error is signaled in this
  6749. case."
  6750. (interactive)
  6751. (goto-char (point-min))
  6752. ;; First check if there are no even levels
  6753. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6754. (org-show-set-visibility 'canonical)
  6755. (error "Not all levels are odd in this file. Conversion not possible"))
  6756. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6757. (let ((outline-regexp org-outline-regexp)
  6758. (outline-level 'org-outline-level)
  6759. (org-odd-levels-only nil) n)
  6760. (save-excursion
  6761. (goto-char (point-min))
  6762. (while (re-search-forward "^\\*\\*+ " nil t)
  6763. (setq n (/ (1- (length (match-string 0))) 2))
  6764. (while (>= (setq n (1- n)) 0)
  6765. (org-promote))
  6766. (end-of-line 1))))))
  6767. (defun org-tr-level (n)
  6768. "Make N odd if required."
  6769. (if org-odd-levels-only (1+ (/ n 2)) n))
  6770. ;;; Vertical tree motion, cutting and pasting of subtrees
  6771. (defun org-move-subtree-up (&optional arg)
  6772. "Move the current subtree up past ARG headlines of the same level."
  6773. (interactive "p")
  6774. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6775. (defun org-move-subtree-down (&optional arg)
  6776. "Move the current subtree down past ARG headlines of the same level."
  6777. (interactive "p")
  6778. (setq arg (prefix-numeric-value arg))
  6779. (org-preserve-local-variables
  6780. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6781. 'org-get-previous-sibling))
  6782. (ins-point (make-marker))
  6783. (cnt (abs arg))
  6784. (col (current-column))
  6785. beg end txt folded)
  6786. ;; Select the tree
  6787. (org-back-to-heading)
  6788. (setq beg (point))
  6789. (save-match-data
  6790. (save-excursion (outline-end-of-heading)
  6791. (setq folded (org-invisible-p)))
  6792. (progn (org-end-of-subtree nil t)
  6793. (unless (eobp) (backward-char))))
  6794. (outline-next-heading)
  6795. (setq end (point))
  6796. (goto-char beg)
  6797. ;; Find insertion point, with error handling
  6798. (while (> cnt 0)
  6799. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6800. (goto-char beg)
  6801. (user-error "Cannot move past superior level or buffer limit"))
  6802. (setq cnt (1- cnt)))
  6803. (when (> arg 0)
  6804. ;; Moving forward - still need to move over subtree
  6805. (org-end-of-subtree t t)
  6806. (save-excursion
  6807. (org-back-over-empty-lines)
  6808. (or (bolp) (newline))))
  6809. (move-marker ins-point (point))
  6810. (setq txt (buffer-substring beg end))
  6811. (org-save-markers-in-region beg end)
  6812. (delete-region beg end)
  6813. (org-remove-empty-overlays-at beg)
  6814. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6815. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6816. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6817. (let ((bbb (point)))
  6818. (insert-before-markers txt)
  6819. (org-reinstall-markers-in-region bbb)
  6820. (move-marker ins-point bbb))
  6821. (or (bolp) (insert "\n"))
  6822. (goto-char ins-point)
  6823. (org-skip-whitespace)
  6824. (move-marker ins-point nil)
  6825. (if folded
  6826. (org-flag-subtree t)
  6827. (org-show-entry)
  6828. (org-show-children))
  6829. (org-clean-visibility-after-subtree-move)
  6830. ;; move back to the initial column we were at
  6831. (move-to-column col))))
  6832. (defvar org-subtree-clip ""
  6833. "Clipboard for cut and paste of subtrees.
  6834. This is actually only a copy of the kill, because we use the normal kill
  6835. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6836. (defvar org-subtree-clip-folded nil
  6837. "Was the last copied subtree folded?
  6838. This is used to fold the tree back after pasting.")
  6839. (defun org-cut-subtree (&optional n)
  6840. "Cut the current subtree into the clipboard.
  6841. With prefix arg N, cut this many sequential subtrees.
  6842. This is a short-hand for marking the subtree and then cutting it."
  6843. (interactive "p")
  6844. (org-copy-subtree n 'cut))
  6845. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6846. "Copy the current subtree into the clipboard.
  6847. With prefix arg N, copy this many sequential subtrees.
  6848. This is a short-hand for marking the subtree and then copying it.
  6849. If CUT is non-nil, actually cut the subtree.
  6850. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6851. of some markers in the region, even if CUT is non-nil. This is
  6852. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6853. (interactive "p")
  6854. (org-preserve-local-variables
  6855. (let (beg end folded (beg0 (point)))
  6856. (if (called-interactively-p 'any)
  6857. (org-back-to-heading nil) ; take what looks like a subtree
  6858. (org-back-to-heading t)) ; take what is really there
  6859. (setq beg (point))
  6860. (skip-chars-forward " \t\r\n")
  6861. (save-match-data
  6862. (if nosubtrees
  6863. (outline-next-heading)
  6864. (save-excursion (outline-end-of-heading)
  6865. (setq folded (org-invisible-p)))
  6866. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6867. (org-end-of-subtree t t)))
  6868. ;; Include the end of an inlinetask
  6869. (when (and (featurep 'org-inlinetask)
  6870. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6871. "END[ \t]*$")))
  6872. (end-of-line))
  6873. (setq end (point))
  6874. (goto-char beg0)
  6875. (when (> end beg)
  6876. (setq org-subtree-clip-folded folded)
  6877. (when (or cut force-store-markers)
  6878. (org-save-markers-in-region beg end))
  6879. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6880. (setq org-subtree-clip (current-kill 0))
  6881. (message "%s: Subtree(s) with %d characters"
  6882. (if cut "Cut" "Copied")
  6883. (length org-subtree-clip))))))
  6884. (defun org-paste-subtree (&optional level tree for-yank remove)
  6885. "Paste the clipboard as a subtree, with modification of headline level.
  6886. The entire subtree is promoted or demoted in order to match a new headline
  6887. level.
  6888. If the cursor is at the beginning of a headline, the same level as
  6889. that headline is used to paste the tree.
  6890. If not, the new level is derived from the *visible* headings
  6891. before and after the insertion point, and taken to be the inferior headline
  6892. level of the two. So if the previous visible heading is level 3 and the
  6893. next is level 4 (or vice versa), level 4 will be used for insertion.
  6894. This makes sure that the subtree remains an independent subtree and does
  6895. not swallow low level entries.
  6896. You can also force a different level, either by using a numeric prefix
  6897. argument, or by inserting the heading marker by hand. For example, if the
  6898. cursor is after \"*****\", then the tree will be shifted to level 5.
  6899. If optional TREE is given, use this text instead of the kill ring.
  6900. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6901. move back over whitespace before inserting, and move point to the end of
  6902. the inserted text when done.
  6903. When REMOVE is non-nil, remove the subtree from the clipboard."
  6904. (interactive "P")
  6905. (setq tree (or tree (and kill-ring (current-kill 0))))
  6906. (unless (org-kill-is-subtree-p tree)
  6907. (user-error
  6908. (substitute-command-keys
  6909. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6910. (org-with-limited-levels
  6911. (let* ((visp (not (org-invisible-p)))
  6912. (txt tree)
  6913. (old-level (if (string-match org-outline-regexp-bol txt)
  6914. (- (match-end 0) (match-beginning 0) 1)
  6915. -1))
  6916. (force-level
  6917. (cond
  6918. (level (prefix-numeric-value level))
  6919. ;; When point is after the stars in an otherwise empty
  6920. ;; headline, use the number of stars as the forced level.
  6921. ((and (org-match-line "^\\*+[ \t]*$")
  6922. (not (eq ?* (char-after))))
  6923. (org-outline-level))
  6924. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6925. (previous-level
  6926. (save-excursion
  6927. (org-previous-visible-heading 1)
  6928. (if (org-at-heading-p) (org-outline-level) 1)))
  6929. (next-level
  6930. (save-excursion
  6931. (if (org-at-heading-p) (org-outline-level)
  6932. (org-next-visible-heading 1)
  6933. (if (org-at-heading-p) (org-outline-level) 1))))
  6934. (new-level (or force-level (max previous-level next-level)))
  6935. (shift (if (or (= old-level -1)
  6936. (= new-level -1)
  6937. (= old-level new-level))
  6938. 0
  6939. (- new-level old-level)))
  6940. (delta (if (> shift 0) -1 1))
  6941. (func (if (> shift 0) #'org-demote #'org-promote))
  6942. (org-odd-levels-only nil)
  6943. beg end newend)
  6944. ;; Remove the forced level indicator.
  6945. (when (and force-level (not level))
  6946. (delete-region (line-beginning-position) (point)))
  6947. ;; Paste before the next visible heading or at end of buffer,
  6948. ;; unless point is at the beginning of a headline.
  6949. (unless (and (bolp) (org-at-heading-p))
  6950. (org-next-visible-heading 1)
  6951. (unless (bolp) (insert "\n")))
  6952. (setq beg (point))
  6953. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6954. (insert-before-markers txt)
  6955. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6956. (setq newend (point))
  6957. (org-reinstall-markers-in-region beg)
  6958. (setq end (point))
  6959. (goto-char beg)
  6960. (skip-chars-forward " \t\n\r")
  6961. (setq beg (point))
  6962. (when (and (org-invisible-p) visp)
  6963. (save-excursion (outline-show-heading)))
  6964. ;; Shift if necessary.
  6965. (unless (= shift 0)
  6966. (save-restriction
  6967. (narrow-to-region beg end)
  6968. (while (not (= shift 0))
  6969. (org-map-region func (point-min) (point-max))
  6970. (setq shift (+ delta shift)))
  6971. (goto-char (point-min))
  6972. (setq newend (point-max))))
  6973. (when (or for-yank (called-interactively-p 'interactive))
  6974. (message "Clipboard pasted as level %d subtree" new-level))
  6975. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6976. kill-ring
  6977. (equal org-subtree-clip (current-kill 0))
  6978. org-subtree-clip-folded)
  6979. ;; The tree was folded before it was killed/copied
  6980. (org-flag-subtree t))
  6981. (when for-yank (goto-char newend))
  6982. (when remove (pop kill-ring)))))
  6983. (defun org-kill-is-subtree-p (&optional txt)
  6984. "Check if the current kill is an outline subtree, or a set of trees.
  6985. Returns nil if kill does not start with a headline, or if the first
  6986. headline level is not the largest headline level in the tree.
  6987. So this will actually accept several entries of equal levels as well,
  6988. which is OK for `org-paste-subtree'.
  6989. If optional TXT is given, check this string instead of the current kill."
  6990. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6991. (re (org-get-limited-outline-regexp))
  6992. (^re (concat "^" re))
  6993. (start-level (and kill
  6994. (string-match
  6995. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6996. kill)
  6997. (- (match-end 2) (match-beginning 2) 1)))
  6998. (start (1+ (or (match-beginning 2) -1))))
  6999. (if (not start-level)
  7000. (progn
  7001. nil) ;; does not even start with a heading
  7002. (catch 'exit
  7003. (while (setq start (string-match ^re kill (1+ start)))
  7004. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7005. (throw 'exit nil)))
  7006. t))))
  7007. (defvar org-markers-to-move nil
  7008. "Markers that should be moved with a cut-and-paste operation.
  7009. Those markers are stored together with their positions relative to
  7010. the start of the region.")
  7011. (defun org-save-markers-in-region (beg end)
  7012. "Check markers in region.
  7013. If these markers are between BEG and END, record their position relative
  7014. to BEG, so that after moving the block of text, we can put the markers back
  7015. into place.
  7016. This function gets called just before an entry or tree gets cut from the
  7017. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7018. called immediately, to move the markers with the entries."
  7019. (setq org-markers-to-move nil)
  7020. (when (featurep 'org-clock)
  7021. (org-clock-save-markers-for-cut-and-paste beg end))
  7022. (when (featurep 'org-agenda)
  7023. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7024. (defun org-check-and-save-marker (marker beg end)
  7025. "Check if MARKER is between BEG and END.
  7026. If yes, remember the marker and the distance to BEG."
  7027. (when (and (marker-buffer marker)
  7028. (or (equal (marker-buffer marker) (current-buffer))
  7029. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  7030. (>= marker beg) (< marker end))
  7031. (push (cons marker (- marker beg)) org-markers-to-move)))
  7032. (defun org-reinstall-markers-in-region (beg)
  7033. "Move all remembered markers to their position relative to BEG."
  7034. (dolist (x org-markers-to-move)
  7035. (move-marker (car x) (+ beg (cdr x))))
  7036. (setq org-markers-to-move nil))
  7037. (defun org-narrow-to-subtree ()
  7038. "Narrow buffer to the current subtree."
  7039. (interactive)
  7040. (save-excursion
  7041. (save-match-data
  7042. (org-with-limited-levels
  7043. (narrow-to-region
  7044. (progn (org-back-to-heading t) (point))
  7045. (progn (org-end-of-subtree t t)
  7046. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7047. (point)))))))
  7048. (defun org-toggle-narrow-to-subtree ()
  7049. "Narrow to the subtree at point or widen a narrowed buffer."
  7050. (interactive)
  7051. (if (buffer-narrowed-p)
  7052. (progn (widen) (message "Buffer widen"))
  7053. (org-narrow-to-subtree)
  7054. (message "Buffer narrowed to current subtree")))
  7055. (defun org-narrow-to-block ()
  7056. "Narrow buffer to the current block."
  7057. (interactive)
  7058. (let* ((case-fold-search t)
  7059. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7060. "^[ \t]*#\\+end_.*")))
  7061. (if blockp
  7062. (narrow-to-region (car blockp) (cdr blockp))
  7063. (user-error "Not in a block"))))
  7064. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7065. "Clone the task (subtree) at point N times.
  7066. The clones will be inserted as siblings.
  7067. In interactive use, the user will be prompted for the number of
  7068. clones to be produced. If the entry has a timestamp, the user
  7069. will also be prompted for a time shift, which may be a repeater
  7070. as used in time stamps, for example `+3d'. To disable this,
  7071. you can call the function with a universal prefix argument.
  7072. When a valid repeater is given and the entry contains any time
  7073. stamps, the clones will become a sequence in time, with time
  7074. stamps in the subtree shifted for each clone produced. If SHIFT
  7075. is nil or the empty string, time stamps will be left alone. The
  7076. ID property of the original subtree is removed.
  7077. In each clone, all the CLOCK entries will be removed. This
  7078. prevents Org from considering that the clocked times overlap.
  7079. If the original subtree did contain time stamps with a repeater,
  7080. the following will happen:
  7081. - the repeater will be removed in each clone
  7082. - an additional clone will be produced, with the current, unshifted
  7083. date(s) in the entry.
  7084. - the original entry will be placed *after* all the clones, with
  7085. repeater intact.
  7086. - the start days in the repeater in the original entry will be shifted
  7087. to past the last clone.
  7088. In this way you can spell out a number of instances of a repeating task,
  7089. and still retain the repeater to cover future instances of the task.
  7090. As described above, N+1 clones are produced when the original
  7091. subtree has a repeater. Setting N to 0, then, can be used to
  7092. remove the repeater from a subtree and create a shifted clone
  7093. with the original repeater."
  7094. (interactive "nNumber of clones to produce: ")
  7095. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7096. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7097. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7098. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7099. (shift
  7100. (or shift
  7101. (if (and (not (equal current-prefix-arg '(4)))
  7102. (save-excursion
  7103. (goto-char beg)
  7104. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7105. (read-from-minibuffer
  7106. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7107. ""))) ;No time shift
  7108. (doshift
  7109. (and (org-string-nw-p shift)
  7110. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7111. shift)
  7112. (user-error "Invalid shift specification %s" shift)))))
  7113. (goto-char end-of-tree)
  7114. (unless (bolp) (insert "\n"))
  7115. (let* ((end (point))
  7116. (template (buffer-substring beg end))
  7117. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7118. (shift-what (pcase (and doshift (match-string 2 shift))
  7119. (`nil nil)
  7120. ("h" 'hour)
  7121. ("d" 'day)
  7122. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7123. ("m" 'month)
  7124. ("y" 'year)
  7125. (_ (error "Unsupported time unit"))))
  7126. (nmin 1)
  7127. (nmax n)
  7128. (n-no-remove -1)
  7129. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7130. (idprop (org-entry-get beg "ID")))
  7131. (when (and doshift
  7132. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7133. template))
  7134. (delete-region beg end)
  7135. (setq end beg)
  7136. (setq nmin 0)
  7137. (setq nmax (1+ nmax))
  7138. (setq n-no-remove nmax))
  7139. (goto-char end)
  7140. (cl-loop for n from nmin to nmax do
  7141. (insert
  7142. ;; Prepare clone.
  7143. (with-temp-buffer
  7144. (insert template)
  7145. (org-mode)
  7146. (goto-char (point-min))
  7147. (org-show-subtree)
  7148. (and idprop (if org-clone-delete-id
  7149. (org-entry-delete nil "ID")
  7150. (org-id-get-create t)))
  7151. (unless (= n 0)
  7152. (while (re-search-forward org-clock-line-re nil t)
  7153. (delete-region (line-beginning-position)
  7154. (line-beginning-position 2)))
  7155. (goto-char (point-min))
  7156. (while (re-search-forward org-drawer-regexp nil t)
  7157. (org-remove-empty-drawer-at (point))))
  7158. (goto-char (point-min))
  7159. (when doshift
  7160. (while (re-search-forward org-ts-regexp-both nil t)
  7161. (org-timestamp-change (* n shift-n) shift-what))
  7162. (unless (= n n-no-remove)
  7163. (goto-char (point-min))
  7164. (while (re-search-forward org-ts-regexp nil t)
  7165. (save-excursion
  7166. (goto-char (match-beginning 0))
  7167. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7168. (delete-region (match-beginning 1) (match-end 1)))))))
  7169. (buffer-string)))))
  7170. (goto-char beg)))
  7171. ;;; Outline path
  7172. (defvar org-outline-path-cache nil
  7173. "Alist between buffer positions and outline paths.
  7174. It value is an alist (POSITION . PATH) where POSITION is the
  7175. buffer position at the beginning of an entry and PATH is a list
  7176. of strings describing the outline path for that entry, in reverse
  7177. order.")
  7178. (defun org--get-outline-path-1 (&optional use-cache)
  7179. "Return outline path to current headline.
  7180. Outline path is a list of strings, in reverse order. When
  7181. optional argument USE-CACHE is non-nil, make use of a cache. See
  7182. `org-get-outline-path' for details.
  7183. Assume buffer is widened and point is on a headline."
  7184. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7185. (let ((p (point))
  7186. (heading (let ((case-fold-search nil))
  7187. (looking-at org-complex-heading-regexp)
  7188. (if (not (match-end 4)) ""
  7189. ;; Remove statistics cookies.
  7190. (org-trim
  7191. (org-link-display-format
  7192. (replace-regexp-in-string
  7193. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7194. (match-string-no-properties 4))))))))
  7195. (if (org-up-heading-safe)
  7196. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7197. (when use-cache
  7198. (push (cons p path) org-outline-path-cache))
  7199. path)
  7200. ;; This is a new root node. Since we assume we are moving
  7201. ;; forward, we can drop previous cache so as to limit number
  7202. ;; of associations there.
  7203. (let ((path (list heading)))
  7204. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7205. path)))))
  7206. (defun org-get-outline-path (&optional with-self use-cache)
  7207. "Return the outline path to the current entry.
  7208. An outline path is a list of ancestors for current headline, as
  7209. a list of strings. Statistics cookies are removed and links are
  7210. replaced with their description, if any, or their path otherwise.
  7211. When optional argument WITH-SELF is non-nil, the path also
  7212. includes the current headline.
  7213. When optional argument USE-CACHE is non-nil, cache outline paths
  7214. between calls to this function so as to avoid backtracking. This
  7215. argument is useful when planning to find more than one outline
  7216. path in the same document. In that case, there are two
  7217. conditions to satisfy:
  7218. - `org-outline-path-cache' is set to nil before starting the
  7219. process;
  7220. - outline paths are computed by increasing buffer positions."
  7221. (org-with-wide-buffer
  7222. (and (or (and with-self (org-back-to-heading t))
  7223. (org-up-heading-safe))
  7224. (reverse (org--get-outline-path-1 use-cache)))))
  7225. (defun org-format-outline-path (path &optional width prefix separator)
  7226. "Format the outline path PATH for display.
  7227. WIDTH is the maximum number of characters that is available.
  7228. PREFIX is a prefix to be included in the returned string,
  7229. such as the file name.
  7230. SEPARATOR is inserted between the different parts of the path,
  7231. the default is \"/\"."
  7232. (setq width (or width 79))
  7233. (setq path (delq nil path))
  7234. (unless (> width 0)
  7235. (user-error "Argument `width' must be positive"))
  7236. (setq separator (or separator "/"))
  7237. (let* ((org-odd-levels-only nil)
  7238. (fpath (concat
  7239. prefix (and prefix path separator)
  7240. (mapconcat
  7241. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7242. (cl-loop for head in path
  7243. for n from 0
  7244. collect (org-add-props
  7245. head nil 'face
  7246. (nth (% n org-n-level-faces) org-level-faces)))
  7247. separator))))
  7248. (when (> (length fpath) width)
  7249. (if (< width 7)
  7250. ;; It's unlikely that `width' will be this small, but don't
  7251. ;; waste characters by adding ".." if it is.
  7252. (setq fpath (substring fpath 0 width))
  7253. (setf (substring fpath (- width 2)) "..")))
  7254. fpath))
  7255. (defun org-display-outline-path (&optional file current separator just-return-string)
  7256. "Display the current outline path in the echo area.
  7257. If FILE is non-nil, prepend the output with the file name.
  7258. If CURRENT is non-nil, append the current heading to the output.
  7259. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7260. the different parts of the path and defaults to \"/\".
  7261. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7262. (interactive "P")
  7263. (let* (case-fold-search
  7264. (bfn (buffer-file-name (buffer-base-buffer)))
  7265. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7266. res)
  7267. (when current (setq path (append path
  7268. (save-excursion
  7269. (org-back-to-heading t)
  7270. (when (looking-at org-complex-heading-regexp)
  7271. (list (match-string 4)))))))
  7272. (setq res
  7273. (org-format-outline-path
  7274. path
  7275. (1- (frame-width))
  7276. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7277. separator))
  7278. (add-face-text-property 0 (length res)
  7279. `(:height ,(face-attribute 'default :height))
  7280. nil res)
  7281. (if just-return-string
  7282. res
  7283. (org-unlogged-message "%s" res))))
  7284. ;;; Outline Sorting
  7285. (defun org-sort (&optional with-case)
  7286. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7287. Optional argument WITH-CASE means sort case-sensitively."
  7288. (interactive "P")
  7289. (org-call-with-arg
  7290. (cond ((org-at-table-p) #'org-table-sort-lines)
  7291. ((org-at-item-p) #'org-sort-list)
  7292. (t #'org-sort-entries))
  7293. with-case))
  7294. (defun org-sort-remove-invisible (s)
  7295. "Remove emphasis markers and any invisible property from string S.
  7296. Assume S may contain only objects."
  7297. ;; org-element-interpret-data clears any text property, including
  7298. ;; invisible part.
  7299. (org-element-interpret-data
  7300. (let ((tree (org-element-parse-secondary-string
  7301. s (org-element-restriction 'paragraph))))
  7302. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7303. (lambda (o)
  7304. (pcase (org-element-type o)
  7305. ;; Terminal object. Replace it with its value.
  7306. ((or `code `verbatim)
  7307. (let ((new (org-element-property :value o)))
  7308. (org-element-insert-before new o)
  7309. (org-element-put-property
  7310. new :post-blank (org-element-property :post-blank o))))
  7311. ;; Non-terminal objects. Splice contents.
  7312. (type
  7313. (let ((contents
  7314. (or (org-element-contents o)
  7315. (and (eq type 'link)
  7316. (list (org-element-property :raw-link o)))))
  7317. (c nil))
  7318. (while contents
  7319. (setq c (pop contents))
  7320. (org-element-insert-before c o))
  7321. (org-element-put-property
  7322. c :post-blank (org-element-property :post-blank o)))))
  7323. (org-element-extract-element o)))
  7324. ;; Return modified tree.
  7325. tree)))
  7326. (defvar org-after-sorting-entries-or-items-hook nil
  7327. "Hook that is run after a bunch of entries or items have been sorted.
  7328. When children are sorted, the cursor is in the parent line when this
  7329. hook gets called. When a region or a plain list is sorted, the cursor
  7330. will be in the first entry of the sorted region/list.")
  7331. (defun org-sort-entries
  7332. (&optional with-case sorting-type getkey-func compare-func property
  7333. interactive?)
  7334. "Sort entries on a certain level of an outline tree.
  7335. If there is an active region, the entries in the region are sorted.
  7336. Else, if the cursor is before the first entry, sort the top-level items.
  7337. Else, the children of the entry at point are sorted.
  7338. Sorting can be alphabetically, numerically, by date/time as given by
  7339. a time stamp, by a property, by priority order, or by a custom function.
  7340. The command prompts for the sorting type unless it has been given to the
  7341. function through the SORTING-TYPE argument, which needs to be a character,
  7342. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7343. the precise meaning of each character:
  7344. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7345. c By creation time, which is assumed to be the first inactive time stamp
  7346. at the beginning of a line.
  7347. d By deadline date/time.
  7348. k By clocking time.
  7349. n Numerically, by converting the beginning of the entry/item to a number.
  7350. o By order of TODO keywords.
  7351. p By priority according to the cookie.
  7352. r By the value of a property.
  7353. s By scheduled date/time.
  7354. t By date/time, either the first active time stamp in the entry, or, if
  7355. none exist, by the first inactive one.
  7356. Capital letters will reverse the sort order.
  7357. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7358. called with point at the beginning of the record. It must return a
  7359. value that is compatible with COMPARE-FUNC, the function used to
  7360. compare entries.
  7361. Comparing entries ignores case by default. However, with an optional argument
  7362. WITH-CASE, the sorting considers case as well.
  7363. Sorting is done against the visible part of the headlines, it ignores hidden
  7364. links.
  7365. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7366. A non-nil value for INTERACTIVE? is used to signal that this
  7367. function is being called interactively."
  7368. (interactive (list current-prefix-arg nil nil nil nil t))
  7369. (let ((case-func (if with-case 'identity 'downcase))
  7370. start beg end stars re re2
  7371. txt what tmp)
  7372. ;; Find beginning and end of region to sort
  7373. (cond
  7374. ((org-region-active-p)
  7375. ;; we will sort the region
  7376. (setq end (region-end)
  7377. what "region")
  7378. (goto-char (region-beginning))
  7379. (unless (org-at-heading-p) (outline-next-heading))
  7380. (setq start (point)))
  7381. ((or (org-at-heading-p)
  7382. (ignore-errors (progn (org-back-to-heading) t)))
  7383. ;; we will sort the children of the current headline
  7384. (org-back-to-heading)
  7385. (setq start (point)
  7386. end (progn (org-end-of-subtree t t)
  7387. (or (bolp) (insert "\n"))
  7388. (when (>= (org-back-over-empty-lines) 1)
  7389. (forward-line 1))
  7390. (point))
  7391. what "children")
  7392. (goto-char start)
  7393. (outline-show-subtree)
  7394. (outline-next-heading))
  7395. (t
  7396. ;; we will sort the top-level entries in this file
  7397. (goto-char (point-min))
  7398. (or (org-at-heading-p) (outline-next-heading))
  7399. (setq start (point))
  7400. (goto-char (point-max))
  7401. (beginning-of-line 1)
  7402. (when (looking-at ".*?\\S-")
  7403. ;; File ends in a non-white line
  7404. (end-of-line 1)
  7405. (insert "\n"))
  7406. (setq end (point-max))
  7407. (setq what "top-level")
  7408. (goto-char start)
  7409. (org-show-all '(headings drawers blocks))))
  7410. (setq beg (point))
  7411. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7412. (looking-at "\\(\\*+\\)")
  7413. (setq stars (match-string 1)
  7414. re (concat "^" (regexp-quote stars) " +")
  7415. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7416. txt (buffer-substring beg end))
  7417. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7418. (when (and (not (equal stars "*")) (string-match re2 txt))
  7419. (user-error "Region to sort contains a level above the first entry"))
  7420. (unless sorting-type
  7421. (message
  7422. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7423. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7424. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7425. what)
  7426. (setq sorting-type (read-char-exclusive)))
  7427. (unless getkey-func
  7428. (and (= (downcase sorting-type) ?f)
  7429. (setq getkey-func
  7430. (or (and interactive?
  7431. (org-read-function
  7432. "Function for extracting keys: "))
  7433. (error "Missing key extractor")))))
  7434. (and (= (downcase sorting-type) ?r)
  7435. (not property)
  7436. (setq property
  7437. (completing-read "Property: "
  7438. (mapcar #'list (org-buffer-property-keys t))
  7439. nil t)))
  7440. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7441. (message "Sorting entries...")
  7442. (save-restriction
  7443. (narrow-to-region start end)
  7444. (let ((restore-clock?
  7445. ;; The clock marker is lost when using `sort-subr'; mark
  7446. ;; the clock with temporary `:org-clock-marker-backup'
  7447. ;; text property.
  7448. (when (and (eq (org-clocking-buffer) (current-buffer))
  7449. (<= start (marker-position org-clock-marker))
  7450. (>= end (marker-position org-clock-marker)))
  7451. (with-silent-modifications
  7452. (put-text-property (1- org-clock-marker) org-clock-marker
  7453. :org-clock-marker-backup t))
  7454. t))
  7455. (dcst (downcase sorting-type))
  7456. (case-fold-search nil)
  7457. (now (current-time)))
  7458. (org-preserve-local-variables
  7459. (sort-subr
  7460. (/= dcst sorting-type)
  7461. ;; This function moves to the beginning character of the
  7462. ;; "record" to be sorted.
  7463. (lambda nil
  7464. (if (re-search-forward re nil t)
  7465. (goto-char (match-beginning 0))
  7466. (goto-char (point-max))))
  7467. ;; This function moves to the last character of the "record" being
  7468. ;; sorted.
  7469. (lambda nil
  7470. (save-match-data
  7471. (condition-case nil
  7472. (outline-forward-same-level 1)
  7473. (error
  7474. (goto-char (point-max))))))
  7475. ;; This function returns the value that gets sorted against.
  7476. (lambda ()
  7477. (cond
  7478. ((= dcst ?n)
  7479. (string-to-number
  7480. (org-sort-remove-invisible (org-get-heading t t t t))))
  7481. ((= dcst ?a)
  7482. (funcall case-func
  7483. (org-sort-remove-invisible (org-get-heading t t t t))))
  7484. ((= dcst ?k)
  7485. (or (get-text-property (point) :org-clock-minutes) 0))
  7486. ((= dcst ?t)
  7487. (let ((end (save-excursion (outline-next-heading) (point))))
  7488. (if (or (re-search-forward org-ts-regexp end t)
  7489. (re-search-forward org-ts-regexp-both end t))
  7490. (org-time-string-to-seconds (match-string 0))
  7491. (float-time now))))
  7492. ((= dcst ?c)
  7493. (let ((end (save-excursion (outline-next-heading) (point))))
  7494. (if (re-search-forward
  7495. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7496. end t)
  7497. (org-time-string-to-seconds (match-string 0))
  7498. (float-time now))))
  7499. ((= dcst ?s)
  7500. (let ((end (save-excursion (outline-next-heading) (point))))
  7501. (if (re-search-forward org-scheduled-time-regexp end t)
  7502. (org-time-string-to-seconds (match-string 1))
  7503. (float-time now))))
  7504. ((= dcst ?d)
  7505. (let ((end (save-excursion (outline-next-heading) (point))))
  7506. (if (re-search-forward org-deadline-time-regexp end t)
  7507. (org-time-string-to-seconds (match-string 1))
  7508. (float-time now))))
  7509. ((= dcst ?p)
  7510. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7511. (string-to-char (match-string 2))
  7512. org-priority-default))
  7513. ((= dcst ?r)
  7514. (or (org-entry-get nil property) ""))
  7515. ((= dcst ?o)
  7516. (when (looking-at org-complex-heading-regexp)
  7517. (let* ((m (match-string 2))
  7518. (s (if (member m org-done-keywords) '- '+)))
  7519. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7520. ((= dcst ?f)
  7521. (if getkey-func
  7522. (progn
  7523. (setq tmp (funcall getkey-func))
  7524. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7525. tmp)
  7526. (error "Invalid key function `%s'" getkey-func)))
  7527. (t (error "Invalid sorting type `%c'" sorting-type))))
  7528. nil
  7529. (cond
  7530. ((= dcst ?a) 'org-string-collate-lessp)
  7531. ((= dcst ?f)
  7532. (or compare-func
  7533. (and interactive?
  7534. (org-read-function
  7535. (concat "Function for comparing keys "
  7536. "(empty for default `sort-subr' predicate): ")
  7537. 'allow-empty))))
  7538. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7539. (org-cycle-hide-drawers 'all)
  7540. (when restore-clock?
  7541. (move-marker org-clock-marker
  7542. (1+ (next-single-property-change
  7543. start :org-clock-marker-backup)))
  7544. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7545. '(:org-clock-marker-backup t)))))
  7546. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7547. (message "Sorting entries...done")))
  7548. (defun org-contextualize-keys (alist contexts)
  7549. "Return valid elements in ALIST depending on CONTEXTS.
  7550. `org-agenda-custom-commands' or `org-capture-templates' are the
  7551. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7552. or `org-capture-templates-contexts' are the associated contexts
  7553. definitions."
  7554. (let ((contexts
  7555. ;; normalize contexts
  7556. (mapcar
  7557. (lambda(c) (cond ((listp (cadr c))
  7558. (list (car c) (car c) (nth 1 c)))
  7559. ((string= "" (cadr c))
  7560. (list (car c) (car c) (nth 2 c)))
  7561. (t c)))
  7562. contexts))
  7563. (a alist) r s)
  7564. ;; loop over all commands or templates
  7565. (dolist (c a)
  7566. (let (vrules repl)
  7567. (cond
  7568. ((not (assoc (car c) contexts))
  7569. (push c r))
  7570. ((and (assoc (car c) contexts)
  7571. (setq vrules (org-contextualize-validate-key
  7572. (car c) contexts)))
  7573. (mapc (lambda (vr)
  7574. (unless (equal (car vr) (cadr vr))
  7575. (setq repl vr)))
  7576. vrules)
  7577. (if (not repl) (push c r)
  7578. (push (cadr repl) s)
  7579. (push
  7580. (cons (car c)
  7581. (cdr (or (assoc (cadr repl) alist)
  7582. (error "Undefined key `%s' as contextual replacement for `%s'"
  7583. (cadr repl) (car c)))))
  7584. r))))))
  7585. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7586. (delq
  7587. nil
  7588. (delete-dups
  7589. (mapcar (lambda (x)
  7590. (let ((tpl (car x)))
  7591. (unless (delq
  7592. nil
  7593. (mapcar (lambda (y)
  7594. (equal y tpl))
  7595. s))
  7596. x)))
  7597. (reverse r))))))
  7598. (defun org-contextualize-validate-key (key contexts)
  7599. "Check CONTEXTS for agenda or capture KEY."
  7600. (let (res)
  7601. (dolist (r contexts)
  7602. (dolist (rr (car (last r)))
  7603. (when
  7604. (and (equal key (car r))
  7605. (if (functionp rr) (funcall rr)
  7606. (or (and (eq (car rr) 'in-file)
  7607. (buffer-file-name)
  7608. (string-match (cdr rr) (buffer-file-name)))
  7609. (and (eq (car rr) 'in-mode)
  7610. (string-match (cdr rr) (symbol-name major-mode)))
  7611. (and (eq (car rr) 'in-buffer)
  7612. (string-match (cdr rr) (buffer-name)))
  7613. (when (and (eq (car rr) 'not-in-file)
  7614. (buffer-file-name))
  7615. (not (string-match (cdr rr) (buffer-file-name))))
  7616. (when (eq (car rr) 'not-in-mode)
  7617. (not (string-match (cdr rr) (symbol-name major-mode))))
  7618. (when (eq (car rr) 'not-in-buffer)
  7619. (not (string-match (cdr rr) (buffer-name)))))))
  7620. (push r res))))
  7621. (delete-dups (delq nil res))))
  7622. ;; Defined to provide a value for defcustom, since there is no
  7623. ;; string-collate-greaterp in Emacs.
  7624. (defun org-string-collate-greaterp (s1 s2)
  7625. "Return non-nil if S1 is greater than S2 in collation order."
  7626. (not (org-string-collate-lessp s1 s2)))
  7627. ;;;###autoload
  7628. (defun org-run-like-in-org-mode (cmd)
  7629. "Run a command, pretending that the current buffer is in Org mode.
  7630. This will temporarily bind local variables that are typically bound in
  7631. Org mode to the values they have in Org mode, and then interactively
  7632. call CMD."
  7633. (org-load-modules-maybe)
  7634. (let (binds)
  7635. (dolist (var (org-get-local-variables))
  7636. (when (or (not (boundp (car var)))
  7637. (eq (symbol-value (car var))
  7638. (default-value (car var))))
  7639. (push (list (car var) `(quote ,(cadr var))) binds)))
  7640. (eval `(let ,binds
  7641. (call-interactively (quote ,cmd))))))
  7642. (defun org-get-category (&optional pos force-refresh)
  7643. "Get the category applying to position POS."
  7644. (save-match-data
  7645. (when force-refresh (org-refresh-category-properties))
  7646. (let ((pos (or pos (point))))
  7647. (or (get-text-property pos 'org-category)
  7648. (progn (org-refresh-category-properties)
  7649. (get-text-property pos 'org-category))))))
  7650. ;;; Refresh properties
  7651. (defun org-refresh-properties (dprop tprop)
  7652. "Refresh buffer text properties.
  7653. DPROP is the drawer property and TPROP is either the
  7654. corresponding text property to set, or an alist with each element
  7655. being a text property (as a symbol) and a function to apply to
  7656. the value of the drawer property."
  7657. (let* ((case-fold-search t)
  7658. (inhibit-read-only t)
  7659. (inherit? (org-property-inherit-p dprop))
  7660. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7661. (global-or-keyword (and inherit?
  7662. (org--property-global-or-keyword-value dprop nil))))
  7663. (with-silent-modifications
  7664. (org-with-point-at 1
  7665. ;; Set global and keyword based values to the whole buffer.
  7666. (when global-or-keyword
  7667. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7668. ;; Set values based on property-drawers throughout the document.
  7669. (while (re-search-forward property-re nil t)
  7670. (when (org-at-property-p)
  7671. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7672. (outline-next-heading))))))
  7673. (defun org-refresh-property (tprop p &optional inherit)
  7674. "Refresh the buffer text property TPROP from the drawer property P.
  7675. The refresh happens only for the current entry, or the whole
  7676. sub-tree if optional argument INHERIT is non-nil.
  7677. If point is before first headline, the function applies to the
  7678. part before the first headline. In that particular case, when
  7679. optional argument INHERIT is non-nil, it refreshes properties for
  7680. the whole buffer."
  7681. (save-excursion
  7682. (org-back-to-heading-or-point-min t)
  7683. (let ((start (point))
  7684. (end (save-excursion
  7685. (cond ((and inherit (org-before-first-heading-p))
  7686. (point-max))
  7687. (inherit
  7688. (org-end-of-subtree t t))
  7689. ((outline-next-heading))
  7690. ((point-max))))))
  7691. (if (symbolp tprop)
  7692. ;; TPROP is a text property symbol.
  7693. (put-text-property start end tprop p)
  7694. ;; TPROP is an alist with (property . function) elements.
  7695. (pcase-dolist (`(,prop . ,f) tprop)
  7696. (put-text-property start end prop (funcall f p)))))))
  7697. (defun org-refresh-category-properties ()
  7698. "Refresh category text properties in the buffer."
  7699. (let ((case-fold-search t)
  7700. (inhibit-read-only t)
  7701. (default-category
  7702. (cond ((null org-category)
  7703. (if buffer-file-name
  7704. (file-name-sans-extension
  7705. (file-name-nondirectory buffer-file-name))
  7706. "???"))
  7707. ((symbolp org-category) (symbol-name org-category))
  7708. (t org-category))))
  7709. (with-silent-modifications
  7710. (org-with-wide-buffer
  7711. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7712. ;; keyword. If none is found, fall-back to `org-category' or
  7713. ;; buffer file name, or set it by the document property drawer.
  7714. (put-text-property
  7715. (point-min) (point-max)
  7716. 'org-category
  7717. (catch 'buffer-category
  7718. (goto-char (point-max))
  7719. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7720. (let ((element (org-element-at-point)))
  7721. (when (eq (org-element-type element) 'keyword)
  7722. (throw 'buffer-category
  7723. (org-element-property :value element)))))
  7724. default-category))
  7725. ;; Set categories from the document property drawer or
  7726. ;; property drawers in the outline. If category is found in
  7727. ;; the property drawer for the whole buffer that value
  7728. ;; overrides the keyword-based value set above.
  7729. (goto-char (point-min))
  7730. (let ((regexp (org-re-property "CATEGORY")))
  7731. (while (re-search-forward regexp nil t)
  7732. (let ((value (match-string-no-properties 3)))
  7733. (when (org-at-property-p)
  7734. (put-text-property
  7735. (save-excursion (org-back-to-heading-or-point-min t))
  7736. (save-excursion (if (org-before-first-heading-p)
  7737. (point-max)
  7738. (org-end-of-subtree t t)))
  7739. 'org-category
  7740. value)))))))))
  7741. (defun org-refresh-stats-properties ()
  7742. "Refresh stats text properties in the buffer."
  7743. (with-silent-modifications
  7744. (org-with-point-at 1
  7745. (let ((regexp (concat org-outline-regexp-bol
  7746. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7747. (while (re-search-forward regexp nil t)
  7748. (let* ((numerator (string-to-number (match-string 1)))
  7749. (denominator (and (match-end 2)
  7750. (string-to-number (match-string 2))))
  7751. (stats (cond ((not denominator) numerator) ;percent
  7752. ((= denominator 0) 0)
  7753. (t (/ (* numerator 100) denominator)))))
  7754. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7755. 'org-stats stats)))))))
  7756. (defun org-refresh-effort-properties ()
  7757. "Refresh effort properties."
  7758. (org-refresh-properties
  7759. org-effort-property
  7760. '((effort . identity)
  7761. (effort-minutes . org-duration-to-minutes))))
  7762. (defun org-find-file-at-mouse (ev)
  7763. "Open file link or URL at mouse."
  7764. (interactive "e")
  7765. (mouse-set-point ev)
  7766. (org-open-at-point 'in-emacs))
  7767. (defun org-open-at-mouse (ev)
  7768. "Open file link or URL at mouse.
  7769. See the docstring of `org-open-file' for details."
  7770. (interactive "e")
  7771. (mouse-set-point ev)
  7772. (when (eq major-mode 'org-agenda-mode)
  7773. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7774. (org-open-at-point))
  7775. (defvar org-window-config-before-follow-link nil
  7776. "The window configuration before following a link.
  7777. This is saved in case the need arises to restore it.")
  7778. (defun org--file-default-apps ()
  7779. "Return the default applications for this operating system."
  7780. (pcase system-type
  7781. (`darwin org-file-apps-macos)
  7782. (`windows-nt org-file-apps-windowsnt)
  7783. (_ org-file-apps-gnu)))
  7784. (defun org--file-apps-entry-dlink-p (entry)
  7785. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7786. It assumes that is the case when the entry uses a regular
  7787. expression which has at least one grouping construct and the
  7788. action is either a Lisp form or a command string containing
  7789. \"%1\", i.e., using at least one subexpression match as
  7790. a parameter."
  7791. (pcase entry
  7792. (`(,selector . ,action)
  7793. (and (stringp selector)
  7794. (> (regexp-opt-depth selector) 0)
  7795. (or (and (stringp action)
  7796. (string-match "%[0-9]" action))
  7797. (consp action))))
  7798. (_ nil)))
  7799. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7800. "Convert extensions to regular expressions in the cars of LIST.
  7801. Also, weed out any non-string entries, because the return value
  7802. is used only for regexp matching.
  7803. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7804. point to the symbol `emacs', indicating that the file should be
  7805. opened in Emacs."
  7806. (append
  7807. (delq nil
  7808. (mapcar (lambda (x)
  7809. (unless (not (stringp (car x)))
  7810. (if (string-match "\\W" (car x))
  7811. x
  7812. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7813. list))
  7814. (when add-auto-mode
  7815. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7816. ;;;###autoload
  7817. (defun org-open-file (path &optional in-emacs line search)
  7818. "Open the file at PATH.
  7819. First, this expands any special file name abbreviations. Then the
  7820. configuration variable `org-file-apps' is checked if it contains an
  7821. entry for this file type, and if yes, the corresponding command is launched.
  7822. If no application is found, Emacs simply visits the file.
  7823. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7824. With a double \\[universal-argument] \\[universal-argument] \
  7825. prefix arg, Org tries to avoid opening in Emacs
  7826. and to use an external application to visit the file.
  7827. Optional LINE specifies a line to go to, optional SEARCH a string
  7828. to search for. If LINE or SEARCH is given, the file will be
  7829. opened in Emacs, unless an entry from `org-file-apps' that makes
  7830. use of groups in a regexp matches.
  7831. If you want to change the way frames are used when following a
  7832. link, please customize `org-link-frame-setup'.
  7833. If the file does not exist, throw an error."
  7834. (let* ((file (if (equal path "") buffer-file-name
  7835. (substitute-in-file-name (expand-file-name path))))
  7836. (file-apps (append org-file-apps (org--file-default-apps)))
  7837. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7838. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7839. file-apps))
  7840. (remp (and (assq 'remote apps) (file-remote-p file)))
  7841. (dirp (unless remp (file-directory-p file)))
  7842. (file (if (and dirp org-open-directory-means-index-dot-org)
  7843. (concat (file-name-as-directory file) "index.org")
  7844. file))
  7845. (a-m-a-p (assq 'auto-mode apps))
  7846. (dfile (downcase file))
  7847. ;; Reconstruct the original link from the PATH, LINE and
  7848. ;; SEARCH args.
  7849. (link (cond (line (concat file "::" (number-to-string line)))
  7850. (search (concat file "::" search))
  7851. (t file)))
  7852. (dlink (downcase link))
  7853. (ext
  7854. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7855. (match-string 1 dfile)))
  7856. (save-position-maybe
  7857. (let ((old-buffer (current-buffer))
  7858. (old-pos (point))
  7859. (old-mode major-mode))
  7860. (lambda ()
  7861. (and (derived-mode-p 'org-mode)
  7862. (eq old-mode 'org-mode)
  7863. (or (not (eq old-buffer (current-buffer)))
  7864. (not (eq old-pos (point))))
  7865. (org-mark-ring-push old-pos old-buffer)))))
  7866. cmd link-match-data)
  7867. (cond
  7868. ((member in-emacs '((16) system))
  7869. (setq cmd (cdr (assq 'system apps))))
  7870. (in-emacs (setq cmd 'emacs))
  7871. (t
  7872. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7873. (and dirp (cdr (assq 'directory apps)))
  7874. ;; First, try matching against apps-dlink if we
  7875. ;; get a match here, store the match data for
  7876. ;; later.
  7877. (let ((match (assoc-default dlink apps-dlink
  7878. 'string-match)))
  7879. (if match
  7880. (progn (setq link-match-data (match-data))
  7881. match)
  7882. (progn (setq in-emacs (or in-emacs line search))
  7883. nil))) ; if we have no match in apps-dlink,
  7884. ; always open the file in emacs if line or search
  7885. ; is given (for backwards compatibility)
  7886. (assoc-default dfile
  7887. (org--file-apps-regexp-alist apps a-m-a-p)
  7888. 'string-match)
  7889. (cdr (assoc ext apps))
  7890. (cdr (assq t apps))))))
  7891. (when (eq cmd 'system)
  7892. (setq cmd (cdr (assq 'system apps))))
  7893. (when (eq cmd 'default)
  7894. (setq cmd (cdr (assoc t apps))))
  7895. (when (eq cmd 'mailcap)
  7896. (require 'mailcap)
  7897. (mailcap-parse-mailcaps)
  7898. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7899. (command (mailcap-mime-info mime-type)))
  7900. (if (stringp command)
  7901. (setq cmd command)
  7902. (setq cmd 'emacs))))
  7903. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7904. (not (file-exists-p file))
  7905. (not org-open-non-existing-files))
  7906. (user-error "No such file: %s" file))
  7907. (cond
  7908. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7909. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7910. (while (string-match "['\"]%s['\"]" cmd)
  7911. (setq cmd (replace-match "%s" t t cmd)))
  7912. (setq cmd (replace-regexp-in-string
  7913. "%s"
  7914. (shell-quote-argument (convert-standard-filename file))
  7915. cmd
  7916. nil t))
  7917. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7918. (save-match-data
  7919. (let ((match-index 1)
  7920. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7921. (set-match-data link-match-data)
  7922. (while (<= match-index number-of-groups)
  7923. (let ((regex (concat "%" (number-to-string match-index)))
  7924. (replace-with (match-string match-index dlink)))
  7925. (while (string-match regex cmd)
  7926. (setq cmd (replace-match replace-with t t cmd))))
  7927. (setq match-index (+ match-index 1)))))
  7928. (save-window-excursion
  7929. (message "Running %s...done" cmd)
  7930. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7931. ;; and exit immediately. Use pipe connection type instead of pty to
  7932. ;; avoid killing children processes with SIGHUP when temporary terminal
  7933. ;; session is finished.
  7934. ;;
  7935. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7936. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7937. ;; error messages.
  7938. (let ((process-connection-type nil))
  7939. (start-process-shell-command cmd nil cmd))
  7940. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7941. ((or (stringp cmd)
  7942. (eq cmd 'emacs))
  7943. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7944. (widen)
  7945. (cond (line (org-goto-line line)
  7946. (when (derived-mode-p 'org-mode) (org-reveal)))
  7947. (search (condition-case err
  7948. (org-link-search search)
  7949. ;; Save position before error-ing out so user
  7950. ;; can easily move back to the original buffer.
  7951. (error (funcall save-position-maybe)
  7952. (error (nth 1 err)))))))
  7953. ((functionp cmd)
  7954. (save-match-data
  7955. (set-match-data link-match-data)
  7956. (condition-case nil
  7957. (funcall cmd file link)
  7958. ;; FIXME: Remove this check when most default installations
  7959. ;; of Emacs have at least Org 9.0.
  7960. ((debug wrong-number-of-arguments wrong-type-argument
  7961. invalid-function)
  7962. (user-error "Please see Org News for version 9.0 about \
  7963. `org-file-apps'--Lisp error: %S" cmd)))))
  7964. ((consp cmd)
  7965. ;; FIXME: Remove this check when most default installations of
  7966. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7967. ;; fall back to `org-link-frame-setup' for an old usage of
  7968. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7969. (user-error "Please see Org News for version 9.0 about \
  7970. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7971. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7972. (funcall save-position-maybe)))
  7973. ;;;###autoload
  7974. (defun org-open-at-point-global ()
  7975. "Follow a link or a time-stamp like Org mode does.
  7976. Also follow links and emails as seen by `thing-at-point'.
  7977. This command can be called in any mode to follow an external
  7978. link or a time-stamp that has Org mode syntax. Its behavior
  7979. is undefined when called on internal links like fuzzy links.
  7980. Raise a user error when there is nothing to follow."
  7981. (interactive)
  7982. (let ((tap-url (thing-at-point 'url))
  7983. (tap-email (thing-at-point 'email)))
  7984. (cond ((org-in-regexp org-link-any-re)
  7985. (org-link-open-from-string (match-string-no-properties 0)))
  7986. ((or (org-in-regexp org-ts-regexp-both nil t)
  7987. (org-in-regexp org-tsr-regexp-both nil t))
  7988. (org-follow-timestamp-link))
  7989. (tap-url (org-link-open-from-string tap-url))
  7990. (tap-email (org-link-open-from-string
  7991. (concat "mailto:" tap-email)))
  7992. (t (user-error "No link found")))))
  7993. (defvar org-open-at-point-functions nil
  7994. "Hook that is run when following a link at point.
  7995. Functions in this hook must return t if they identify and follow
  7996. a link at point. If they don't find anything interesting at point,
  7997. they must return nil.")
  7998. (defun org-open-at-point (&optional arg)
  7999. "Open link, timestamp, footnote or tags at point.
  8000. When point is on a link, follow it. Normally, files will be
  8001. opened by an appropriate application. If the optional prefix
  8002. argument ARG is non-nil, Emacs will visit the file. With
  8003. a double prefix argument, try to open outside of Emacs, in the
  8004. application the system uses for this file type.
  8005. When point is on a timestamp, open the agenda at the day
  8006. specified.
  8007. When point is a footnote definition, move to the first reference
  8008. found. If it is on a reference, move to the associated
  8009. definition.
  8010. When point is on a headline, display a list of every link in the
  8011. entry, so it is possible to pick one, or all, of them. If point
  8012. is on a tag, call `org-tags-view' instead.
  8013. On top of syntactically correct links, this function also tries
  8014. to open links and time-stamps in comments, node properties, and
  8015. keywords if point is on something looking like a timestamp or
  8016. a link."
  8017. (interactive "P")
  8018. (org-load-modules-maybe)
  8019. (setq org-window-config-before-follow-link (current-window-configuration))
  8020. (org-remove-occur-highlights nil nil t)
  8021. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8022. (let* ((context
  8023. ;; Only consider supported types, even if they are not the
  8024. ;; closest one.
  8025. (org-element-lineage
  8026. (org-element-context)
  8027. '(citation citation-reference clock comment comment-block
  8028. footnote-definition footnote-reference headline
  8029. inline-src-block inlinetask keyword link node-property
  8030. planning src-block timestamp)
  8031. t))
  8032. (type (org-element-type context))
  8033. (value (org-element-property :value context)))
  8034. (cond
  8035. ((not type) (user-error "No link found"))
  8036. ;; No valid link at point. For convenience, look if something
  8037. ;; looks like a link under point in some specific places.
  8038. ((memq type '(comment comment-block node-property keyword))
  8039. (call-interactively #'org-open-at-point-global))
  8040. ;; On a headline or an inlinetask, but not on a timestamp,
  8041. ;; a link, a footnote reference or a citation.
  8042. ((memq type '(headline inlinetask))
  8043. (org-match-line org-complex-heading-regexp)
  8044. (let ((tags-beg (match-beginning 5))
  8045. (tags-end (match-end 5)))
  8046. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8047. ;; On tags.
  8048. (org-tags-view
  8049. arg
  8050. (save-excursion
  8051. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8052. (end-tag (search-forward ":" tags-end nil 2)))
  8053. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8054. ;; Not on tags.
  8055. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8056. (`(nil . ,_)
  8057. (require 'org-attach)
  8058. (when (org-attach-dir)
  8059. (message "Opening attachment")
  8060. (if (equal arg '(4))
  8061. (org-attach-reveal-in-emacs)
  8062. (org-attach-reveal))))
  8063. (`(,links . ,links-end)
  8064. (dolist (link (if (stringp links) (list links) links))
  8065. (search-forward link nil links-end)
  8066. (goto-char (match-beginning 0))
  8067. (org-open-at-point arg)))))))
  8068. ;; On a footnote reference or at definition's label.
  8069. ((or (eq type 'footnote-reference)
  8070. (and (eq type 'footnote-definition)
  8071. (save-excursion
  8072. ;; Do not validate action when point is on the
  8073. ;; spaces right after the footnote label, in order
  8074. ;; to be on par with behavior on links.
  8075. (skip-chars-forward " \t")
  8076. (let ((begin
  8077. (org-element-property :contents-begin context)))
  8078. (if begin (< (point) begin)
  8079. (= (org-element-property :post-affiliated context)
  8080. (line-beginning-position)))))))
  8081. (org-footnote-action))
  8082. ;; On a planning line. Check if we are really on a timestamp.
  8083. ((and (eq type 'planning)
  8084. (org-in-regexp org-ts-regexp-both nil t))
  8085. (org-follow-timestamp-link))
  8086. ;; On a clock line, make sure point is on the timestamp
  8087. ;; before opening it.
  8088. ((and (eq type 'clock)
  8089. value
  8090. (>= (point) (org-element-property :begin value))
  8091. (<= (point) (org-element-property :end value)))
  8092. (org-follow-timestamp-link))
  8093. ((eq type 'src-block) (org-babel-open-src-block-result))
  8094. ;; Do nothing on white spaces after an object.
  8095. ((>= (point)
  8096. (save-excursion
  8097. (goto-char (org-element-property :end context))
  8098. (skip-chars-backward " \t")
  8099. (point)))
  8100. (user-error "No link found"))
  8101. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8102. ((eq type 'timestamp) (org-follow-timestamp-link))
  8103. ((eq type 'link) (org-link-open context arg))
  8104. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  8105. (t (user-error "No link found")))))
  8106. (run-hook-with-args 'org-follow-link-hook))
  8107. ;;;###autoload
  8108. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8109. "Offer links in the current entry and return the selected link.
  8110. If there is only one link, return it.
  8111. If NTH is an integer, return the NTH link found.
  8112. If ZERO is a string, check also this string for a link, and if
  8113. there is one, return it."
  8114. (with-current-buffer buffer
  8115. (org-with-wide-buffer
  8116. (goto-char marker)
  8117. (let ((cnt ?0)
  8118. have-zero end links link c)
  8119. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8120. (push (match-string 0 zero) links)
  8121. (setq cnt (1- cnt) have-zero t))
  8122. (save-excursion
  8123. (org-back-to-heading t)
  8124. (setq end (save-excursion (outline-next-heading) (point)))
  8125. (while (re-search-forward org-link-any-re end t)
  8126. (push (match-string 0) links))
  8127. (setq links (org-uniquify (reverse links))))
  8128. (cond
  8129. ((null links)
  8130. (message "No links"))
  8131. ((equal (length links) 1)
  8132. (setq link (car links)))
  8133. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8134. (setq link (nth (if have-zero nth (1- nth)) links)))
  8135. (t ; we have to select a link
  8136. (save-excursion
  8137. (save-window-excursion
  8138. (delete-other-windows)
  8139. (with-output-to-temp-buffer "*Select Link*"
  8140. (dolist (l links)
  8141. (cond
  8142. ((not (string-match org-link-bracket-re l))
  8143. (princ (format "[%c] %s\n" (cl-incf cnt)
  8144. (org-unbracket-string "<" ">" l))))
  8145. ((match-end 2)
  8146. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8147. (match-string 2 l) (match-string 1 l))))
  8148. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8149. (match-string 1 l)))))))
  8150. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8151. (message "Select link to open, RET to open all:")
  8152. (setq c (read-char-exclusive))
  8153. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8154. (when (equal c ?q) (user-error "Abort"))
  8155. (if (equal c ?\C-m)
  8156. (setq link links)
  8157. (setq nth (- c ?0))
  8158. (when have-zero (setq nth (1+ nth)))
  8159. (unless (and (integerp nth) (>= (length links) nth))
  8160. (user-error "Invalid link selection"))
  8161. (setq link (nth (1- nth) links)))))
  8162. (cons link end)))))
  8163. ;;; File search
  8164. (defun org-do-occur (regexp &optional cleanup)
  8165. "Call the Emacs command `occur'.
  8166. If CLEANUP is non-nil, remove the printout of the regular expression
  8167. in the *Occur* buffer. This is useful if the regex is long and not useful
  8168. to read."
  8169. (occur regexp)
  8170. (when cleanup
  8171. (let ((cwin (selected-window)) win beg end)
  8172. (when (setq win (get-buffer-window "*Occur*"))
  8173. (select-window win))
  8174. (goto-char (point-min))
  8175. (when (re-search-forward "match[a-z]+" nil t)
  8176. (setq beg (match-end 0))
  8177. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8178. (setq end (1- (match-beginning 0)))))
  8179. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8180. (goto-char (point-min))
  8181. (select-window cwin))))
  8182. ;;; The Mark Ring
  8183. (defvar org-mark-ring nil
  8184. "Mark ring for positions before jumps in Org mode.")
  8185. (defvar org-mark-ring-last-goto nil
  8186. "Last position in the mark ring used to go back.")
  8187. ;; Fill and close the ring
  8188. (setq org-mark-ring nil)
  8189. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8190. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8191. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8192. org-mark-ring)
  8193. (defun org-mark-ring-push (&optional pos buffer)
  8194. "Put the current position into the mark ring and rotate it.
  8195. Also push position into the Emacs mark ring. If optional
  8196. argument POS and BUFFER are not nil, mark this location instead."
  8197. (interactive)
  8198. (let ((pos (or pos (point)))
  8199. (buffer (or buffer (current-buffer))))
  8200. (with-current-buffer buffer
  8201. (org-with-point-at pos (push-mark nil t)))
  8202. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8203. (move-marker (car org-mark-ring) pos buffer))
  8204. (message
  8205. (substitute-command-keys
  8206. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8207. (defun org-mark-ring-goto (&optional n)
  8208. "Jump to the previous position in the mark ring.
  8209. With prefix arg N, jump back that many stored positions. When
  8210. called several times in succession, walk through the entire ring.
  8211. Org mode commands jumping to a different position in the current file,
  8212. or to another Org file, automatically push the old position onto the ring."
  8213. (interactive "p")
  8214. (let (p m)
  8215. (if (eq last-command this-command)
  8216. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8217. (setq p org-mark-ring))
  8218. (setq org-mark-ring-last-goto p)
  8219. (setq m (car p))
  8220. (pop-to-buffer-same-window (marker-buffer m))
  8221. (goto-char m)
  8222. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8223. ;;; Following specific links
  8224. (defvar org-agenda-buffer-tmp-name)
  8225. (defvar org-agenda-start-on-weekday)
  8226. (defvar org-agenda-buffer-name)
  8227. (defun org-follow-timestamp-link ()
  8228. "Open an agenda view for the time-stamp date/range at point."
  8229. ;; Avoid changing the global value.
  8230. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  8231. (cond
  8232. ((org-at-date-range-p t)
  8233. (let ((org-agenda-start-on-weekday)
  8234. (t1 (match-string 1))
  8235. (t2 (match-string 2)) tt1 tt2)
  8236. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8237. tt2 (time-to-days (org-time-string-to-time t2)))
  8238. (let ((org-agenda-buffer-tmp-name
  8239. (format "*Org Agenda(a:%s)"
  8240. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8241. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8242. ((org-at-timestamp-p 'lax)
  8243. (let ((org-agenda-buffer-tmp-name
  8244. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8245. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8246. (substring (match-string 1) 0 10)))
  8247. 1)))
  8248. (t (error "This should not happen")))))
  8249. ;;; Following file links
  8250. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8251. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8252. (declare-function mailcap-mime-info
  8253. "mailcap" (string &optional request no-decode))
  8254. (defvar org-wait nil)
  8255. ;;;; Refiling
  8256. (defun org-get-org-file ()
  8257. "Read a filename, with default directory `org-directory'."
  8258. (let ((default (or org-default-notes-file remember-data-file)))
  8259. (read-file-name (format "File name [%s]: " default)
  8260. (file-name-as-directory org-directory)
  8261. default)))
  8262. (defun org-notes-order-reversed-p ()
  8263. "Check if the current file should receive notes in reversed order."
  8264. (cond
  8265. ((not org-reverse-note-order) nil)
  8266. ((eq t org-reverse-note-order) t)
  8267. ((not (listp org-reverse-note-order)) nil)
  8268. (t (catch 'exit
  8269. (dolist (entry org-reverse-note-order)
  8270. (when (string-match (car entry) buffer-file-name)
  8271. (throw 'exit (cdr entry))))))))
  8272. (defvar org-agenda-new-buffers nil
  8273. "Buffers created to visit agenda files.")
  8274. (declare-function org-string-nw-p "org-macs" (s))
  8275. ;;;; Dynamic blocks
  8276. (defun org-find-dblock (name)
  8277. "Find the first dynamic block with name NAME in the buffer.
  8278. If not found, stay at current position and return nil."
  8279. (let ((case-fold-search t) pos)
  8280. (save-excursion
  8281. (goto-char (point-min))
  8282. (setq pos (and (re-search-forward
  8283. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8284. (match-beginning 0))))
  8285. (when pos (goto-char pos))
  8286. pos))
  8287. (defun org-create-dblock (plist)
  8288. "Create a dynamic block section, with parameters taken from PLIST.
  8289. PLIST must contain a :name entry which is used as the name of the block."
  8290. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8291. (end-of-line 1)
  8292. (newline))
  8293. (let ((col (current-column))
  8294. (name (plist-get plist :name)))
  8295. (insert "#+BEGIN: " name)
  8296. (while plist
  8297. (if (eq (car plist) :name)
  8298. (setq plist (cddr plist))
  8299. (insert " " (prin1-to-string (pop plist)))))
  8300. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8301. (beginning-of-line -2)))
  8302. (defun org-prepare-dblock ()
  8303. "Prepare dynamic block for refresh.
  8304. This empties the block, puts the cursor at the insert position and returns
  8305. the property list including an extra property :name with the block name."
  8306. (unless (looking-at org-dblock-start-re)
  8307. (user-error "Not at a dynamic block"))
  8308. (let* ((begdel (1+ (match-end 0)))
  8309. (name (org-no-properties (match-string 1)))
  8310. (params (append (list :name name)
  8311. (read (concat "(" (match-string 3) ")")))))
  8312. (save-excursion
  8313. (beginning-of-line 1)
  8314. (skip-chars-forward " \t")
  8315. (setq params (plist-put params :indentation-column (current-column))))
  8316. (unless (re-search-forward org-dblock-end-re nil t)
  8317. (error "Dynamic block not terminated"))
  8318. (setq params
  8319. (append params
  8320. (list :content (buffer-substring
  8321. begdel (match-beginning 0)))))
  8322. (delete-region begdel (match-beginning 0))
  8323. (goto-char begdel)
  8324. (open-line 1)
  8325. params))
  8326. (defun org-map-dblocks (&optional command)
  8327. "Apply COMMAND to all dynamic blocks in the current buffer.
  8328. If COMMAND is not given, use `org-update-dblock'."
  8329. (let ((cmd (or command 'org-update-dblock)))
  8330. (save-excursion
  8331. (goto-char (point-min))
  8332. (while (re-search-forward org-dblock-start-re nil t)
  8333. (goto-char (match-beginning 0))
  8334. (save-excursion
  8335. (condition-case nil
  8336. (funcall cmd)
  8337. (error (message "Error during update of dynamic block"))))
  8338. (unless (re-search-forward org-dblock-end-re nil t)
  8339. (error "Dynamic block not terminated"))))))
  8340. (defvar org-dynamic-block-alist nil
  8341. "Alist defining all the Org dynamic blocks.
  8342. The key is the dynamic block type name, as a string. The value
  8343. is the function used to insert the dynamic block.
  8344. Use `org-dynamic-block-define' to populate it.")
  8345. (defun org-dynamic-block-function (type)
  8346. "Return function associated to a given dynamic block type.
  8347. TYPE is the dynamic block type, as a string."
  8348. (cdr (assoc type org-dynamic-block-alist)))
  8349. (defun org-dynamic-block-types ()
  8350. "List all defined dynamic block types."
  8351. (mapcar #'car org-dynamic-block-alist))
  8352. (defun org-dynamic-block-define (type func)
  8353. "Define dynamic block TYPE with FUNC.
  8354. TYPE is a string. FUNC is the function creating the dynamic
  8355. block of such type."
  8356. (pcase (assoc type org-dynamic-block-alist)
  8357. (`nil (push (cons type func) org-dynamic-block-alist))
  8358. (def (setcdr def func))))
  8359. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8360. "Insert a dynamic block of type TYPE.
  8361. When used interactively, select the dynamic block types among
  8362. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8363. is non-nil, call the dynamic block function interactively."
  8364. (interactive (list (completing-read "Dynamic block: "
  8365. (org-dynamic-block-types))
  8366. t))
  8367. (pcase (org-dynamic-block-function type)
  8368. (`nil (error "No such dynamic block: %S" type))
  8369. ((and f (pred functionp))
  8370. (if interactive-p (call-interactively f) (funcall f)))
  8371. (_ (error "Invalid function for dynamic block %S" type))))
  8372. (defun org-dblock-update (&optional arg)
  8373. "User command for updating dynamic blocks.
  8374. Update the dynamic block at point. With prefix ARG, update all dynamic
  8375. blocks in the buffer."
  8376. (interactive "P")
  8377. (if arg
  8378. (org-update-all-dblocks)
  8379. (or (looking-at org-dblock-start-re)
  8380. (org-beginning-of-dblock))
  8381. (org-update-dblock)))
  8382. (defun org-update-dblock ()
  8383. "Update the dynamic block at point.
  8384. This means to empty the block, parse for parameters and then call
  8385. the correct writing function."
  8386. (interactive)
  8387. (save-excursion
  8388. (let* ((win (selected-window))
  8389. (pos (point))
  8390. (line (org-current-line))
  8391. (params (org-prepare-dblock))
  8392. (name (plist-get params :name))
  8393. (indent (plist-get params :indentation-column))
  8394. (cmd (intern (concat "org-dblock-write:" name))))
  8395. (message "Updating dynamic block `%s' at line %d..." name line)
  8396. (funcall cmd params)
  8397. (message "Updating dynamic block `%s' at line %d...done" name line)
  8398. (goto-char pos)
  8399. (when (and indent (> indent 0))
  8400. (setq indent (make-string indent ?\ ))
  8401. (save-excursion
  8402. (select-window win)
  8403. (org-beginning-of-dblock)
  8404. (forward-line 1)
  8405. (while (not (looking-at org-dblock-end-re))
  8406. (insert indent)
  8407. (beginning-of-line 2))
  8408. (when (looking-at org-dblock-end-re)
  8409. (and (looking-at "[ \t]+")
  8410. (replace-match ""))
  8411. (insert indent)))))))
  8412. (defun org-beginning-of-dblock ()
  8413. "Find the beginning of the dynamic block at point.
  8414. Error if there is no such block at point."
  8415. (let ((pos (point))
  8416. beg)
  8417. (end-of-line 1)
  8418. (if (and (re-search-backward org-dblock-start-re nil t)
  8419. (setq beg (match-beginning 0))
  8420. (re-search-forward org-dblock-end-re nil t)
  8421. (> (match-end 0) pos))
  8422. (goto-char beg)
  8423. (goto-char pos)
  8424. (error "Not in a dynamic block"))))
  8425. (defun org-update-all-dblocks ()
  8426. "Update all dynamic blocks in the buffer.
  8427. This function can be used in a hook."
  8428. (interactive)
  8429. (when (derived-mode-p 'org-mode)
  8430. (org-map-dblocks 'org-update-dblock)))
  8431. ;;;; Completion
  8432. (declare-function org-export-backend-options "ox" (cl-x) t)
  8433. (defun org-get-export-keywords ()
  8434. "Return a list of all currently understood export keywords.
  8435. Export keywords include options, block names, attributes and
  8436. keywords relative to each registered export back-end."
  8437. (let (keywords)
  8438. (dolist (backend
  8439. (bound-and-true-p org-export-registered-backends)
  8440. (delq nil keywords))
  8441. ;; Back-end name (for keywords, like #+LATEX:)
  8442. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8443. (dolist (option-entry (org-export-backend-options backend))
  8444. ;; Back-end options.
  8445. (push (nth 1 option-entry) keywords)))))
  8446. (defconst org-options-keywords
  8447. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8448. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8449. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8450. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8451. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8452. (defcustom org-structure-template-alist
  8453. '(("a" . "export ascii")
  8454. ("c" . "center")
  8455. ("C" . "comment")
  8456. ("e" . "example")
  8457. ("E" . "export")
  8458. ("h" . "export html")
  8459. ("l" . "export latex")
  8460. ("q" . "quote")
  8461. ("s" . "src")
  8462. ("v" . "verse"))
  8463. "An alist of keys and block types.
  8464. `org-insert-structure-template' will display a menu with this
  8465. list of templates to choose from. The block type is inserted,
  8466. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8467. The menu keys are defined by the car of each entry in this alist.
  8468. If two entries have the keys \"a\" and \"aa\" respectively, the
  8469. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8470. latter will be inserted by typing \"aa\". If an entry with the
  8471. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8472. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8473. block can be inserted by pressing TAB after the string \"<KEY\"."
  8474. :group 'org-edit-structure
  8475. :type '(repeat
  8476. (cons (string :tag "Key")
  8477. (string :tag "Template")))
  8478. :package-version '(Org . "9.2"))
  8479. (defun org--check-org-structure-template-alist (&optional checklist)
  8480. "Check whether `org-structure-template-alist' is set up correctly.
  8481. In particular, check if the Org 9.2 format is used as opposed to
  8482. previous format."
  8483. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8484. (or (eval checklist)
  8485. org-structure-template-alist))))
  8486. (when elm
  8487. (org-display-warning
  8488. (format "
  8489. Please update the entries of `%s'.
  8490. In Org 9.2 the format was changed from something like
  8491. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8492. to something like
  8493. (\"s\" . \"src\")
  8494. Please refer to the documentation of `org-structure-template-alist'.
  8495. The following entries must be updated:
  8496. %s"
  8497. (or checklist 'org-structure-template-alist)
  8498. (pp-to-string elm))))))
  8499. (defun org--insert-structure-template-mks ()
  8500. "Present `org-structure-template-alist' with `org-mks'.
  8501. Menus are added if keys require more than one keystroke. Tabs
  8502. are added to single key entries when more than one stroke is
  8503. needed. Keys longer than two characters are reduced to two
  8504. characters."
  8505. (org--check-org-structure-template-alist)
  8506. (let* (case-fold-search
  8507. (templates (append org-structure-template-alist
  8508. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8509. (keys (mapcar #'car templates))
  8510. (start-letters
  8511. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8512. ;; Sort each element of `org-structure-template-alist' into
  8513. ;; sublists according to the first letter.
  8514. (superlist
  8515. (mapcar (lambda (letter)
  8516. (list letter
  8517. (cl-remove-if-not
  8518. (apply-partially #'string-match-p (concat "^" letter))
  8519. templates :key #'car)))
  8520. start-letters)))
  8521. (org-mks
  8522. (apply #'append
  8523. ;; Make an `org-mks' table. If only one element is
  8524. ;; present in a sublist, make it part of the top-menu,
  8525. ;; otherwise make a submenu according to the starting
  8526. ;; letter and populate it.
  8527. (mapcar (lambda (sublist)
  8528. (if (eq 1 (length (cadr sublist)))
  8529. (mapcar (lambda (elm)
  8530. (list (substring (car elm) 0 1)
  8531. (cdr elm) ""))
  8532. (cadr sublist))
  8533. ;; Create submenu.
  8534. (let* ((topkey (car sublist))
  8535. (elms (cadr sublist))
  8536. (keys (mapcar #'car elms))
  8537. (long (> (length elms) 3)))
  8538. (append
  8539. (list
  8540. ;; Make a description of the submenu.
  8541. (list topkey
  8542. (concat
  8543. (mapconcat #'cdr
  8544. (cl-subseq elms 0 (if long 3 (length elms)))
  8545. ", ")
  8546. (when long ", ..."))))
  8547. ;; List of entries in submenu.
  8548. (cl-mapcar #'list
  8549. (org--insert-structure-template-unique-keys keys)
  8550. (mapcar #'cdr elms)
  8551. (make-list (length elms) ""))))))
  8552. superlist))
  8553. "Select a key\n============"
  8554. "Key: ")))
  8555. (defun org--insert-structure-template-unique-keys (keys)
  8556. "Make a list of unique, two characters long elements from KEYS.
  8557. Elements of length one have a tab appended. Elements of length
  8558. two are kept as is. Longer elements are truncated to length two.
  8559. If an element cannot be made unique, an error is raised."
  8560. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8561. menu-keys)
  8562. (dolist (key ordered-keys)
  8563. (let ((potential-key
  8564. (cl-case (length key)
  8565. (1 (concat key "\t"))
  8566. (2 key)
  8567. (otherwise
  8568. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8569. (mapcar (apply-partially #'concat (substring key 0 1))
  8570. (split-string (substring key 1) "" t)))))))
  8571. (if (or (not potential-key) (assoc potential-key menu-keys))
  8572. (user-error "Could not make unique key for `%s'" key)
  8573. (push (cons potential-key key) menu-keys))))
  8574. (mapcar #'car
  8575. (cl-sort menu-keys #'<
  8576. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8577. (defun org-insert-structure-template (type)
  8578. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8579. Select a block from `org-structure-template-alist' then type
  8580. either RET, TAB or SPC to write the block type. With an active
  8581. region, wrap the region in the block. Otherwise, insert an empty
  8582. block."
  8583. (interactive
  8584. (list (pcase (org--insert-structure-template-mks)
  8585. (`("\t" . ,_) (read-string "Structure type: "))
  8586. (`(,_ ,choice . ,_) choice))))
  8587. (let* ((region? (use-region-p))
  8588. (region-start (and region? (region-beginning)))
  8589. (region-end (and region? (copy-marker (region-end))))
  8590. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8591. (verbatim? (string-match-p
  8592. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8593. type)))
  8594. (when region? (goto-char region-start))
  8595. (let ((column (current-indentation)))
  8596. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8597. (beginning-of-line)
  8598. (insert "\n"))
  8599. (save-excursion
  8600. (indent-to column)
  8601. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8602. (when region?
  8603. (when verbatim? (org-escape-code-in-region (point) region-end))
  8604. (goto-char region-end)
  8605. ;; Ignore empty lines at the end of the region.
  8606. (skip-chars-backward " \r\t\n")
  8607. (end-of-line))
  8608. (unless (bolp) (insert "\n"))
  8609. (indent-to column)
  8610. (insert (format "#+end_%s" (car (split-string type))))
  8611. (if (looking-at "[ \t]*$") (replace-match "")
  8612. (insert "\n"))
  8613. (when (and (eobp) (not (bolp))) (insert "\n")))
  8614. (if extended? (end-of-line)
  8615. (forward-line)
  8616. (skip-chars-forward " \t")))))
  8617. ;;;; TODO, DEADLINE, Comments
  8618. (defun org-toggle-comment ()
  8619. "Change the COMMENT state of an entry."
  8620. (interactive)
  8621. (save-excursion
  8622. (org-back-to-heading)
  8623. (let ((case-fold-search nil))
  8624. (looking-at org-complex-heading-regexp))
  8625. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8626. (skip-chars-forward " \t")
  8627. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8628. (if (org-in-commented-heading-p t)
  8629. (delete-region (point)
  8630. (progn (search-forward " " (line-end-position) 'move)
  8631. (skip-chars-forward " \t")
  8632. (point)))
  8633. (insert org-comment-string)
  8634. (unless (eolp) (insert " ")))))
  8635. (defvar org-last-todo-state-is-todo nil
  8636. "This is non-nil when the last TODO state change led to a TODO state.
  8637. If the last change removed the TODO tag or switched to DONE, then
  8638. this is nil.")
  8639. (defvar org-todo-setup-filter-hook nil
  8640. "Hook for functions that pre-filter todo specs.
  8641. Each function takes a todo spec and returns either nil or the spec
  8642. transformed into canonical form." )
  8643. (defvar org-todo-get-default-hook nil
  8644. "Hook for functions that get a default item for todo.
  8645. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8646. nil or a string to be used for the todo mark." )
  8647. (defvar org-agenda-headline-snapshot-before-repeat)
  8648. (defun org-current-effective-time ()
  8649. "Return current time adjusted for `org-extend-today-until' variable."
  8650. (let* ((ct (org-current-time))
  8651. (dct (decode-time ct))
  8652. (ct1
  8653. (cond
  8654. (org-use-last-clock-out-time-as-effective-time
  8655. (or (org-clock-get-last-clock-out-time) ct))
  8656. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8657. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8658. (t ct))))
  8659. ct1))
  8660. (defun org-todo-yesterday (&optional arg)
  8661. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8662. (interactive "P")
  8663. (if (eq major-mode 'org-agenda-mode)
  8664. (apply 'org-agenda-todo-yesterday arg)
  8665. (let* ((org-use-effective-time t)
  8666. (hour (nth 2 (decode-time (org-current-time))))
  8667. (org-extend-today-until (1+ hour)))
  8668. (org-todo arg))))
  8669. (defvar org-block-entry-blocking ""
  8670. "First entry preventing the TODO state change.")
  8671. (defun org-cancel-repeater ()
  8672. "Cancel a repeater by setting its numeric value to zero."
  8673. (interactive)
  8674. (save-excursion
  8675. (org-back-to-heading t)
  8676. (let ((bound1 (point))
  8677. (bound0 (save-excursion (outline-next-heading) (point))))
  8678. (when (and (re-search-forward
  8679. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8680. org-deadline-time-regexp "\\)\\|\\("
  8681. org-ts-regexp "\\)")
  8682. bound0 t)
  8683. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8684. bound1 t))
  8685. (replace-match "0" t nil nil 1)))))
  8686. (defvar org-state)
  8687. (defvar org-blocked-by-checkboxes)
  8688. (defun org-todo (&optional arg)
  8689. "Change the TODO state of an item.
  8690. The state of an item is given by a keyword at the start of the heading,
  8691. like
  8692. *** TODO Write paper
  8693. *** DONE Call mom
  8694. The different keywords are specified in the variable `org-todo-keywords'.
  8695. By default the available states are \"TODO\" and \"DONE\". So, for this
  8696. example: when the item starts with TODO, it is changed to DONE.
  8697. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8698. DONE are present, add TODO at the beginning of the heading.
  8699. You can set up single-character keys to fast-select the new state. See the
  8700. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8701. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8702. and take a
  8703. logging note.
  8704. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8705. next set of TODO \
  8706. keywords (nextset).
  8707. Another way to achieve this is `S-C-<right>'.
  8708. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8709. prefix, circumvent any state blocking.
  8710. With numeric prefix arg, switch to the Nth state.
  8711. With a numeric prefix arg of 0, inhibit note taking for the change.
  8712. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8713. When called through ELisp, arg is also interpreted in the following way:
  8714. `none' -> empty state
  8715. \"\" -> switch to empty state
  8716. `done' -> switch to DONE
  8717. `nextset' -> switch to the next set of keywords
  8718. `previousset' -> switch to the previous set of keywords
  8719. \"WAITING\" -> switch to the specified keyword, but only if it
  8720. really is a member of `org-todo-keywords'."
  8721. (interactive "P")
  8722. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8723. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8724. 'region-start-level 'region))
  8725. org-loop-over-headlines-in-active-region)
  8726. (org-map-entries
  8727. (lambda () (org-todo arg))
  8728. nil cl
  8729. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8730. (when (equal arg '(16)) (setq arg 'nextset))
  8731. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8732. (let ((org-blocker-hook org-blocker-hook)
  8733. commentp
  8734. case-fold-search)
  8735. (when (equal arg '(64))
  8736. (setq arg nil org-blocker-hook nil))
  8737. (when (and org-blocker-hook
  8738. (or org-inhibit-blocking
  8739. (org-entry-get nil "NOBLOCKING")))
  8740. (setq org-blocker-hook nil))
  8741. (save-excursion
  8742. (catch 'exit
  8743. (org-back-to-heading t)
  8744. (when (org-in-commented-heading-p t)
  8745. (org-toggle-comment)
  8746. (setq commentp t))
  8747. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8748. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8749. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8750. (let* ((match-data (match-data))
  8751. (startpos (copy-marker (line-beginning-position)))
  8752. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8753. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8754. (org-log-done org-log-done)
  8755. (org-log-repeat org-log-repeat)
  8756. (org-todo-log-states org-todo-log-states)
  8757. (org-inhibit-logging
  8758. (if (equal arg 0)
  8759. (progn (setq arg nil) 'note) org-inhibit-logging))
  8760. (this (match-string 1))
  8761. (hl-pos (match-beginning 0))
  8762. (head (org-get-todo-sequence-head this))
  8763. (ass (assoc head org-todo-kwd-alist))
  8764. (interpret (nth 1 ass))
  8765. (done-word (nth 3 ass))
  8766. (final-done-word (nth 4 ass))
  8767. (org-last-state (or this ""))
  8768. (completion-ignore-case t)
  8769. (member (member this org-todo-keywords-1))
  8770. (tail (cdr member))
  8771. (org-state (cond
  8772. ((eq arg 'right)
  8773. ;; Next state
  8774. (if this
  8775. (if tail (car tail) nil)
  8776. (car org-todo-keywords-1)))
  8777. ((eq arg 'left)
  8778. ;; Previous state
  8779. (unless (equal member org-todo-keywords-1)
  8780. (if this
  8781. (nth (- (length org-todo-keywords-1)
  8782. (length tail) 2)
  8783. org-todo-keywords-1)
  8784. (org-last org-todo-keywords-1))))
  8785. (arg
  8786. ;; User or caller requests a specific state.
  8787. (cond
  8788. ((equal arg "") nil)
  8789. ((eq arg 'none) nil)
  8790. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8791. ((eq arg 'nextset)
  8792. (or (car (cdr (member head org-todo-heads)))
  8793. (car org-todo-heads)))
  8794. ((eq arg 'previousset)
  8795. (let ((org-todo-heads (reverse org-todo-heads)))
  8796. (or (car (cdr (member head org-todo-heads)))
  8797. (car org-todo-heads))))
  8798. ((car (member arg org-todo-keywords-1)))
  8799. ((stringp arg)
  8800. (user-error "State `%s' not valid in this file" arg))
  8801. ((nth (1- (prefix-numeric-value arg))
  8802. org-todo-keywords-1))))
  8803. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8804. ;; Use fast selection.
  8805. (org-fast-todo-selection this))
  8806. ((null member) (or head (car org-todo-keywords-1)))
  8807. ((equal this final-done-word) nil) ;-> make empty
  8808. ((null tail) nil) ;-> first entry
  8809. ((memq interpret '(type priority))
  8810. (if (eq this-command last-command)
  8811. (car tail)
  8812. (if (> (length tail) 0)
  8813. (or done-word (car org-done-keywords))
  8814. nil)))
  8815. (t
  8816. (car tail))))
  8817. (org-state (or
  8818. (run-hook-with-args-until-success
  8819. 'org-todo-get-default-hook org-state org-last-state)
  8820. org-state))
  8821. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8822. (change-plist (list :type 'todo-state-change :from this :to org-state
  8823. :position startpos))
  8824. dolog now-done-p)
  8825. (when org-blocker-hook
  8826. (let (org-blocked-by-checkboxes block-reason)
  8827. (setq org-last-todo-state-is-todo
  8828. (not (member this org-done-keywords)))
  8829. (unless (save-excursion
  8830. (save-match-data
  8831. (org-with-wide-buffer
  8832. (run-hook-with-args-until-failure
  8833. 'org-blocker-hook change-plist))))
  8834. (setq block-reason (if org-blocked-by-checkboxes
  8835. "contained checkboxes"
  8836. (format "\"%s\"" org-block-entry-blocking)))
  8837. (if (called-interactively-p 'interactive)
  8838. (user-error "TODO state change from %s to %s blocked (by %s)"
  8839. this org-state block-reason)
  8840. ;; Fail silently.
  8841. (message "TODO state change from %s to %s blocked (by %s)"
  8842. this org-state block-reason)
  8843. (throw 'exit nil)))))
  8844. (store-match-data match-data)
  8845. (replace-match next t t)
  8846. (cond ((and org-state (equal this org-state))
  8847. (message "TODO state was already %s" (org-trim next)))
  8848. ((not (pos-visible-in-window-p hl-pos))
  8849. (message "TODO state changed to %s" (org-trim next))))
  8850. (unless head
  8851. (setq head (org-get-todo-sequence-head org-state)
  8852. ass (assoc head org-todo-kwd-alist)
  8853. interpret (nth 1 ass)
  8854. done-word (nth 3 ass)
  8855. final-done-word (nth 4 ass)))
  8856. (when (memq arg '(nextset previousset))
  8857. (message "Keyword-Set %d/%d: %s"
  8858. (- (length org-todo-sets) -1
  8859. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8860. (length org-todo-sets)
  8861. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8862. (setq org-last-todo-state-is-todo
  8863. (not (member org-state org-done-keywords)))
  8864. (setq now-done-p (and (member org-state org-done-keywords)
  8865. (not (member this org-done-keywords))))
  8866. (and logging (org-local-logging logging))
  8867. (when (or (and (or org-todo-log-states org-log-done)
  8868. (not (eq org-inhibit-logging t))
  8869. (not (memq arg '(nextset previousset))))
  8870. force-log)
  8871. ;; We need to look at recording a time and note.
  8872. (setq dolog (or (if force-log 'note)
  8873. (nth 1 (assoc org-state org-todo-log-states))
  8874. (nth 2 (assoc this org-todo-log-states))))
  8875. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8876. (setq dolog 'time))
  8877. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8878. (and org-state
  8879. (member org-state org-not-done-keywords)
  8880. (not (member this org-not-done-keywords))))
  8881. ;; This is now a todo state and was not one before
  8882. ;; If there was a CLOSED time stamp, get rid of it.
  8883. (org-add-planning-info nil nil 'closed))
  8884. (when (and now-done-p org-log-done)
  8885. ;; It is now done, and it was not done before.
  8886. (org-add-planning-info 'closed (org-current-effective-time))
  8887. (when (and (not dolog) (eq 'note org-log-done))
  8888. (org-add-log-setup 'done org-state this 'note)))
  8889. (when (and org-state dolog)
  8890. ;; This is a non-nil state, and we need to log it.
  8891. (org-add-log-setup 'state org-state this dolog)))
  8892. ;; Fixup tag positioning.
  8893. (org-todo-trigger-tag-changes org-state)
  8894. (when org-auto-align-tags (org-align-tags))
  8895. (when org-provide-todo-statistics
  8896. (org-update-parent-todo-statistics))
  8897. (when (bound-and-true-p org-clock-out-when-done)
  8898. (org-clock-out-if-current))
  8899. (run-hooks 'org-after-todo-state-change-hook)
  8900. (when (and arg (not (member org-state org-done-keywords)))
  8901. (setq head (org-get-todo-sequence-head org-state)))
  8902. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8903. ;; Do we need to trigger a repeat?
  8904. (when now-done-p
  8905. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8906. ;; This is for the agenda, take a snapshot of the headline.
  8907. (save-match-data
  8908. (setq org-agenda-headline-snapshot-before-repeat
  8909. (org-get-heading))))
  8910. (org-auto-repeat-maybe org-state))
  8911. ;; Fixup cursor location if close to the keyword.
  8912. (when (and (outline-on-heading-p)
  8913. (not (bolp))
  8914. (save-excursion (beginning-of-line 1)
  8915. (looking-at org-todo-line-regexp))
  8916. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8917. (goto-char (or (match-end 2) (match-end 1)))
  8918. (and (looking-at " ")
  8919. (not (looking-at " *:"))
  8920. (just-one-space)))
  8921. (when org-trigger-hook
  8922. (save-excursion
  8923. (run-hook-with-args 'org-trigger-hook change-plist)))
  8924. (when commentp (org-toggle-comment))))))))
  8925. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8926. "Block turning an entry into a TODO, using the hierarchy.
  8927. This checks whether the current task should be blocked from state
  8928. changes. Such blocking occurs when:
  8929. 1. The task has children which are not all in a completed state.
  8930. 2. A task has a parent with the property :ORDERED:, and there
  8931. are siblings prior to the current task with incomplete
  8932. status.
  8933. 3. The parent of the task is blocked because it has siblings that should
  8934. be done first, or is child of a block grandparent TODO entry."
  8935. (if (not org-enforce-todo-dependencies)
  8936. t ; if locally turned off don't block
  8937. (catch 'dont-block
  8938. ;; If this is not a todo state change, or if this entry is already DONE,
  8939. ;; do not block
  8940. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8941. (member (plist-get change-plist :from)
  8942. (cons 'done org-done-keywords))
  8943. (member (plist-get change-plist :to)
  8944. (cons 'todo org-not-done-keywords))
  8945. (not (plist-get change-plist :to)))
  8946. (throw 'dont-block t))
  8947. ;; If this task has children, and any are undone, it's blocked
  8948. (save-excursion
  8949. (org-back-to-heading t)
  8950. (let ((this-level (funcall outline-level)))
  8951. (outline-next-heading)
  8952. (let ((child-level (funcall outline-level)))
  8953. (while (and (not (eobp))
  8954. (> child-level this-level))
  8955. ;; this todo has children, check whether they are all
  8956. ;; completed
  8957. (when (and (not (org-entry-is-done-p))
  8958. (org-entry-is-todo-p))
  8959. (setq org-block-entry-blocking (org-get-heading))
  8960. (throw 'dont-block nil))
  8961. (outline-next-heading)
  8962. (setq child-level (funcall outline-level))))))
  8963. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8964. ;; any previous siblings are undone, it's blocked
  8965. (save-excursion
  8966. (org-back-to-heading t)
  8967. (let* ((pos (point))
  8968. (parent-pos (and (org-up-heading-safe) (point)))
  8969. (case-fold-search nil))
  8970. (unless parent-pos (throw 'dont-block t)) ; no parent
  8971. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8972. (forward-line 1)
  8973. (re-search-forward org-not-done-heading-regexp pos t))
  8974. (setq org-block-entry-blocking (match-string 0))
  8975. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8976. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8977. (while t
  8978. (goto-char parent-pos)
  8979. (unless (looking-at org-not-done-heading-regexp)
  8980. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8981. (setq pos (point))
  8982. (setq parent-pos (and (org-up-heading-safe) (point)))
  8983. (unless parent-pos (throw 'dont-block t)) ; no parent
  8984. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8985. (forward-line 1)
  8986. (re-search-forward org-not-done-heading-regexp pos t)
  8987. (setq org-block-entry-blocking (org-get-heading)))
  8988. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8989. (defcustom org-track-ordered-property-with-tag nil
  8990. "Should the ORDERED property also be shown as a tag?
  8991. The ORDERED property decides if an entry should require subtasks to be
  8992. completed in sequence. Since a property is not very visible, setting
  8993. this option means that toggling the ORDERED property with the command
  8994. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8995. not relevant for the behavior, but it makes things more visible.
  8996. Note that toggling the tag with tags commands will not change the property
  8997. and therefore not influence behavior!
  8998. This can be t, meaning the tag ORDERED should be used. It can also be a
  8999. string to select a different tag for this task."
  9000. :group 'org-todo
  9001. :type '(choice
  9002. (const :tag "No tracking" nil)
  9003. (const :tag "Track with ORDERED tag" t)
  9004. (string :tag "Use other tag")))
  9005. (defun org-toggle-ordered-property ()
  9006. "Toggle the ORDERED property of the current entry.
  9007. For better visibility, you can track the value of this property with a tag.
  9008. See variable `org-track-ordered-property-with-tag'."
  9009. (interactive)
  9010. (let* ((t1 org-track-ordered-property-with-tag)
  9011. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9012. (save-excursion
  9013. (org-back-to-heading)
  9014. (if (org-entry-get nil "ORDERED")
  9015. (progn
  9016. (org-delete-property "ORDERED")
  9017. (and tag (org-toggle-tag tag 'off))
  9018. (message "Subtasks can be completed in arbitrary order"))
  9019. (org-entry-put nil "ORDERED" "t")
  9020. (and tag (org-toggle-tag tag 'on))
  9021. (message "Subtasks must be completed in sequence")))))
  9022. (defun org-block-todo-from-checkboxes (change-plist)
  9023. "Block turning an entry into a TODO, using checkboxes.
  9024. This checks whether the current task should be blocked from state
  9025. changes because there are unchecked boxes in this entry."
  9026. (if (not org-enforce-todo-checkbox-dependencies)
  9027. t ; if locally turned off don't block
  9028. (catch 'dont-block
  9029. ;; If this is not a todo state change, or if this entry is already DONE,
  9030. ;; do not block
  9031. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9032. (member (plist-get change-plist :from)
  9033. (cons 'done org-done-keywords))
  9034. (member (plist-get change-plist :to)
  9035. (cons 'todo org-not-done-keywords))
  9036. (not (plist-get change-plist :to)))
  9037. (throw 'dont-block t))
  9038. ;; If this task has checkboxes that are not checked, it's blocked
  9039. (save-excursion
  9040. (org-back-to-heading t)
  9041. (let ((beg (point)) end)
  9042. (outline-next-heading)
  9043. (setq end (point))
  9044. (goto-char beg)
  9045. (when (org-list-search-forward
  9046. (concat (org-item-beginning-re)
  9047. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9048. "\\[[- ]\\]")
  9049. end t)
  9050. (when (boundp 'org-blocked-by-checkboxes)
  9051. (setq org-blocked-by-checkboxes t))
  9052. (throw 'dont-block nil))))
  9053. t))) ; do not block
  9054. (defun org-entry-blocked-p ()
  9055. "Non-nil if entry at point is blocked."
  9056. (and (not (org-entry-get nil "NOBLOCKING"))
  9057. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9058. (not (run-hook-with-args-until-failure
  9059. 'org-blocker-hook
  9060. (list :type 'todo-state-change
  9061. :position (point)
  9062. :from 'todo
  9063. :to 'done)))))
  9064. (defun org-update-statistics-cookies (all)
  9065. "Update the statistics cookie, either from TODO or from checkboxes.
  9066. This should be called with the cursor in a line with a statistics
  9067. cookie. When called with a \\[universal-argument] prefix, update
  9068. all statistics cookies in the buffer."
  9069. (interactive "P")
  9070. (if all
  9071. (progn
  9072. (org-update-checkbox-count 'all)
  9073. (org-map-region 'org-update-parent-todo-statistics
  9074. (point-min) (point-max)))
  9075. (if (not (org-at-heading-p))
  9076. (org-update-checkbox-count)
  9077. (let ((pos (point-marker))
  9078. end l1 l2)
  9079. (ignore-errors (org-back-to-heading t))
  9080. (if (not (org-at-heading-p))
  9081. (org-update-checkbox-count)
  9082. (setq l1 (org-outline-level))
  9083. (setq end
  9084. (save-excursion
  9085. (outline-next-heading)
  9086. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9087. (point)))
  9088. (if (and (save-excursion
  9089. (re-search-forward
  9090. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9091. (not (save-excursion
  9092. (re-search-forward
  9093. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9094. (org-update-checkbox-count)
  9095. (if (and l2 (> l2 l1))
  9096. (progn
  9097. (goto-char end)
  9098. (org-update-parent-todo-statistics))
  9099. (goto-char pos)
  9100. (beginning-of-line 1)
  9101. (while (re-search-forward
  9102. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9103. (point-at-eol) t)
  9104. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9105. (goto-char pos)
  9106. (move-marker pos nil)))))
  9107. (defvar org-entry-property-inherited-from) ;; defined below
  9108. (defun org-update-parent-todo-statistics ()
  9109. "Update any statistics cookie in the parent of the current headline.
  9110. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9111. the entire subtree and this will travel up the hierarchy and update
  9112. statistics everywhere."
  9113. (let* ((prop (save-excursion
  9114. (org-up-heading-safe)
  9115. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9116. (recursive (or (not org-hierarchical-todo-statistics)
  9117. (and prop (string-match "\\<recursive\\>" prop))))
  9118. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9119. 0))
  9120. (first t)
  9121. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9122. level ltoggle l1 new ndel
  9123. (cnt-all 0) (cnt-done 0) is-percent kwd
  9124. checkbox-beg cookie-present)
  9125. (catch 'exit
  9126. (save-excursion
  9127. (beginning-of-line 1)
  9128. (setq ltoggle (funcall outline-level))
  9129. ;; Three situations are to consider:
  9130. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9131. ;; to the top-level ancestor on the headline;
  9132. ;; 2. If parent has "recursive" property, repeat up to the
  9133. ;; headline setting that property, taking inheritance into
  9134. ;; account;
  9135. ;; 3. Else, move up to direct parent and proceed only once.
  9136. (while (and (setq level (org-up-heading-safe))
  9137. (or recursive first)
  9138. (>= (point) lim))
  9139. (setq first nil cookie-present nil)
  9140. (unless (and level
  9141. (not (string-match
  9142. "\\<checkbox\\>"
  9143. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9144. "")))))
  9145. (throw 'exit nil))
  9146. (while (re-search-forward box-re (point-at-eol) t)
  9147. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9148. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9149. (save-match-data
  9150. (unless (outline-next-heading) (throw 'exit nil))
  9151. (while (and (looking-at org-complex-heading-regexp)
  9152. (> (setq l1 (length (match-string 1))) level))
  9153. (setq kwd (and (or recursive (= l1 ltoggle))
  9154. (match-string 2)))
  9155. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9156. (and (eq org-provide-todo-statistics t)
  9157. (or (member kwd org-done-keywords)))
  9158. (and (listp org-provide-todo-statistics)
  9159. (stringp (car org-provide-todo-statistics))
  9160. (or (member kwd org-provide-todo-statistics)
  9161. (member kwd org-done-keywords)))
  9162. (and (listp org-provide-todo-statistics)
  9163. (listp (car org-provide-todo-statistics))
  9164. (or (member kwd (car org-provide-todo-statistics))
  9165. (and (member kwd org-done-keywords)
  9166. (member kwd (cadr org-provide-todo-statistics))))))
  9167. (setq cnt-all (1+ cnt-all))
  9168. (and (eq org-provide-todo-statistics t)
  9169. kwd
  9170. (setq cnt-all (1+ cnt-all))))
  9171. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9172. (member kwd org-done-keywords))
  9173. (and (listp org-provide-todo-statistics)
  9174. (listp (car org-provide-todo-statistics))
  9175. (member kwd org-done-keywords)
  9176. (member kwd (cadr org-provide-todo-statistics)))
  9177. (and (listp org-provide-todo-statistics)
  9178. (stringp (car org-provide-todo-statistics))
  9179. (member kwd org-done-keywords)))
  9180. (setq cnt-done (1+ cnt-done)))
  9181. (outline-next-heading)))
  9182. (setq new
  9183. (if is-percent
  9184. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9185. (max 1 cnt-all)))
  9186. (format "[%d/%d]" cnt-done cnt-all))
  9187. ndel (- (match-end 0) checkbox-beg))
  9188. (goto-char checkbox-beg)
  9189. (insert new)
  9190. (delete-region (point) (+ (point) ndel))
  9191. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9192. (when cookie-present
  9193. (run-hook-with-args 'org-after-todo-statistics-hook
  9194. cnt-done (- cnt-all cnt-done))))))
  9195. (run-hooks 'org-todo-statistics-hook)))
  9196. (defvar org-after-todo-statistics-hook nil
  9197. "Hook that is called after a TODO statistics cookie has been updated.
  9198. Each function is called with two arguments: the number of not-done entries
  9199. and the number of done entries.
  9200. For example, the following function, when added to this hook, will switch
  9201. an entry to DONE when all children are done, and back to TODO when new
  9202. entries are set to a TODO status. Note that this hook is only called
  9203. when there is a statistics cookie in the headline!
  9204. (defun org-summary-todo (n-done n-not-done)
  9205. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9206. (let (org-log-done org-log-states) ; turn off logging
  9207. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9208. (defvar org-todo-statistics-hook nil
  9209. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9210. This hook runs even if there is no statistics cookie present, in which case
  9211. `org-after-todo-statistics-hook' would not run.")
  9212. (defun org-todo-trigger-tag-changes (state)
  9213. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9214. (let ((l org-todo-state-tags-triggers)
  9215. changes)
  9216. (when (or (not state) (equal state ""))
  9217. (setq changes (append changes (cdr (assoc "" l)))))
  9218. (when (and (stringp state) (> (length state) 0))
  9219. (setq changes (append changes (cdr (assoc state l)))))
  9220. (when (member state org-not-done-keywords)
  9221. (setq changes (append changes (cdr (assq 'todo l)))))
  9222. (when (member state org-done-keywords)
  9223. (setq changes (append changes (cdr (assq 'done l)))))
  9224. (dolist (c changes)
  9225. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9226. (defun org-local-logging (value)
  9227. "Get logging settings from a property VALUE."
  9228. ;; Directly set the variables, they are already local.
  9229. (setq org-log-done nil
  9230. org-log-repeat nil
  9231. org-todo-log-states nil)
  9232. (dolist (w (split-string value))
  9233. (let (a)
  9234. (cond
  9235. ((setq a (assoc w org-startup-options))
  9236. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9237. (set (nth 1 a) (nth 2 a))))
  9238. ((setq a (org-extract-log-state-settings w))
  9239. (and (member (car a) org-todo-keywords-1)
  9240. (push a org-todo-log-states)))))))
  9241. (defun org-get-todo-sequence-head (kwd)
  9242. "Return the head of the TODO sequence to which KWD belongs.
  9243. If KWD is not set, check if there is a text property remembering the
  9244. right sequence."
  9245. (let (p)
  9246. (cond
  9247. ((not kwd)
  9248. (or (get-text-property (point-at-bol) 'org-todo-head)
  9249. (progn
  9250. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9251. nil (point-at-eol)))
  9252. (get-text-property p 'org-todo-head))))
  9253. ((not (member kwd org-todo-keywords-1))
  9254. (car org-todo-keywords-1))
  9255. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9256. (defun org-fast-todo-selection (&optional current-state)
  9257. "Fast TODO keyword selection with single keys.
  9258. Returns the new TODO keyword, or nil if no state change should occur.
  9259. When CURRENT-STATE is given and selection letters are not unique globally,
  9260. prefer a state in the current sequence over on in another sequence."
  9261. (let* ((fulltable org-todo-key-alist)
  9262. (head (org-get-todo-sequence-head current-state))
  9263. (done-keywords org-done-keywords) ;; needed for the faces.
  9264. (maxlen (apply 'max (mapcar
  9265. (lambda (x)
  9266. (if (stringp (car x)) (string-width (car x)) 0))
  9267. fulltable)))
  9268. (expert (equal org-use-fast-todo-selection 'expert))
  9269. (prompt "")
  9270. (fwidth (+ maxlen 3 1 3))
  9271. (ncol (/ (- (window-width) 4) fwidth))
  9272. tg cnt e c tbl subtable
  9273. groups ingroup in-current-sequence)
  9274. (save-excursion
  9275. (save-window-excursion
  9276. (if expert
  9277. (set-buffer (get-buffer-create " *Org todo*"))
  9278. (delete-other-windows)
  9279. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9280. (org-switch-to-buffer-other-window " *Org todo*"))
  9281. (erase-buffer)
  9282. (setq-local org-done-keywords done-keywords)
  9283. (setq tbl fulltable cnt 0)
  9284. (while (setq e (pop tbl))
  9285. (cond
  9286. ((equal e '(:startgroup))
  9287. (push '() groups) (setq ingroup t)
  9288. (unless (= cnt 0)
  9289. (setq cnt 0)
  9290. (insert "\n"))
  9291. (setq prompt (concat prompt "{"))
  9292. (insert "{ "))
  9293. ((equal e '(:endgroup))
  9294. (setq ingroup nil cnt 0 in-current-sequence nil)
  9295. (setq prompt (concat prompt "}"))
  9296. (insert "}\n"))
  9297. ((equal e '(:newline))
  9298. (unless (= cnt 0)
  9299. (setq cnt 0)
  9300. (insert "\n")
  9301. (setq e (car tbl))
  9302. (while (equal (car tbl) '(:newline))
  9303. (insert "\n")
  9304. (setq tbl (cdr tbl)))))
  9305. (t
  9306. (setq tg (car e) c (cdr e))
  9307. (if (equal tg head) (setq in-current-sequence t))
  9308. (when ingroup (push tg (car groups)))
  9309. (when in-current-sequence (push e subtable))
  9310. (setq tg (org-add-props tg nil 'face
  9311. (org-get-todo-face tg)))
  9312. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9313. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9314. (insert "[" c "] " tg (make-string
  9315. (- fwidth 4 (length tg)) ?\ ))
  9316. (when (and (= (setq cnt (1+ cnt)) ncol)
  9317. ;; Avoid lines with just a closing delimiter.
  9318. (not (equal (car tbl) '(:endgroup))))
  9319. (insert "\n")
  9320. (when ingroup (insert " "))
  9321. (setq cnt 0)))))
  9322. (insert "\n")
  9323. (goto-char (point-min))
  9324. (unless expert (org-fit-window-to-buffer))
  9325. (message (concat "[a-z..]:Set [SPC]:clear"
  9326. (if expert (concat "\n" prompt) "")))
  9327. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9328. (setq subtable (nreverse subtable))
  9329. (cond
  9330. ((or (= c ?\C-g)
  9331. (and (= c ?q) (not (rassoc c fulltable))))
  9332. (setq quit-flag t))
  9333. ((= c ?\ ) nil)
  9334. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9335. tg (car e))
  9336. tg)
  9337. (t (setq quit-flag t)))))))
  9338. (defun org-entry-is-todo-p ()
  9339. (member (org-get-todo-state) org-not-done-keywords))
  9340. (defun org-entry-is-done-p ()
  9341. (member (org-get-todo-state) org-done-keywords))
  9342. (defun org-get-todo-state ()
  9343. "Return the TODO keyword of the current subtree."
  9344. (save-excursion
  9345. (org-back-to-heading t)
  9346. (and (let ((case-fold-search nil))
  9347. (looking-at org-todo-line-regexp))
  9348. (match-end 2)
  9349. (match-string 2))))
  9350. (defun org-at-date-range-p (&optional inactive-ok)
  9351. "Non-nil if point is inside a date range.
  9352. When optional argument INACTIVE-OK is non-nil, also consider
  9353. inactive time ranges.
  9354. When this function returns a non-nil value, match data is set
  9355. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9356. on INACTIVE-OK."
  9357. (interactive)
  9358. (save-excursion
  9359. (catch 'exit
  9360. (let ((pos (point)))
  9361. (skip-chars-backward "^[<\r\n")
  9362. (skip-chars-backward "<[")
  9363. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9364. (>= (match-end 0) pos)
  9365. (throw 'exit t))
  9366. (skip-chars-backward "^<[\r\n")
  9367. (skip-chars-backward "<[")
  9368. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9369. (>= (match-end 0) pos)
  9370. (throw 'exit t)))
  9371. nil)))
  9372. (defun org-get-repeat (&optional timestamp)
  9373. "Check if there is a time-stamp with repeater in this entry.
  9374. Return the repeater, as a string, or nil. Also return nil when
  9375. this function is called before first heading.
  9376. When optional argument TIMESTAMP is a string, extract the
  9377. repeater from there instead."
  9378. (save-match-data
  9379. (cond
  9380. (timestamp
  9381. (and (string-match org-repeat-re timestamp)
  9382. (match-string-no-properties 1 timestamp)))
  9383. ((org-before-first-heading-p) nil)
  9384. (t
  9385. (save-excursion
  9386. (org-back-to-heading t)
  9387. (let ((end (org-entry-end-position)))
  9388. (catch :repeat
  9389. (while (re-search-forward org-repeat-re end t)
  9390. (when (save-match-data (org-at-timestamp-p 'agenda))
  9391. (throw :repeat (match-string-no-properties 1)))))))))))
  9392. (defvar org-last-changed-timestamp)
  9393. (defvar org-last-inserted-timestamp)
  9394. (defvar org-log-post-message)
  9395. (defvar org-log-note-purpose)
  9396. (defvar org-log-note-how nil)
  9397. (defvar org-log-note-extra)
  9398. (defvar org-log-setup nil)
  9399. (defun org-auto-repeat-maybe (done-word)
  9400. "Check if the current headline contains a repeated time-stamp.
  9401. If yes, set TODO state back to what it was and change the base date
  9402. of repeating deadline/scheduled time stamps to new date.
  9403. This function is run automatically after each state change to a DONE state."
  9404. (let* ((repeat (org-get-repeat))
  9405. (aa (assoc org-last-state org-todo-kwd-alist))
  9406. (interpret (nth 1 aa))
  9407. (head (nth 2 aa))
  9408. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9409. (msg "Entry repeats: ")
  9410. (org-log-done nil)
  9411. (org-todo-log-states nil)
  9412. (end (copy-marker (org-entry-end-position))))
  9413. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9414. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9415. (let ((to-state
  9416. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9417. (and (stringp org-todo-repeat-to-state)
  9418. org-todo-repeat-to-state)
  9419. (and org-todo-repeat-to-state org-last-state))))
  9420. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9421. to-state)
  9422. ((eq interpret 'type) org-last-state)
  9423. (head)
  9424. (t 'none))))
  9425. (org-back-to-heading t)
  9426. (org-add-planning-info nil nil 'closed)
  9427. ;; When `org-log-repeat' is non-nil or entry contains
  9428. ;; a clock, set LAST_REPEAT property.
  9429. (when (or org-log-repeat
  9430. (catch :clock
  9431. (save-excursion
  9432. (while (re-search-forward org-clock-line-re end t)
  9433. (when (org-at-clock-log-p) (throw :clock t))))))
  9434. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9435. (org-time-stamp-format t t))))
  9436. (when org-log-repeat
  9437. (if org-log-setup
  9438. ;; We are already setup for some record.
  9439. (when (eq org-log-repeat 'note)
  9440. ;; Make sure we take a note, not only a time stamp.
  9441. (setq org-log-note-how 'note))
  9442. ;; Set up for taking a record.
  9443. (org-add-log-setup 'state
  9444. (or done-word (car org-done-keywords))
  9445. org-last-state
  9446. org-log-repeat)))
  9447. ;; Time-stamps without a repeater are usually skipped. However,
  9448. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9449. ;; longer relevant.
  9450. (save-excursion
  9451. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9452. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9453. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9454. ;; Update every time-stamp with a repeater in the entry.
  9455. (let ((planning-re (regexp-opt
  9456. (list org-scheduled-string org-deadline-string))))
  9457. (while (re-search-forward org-repeat-re end t)
  9458. (let* ((ts (match-string 0))
  9459. (type (if (not (org-at-planning-p)) "Plain:"
  9460. (save-excursion
  9461. (re-search-backward
  9462. planning-re (line-beginning-position) t)
  9463. (match-string 0)))))
  9464. (when (and (org-at-timestamp-p 'agenda)
  9465. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9466. (let ((n (string-to-number (match-string 2 ts)))
  9467. (what (match-string 3 ts)))
  9468. (when (equal what "w") (setq n (* n 7) what "d"))
  9469. (when (and (equal what "h")
  9470. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9471. ts)))
  9472. (user-error
  9473. "Cannot repeat in %d hour(s) because no hour has been set"
  9474. n))
  9475. ;; Preparation, see if we need to modify the start
  9476. ;; date for the change.
  9477. (when (match-end 1)
  9478. (let ((time (save-match-data (org-time-string-to-time ts)))
  9479. (repeater-type (match-string 1 ts)))
  9480. (cond
  9481. ((equal "." repeater-type)
  9482. ;; Shift starting date to today, or now if
  9483. ;; repeater is by hours.
  9484. (if (equal what "h")
  9485. (org-timestamp-change
  9486. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9487. (org-timestamp-change
  9488. (- (org-today) (time-to-days time)) 'day)))
  9489. ((equal "+" repeater-type)
  9490. (let ((nshiftmax 10)
  9491. (nshift 0))
  9492. (while (or (= nshift 0)
  9493. (not (org-time-less-p nil time)))
  9494. (when (= nshiftmax (cl-incf nshift))
  9495. (or (y-or-n-p
  9496. (format "%d repeater intervals were not \
  9497. enough to shift date past today. Continue? "
  9498. nshift))
  9499. (user-error "Abort")))
  9500. (org-timestamp-change n (cdr (assoc what whata)))
  9501. (org-in-regexp org-ts-regexp3)
  9502. (setq ts (match-string 1))
  9503. (setq time
  9504. (save-match-data
  9505. (org-time-string-to-time ts)))))
  9506. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9507. ;; Rematch, so that we have everything in place
  9508. ;; for the real shift.
  9509. (org-in-regexp org-ts-regexp3)
  9510. (setq ts (match-string 1))
  9511. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9512. ts)))))
  9513. (save-excursion
  9514. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9515. (setq msg
  9516. (concat msg type " " org-last-changed-timestamp " ")))))))
  9517. (run-hooks 'org-todo-repeat-hook)
  9518. (setq org-log-post-message msg)
  9519. (message msg))))
  9520. (defun org-show-todo-tree (arg)
  9521. "Make a compact tree which shows all headlines marked with TODO.
  9522. The tree will show the lines where the regexp matches, and all higher
  9523. headlines above the match.
  9524. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9525. With a numeric prefix N, construct a sparse tree for the Nth element
  9526. of `org-todo-keywords-1'."
  9527. (interactive "P")
  9528. (let ((case-fold-search nil)
  9529. (kwd-re
  9530. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9531. ((equal arg '(4))
  9532. (let ((kwd
  9533. (completing-read "Keyword (or KWD1|KWD2|...): "
  9534. (mapcar #'list org-todo-keywords-1))))
  9535. (concat "\\("
  9536. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9537. "\\)\\>")))
  9538. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9539. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9540. org-todo-keywords-1)))
  9541. (t (user-error "Invalid prefix argument: %s" arg)))))
  9542. (message "%d TODO entries found"
  9543. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9544. (defun org--deadline-or-schedule (arg type time)
  9545. "Insert DEADLINE or SCHEDULE information in current entry.
  9546. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9547. `org-schedule' for information about ARG and TIME arguments."
  9548. (let* ((deadline? (eq type 'deadline))
  9549. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9550. (log (if deadline? org-log-redeadline org-log-reschedule))
  9551. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9552. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9553. ;; Save repeater cookie from either TIME or current scheduled
  9554. ;; time stamp. We are going to insert it back at the end of
  9555. ;; the process.
  9556. (repeater (or (and (org-string-nw-p time)
  9557. ;; We use `org-repeat-re' because we need
  9558. ;; to tell the difference between a real
  9559. ;; repeater and a time delta, e.g. "+2d".
  9560. (string-match org-repeat-re time)
  9561. (match-string 1 time))
  9562. (and (org-string-nw-p old-date)
  9563. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9564. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9565. old-date)
  9566. (match-string 1 old-date)))))
  9567. (pcase arg
  9568. (`(4)
  9569. (if (not old-date)
  9570. (message (if deadline? "Entry had no deadline to remove"
  9571. "Entry was not scheduled"))
  9572. (when (and old-date log)
  9573. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9574. nil old-date log))
  9575. (org-remove-timestamp-with-keyword keyword)
  9576. (message (if deadline? "Entry no longer has a deadline."
  9577. "Entry is no longer scheduled."))))
  9578. (`(16)
  9579. (save-excursion
  9580. (org-back-to-heading t)
  9581. (let ((regexp (if deadline? org-deadline-time-regexp
  9582. org-scheduled-time-regexp)))
  9583. (if (not (re-search-forward regexp (line-end-position 2) t))
  9584. (user-error (if deadline? "No deadline information to update"
  9585. "No scheduled information to update"))
  9586. (let* ((rpl0 (match-string 1))
  9587. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9588. (msg (if deadline? "Warn starting from" "Delay until")))
  9589. (replace-match
  9590. (concat keyword
  9591. " <" rpl
  9592. (format " -%dd"
  9593. (abs (- (time-to-days
  9594. (save-match-data
  9595. (org-read-date
  9596. nil t nil msg old-date-time)))
  9597. (time-to-days old-date-time))))
  9598. ">") t t))))))
  9599. (_
  9600. (org-add-planning-info type time 'closed)
  9601. (when (and old-date
  9602. log
  9603. (not (equal old-date org-last-inserted-timestamp)))
  9604. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9605. org-last-inserted-timestamp
  9606. old-date
  9607. log))
  9608. (when repeater
  9609. (save-excursion
  9610. (org-back-to-heading t)
  9611. (when (re-search-forward
  9612. (concat keyword " " org-last-inserted-timestamp)
  9613. (line-end-position 2)
  9614. t)
  9615. (goto-char (1- (match-end 0)))
  9616. (insert " " repeater)
  9617. (setq org-last-inserted-timestamp
  9618. (concat (substring org-last-inserted-timestamp 0 -1)
  9619. " " repeater
  9620. (substring org-last-inserted-timestamp -1))))))
  9621. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9622. org-last-inserted-timestamp)))))
  9623. (defun org-deadline (arg &optional time)
  9624. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9625. When called interactively, this command pops up the Emacs calendar to let
  9626. the user select a date.
  9627. With one universal prefix argument, remove any deadline from the item.
  9628. With two universal prefix arguments, prompt for a warning delay.
  9629. With argument TIME, set the deadline at the corresponding date. TIME
  9630. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9631. (interactive "P")
  9632. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9633. (org-map-entries
  9634. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9635. nil
  9636. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9637. 'region-start-level
  9638. 'region)
  9639. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9640. (org--deadline-or-schedule arg 'deadline time)))
  9641. (defun org-schedule (arg &optional time)
  9642. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9643. When called interactively, this command pops up the Emacs calendar to let
  9644. the user select a date.
  9645. With one universal prefix argument, remove any scheduling date from the item.
  9646. With two universal prefix arguments, prompt for a delay cookie.
  9647. With argument TIME, scheduled at the corresponding date. TIME can
  9648. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9649. (interactive "P")
  9650. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9651. (org-map-entries
  9652. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9653. nil
  9654. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9655. 'region-start-level
  9656. 'region)
  9657. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9658. (org--deadline-or-schedule arg 'scheduled time)))
  9659. (defun org-get-scheduled-time (pom &optional inherit)
  9660. "Get the scheduled time as a time tuple, of a format suitable
  9661. for calling org-schedule with, or if there is no scheduling,
  9662. returns nil."
  9663. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9664. (when time
  9665. (org-time-string-to-time time))))
  9666. (defun org-get-deadline-time (pom &optional inherit)
  9667. "Get the deadline as a time tuple, of a format suitable for
  9668. calling org-deadline with, or if there is no scheduling, returns
  9669. nil."
  9670. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9671. (when time
  9672. (org-time-string-to-time time))))
  9673. (defun org-remove-timestamp-with-keyword (keyword)
  9674. "Remove all time stamps with KEYWORD in the current entry."
  9675. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9676. beg)
  9677. (save-excursion
  9678. (org-back-to-heading t)
  9679. (setq beg (point))
  9680. (outline-next-heading)
  9681. (while (re-search-backward re beg t)
  9682. (replace-match "")
  9683. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9684. (equal (char-before) ?\ ))
  9685. (backward-delete-char 1)
  9686. (when (string-match "^[ \t]*$" (buffer-substring
  9687. (point-at-bol) (point-at-eol)))
  9688. (delete-region (point-at-bol)
  9689. (min (point-max) (1+ (point-at-eol))))))))))
  9690. (defvar org-time-was-given) ; dynamically scoped parameter
  9691. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9692. (defun org-at-planning-p ()
  9693. "Non-nil when point is on a planning info line."
  9694. ;; This is as accurate and faster than `org-element-at-point' since
  9695. ;; planning info location is fixed in the section.
  9696. (org-with-wide-buffer
  9697. (beginning-of-line)
  9698. (and (looking-at-p org-planning-line-re)
  9699. (eq (point)
  9700. (ignore-errors
  9701. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9702. (org-back-to-heading t)
  9703. (org-with-limited-levels (org-back-to-heading t)))
  9704. (line-beginning-position 2))))))
  9705. (defun org-add-planning-info (what &optional time &rest remove)
  9706. "Insert new timestamp with keyword in the planning line.
  9707. WHAT indicates what kind of time stamp to add. It is a symbol
  9708. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9709. the time to use. If none is given, the user is prompted for
  9710. a date. REMOVE indicates what kind of entries to remove. An old
  9711. WHAT entry will also be removed."
  9712. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9713. (when (and (memq what '(scheduled deadline))
  9714. (or (not time)
  9715. (and (stringp time)
  9716. (string-match "^[-+]+[0-9]" time))))
  9717. ;; Try to get a default date/time from existing timestamp
  9718. (save-excursion
  9719. (org-back-to-heading t)
  9720. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9721. (when (re-search-forward (if (eq what 'scheduled)
  9722. org-scheduled-time-regexp
  9723. org-deadline-time-regexp)
  9724. end t)
  9725. (setq ts (match-string 1)
  9726. default-time (org-time-string-to-time ts)
  9727. default-input (and ts (org-get-compact-tod ts)))))))
  9728. (when what
  9729. (setq time
  9730. (if (stringp time)
  9731. ;; This is a string (relative or absolute), set
  9732. ;; proper date.
  9733. (apply #'encode-time
  9734. (org-read-date-analyze
  9735. time default-time (decode-time default-time)))
  9736. ;; If necessary, get the time from the user
  9737. (or time (org-read-date nil 'to-time nil
  9738. (cl-case what
  9739. (deadline "DEADLINE")
  9740. (scheduled "SCHEDULED")
  9741. (otherwise nil))
  9742. default-time default-input)))))
  9743. (org-with-wide-buffer
  9744. (org-back-to-heading t)
  9745. (let ((planning? (save-excursion
  9746. (forward-line)
  9747. (looking-at-p org-planning-line-re))))
  9748. (cond
  9749. (planning?
  9750. (forward-line)
  9751. ;; Move to current indentation.
  9752. (skip-chars-forward " \t")
  9753. ;; Check if we have to remove something.
  9754. (dolist (type (if what (cons what remove) remove))
  9755. (save-excursion
  9756. (when (re-search-forward
  9757. (cl-case type
  9758. (closed org-closed-time-regexp)
  9759. (deadline org-deadline-time-regexp)
  9760. (scheduled org-scheduled-time-regexp)
  9761. (otherwise (error "Invalid planning type: %s" type)))
  9762. (line-end-position)
  9763. t)
  9764. ;; Delete until next keyword or end of line.
  9765. (delete-region
  9766. (match-beginning 0)
  9767. (if (re-search-forward org-keyword-time-not-clock-regexp
  9768. (line-end-position)
  9769. t)
  9770. (match-beginning 0)
  9771. (line-end-position))))))
  9772. ;; If there is nothing more to add and no more keyword is
  9773. ;; left, remove the line completely.
  9774. (if (and (looking-at-p "[ \t]*$") (not what))
  9775. (delete-region (line-end-position 0)
  9776. (line-end-position))
  9777. ;; If we removed last keyword, do not leave trailing white
  9778. ;; space at the end of line.
  9779. (let ((p (point)))
  9780. (save-excursion
  9781. (end-of-line)
  9782. (unless (= (skip-chars-backward " \t" p) 0)
  9783. (delete-region (point) (line-end-position)))))))
  9784. (what
  9785. (end-of-line)
  9786. (insert "\n")
  9787. (when org-adapt-indentation
  9788. (indent-to-column (1+ (org-outline-level)))))
  9789. (t nil)))
  9790. (when what
  9791. ;; Insert planning keyword.
  9792. (insert (cl-case what
  9793. (closed org-closed-string)
  9794. (deadline org-deadline-string)
  9795. (scheduled org-scheduled-string)
  9796. (otherwise (error "Invalid planning type: %s" what)))
  9797. " ")
  9798. ;; Insert associated timestamp.
  9799. (let ((ts (org-insert-time-stamp
  9800. time
  9801. (or org-time-was-given
  9802. (and (eq what 'closed) org-log-done-with-time))
  9803. (eq what 'closed)
  9804. nil nil (list org-end-time-was-given))))
  9805. (unless (eolp) (insert " "))
  9806. ts)))))
  9807. (defvar org-log-note-marker (make-marker)
  9808. "Marker pointing at the entry where the note is to be inserted.")
  9809. (defvar org-log-note-purpose nil)
  9810. (defvar org-log-note-state nil)
  9811. (defvar org-log-note-previous-state nil)
  9812. (defvar org-log-note-extra nil)
  9813. (defvar org-log-note-window-configuration nil)
  9814. (defvar org-log-note-return-to (make-marker))
  9815. (defvar org-log-note-effective-time nil
  9816. "Remembered current time.
  9817. So that dynamically scoped `org-extend-today-until' affects
  9818. timestamps in state change log.")
  9819. (defvar org-log-post-message nil
  9820. "Message to be displayed after a log note has been stored.
  9821. The auto-repeater uses this.")
  9822. (defun org-add-note ()
  9823. "Add a note to the current entry.
  9824. This is done in the same way as adding a state change note."
  9825. (interactive)
  9826. (org-add-log-setup 'note))
  9827. (defun org-log-beginning (&optional create)
  9828. "Return expected start of log notes in current entry.
  9829. When optional argument CREATE is non-nil, the function creates
  9830. a drawer to store notes, if necessary. Returned position ignores
  9831. narrowing."
  9832. (org-with-wide-buffer
  9833. (let ((drawer (org-log-into-drawer)))
  9834. (cond
  9835. (drawer
  9836. (org-end-of-meta-data)
  9837. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9838. (end (if (org-at-heading-p) (point)
  9839. (save-excursion (outline-next-heading) (point))))
  9840. (case-fold-search t))
  9841. (catch 'exit
  9842. ;; Try to find existing drawer.
  9843. (while (re-search-forward regexp end t)
  9844. (let ((element (org-element-at-point)))
  9845. (when (eq (org-element-type element) 'drawer)
  9846. (let ((cend (org-element-property :contents-end element)))
  9847. (when (and (not org-log-states-order-reversed) cend)
  9848. (goto-char cend)))
  9849. (throw 'exit nil))))
  9850. ;; No drawer found. Create one, if permitted.
  9851. (when create
  9852. (unless (bolp) (insert "\n"))
  9853. (let ((beg (point)))
  9854. (insert ":" drawer ":\n:END:\n")
  9855. (org-indent-region beg (point))
  9856. (org-flag-region (line-end-position -1)
  9857. (1- (point)) t 'outline))
  9858. (end-of-line -1)))))
  9859. (t
  9860. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9861. (skip-chars-forward " \t\n")
  9862. (beginning-of-line)
  9863. (unless org-log-states-order-reversed
  9864. (org-skip-over-state-notes)
  9865. (skip-chars-backward " \t\n")
  9866. (forward-line)))))
  9867. (if (bolp) (point) (line-beginning-position 2))))
  9868. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9869. "Set up the post command hook to take a note.
  9870. If this is about to TODO state change, the new state is expected in STATE.
  9871. HOW is an indicator what kind of note should be created.
  9872. EXTRA is additional text that will be inserted into the notes buffer."
  9873. (move-marker org-log-note-marker (point))
  9874. (setq org-log-note-purpose purpose
  9875. org-log-note-state state
  9876. org-log-note-previous-state prev-state
  9877. org-log-note-how how
  9878. org-log-note-extra extra
  9879. org-log-note-effective-time (org-current-effective-time)
  9880. org-log-setup t)
  9881. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9882. (defun org-skip-over-state-notes ()
  9883. "Skip past the list of State notes in an entry."
  9884. (when (ignore-errors (goto-char (org-in-item-p)))
  9885. (let* ((struct (org-list-struct))
  9886. (prevs (org-list-prevs-alist struct))
  9887. (regexp
  9888. (concat "[ \t]*- +"
  9889. (replace-regexp-in-string
  9890. " +" " +"
  9891. (org-replace-escapes
  9892. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9893. `(("%d" . ,org-ts-regexp-inactive)
  9894. ("%D" . ,org-ts-regexp)
  9895. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9896. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9897. ("%t" . ,org-ts-regexp-inactive)
  9898. ("%T" . ,org-ts-regexp)
  9899. ("%u" . ".*?")
  9900. ("%U" . ".*?")))))))
  9901. (while (looking-at-p regexp)
  9902. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9903. (org-list-get-item-end (point) struct)))))))
  9904. (defun org-add-log-note (&optional _purpose)
  9905. "Pop up a window for taking a note, and add this note later."
  9906. (remove-hook 'post-command-hook 'org-add-log-note)
  9907. (setq org-log-setup nil)
  9908. (setq org-log-note-window-configuration (current-window-configuration))
  9909. (delete-other-windows)
  9910. (move-marker org-log-note-return-to (point))
  9911. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9912. (goto-char org-log-note-marker)
  9913. (org-switch-to-buffer-other-window "*Org Note*")
  9914. (erase-buffer)
  9915. (if (memq org-log-note-how '(time state))
  9916. (org-store-log-note)
  9917. (let ((org-inhibit-startup t)) (org-mode))
  9918. (insert (format "# Insert note for %s.
  9919. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9920. (cl-case org-log-note-purpose
  9921. (clock-out "stopped clock")
  9922. (done "closed todo item")
  9923. (reschedule "rescheduling")
  9924. (delschedule "no longer scheduled")
  9925. (redeadline "changing deadline")
  9926. (deldeadline "removing deadline")
  9927. (refile "refiling")
  9928. (note "this entry")
  9929. (state
  9930. (format "state change from \"%s\" to \"%s\""
  9931. (or org-log-note-previous-state "")
  9932. (or org-log-note-state "")))
  9933. (t (error "This should not happen")))))
  9934. (when org-log-note-extra (insert org-log-note-extra))
  9935. (setq-local org-finish-function 'org-store-log-note)
  9936. (run-hooks 'org-log-buffer-setup-hook)))
  9937. (defvar org-note-abort nil) ; dynamically scoped
  9938. (defun org-store-log-note ()
  9939. "Finish taking a log note, and insert it to where it belongs."
  9940. (let ((txt (prog1 (buffer-string)
  9941. (kill-buffer)))
  9942. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9943. lines)
  9944. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9945. (setq txt (replace-match "" t t txt)))
  9946. (when (string-match "\\s-+\\'" txt)
  9947. (setq txt (replace-match "" t t txt)))
  9948. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9949. (when (org-string-nw-p note)
  9950. (setq note
  9951. (org-replace-escapes
  9952. note
  9953. (list (cons "%u" (user-login-name))
  9954. (cons "%U" user-full-name)
  9955. (cons "%t" (format-time-string
  9956. (org-time-stamp-format 'long 'inactive)
  9957. org-log-note-effective-time))
  9958. (cons "%T" (format-time-string
  9959. (org-time-stamp-format 'long nil)
  9960. org-log-note-effective-time))
  9961. (cons "%d" (format-time-string
  9962. (org-time-stamp-format nil 'inactive)
  9963. org-log-note-effective-time))
  9964. (cons "%D" (format-time-string
  9965. (org-time-stamp-format nil nil)
  9966. org-log-note-effective-time))
  9967. (cons "%s" (cond
  9968. ((not org-log-note-state) "")
  9969. ((string-match-p org-ts-regexp
  9970. org-log-note-state)
  9971. (format "\"[%s]\""
  9972. (substring org-log-note-state 1 -1)))
  9973. (t (format "\"%s\"" org-log-note-state))))
  9974. (cons "%S"
  9975. (cond
  9976. ((not org-log-note-previous-state) "")
  9977. ((string-match-p org-ts-regexp
  9978. org-log-note-previous-state)
  9979. (format "\"[%s]\""
  9980. (substring
  9981. org-log-note-previous-state 1 -1)))
  9982. (t (format "\"%s\""
  9983. org-log-note-previous-state)))))))
  9984. (when lines (setq note (concat note " \\\\")))
  9985. (push note lines))
  9986. (when (and lines (not org-note-abort))
  9987. (with-current-buffer (marker-buffer org-log-note-marker)
  9988. (org-with-wide-buffer
  9989. ;; Find location for the new note.
  9990. (goto-char org-log-note-marker)
  9991. (set-marker org-log-note-marker nil)
  9992. ;; Note associated to a clock is to be located right after
  9993. ;; the clock. Do not move point.
  9994. (unless (eq org-log-note-purpose 'clock-out)
  9995. (goto-char (org-log-beginning t)))
  9996. ;; Make sure point is at the beginning of an empty line.
  9997. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9998. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9999. ;; In an existing list, add a new item at the top level.
  10000. ;; Otherwise, indent line like a regular one.
  10001. (let ((itemp (org-in-item-p)))
  10002. (if itemp
  10003. (indent-line-to
  10004. (let ((struct (save-excursion
  10005. (goto-char itemp) (org-list-struct))))
  10006. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10007. (org-indent-line)))
  10008. (insert (org-list-bullet-string "-") (pop lines))
  10009. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10010. (dolist (line lines)
  10011. (insert "\n")
  10012. (indent-line-to ind)
  10013. (insert line)))
  10014. (message "Note stored")
  10015. (org-back-to-heading t)))))
  10016. ;; Don't add undo information when called from `org-agenda-todo'.
  10017. (set-window-configuration org-log-note-window-configuration)
  10018. (with-current-buffer (marker-buffer org-log-note-return-to)
  10019. (goto-char org-log-note-return-to))
  10020. (move-marker org-log-note-return-to nil)
  10021. (when org-log-post-message (message "%s" org-log-post-message)))
  10022. (defun org-remove-empty-drawer-at (pos)
  10023. "Remove an empty drawer at position POS.
  10024. POS may also be a marker."
  10025. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10026. (org-with-wide-buffer
  10027. (goto-char pos)
  10028. (let ((drawer (org-element-at-point)))
  10029. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10030. (not (org-element-property :contents-begin drawer)))
  10031. (delete-region (org-element-property :begin drawer)
  10032. (progn (goto-char (org-element-property :end drawer))
  10033. (skip-chars-backward " \r\t\n")
  10034. (forward-line)
  10035. (point))))))))
  10036. (defvar org-ts-type nil)
  10037. (defun org-sparse-tree (&optional arg type)
  10038. "Create a sparse tree, prompt for the details.
  10039. This command can create sparse trees. You first need to select the type
  10040. of match used to create the tree:
  10041. t Show all TODO entries.
  10042. T Show entries with a specific TODO keyword.
  10043. m Show entries selected by a tags/property match.
  10044. p Enter a property name and its value (both with completion on existing
  10045. names/values) and show entries with that property.
  10046. r Show entries matching a regular expression (`/' can be used as well).
  10047. b Show deadlines and scheduled items before a date.
  10048. a Show deadlines and scheduled items after a date.
  10049. d Show deadlines due within `org-deadline-warning-days'.
  10050. D Show deadlines and scheduled items between a date range."
  10051. (interactive "P")
  10052. (setq type (or type org-sparse-tree-default-date-type))
  10053. (setq org-ts-type type)
  10054. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10055. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10056. [c]ycle through date types: %s"
  10057. (cl-case type
  10058. (all "all timestamps")
  10059. (scheduled "only scheduled")
  10060. (deadline "only deadline")
  10061. (active "only active timestamps")
  10062. (inactive "only inactive timestamps")
  10063. (closed "with a closed time-stamp")
  10064. (otherwise "scheduled/deadline")))
  10065. (let ((answer (read-char-exclusive)))
  10066. (cl-case answer
  10067. (?c
  10068. (org-sparse-tree
  10069. arg
  10070. (cadr
  10071. (memq type '(nil all scheduled deadline active inactive closed)))))
  10072. (?d (call-interactively 'org-check-deadlines))
  10073. (?b (call-interactively 'org-check-before-date))
  10074. (?a (call-interactively 'org-check-after-date))
  10075. (?D (call-interactively 'org-check-dates-range))
  10076. (?t (call-interactively 'org-show-todo-tree))
  10077. (?T (org-show-todo-tree '(4)))
  10078. (?m (call-interactively 'org-match-sparse-tree))
  10079. ((?p ?P)
  10080. (let* ((kwd (completing-read
  10081. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10082. (value (completing-read
  10083. "Value: " (mapcar #'list (org-property-values kwd)))))
  10084. (unless (string-match "\\`{.*}\\'" value)
  10085. (setq value (concat "\"" value "\"")))
  10086. (org-match-sparse-tree arg (concat kwd "=" value))))
  10087. ((?r ?R ?/) (call-interactively 'org-occur))
  10088. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10089. (defvar-local org-occur-highlights nil
  10090. "List of overlays used for occur matches.")
  10091. (defvar-local org-occur-parameters nil
  10092. "Parameters of the active org-occur calls.
  10093. This is a list, each call to org-occur pushes as cons cell,
  10094. containing the regular expression and the callback, onto the list.
  10095. The list can contain several entries if `org-occur' has been called
  10096. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10097. will only contain one set of parameters. When the highlights are
  10098. removed (for example with `C-c C-c', or with the next edit (depending
  10099. on `org-remove-highlights-with-change'), this variable is emptied
  10100. as well.")
  10101. (defun org-occur (regexp &optional keep-previous callback)
  10102. "Make a compact tree showing all matches of REGEXP.
  10103. The tree will show the lines where the regexp matches, and any other context
  10104. defined in `org-show-context-detail', which see.
  10105. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10106. done by a previous call to `org-occur' will be kept, to allow stacking of
  10107. calls to this command.
  10108. Optional argument CALLBACK can be a function of no argument. In this case,
  10109. it is called with point at the end of the match, match data being set
  10110. accordingly. Current match is shown only if the return value is non-nil.
  10111. The function must neither move point nor alter narrowing."
  10112. (interactive "sRegexp: \nP")
  10113. (when (equal regexp "")
  10114. (user-error "Regexp cannot be empty"))
  10115. (unless keep-previous
  10116. (org-remove-occur-highlights nil nil t))
  10117. (push (cons regexp callback) org-occur-parameters)
  10118. (let ((cnt 0))
  10119. (save-excursion
  10120. (goto-char (point-min))
  10121. (when (or (not keep-previous) ; do not want to keep
  10122. (not org-occur-highlights)) ; no previous matches
  10123. ;; hide everything
  10124. (org-overview))
  10125. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10126. (isearch-no-upper-case-p regexp t)
  10127. org-occur-case-fold-search)))
  10128. (while (re-search-forward regexp nil t)
  10129. (when (or (not callback)
  10130. (save-match-data (funcall callback)))
  10131. (setq cnt (1+ cnt))
  10132. (when org-highlight-sparse-tree-matches
  10133. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10134. (org-show-context 'occur-tree)))))
  10135. (when org-remove-highlights-with-change
  10136. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10137. nil 'local))
  10138. (unless org-sparse-tree-open-archived-trees
  10139. (org-hide-archived-subtrees (point-min) (point-max)))
  10140. (run-hooks 'org-occur-hook)
  10141. (when (called-interactively-p 'interactive)
  10142. (message "%d match(es) for regexp %s" cnt regexp))
  10143. cnt))
  10144. (defun org-occur-next-match (&optional n _reset)
  10145. "Function for `next-error-function' to find sparse tree matches.
  10146. N is the number of matches to move, when negative move backwards.
  10147. This function always goes back to the starting point when no
  10148. match is found."
  10149. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10150. (search-func (if (< n 0)
  10151. 'previous-single-char-property-change
  10152. 'next-single-char-property-change))
  10153. (n (abs n))
  10154. (pos (point))
  10155. p1)
  10156. (catch 'exit
  10157. (while (setq p1 (funcall search-func (point) 'org-type))
  10158. (when (equal p1 limit)
  10159. (goto-char pos)
  10160. (user-error "No more matches"))
  10161. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10162. (setq n (1- n))
  10163. (when (= n 0)
  10164. (goto-char p1)
  10165. (throw 'exit (point))))
  10166. (goto-char p1))
  10167. (goto-char p1)
  10168. (user-error "No more matches"))))
  10169. (defun org-highlight-new-match (beg end)
  10170. "Highlight from BEG to END and mark the highlight is an occur headline."
  10171. (let ((ov (make-overlay beg end)))
  10172. (overlay-put ov 'face 'secondary-selection)
  10173. (overlay-put ov 'org-type 'org-occur)
  10174. (push ov org-occur-highlights)))
  10175. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10176. "Remove the occur highlights from the buffer.
  10177. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10178. from the `before-change-functions' in the current buffer."
  10179. (interactive)
  10180. (unless org-inhibit-highlight-removal
  10181. (mapc #'delete-overlay org-occur-highlights)
  10182. (setq org-occur-highlights nil)
  10183. (setq org-occur-parameters nil)
  10184. (unless noremove
  10185. (remove-hook 'before-change-functions
  10186. 'org-remove-occur-highlights 'local))))
  10187. ;;;; Priorities
  10188. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10189. "Regular expression matching the priority indicator.
  10190. A priority indicator can be e.g. [#A] or [#1].
  10191. This regular expression matches these groups:
  10192. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10193. 1 : the priority cookie, e.g. \"[#A]\"
  10194. 2 : the value of the priority cookie, e.g. \"A\".")
  10195. (defun org-priority-up ()
  10196. "Increase the priority of the current item."
  10197. (interactive)
  10198. (org-priority 'up))
  10199. (defun org-priority-down ()
  10200. "Decrease the priority of the current item."
  10201. (interactive)
  10202. (org-priority 'down))
  10203. (defun org-priority (&optional action show)
  10204. "Change the priority of an item.
  10205. When called interactively with a `\\[universal-argument]' prefix,
  10206. show the priority in the minibuffer instead of changing it.
  10207. When called programmatically, ACTION can be `set', `up', `down',
  10208. or a character."
  10209. (interactive "P")
  10210. (when show
  10211. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10212. ;; passed the SHOW argument should be removed.
  10213. (warn "`org-priority' called with deprecated SHOW argument"))
  10214. (if (equal action '(4))
  10215. (org-priority-show)
  10216. (unless org-priority-enable-commands
  10217. (user-error "Priority commands are disabled"))
  10218. (setq action (or action 'set))
  10219. (let ((nump (< org-priority-lowest 65))
  10220. current new news have remove)
  10221. (save-excursion
  10222. (org-back-to-heading t)
  10223. (when (looking-at org-priority-regexp)
  10224. (let ((ms (match-string 2)))
  10225. (setq current (org-priority-to-value ms)
  10226. have t)))
  10227. (cond
  10228. ((eq action 'remove)
  10229. (setq remove t new ?\ ))
  10230. ((or (eq action 'set)
  10231. (integerp action))
  10232. (if (not (eq action 'set))
  10233. (setq new action)
  10234. (setq
  10235. new
  10236. (if nump
  10237. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  10238. (number-to-string org-priority-highest)
  10239. (number-to-string org-priority-lowest)))
  10240. (s (if (< 9 org-priority-lowest)
  10241. (read-string msg)
  10242. (message msg)
  10243. (char-to-string (read-char-exclusive)))))
  10244. (if (equal s " ") ?\s (string-to-number s)))
  10245. (progn (message "Priority %c-%c, SPC to remove: "
  10246. org-priority-highest org-priority-lowest)
  10247. (save-match-data
  10248. (setq new (read-char-exclusive)))))))
  10249. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10250. (= (upcase org-priority-lowest) org-priority-lowest))
  10251. (setq new (upcase new)))
  10252. (cond ((equal new ?\s) (setq remove t))
  10253. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10254. (user-error
  10255. (if nump
  10256. "Priority must be between `%s' and `%s'"
  10257. "Priority must be between `%c' and `%c'")
  10258. org-priority-highest org-priority-lowest))))
  10259. ((eq action 'up)
  10260. (setq new (if have
  10261. (1- current) ; normal cycling
  10262. ;; last priority was empty
  10263. (if (eq last-command this-command)
  10264. org-priority-lowest ; wrap around empty to lowest
  10265. ;; default
  10266. (if org-priority-start-cycle-with-default
  10267. org-priority-default
  10268. (1- org-priority-default))))))
  10269. ((eq action 'down)
  10270. (setq new (if have
  10271. (1+ current) ; normal cycling
  10272. ;; last priority was empty
  10273. (if (eq last-command this-command)
  10274. org-priority-highest ; wrap around empty to highest
  10275. ;; default
  10276. (if org-priority-start-cycle-with-default
  10277. org-priority-default
  10278. (1+ org-priority-default))))))
  10279. (t (user-error "Invalid action")))
  10280. (when (or (< (upcase new) org-priority-highest)
  10281. (> (upcase new) org-priority-lowest))
  10282. (if (and (memq action '(up down))
  10283. (not have) (not (eq last-command this-command)))
  10284. ;; `new' is from default priority
  10285. (error
  10286. "The default can not be set, see `org-priority-default' why")
  10287. ;; normal cycling: `new' is beyond highest/lowest priority
  10288. ;; and is wrapped around to the empty priority
  10289. (setq remove t)))
  10290. ;; Numerical priorities are limited to 64, beyond that number,
  10291. ;; assume the priority cookie is a character.
  10292. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10293. (if have
  10294. (if remove
  10295. (replace-match "" t t nil 1)
  10296. (replace-match news t t nil 2))
  10297. (if remove
  10298. (user-error "No priority cookie found in line")
  10299. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10300. (if (match-end 2)
  10301. (progn
  10302. (goto-char (match-end 2))
  10303. (insert " [#" news "]"))
  10304. (goto-char (match-beginning 3))
  10305. (insert "[#" news "] "))))
  10306. (org-align-tags))
  10307. (if remove
  10308. (message "Priority removed")
  10309. (message "Priority of current item set to %s" news)))))
  10310. (defalias 'org-show-priority 'org-priority-show)
  10311. (defun org-priority-show ()
  10312. "Show the priority of the current item.
  10313. This priority is composed of the main priority given with the [#A] cookies,
  10314. and by additional input from the age of a schedules or deadline entry."
  10315. (interactive)
  10316. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10317. (org-get-at-bol 'priority)
  10318. (save-excursion
  10319. (save-match-data
  10320. (beginning-of-line)
  10321. (and (looking-at org-heading-regexp)
  10322. (org-get-priority (match-string 0))))))))
  10323. (message "Priority is %d" (if pri pri -1000))))
  10324. (defun org-get-priority (s)
  10325. "Find priority cookie and return priority.
  10326. S is a string against which you can match `org-priority-regexp'.
  10327. If `org-priority-get-priority-function' is set to a custom
  10328. function, use it. Otherwise process S and output the priority
  10329. value, an integer."
  10330. (save-match-data
  10331. (if (functionp org-priority-get-priority-function)
  10332. (funcall org-priority-get-priority-function s)
  10333. (if (not (string-match org-priority-regexp s))
  10334. (* 1000 (- org-priority-lowest org-priority-default))
  10335. (* 1000 (- org-priority-lowest
  10336. (org-priority-to-value (match-string 2 s))))))))
  10337. ;;;; Tags
  10338. (defvar org-agenda-archives-mode)
  10339. (defvar org-map-continue-from nil
  10340. "Position from where mapping should continue.
  10341. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10342. (defvar org-scanner-tags nil
  10343. "The current tag list while the tags scanner is running.")
  10344. (defvar org-trust-scanner-tags nil
  10345. "Should `org-get-tags' use the tags for the scanner.
  10346. This is for internal dynamical scoping only.
  10347. When this is non-nil, the function `org-get-tags' will return the value
  10348. of `org-scanner-tags' instead of building the list by itself. This
  10349. can lead to large speed-ups when the tags scanner is used in a file with
  10350. many entries, and when the list of tags is retrieved, for example to
  10351. obtain a list of properties. Building the tags list for each entry in such
  10352. a file becomes an N^2 operation - but with this variable set, it scales
  10353. as N.")
  10354. (defvar org--matcher-tags-todo-only nil)
  10355. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10356. "Scan headline tags with inheritance and produce output ACTION.
  10357. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10358. or `agenda' to produce an entry list for an agenda view. It can also be
  10359. a Lisp form or a function that should be called at each matched headline, in
  10360. this case the return value is a list of all return values from these calls.
  10361. MATCHER is a function accepting three arguments, returning
  10362. a non-nil value whenever a given set of tags qualifies a headline
  10363. for inclusion. See `org-make-tags-matcher' for more information.
  10364. As a special case, it can also be set to t (respectively nil) in
  10365. order to match all (respectively none) headline.
  10366. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10367. included in the output.
  10368. START-LEVEL can be a string with asterisks, reducing the scope to
  10369. headlines matching this string."
  10370. (require 'org-agenda)
  10371. (let* ((re (concat "^"
  10372. (if start-level
  10373. ;; Get the correct level to match
  10374. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10375. org-outline-regexp)
  10376. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10377. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10378. (props (list 'face 'default
  10379. 'done-face 'org-agenda-done
  10380. 'undone-face 'default
  10381. 'mouse-face 'highlight
  10382. 'org-not-done-regexp org-not-done-regexp
  10383. 'org-todo-regexp org-todo-regexp
  10384. 'org-complex-heading-regexp org-complex-heading-regexp
  10385. 'help-echo
  10386. (format "mouse-2 or RET jump to Org file %S"
  10387. (abbreviate-file-name
  10388. (or (buffer-file-name (buffer-base-buffer))
  10389. (buffer-name (buffer-base-buffer)))))))
  10390. (org-map-continue-from nil)
  10391. lspos tags tags-list
  10392. (tags-alist (list (cons 0 org-file-tags)))
  10393. (llast 0) rtn rtn1 level category i txt
  10394. todo marker entry priority
  10395. ts-date ts-date-type ts-date-pair)
  10396. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10397. (setq action (list 'lambda nil action)))
  10398. (save-excursion
  10399. (goto-char (point-min))
  10400. (when (eq action 'sparse-tree)
  10401. (org-overview)
  10402. (org-remove-occur-highlights))
  10403. (while (let (case-fold-search)
  10404. (re-search-forward re nil t))
  10405. (setq org-map-continue-from nil)
  10406. (catch :skip
  10407. ;; Ignore closing parts of inline tasks.
  10408. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10409. (throw :skip t))
  10410. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10411. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10412. (goto-char (setq lspos (match-beginning 0)))
  10413. (setq level (org-reduced-level (org-outline-level))
  10414. category (org-get-category))
  10415. (when (eq action 'agenda)
  10416. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10417. ts-date (car ts-date-pair)
  10418. ts-date-type (cdr ts-date-pair)))
  10419. (setq i llast llast level)
  10420. ;; remove tag lists from same and sublevels
  10421. (while (>= i level)
  10422. (when (setq entry (assoc i tags-alist))
  10423. (setq tags-alist (delete entry tags-alist)))
  10424. (setq i (1- i)))
  10425. ;; add the next tags
  10426. (when tags
  10427. (setq tags (org-split-string tags ":")
  10428. tags-alist
  10429. (cons (cons level tags) tags-alist)))
  10430. ;; compile tags for current headline
  10431. (setq tags-list
  10432. (if org-use-tag-inheritance
  10433. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10434. tags)
  10435. org-scanner-tags tags-list)
  10436. (when org-use-tag-inheritance
  10437. (setcdr (car tags-alist)
  10438. (mapcar (lambda (x)
  10439. (setq x (copy-sequence x))
  10440. (org-add-prop-inherited x))
  10441. (cdar tags-alist))))
  10442. (when (and tags org-use-tag-inheritance
  10443. (or (not (eq t org-use-tag-inheritance))
  10444. org-tags-exclude-from-inheritance))
  10445. ;; Selective inheritance, remove uninherited ones.
  10446. (setcdr (car tags-alist)
  10447. (org-remove-uninherited-tags (cdar tags-alist))))
  10448. (when (and
  10449. ;; eval matcher only when the todo condition is OK
  10450. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10451. (if (functionp matcher)
  10452. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10453. (funcall matcher todo tags-list level))
  10454. matcher))
  10455. ;; Call the skipper, but return t if it does not
  10456. ;; skip, so that the `and' form continues evaluating.
  10457. (progn
  10458. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10459. t)
  10460. ;; Check if timestamps are deselecting this entry
  10461. (or (not todo-only)
  10462. (and (member todo org-todo-keywords-1)
  10463. (or (not org-agenda-tags-todo-honor-ignore-options)
  10464. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10465. ;; select this headline
  10466. (cond
  10467. ((eq action 'sparse-tree)
  10468. (and org-highlight-sparse-tree-matches
  10469. (org-get-heading) (match-end 0)
  10470. (org-highlight-new-match
  10471. (match-beginning 1) (match-end 1)))
  10472. (org-show-context 'tags-tree))
  10473. ((eq action 'agenda)
  10474. (setq txt (org-agenda-format-item
  10475. ""
  10476. (concat
  10477. (if (eq org-tags-match-list-sublevels 'indented)
  10478. (make-string (1- level) ?.) "")
  10479. (org-get-heading))
  10480. (make-string level ?\s)
  10481. category
  10482. tags-list)
  10483. priority (org-get-priority txt))
  10484. (goto-char lspos)
  10485. (setq marker (org-agenda-new-marker))
  10486. (org-add-props txt props
  10487. 'org-marker marker 'org-hd-marker marker 'org-category category
  10488. 'todo-state todo
  10489. 'ts-date ts-date
  10490. 'priority priority
  10491. 'type (concat "tagsmatch" ts-date-type))
  10492. (push txt rtn))
  10493. ((functionp action)
  10494. (setq org-map-continue-from nil)
  10495. (save-excursion
  10496. (setq rtn1 (funcall action))
  10497. (push rtn1 rtn)))
  10498. (t (user-error "Invalid action")))
  10499. ;; if we are to skip sublevels, jump to end of subtree
  10500. (unless org-tags-match-list-sublevels
  10501. (org-end-of-subtree t)
  10502. (backward-char 1))))
  10503. ;; Get the correct position from where to continue
  10504. (if org-map-continue-from
  10505. (goto-char org-map-continue-from)
  10506. (and (= (point) lspos) (end-of-line 1)))))
  10507. (when (and (eq action 'sparse-tree)
  10508. (not org-sparse-tree-open-archived-trees))
  10509. (org-hide-archived-subtrees (point-min) (point-max)))
  10510. (nreverse rtn)))
  10511. (defun org-remove-uninherited-tags (tags)
  10512. "Remove all tags that are not inherited from the list TAGS."
  10513. (cond
  10514. ((eq org-use-tag-inheritance t)
  10515. (if org-tags-exclude-from-inheritance
  10516. (org-delete-all org-tags-exclude-from-inheritance tags)
  10517. tags))
  10518. ((not org-use-tag-inheritance) nil)
  10519. ((stringp org-use-tag-inheritance)
  10520. (delq nil (mapcar
  10521. (lambda (x)
  10522. (if (and (string-match org-use-tag-inheritance x)
  10523. (not (member x org-tags-exclude-from-inheritance)))
  10524. x nil))
  10525. tags)))
  10526. ((listp org-use-tag-inheritance)
  10527. (delq nil (mapcar
  10528. (lambda (x)
  10529. (if (member x org-use-tag-inheritance) x nil))
  10530. tags)))))
  10531. (defun org-match-sparse-tree (&optional todo-only match)
  10532. "Create a sparse tree according to tags string MATCH.
  10533. MATCH is a string with match syntax. It can contain a selection
  10534. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10535. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10536. those. See the manual for details.
  10537. If optional argument TODO-ONLY is non-nil, only select lines that
  10538. are also TODO tasks."
  10539. (interactive "P")
  10540. (org-agenda-prepare-buffers (list (current-buffer)))
  10541. (let ((org--matcher-tags-todo-only todo-only))
  10542. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10543. org--matcher-tags-todo-only)))
  10544. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10545. (defvar org-cached-props nil)
  10546. (defun org-cached-entry-get (pom property)
  10547. (if (or (eq t org-use-property-inheritance)
  10548. (and (stringp org-use-property-inheritance)
  10549. (let ((case-fold-search t))
  10550. (string-match-p org-use-property-inheritance property)))
  10551. (and (listp org-use-property-inheritance)
  10552. (member-ignore-case property org-use-property-inheritance)))
  10553. ;; Caching is not possible, check it directly.
  10554. (org-entry-get pom property 'inherit)
  10555. ;; Get all properties, so we can do complicated checks easily.
  10556. (cdr (assoc-string property
  10557. (or org-cached-props
  10558. (setq org-cached-props (org-entry-properties pom)))
  10559. t))))
  10560. (defun org-global-tags-completion-table (&optional files)
  10561. "Return the list of all tags in all agenda buffer/files.
  10562. Optional FILES argument is a list of files which can be used
  10563. instead of the agenda files."
  10564. (save-excursion
  10565. (org-uniquify
  10566. (delq nil
  10567. (apply #'append
  10568. (mapcar
  10569. (lambda (file)
  10570. (set-buffer (find-file-noselect file))
  10571. (org--tag-add-to-alist
  10572. (org-get-buffer-tags)
  10573. (mapcar (lambda (x)
  10574. (and (stringp (car-safe x))
  10575. (list (car-safe x))))
  10576. org-current-tag-alist)))
  10577. (if (car-safe files) files
  10578. (org-agenda-files))))))))
  10579. (defun org-make-tags-matcher (match &optional only-local-tags)
  10580. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10581. Returns a cons of the selection string MATCH and a function
  10582. implementing the matcher.
  10583. The matcher is to be called at an Org entry, with point on the
  10584. headline, and returns non-nil if the entry matches the selection
  10585. string MATCH. It must be called with three arguments: the TODO
  10586. keyword at the entry (or nil if none), the list of all tags at
  10587. the entry including inherited ones and the reduced level of the
  10588. headline. Additionally, the category of the entry, if any, must
  10589. be specified as the text property `org-category' on the headline.
  10590. This function sets the variable `org--matcher-tags-todo-only' to
  10591. a non-nil value if the matcher restricts matching to TODO
  10592. entries, otherwise it is not touched.
  10593. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10594. table, only get buffer tags.
  10595. See also `org-scan-tags'."
  10596. (unless match
  10597. ;; Get a new match request, with completion against the global
  10598. ;; tags table and the local tags in current buffer.
  10599. (let ((org-last-tags-completion-table
  10600. (org--tag-add-to-alist
  10601. (org-get-buffer-tags)
  10602. (unless only-local-tags
  10603. (org-global-tags-completion-table)))))
  10604. (setq match
  10605. (completing-read
  10606. "Match: "
  10607. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10608. (let ((match0 match)
  10609. (re (concat
  10610. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10611. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10612. "\\([<>=]\\{1,2\\}\\)"
  10613. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10614. "\\|" org-tag-re "\\)"))
  10615. (start 0)
  10616. tagsmatch todomatch tagsmatcher todomatcher)
  10617. ;; Expand group tags.
  10618. (setq match (org-tags-expand match))
  10619. ;; Check if there is a TODO part of this match, which would be the
  10620. ;; part after a "/". To make sure that this slash is not part of
  10621. ;; a property value to be matched against, we also check that
  10622. ;; there is no / after that slash. First, find the last slash.
  10623. (let ((s 0))
  10624. (while (string-match "/+" match s)
  10625. (setq start (match-beginning 0))
  10626. (setq s (match-end 0))))
  10627. (if (and (string-match "/+" match start)
  10628. (not (string-match-p "\"" match start)))
  10629. ;; Match contains also a TODO-matching request.
  10630. (progn
  10631. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10632. (setq todomatch (substring match (match-end 0)))
  10633. (when (string-prefix-p "!" todomatch)
  10634. (setq org--matcher-tags-todo-only t)
  10635. (setq todomatch (substring todomatch 1)))
  10636. (when (string-match "\\`\\s-*\\'" todomatch)
  10637. (setq todomatch nil)))
  10638. ;; Only matching tags.
  10639. (setq tagsmatch match)
  10640. (setq todomatch nil))
  10641. ;; Make the tags matcher.
  10642. (when (org-string-nw-p tagsmatch)
  10643. (let ((orlist nil)
  10644. (orterms (org-split-string tagsmatch "|"))
  10645. term)
  10646. (while (setq term (pop orterms))
  10647. (while (and (equal (substring term -1) "\\") orterms)
  10648. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10649. (while (string-match re term)
  10650. (let* ((rest (substring term (match-end 0)))
  10651. (minus (and (match-end 1)
  10652. (equal (match-string 1 term) "-")))
  10653. (tag (save-match-data
  10654. (replace-regexp-in-string
  10655. "\\\\-" "-" (match-string 2 term))))
  10656. (regexp (eq (string-to-char tag) ?{))
  10657. (levelp (match-end 4))
  10658. (propp (match-end 5))
  10659. (mm
  10660. (cond
  10661. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10662. (levelp
  10663. `(,(org-op-to-function (match-string 3 term))
  10664. level
  10665. ,(string-to-number (match-string 4 term))))
  10666. (propp
  10667. (let* ((gv (pcase (upcase (match-string 5 term))
  10668. ("CATEGORY"
  10669. '(get-text-property (point) 'org-category))
  10670. ("TODO" 'todo)
  10671. (p `(org-cached-entry-get nil ,p))))
  10672. (pv (match-string 7 term))
  10673. (regexp (eq (string-to-char pv) ?{))
  10674. (strp (eq (string-to-char pv) ?\"))
  10675. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10676. (po (org-op-to-function (match-string 6 term)
  10677. (if timep 'time strp))))
  10678. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10679. (when timep (setq pv (org-matcher-time pv)))
  10680. (cond ((and regexp (eq po '/=))
  10681. `(not (string-match ,pv (or ,gv ""))))
  10682. (regexp `(string-match ,pv (or ,gv "")))
  10683. (strp `(,po (or ,gv "") ,pv))
  10684. (t
  10685. `(,po
  10686. (string-to-number (or ,gv ""))
  10687. ,(string-to-number pv))))))
  10688. (t `(member ,tag tags-list)))))
  10689. (push (if minus `(not ,mm) mm) tagsmatcher)
  10690. (setq term rest)))
  10691. (push `(and ,@tagsmatcher) orlist)
  10692. (setq tagsmatcher nil))
  10693. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10694. ;; Make the TODO matcher.
  10695. (when (org-string-nw-p todomatch)
  10696. (let ((orlist nil))
  10697. (dolist (term (org-split-string todomatch "|"))
  10698. (while (string-match re term)
  10699. (let* ((minus (and (match-end 1)
  10700. (equal (match-string 1 term) "-")))
  10701. (kwd (match-string 2 term))
  10702. (regexp (eq (string-to-char kwd) ?{))
  10703. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10704. `(equal todo ,kwd))))
  10705. (push (if minus `(not ,mm) mm) todomatcher))
  10706. (setq term (substring term (match-end 0))))
  10707. (push (if (> (length todomatcher) 1)
  10708. (cons 'and todomatcher)
  10709. (car todomatcher))
  10710. orlist)
  10711. (setq todomatcher nil))
  10712. (setq todomatcher (cons 'or orlist))))
  10713. ;; Return the string and function of the matcher. If no
  10714. ;; tags-specific or todo-specific matcher exists, match
  10715. ;; everything.
  10716. (let ((matcher (if (and tagsmatcher todomatcher)
  10717. `(and ,tagsmatcher ,todomatcher)
  10718. (or tagsmatcher todomatcher t))))
  10719. (when org--matcher-tags-todo-only
  10720. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10721. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10722. (defun org--tags-expand-group (group tag-groups expanded)
  10723. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10724. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10725. an accumulator used in recursive calls."
  10726. (dolist (tag group)
  10727. (unless (member tag expanded)
  10728. (let ((group (assoc tag tag-groups)))
  10729. (push tag expanded)
  10730. (when group
  10731. (setq expanded
  10732. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10733. expanded)
  10734. (defun org-tags-expand (match &optional single-as-list)
  10735. "Expand group tags in MATCH.
  10736. This replaces every group tag in MATCH with a regexp tag search.
  10737. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10738. will be replaced like this:
  10739. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10740. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10741. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10742. Replacing by a regexp preserves the structure of the match.
  10743. E.g., this expansion
  10744. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10745. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10746. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10747. A group tag in MATCH can contain regular expressions of its own.
  10748. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10749. will be replaced like this:
  10750. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10751. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10752. assumed to be a single group tag, and the function will return
  10753. the list of tags in this group."
  10754. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10755. (let ((tag-groups
  10756. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10757. (cond
  10758. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10759. (org-group-tags
  10760. (let* ((case-fold-search t)
  10761. (tag-syntax org-mode-syntax-table)
  10762. (group-keys (mapcar #'car tag-groups))
  10763. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10764. (return-match match))
  10765. ;; Mark regexp-expressions in the match-expression so that we
  10766. ;; do not replace them later on.
  10767. (let ((s 0))
  10768. (while (string-match "{.+?}" return-match s)
  10769. (setq s (match-end 0))
  10770. (add-text-properties
  10771. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10772. ;; @ and _ are allowed as word-components in tags.
  10773. (modify-syntax-entry ?@ "w" tag-syntax)
  10774. (modify-syntax-entry ?_ "w" tag-syntax)
  10775. ;; For each tag token found in MATCH, compute a regexp and it
  10776. (with-syntax-table tag-syntax
  10777. (replace-regexp-in-string
  10778. key-regexp
  10779. (lambda (m)
  10780. (if (get-text-property (match-beginning 2) 'regexp m)
  10781. m ;regexp tag: ignore
  10782. (let* ((operator (match-string 1 m))
  10783. (tag-token (let ((tag (match-string 2 m)))
  10784. (list tag)))
  10785. regexp-tags regular-tags)
  10786. ;; Partition tags between regexp and regular tags.
  10787. ;; Remove curly bracket syntax from regexp tags.
  10788. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10789. (save-match-data
  10790. (if (string-match "{\\(.+?\\)}" tag)
  10791. (push (match-string 1 tag) regexp-tags)
  10792. (push tag regular-tags))))
  10793. ;; Replace tag token by the appropriate regexp.
  10794. ;; Regular tags need to be regexp-quoted, whereas
  10795. ;; regexp-tags are inserted as-is.
  10796. (let ((regular (regexp-opt regular-tags))
  10797. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10798. (concat operator
  10799. (cond
  10800. ((null regular-tags) (format "{%s}" regexp))
  10801. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10802. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10803. return-match
  10804. t t))))
  10805. (t match))))
  10806. (defun org-op-to-function (op &optional stringp)
  10807. "Turn an operator into the appropriate function."
  10808. (setq op
  10809. (cond
  10810. ((equal op "<" ) '(< org-string< org-time<))
  10811. ((equal op ">" ) '(> org-string> org-time>))
  10812. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10813. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10814. ((member op '("=" "==")) '(= string= org-time=))
  10815. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10816. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10817. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10818. (defvar org-tags-overlay (make-overlay 1 1))
  10819. (delete-overlay org-tags-overlay)
  10820. (defun org-add-prop-inherited (s)
  10821. (add-text-properties 0 (length s) '(inherited t) s)
  10822. s)
  10823. (defun org-toggle-tag (tag &optional onoff)
  10824. "Toggle the tag TAG for the current line.
  10825. If ONOFF is `on' or `off', don't toggle but set to this state."
  10826. (save-excursion
  10827. (org-back-to-heading t)
  10828. (let ((current
  10829. ;; Reverse the tags list so any new tag is appended to the
  10830. ;; current list of tags.
  10831. (nreverse (org-get-tags nil t)))
  10832. res)
  10833. (pcase onoff
  10834. (`off (setq current (delete tag current)))
  10835. ((or `on (guard (not (member tag current))))
  10836. (setq res t)
  10837. (cl-pushnew tag current :test #'equal))
  10838. (_ (setq current (delete tag current))))
  10839. (org-set-tags (nreverse current))
  10840. res)))
  10841. (defun org--align-tags-here (to-col)
  10842. "Align tags on the current headline to TO-COL.
  10843. Assume point is on a headline. Preserve point when aligning
  10844. tags."
  10845. (when (org-match-line org-tag-line-re)
  10846. (let* ((tags-start (match-beginning 1))
  10847. (blank-start (save-excursion
  10848. (goto-char tags-start)
  10849. (skip-chars-backward " \t")
  10850. (point)))
  10851. (new (max (if (>= to-col 0) to-col
  10852. (- (abs to-col) (string-width (match-string 1))))
  10853. ;; Introduce at least one space after the heading
  10854. ;; or the stars.
  10855. (save-excursion
  10856. (goto-char blank-start)
  10857. (1+ (current-column)))))
  10858. (current
  10859. (save-excursion (goto-char tags-start) (current-column)))
  10860. (origin (point-marker))
  10861. (column (current-column))
  10862. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10863. (when (/= new current)
  10864. (delete-region blank-start tags-start)
  10865. (goto-char blank-start)
  10866. (let ((indent-tabs-mode nil)) (indent-to new))
  10867. ;; Try to move back to original position. If point was in the
  10868. ;; blanks before the tags, ORIGIN marker is of no use because
  10869. ;; it now points to BLANK-START. Use COLUMN instead.
  10870. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10871. (defun org-set-tags-command (&optional arg)
  10872. "Set the tags for the current visible entry.
  10873. When called with `\\[universal-argument]' prefix argument ARG, \
  10874. realign all tags
  10875. in the current buffer.
  10876. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10877. unconditionally do not
  10878. offer the fast tag selection interface.
  10879. If a region is active, set tags in the region according to the
  10880. setting of `org-loop-over-headlines-in-active-region'.
  10881. This function is for interactive use only;
  10882. in Lisp code use `org-set-tags' instead."
  10883. (interactive "P")
  10884. (let ((org-use-fast-tag-selection
  10885. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10886. (cond
  10887. ((equal '(4) arg) (org-align-tags t))
  10888. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10889. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10890. (org-map-entries
  10891. #'org-set-tags-command
  10892. nil
  10893. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10894. 'region-start-level
  10895. 'region)
  10896. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10897. (t
  10898. (save-excursion
  10899. (org-back-to-heading)
  10900. (let* ((all-tags (org-get-tags))
  10901. (table (setq org-last-tags-completion-table
  10902. (org--tag-add-to-alist
  10903. (and org-complete-tags-always-offer-all-agenda-tags
  10904. (org-global-tags-completion-table
  10905. (org-agenda-files)))
  10906. (or org-current-tag-alist (org-get-buffer-tags)))))
  10907. (current-tags
  10908. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10909. all-tags))
  10910. (inherited-tags
  10911. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10912. all-tags))
  10913. (tags
  10914. (replace-regexp-in-string
  10915. ;; Ignore all forbidden characters in tags.
  10916. "[^[:alnum:]_@#%]+" ":"
  10917. (if (or (eq t org-use-fast-tag-selection)
  10918. (and org-use-fast-tag-selection
  10919. (delq nil (mapcar #'cdr table))))
  10920. (org-fast-tag-selection
  10921. current-tags
  10922. inherited-tags
  10923. table
  10924. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10925. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10926. (crm-separator "[ \t]*:[ \t]*"))
  10927. (mapconcat #'identity
  10928. (completing-read-multiple
  10929. "Tags: "
  10930. org-last-tags-completion-table
  10931. nil nil (org-make-tag-string current-tags)
  10932. 'org-tags-history)
  10933. ":"))))))
  10934. (org-set-tags tags)))))
  10935. ;; `save-excursion' may not replace the point at the right
  10936. ;; position.
  10937. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10938. (looking-at-p " "))
  10939. (forward-char))))
  10940. (defun org-align-tags (&optional all)
  10941. "Align tags in current entry.
  10942. When optional argument ALL is non-nil, align all tags in the
  10943. visible part of the buffer."
  10944. (let ((get-indent-column
  10945. (lambda ()
  10946. (let ((offset (if (bound-and-true-p org-indent-mode)
  10947. (* (1- org-indent-indentation-per-level)
  10948. (1- (org-current-level)))
  10949. 0)))
  10950. (+ org-tags-column
  10951. (if (> org-tags-column 0) (- offset) offset))))))
  10952. (if (and (not all) (org-at-heading-p))
  10953. (org--align-tags-here (funcall get-indent-column))
  10954. (save-excursion
  10955. (if all
  10956. (progn
  10957. (goto-char (point-min))
  10958. (while (re-search-forward org-tag-line-re nil t)
  10959. (org--align-tags-here (funcall get-indent-column))))
  10960. (org-back-to-heading t)
  10961. (org--align-tags-here (funcall get-indent-column)))))))
  10962. (defun org-set-tags (tags)
  10963. "Set the tags of the current entry to TAGS, replacing current tags.
  10964. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10965. If TAGS is nil or the empty string, all tags are removed.
  10966. This function assumes point is on a headline."
  10967. (org-with-wide-buffer
  10968. (let ((tags (pcase tags
  10969. ((pred listp) tags)
  10970. ((pred stringp) (split-string (org-trim tags) ":" t))
  10971. (_ (error "Invalid tag specification: %S" tags))))
  10972. (old-tags (org-get-tags nil t))
  10973. (tags-change? nil))
  10974. (when (functionp org-tags-sort-function)
  10975. (setq tags (sort tags org-tags-sort-function)))
  10976. (setq tags-change? (not (equal tags old-tags)))
  10977. (when tags-change?
  10978. ;; Delete previous tags and any trailing white space.
  10979. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10980. (line-end-position)))
  10981. (skip-chars-backward " \t")
  10982. (delete-region (point) (line-end-position))
  10983. ;; Deleting white spaces may break an otherwise empty headline.
  10984. ;; Re-introduce one space in this case.
  10985. (unless (org-at-heading-p) (insert " "))
  10986. (when tags
  10987. (save-excursion (insert " " (org-make-tag-string tags)))
  10988. ;; When text is being inserted on an invisible region
  10989. ;; boundary, it can be inadvertently sucked into
  10990. ;; invisibility.
  10991. (unless (org-invisible-p (line-beginning-position))
  10992. (org-flag-region (point) (line-end-position) nil 'outline))))
  10993. ;; Align tags, if any.
  10994. (when tags (org-align-tags))
  10995. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10996. (defun org-change-tag-in-region (beg end tag off)
  10997. "Add or remove TAG for each entry in the region.
  10998. This works in the agenda, and also in an Org buffer."
  10999. (interactive
  11000. (list (region-beginning) (region-end)
  11001. (let ((org-last-tags-completion-table
  11002. (if (derived-mode-p 'org-mode)
  11003. (org--tag-add-to-alist
  11004. (org-get-buffer-tags)
  11005. (org-global-tags-completion-table))
  11006. (org-global-tags-completion-table))))
  11007. (completing-read
  11008. "Tag: " org-last-tags-completion-table nil nil nil
  11009. 'org-tags-history))
  11010. (progn
  11011. (message "[s]et or [r]emove? ")
  11012. (equal (read-char-exclusive) ?r))))
  11013. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11014. (let ((agendap (equal major-mode 'org-agenda-mode))
  11015. l1 l2 m buf pos newhead (cnt 0))
  11016. (goto-char end)
  11017. (setq l2 (1- (org-current-line)))
  11018. (goto-char beg)
  11019. (setq l1 (org-current-line))
  11020. (cl-loop for l from l1 to l2 do
  11021. (org-goto-line l)
  11022. (setq m (get-text-property (point) 'org-hd-marker))
  11023. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11024. (and agendap m))
  11025. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11026. pos (if agendap m (point)))
  11027. (with-current-buffer buf
  11028. (save-excursion
  11029. (save-restriction
  11030. (goto-char pos)
  11031. (setq cnt (1+ cnt))
  11032. (org-toggle-tag tag (if off 'off 'on))
  11033. (setq newhead (org-get-heading)))))
  11034. (and agendap (org-agenda-change-all-lines newhead m))))
  11035. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11036. (defun org-tags-completion-function (string _predicate &optional flag)
  11037. "Complete tag STRING.
  11038. FLAG specifies the type of completion operation to perform. This
  11039. function is passed as a collection function to `completing-read',
  11040. which see."
  11041. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11042. (confirm (lambda (x) (stringp (car x))))
  11043. (prefix ""))
  11044. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11045. (setq prefix (match-string 1 string))
  11046. (setq string (match-string 2 string)))
  11047. (pcase flag
  11048. (`t (all-completions string org-last-tags-completion-table confirm))
  11049. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11050. (`nil
  11051. (pcase (try-completion string org-last-tags-completion-table confirm)
  11052. ((and completion (pred stringp))
  11053. (concat prefix
  11054. completion
  11055. (if (and org-add-colon-after-tag-completion
  11056. (assoc completion org-last-tags-completion-table))
  11057. ":"
  11058. "")))
  11059. (completion completion)))
  11060. (_ nil))))
  11061. (defun org-fast-tag-insert (kwd tags face &optional end)
  11062. "Insert KWD, and the TAGS, the latter with face FACE.
  11063. Also insert END."
  11064. (insert (format "%-12s" (concat kwd ":"))
  11065. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11066. (or end "")))
  11067. (defun org-fast-tag-show-exit (flag)
  11068. (save-excursion
  11069. (org-goto-line 3)
  11070. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11071. (replace-match ""))
  11072. (when flag
  11073. (end-of-line 1)
  11074. (org-move-to-column (- (window-width) 19) t)
  11075. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11076. (defun org-set-current-tags-overlay (current prefix)
  11077. "Add an overlay to CURRENT tag with PREFIX."
  11078. (let ((s (org-make-tag-string current)))
  11079. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11080. (org-overlay-display org-tags-overlay (concat prefix s))))
  11081. (defvar org-last-tag-selection-key nil)
  11082. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11083. "Fast tag selection with single keys.
  11084. CURRENT is the current list of tags in the headline, INHERITED is the
  11085. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11086. possibly with grouping information. TODO-TABLE is a similar table with
  11087. TODO keywords, should these have keys assigned to them.
  11088. If the keys are nil, a-z are automatically assigned.
  11089. Returns the new tags string, or nil to not change the current settings."
  11090. (let* ((fulltable (append table todo-table))
  11091. (maxlen (if (null fulltable) 0
  11092. (apply #'max
  11093. (mapcar (lambda (x)
  11094. (if (stringp (car x)) (string-width (car x))
  11095. 0))
  11096. fulltable))))
  11097. (buf (current-buffer))
  11098. (expert (eq org-fast-tag-selection-single-key 'expert))
  11099. (tab-tags nil)
  11100. (fwidth (+ maxlen 3 1 3))
  11101. (ncol (/ (- (window-width) 4) fwidth))
  11102. (i-face 'org-done)
  11103. (c-face 'org-todo)
  11104. tg cnt e c char c1 c2 ntable tbl rtn
  11105. ov-start ov-end ov-prefix
  11106. (exit-after-next org-fast-tag-selection-single-key)
  11107. (done-keywords org-done-keywords)
  11108. groups ingroup intaggroup)
  11109. (save-excursion
  11110. (beginning-of-line)
  11111. (if (looking-at org-tag-line-re)
  11112. (setq ov-start (match-beginning 1)
  11113. ov-end (match-end 1)
  11114. ov-prefix "")
  11115. (setq ov-start (1- (point-at-eol))
  11116. ov-end (1+ ov-start))
  11117. (skip-chars-forward "^\n\r")
  11118. (setq ov-prefix
  11119. (concat
  11120. (buffer-substring (1- (point)) (point))
  11121. (if (> (current-column) org-tags-column)
  11122. " "
  11123. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11124. (move-overlay org-tags-overlay ov-start ov-end)
  11125. (save-excursion
  11126. (save-window-excursion
  11127. (if expert
  11128. (set-buffer (get-buffer-create " *Org tags*"))
  11129. (delete-other-windows)
  11130. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11131. (org-switch-to-buffer-other-window " *Org tags*"))
  11132. (erase-buffer)
  11133. (setq-local org-done-keywords done-keywords)
  11134. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11135. (org-fast-tag-insert "Current" current c-face "\n\n")
  11136. (org-fast-tag-show-exit exit-after-next)
  11137. (org-set-current-tags-overlay current ov-prefix)
  11138. (setq tbl fulltable char ?a cnt 0)
  11139. (while (setq e (pop tbl))
  11140. (cond
  11141. ((eq (car e) :startgroup)
  11142. (push '() groups) (setq ingroup t)
  11143. (unless (zerop cnt)
  11144. (setq cnt 0)
  11145. (insert "\n"))
  11146. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11147. ((eq (car e) :endgroup)
  11148. (setq ingroup nil cnt 0)
  11149. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11150. ((eq (car e) :startgrouptag)
  11151. (setq intaggroup t)
  11152. (unless (zerop cnt)
  11153. (setq cnt 0)
  11154. (insert "\n"))
  11155. (insert "[ "))
  11156. ((eq (car e) :endgrouptag)
  11157. (setq intaggroup nil cnt 0)
  11158. (insert "]\n"))
  11159. ((equal e '(:newline))
  11160. (unless (zerop cnt)
  11161. (setq cnt 0)
  11162. (insert "\n")
  11163. (setq e (car tbl))
  11164. (while (equal (car tbl) '(:newline))
  11165. (insert "\n")
  11166. (setq tbl (cdr tbl)))))
  11167. ((equal e '(:grouptags)) (insert " : "))
  11168. (t
  11169. (setq tg (copy-sequence (car e)) c2 nil)
  11170. (if (cdr e)
  11171. (setq c (cdr e))
  11172. ;; automatically assign a character.
  11173. (setq c1 (string-to-char
  11174. (downcase (substring
  11175. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11176. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11177. (while (or (rassoc char ntable) (rassoc char table))
  11178. (setq char (1+ char)))
  11179. (setq c2 c1))
  11180. (setq c (or c2 char)))
  11181. (when ingroup (push tg (car groups)))
  11182. (setq tg (org-add-props tg nil 'face
  11183. (cond
  11184. ((not (assoc tg table))
  11185. (org-get-todo-face tg))
  11186. ((member tg current) c-face)
  11187. ((member tg inherited) i-face))))
  11188. (when (equal (caar tbl) :grouptags)
  11189. (org-add-props tg nil 'face 'org-tag-group))
  11190. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11191. (insert "[" c "] " tg (make-string
  11192. (- fwidth 4 (length tg)) ?\ ))
  11193. (push (cons tg c) ntable)
  11194. (when (= (cl-incf cnt) ncol)
  11195. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11196. (insert "\n")
  11197. (when (or ingroup intaggroup) (insert " ")))
  11198. (setq cnt 0)))))
  11199. (setq ntable (nreverse ntable))
  11200. (insert "\n")
  11201. (goto-char (point-min))
  11202. (unless expert (org-fit-window-to-buffer))
  11203. (setq rtn
  11204. (catch 'exit
  11205. (while t
  11206. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11207. (if (not groups) "no " "")
  11208. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11209. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11210. (setq org-last-tag-selection-key c)
  11211. (cond
  11212. ((= c ?\r) (throw 'exit t))
  11213. ((= c ?!)
  11214. (setq groups (not groups))
  11215. (goto-char (point-min))
  11216. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11217. ((= c ?\C-c)
  11218. (if (not expert)
  11219. (org-fast-tag-show-exit
  11220. (setq exit-after-next (not exit-after-next)))
  11221. (setq expert nil)
  11222. (delete-other-windows)
  11223. (set-window-buffer (split-window-vertically) " *Org tags*")
  11224. (org-switch-to-buffer-other-window " *Org tags*")
  11225. (org-fit-window-to-buffer)))
  11226. ((or (= c ?\C-g)
  11227. (and (= c ?q) (not (rassoc c ntable))))
  11228. (delete-overlay org-tags-overlay)
  11229. (setq quit-flag t))
  11230. ((= c ?\ )
  11231. (setq current nil)
  11232. (when exit-after-next (setq exit-after-next 'now)))
  11233. ((= c ?\t)
  11234. (condition-case nil
  11235. (unless tab-tags
  11236. (setq tab-tags
  11237. (delq nil
  11238. (mapcar (lambda (x)
  11239. (let ((item (car-safe x)))
  11240. (and (stringp item)
  11241. (list item))))
  11242. (org--tag-add-to-alist
  11243. (with-current-buffer buf
  11244. (org-get-buffer-tags))
  11245. table))))))
  11246. (setq tg (completing-read "Tag: " tab-tags))
  11247. (when (string-match "\\S-" tg)
  11248. (cl-pushnew (list tg) tab-tags :test #'equal)
  11249. (if (member tg current)
  11250. (setq current (delete tg current))
  11251. (push tg current)))
  11252. (when exit-after-next (setq exit-after-next 'now)))
  11253. ((setq e (rassoc c todo-table) tg (car e))
  11254. (with-current-buffer buf
  11255. (save-excursion (org-todo tg)))
  11256. (when exit-after-next (setq exit-after-next 'now)))
  11257. ((setq e (rassoc c ntable) tg (car e))
  11258. (if (member tg current)
  11259. (setq current (delete tg current))
  11260. (cl-loop for g in groups do
  11261. (when (member tg g)
  11262. (dolist (x g) (setq current (delete x current)))))
  11263. (push tg current))
  11264. (when exit-after-next (setq exit-after-next 'now))))
  11265. ;; Create a sorted list
  11266. (setq current
  11267. (sort current
  11268. (lambda (a b)
  11269. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11270. (when (eq exit-after-next 'now) (throw 'exit t))
  11271. (goto-char (point-min))
  11272. (beginning-of-line 2)
  11273. (delete-region (point) (point-at-eol))
  11274. (org-fast-tag-insert "Current" current c-face)
  11275. (org-set-current-tags-overlay current ov-prefix)
  11276. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11277. (while (re-search-forward tag-re nil t)
  11278. (let ((tag (match-string 1)))
  11279. (add-text-properties
  11280. (match-beginning 1) (match-end 1)
  11281. (list 'face
  11282. (cond
  11283. ((member tag current) c-face)
  11284. ((member tag inherited) i-face)
  11285. (t (get-text-property (match-beginning 1) '
  11286. face))))))))
  11287. (goto-char (point-min)))))
  11288. (delete-overlay org-tags-overlay)
  11289. (if rtn
  11290. (mapconcat 'identity current ":")
  11291. nil)))))
  11292. (defun org-make-tag-string (tags)
  11293. "Return string associated to TAGS.
  11294. TAGS is a list of strings."
  11295. (if (null tags) ""
  11296. (format ":%s:" (mapconcat #'identity tags ":"))))
  11297. (defun org--get-local-tags ()
  11298. "Return list of tags for the current headline.
  11299. Assume point is at the beginning of the headline."
  11300. (and (looking-at org-tag-line-re)
  11301. (split-string (match-string-no-properties 2) ":" t)))
  11302. (defun org-get-tags (&optional pos local)
  11303. "Get the list of tags specified in the current headline.
  11304. When argument POS is non-nil, retrieve tags for headline at POS.
  11305. According to `org-use-tag-inheritance', tags may be inherited
  11306. from parent headlines, and from the whole document, through
  11307. `org-file-tags'. In this case, the returned list of tags
  11308. contains tags in this order: file tags, tags inherited from
  11309. parent headlines, local tags. If a tag appears multiple times,
  11310. only the most local tag is returned.
  11311. However, when optional argument LOCAL is non-nil, only return
  11312. tags specified at the headline.
  11313. Inherited tags have the `inherited' text property."
  11314. (if (and org-trust-scanner-tags
  11315. (or (not pos) (eq pos (point)))
  11316. (not local))
  11317. org-scanner-tags
  11318. (org-with-point-at (or pos (point))
  11319. (unless (org-before-first-heading-p)
  11320. (org-back-to-heading t)
  11321. (let ((ltags (org--get-local-tags)) itags)
  11322. (if (or local (not org-use-tag-inheritance)) ltags
  11323. (while (org-up-heading-safe)
  11324. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11325. (org--get-local-tags))
  11326. itags)))
  11327. (setq itags (append org-file-tags itags))
  11328. (nreverse
  11329. (delete-dups
  11330. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11331. (defun org-get-buffer-tags ()
  11332. "Get a table of all tags used in the buffer, for completion."
  11333. (org-with-point-at 1
  11334. (let (tags)
  11335. (while (re-search-forward org-tag-line-re nil t)
  11336. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11337. tags)))
  11338. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11339. ;;;; The mapping API
  11340. (defvar org-agenda-skip-comment-trees)
  11341. (defvar org-agenda-skip-function)
  11342. (defun org-map-entries (func &optional match scope &rest skip)
  11343. "Call FUNC at each headline selected by MATCH in SCOPE.
  11344. FUNC is a function or a Lisp form. The function will be called without
  11345. arguments, with the cursor positioned at the beginning of the headline.
  11346. The return values of all calls to the function will be collected and
  11347. returned as a list.
  11348. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  11349. does not need to preserve point. After evaluation, the cursor will be
  11350. moved to the end of the line (presumably of the headline of the
  11351. processed entry) and search continues from there. Under some
  11352. circumstances, this may not produce the wanted results. For example,
  11353. if you have removed (e.g. archived) the current (sub)tree it could
  11354. mean that the next entry will be skipped entirely. In such cases, you
  11355. can specify the position from where search should continue by making
  11356. FUNC set the variable `org-map-continue-from' to the desired buffer
  11357. position.
  11358. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11359. Only headlines that are matched by this query will be considered during
  11360. the iteration. When MATCH is nil or t, all headlines will be
  11361. visited by the iteration.
  11362. SCOPE determines the scope of this command. It can be any of:
  11363. nil The current buffer, respecting the restriction if any
  11364. tree The subtree started with the entry at point
  11365. region The entries within the active region, if any
  11366. region-start-level
  11367. The entries within the active region, but only those at
  11368. the same level than the first one.
  11369. file The current buffer, without restriction
  11370. file-with-archives
  11371. The current buffer, and any archives associated with it
  11372. agenda All agenda files
  11373. agenda-with-archives
  11374. All agenda files with any archive files associated with them
  11375. \(file1 file2 ...)
  11376. If this is a list, all files in the list will be scanned
  11377. The remaining args are treated as settings for the skipping facilities of
  11378. the scanner. The following items can be given here:
  11379. archive skip trees with the archive tag
  11380. comment skip trees with the COMMENT keyword
  11381. function or Emacs Lisp form:
  11382. will be used as value for `org-agenda-skip-function', so
  11383. whenever the function returns a position, FUNC will not be
  11384. called for that entry and search will continue from the
  11385. position returned
  11386. If your function needs to retrieve the tags including inherited tags
  11387. at the *current* entry, you can use the value of the variable
  11388. `org-scanner-tags' which will be much faster than getting the value
  11389. with `org-get-tags'. If your function gets properties with
  11390. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11391. to t around the call to `org-entry-properties' to get the same speedup.
  11392. Note that if your function moves around to retrieve tags and properties at
  11393. a *different* entry, you cannot use these techniques."
  11394. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11395. (not (org-region-active-p)))
  11396. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11397. (org-agenda-skip-archived-trees (memq 'archive skip))
  11398. (org-agenda-skip-comment-trees (memq 'comment skip))
  11399. (org-agenda-skip-function
  11400. (car (org-delete-all '(comment archive) skip)))
  11401. (org-tags-match-list-sublevels t)
  11402. (start-level (eq scope 'region-start-level))
  11403. matcher res
  11404. org-todo-keywords-for-agenda
  11405. org-done-keywords-for-agenda
  11406. org-todo-keyword-alist-for-agenda
  11407. org-tag-alist-for-agenda
  11408. org--matcher-tags-todo-only)
  11409. (cond
  11410. ((eq match t) (setq matcher t))
  11411. ((eq match nil) (setq matcher t))
  11412. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11413. (save-excursion
  11414. (save-restriction
  11415. (cond ((eq scope 'tree)
  11416. (org-back-to-heading t)
  11417. (org-narrow-to-subtree)
  11418. (setq scope nil))
  11419. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11420. (org-region-active-p))
  11421. ;; If needed, set start-level to a string like "2"
  11422. (when start-level
  11423. (save-excursion
  11424. (goto-char (region-beginning))
  11425. (unless (org-at-heading-p) (outline-next-heading))
  11426. (setq start-level (org-current-level))))
  11427. (narrow-to-region (region-beginning)
  11428. (save-excursion
  11429. (goto-char (region-end))
  11430. (unless (and (bolp) (org-at-heading-p))
  11431. (outline-next-heading))
  11432. (point)))
  11433. (setq scope nil)))
  11434. (if (not scope)
  11435. (progn
  11436. (org-agenda-prepare-buffers
  11437. (and buffer-file-name (list buffer-file-name)))
  11438. (setq res
  11439. (org-scan-tags
  11440. func matcher org--matcher-tags-todo-only start-level)))
  11441. ;; Get the right scope
  11442. (cond
  11443. ((and scope (listp scope) (symbolp (car scope)))
  11444. (setq scope (eval scope)))
  11445. ((eq scope 'agenda)
  11446. (setq scope (org-agenda-files t)))
  11447. ((eq scope 'agenda-with-archives)
  11448. (setq scope (org-agenda-files t))
  11449. (setq scope (org-add-archive-files scope)))
  11450. ((eq scope 'file)
  11451. (setq scope (and buffer-file-name (list buffer-file-name))))
  11452. ((eq scope 'file-with-archives)
  11453. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11454. (org-agenda-prepare-buffers scope)
  11455. (dolist (file scope)
  11456. (with-current-buffer (org-find-base-buffer-visiting file)
  11457. (org-with-wide-buffer
  11458. (goto-char (point-min))
  11459. (setq res
  11460. (append
  11461. res
  11462. (org-scan-tags
  11463. func matcher org--matcher-tags-todo-only)))))))))
  11464. res)))
  11465. ;;; Properties API
  11466. (defconst org-special-properties
  11467. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11468. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11469. "The special properties valid in Org mode.
  11470. These are properties that are not defined in the property drawer,
  11471. but in some other way.")
  11472. (defconst org-default-properties
  11473. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11474. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11475. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11476. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11477. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11478. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11479. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11480. "Some properties that are used by Org mode for various purposes.
  11481. Being in this list makes sure that they are offered for completion.")
  11482. (defun org--valid-property-p (property)
  11483. "Non-nil when string PROPERTY is a valid property name."
  11484. (not
  11485. (or (equal property "")
  11486. (string-match-p "\\s-" property))))
  11487. (defun org--update-property-plist (key val props)
  11488. "Associate KEY to VAL in alist PROPS.
  11489. Modifications are made by side-effect. Return new alist."
  11490. (let* ((appending (string= (substring key -1) "+"))
  11491. (key (if appending (substring key 0 -1) key))
  11492. (old (assoc-string key props t)))
  11493. (if (not old) (cons (cons key val) props)
  11494. (setcdr old (if appending (concat (cdr old) " " val) val))
  11495. props)))
  11496. (defun org-get-property-block (&optional beg force)
  11497. "Return the (beg . end) range of the body of the property drawer.
  11498. BEG is the beginning of the current subtree or the beginning of
  11499. the document if before the first headline. If it is not given,
  11500. it will be found. If the drawer does not exist, create it if
  11501. FORCE is non-nil, or return nil."
  11502. (org-with-wide-buffer
  11503. (let ((beg (cond (beg (goto-char beg))
  11504. ((or (not (featurep 'org-inlinetask))
  11505. (org-inlinetask-in-task-p))
  11506. (org-back-to-heading-or-point-min t) (point))
  11507. (t (org-with-limited-levels
  11508. (org-back-to-heading-or-point-min t))
  11509. (point)))))
  11510. ;; Move point to its position according to its positional rules.
  11511. (cond ((org-before-first-heading-p)
  11512. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11513. (t (forward-line)
  11514. (when (looking-at-p org-planning-line-re) (forward-line))))
  11515. (cond ((looking-at org-property-drawer-re)
  11516. (forward-line)
  11517. (cons (point) (progn (goto-char (match-end 0))
  11518. (line-beginning-position))))
  11519. (force
  11520. (goto-char beg)
  11521. (org-insert-property-drawer)
  11522. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11523. (line-beginning-position))))
  11524. (cons pos pos)))))))
  11525. (defun org-at-property-drawer-p ()
  11526. "Non-nil when point is at the first line of a property drawer."
  11527. (org-with-wide-buffer
  11528. (beginning-of-line)
  11529. (and (looking-at org-property-drawer-re)
  11530. (or (bobp)
  11531. (progn
  11532. (forward-line -1)
  11533. (cond ((org-at-heading-p))
  11534. ((looking-at org-planning-line-re)
  11535. (forward-line -1)
  11536. (org-at-heading-p))
  11537. ((looking-at org-comment-regexp)
  11538. (forward-line -1)
  11539. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11540. (forward-line -1))
  11541. (looking-at org-comment-regexp))
  11542. (t nil)))))))
  11543. (defun org-at-property-p ()
  11544. "Non-nil when point is inside a property drawer.
  11545. See `org-property-re' for match data, if applicable."
  11546. (save-excursion
  11547. (beginning-of-line)
  11548. (and (looking-at org-property-re)
  11549. (let ((property-drawer (save-match-data (org-get-property-block))))
  11550. (and property-drawer
  11551. (>= (point) (car property-drawer))
  11552. (< (point) (cdr property-drawer)))))))
  11553. (defun org-property-action ()
  11554. "Do an action on properties."
  11555. (interactive)
  11556. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11557. (let ((c (read-char-exclusive)))
  11558. (cl-case c
  11559. (?s (call-interactively #'org-set-property))
  11560. (?d (call-interactively #'org-delete-property))
  11561. (?D (call-interactively #'org-delete-property-globally))
  11562. (?c (call-interactively #'org-compute-property-at-point))
  11563. (otherwise (user-error "No such property action %c" c)))))
  11564. (defun org-inc-effort ()
  11565. "Increment the value of the effort property in the current entry."
  11566. (interactive)
  11567. (org-set-effort t))
  11568. (defvar org-clock-effort) ; Defined in org-clock.el.
  11569. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11570. (defun org-set-effort (&optional increment value)
  11571. "Set the effort property of the current entry.
  11572. If INCREMENT is non-nil, set the property to the next allowed
  11573. value. Otherwise, if optional argument VALUE is provided, use
  11574. it. Eventually, prompt for the new value if none of the previous
  11575. variables is set."
  11576. (interactive "P")
  11577. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11578. (current (org-entry-get nil org-effort-property))
  11579. (value
  11580. (cond
  11581. (increment
  11582. (unless allowed (user-error "Allowed effort values are not set"))
  11583. (or (cl-caadr (member (list current) allowed))
  11584. (user-error "Unknown value %S among allowed values" current)))
  11585. (value
  11586. (if (stringp value) value
  11587. (error "Invalid effort value: %S" value)))
  11588. (t
  11589. (let ((must-match
  11590. (and allowed
  11591. (not (get-text-property 0 'org-unrestricted
  11592. (caar allowed))))))
  11593. (completing-read "Effort: " allowed nil must-match))))))
  11594. ;; Test whether the value can be interpreted as a duration before
  11595. ;; inserting it in the buffer:
  11596. (org-duration-to-minutes value)
  11597. ;; Maybe update the effort value:
  11598. (unless (equal current value)
  11599. (org-entry-put nil org-effort-property value))
  11600. (org-refresh-property '((effort . identity)
  11601. (effort-minutes . org-duration-to-minutes))
  11602. value)
  11603. (when (equal (org-get-heading t t t t)
  11604. (bound-and-true-p org-clock-current-task))
  11605. (setq org-clock-effort value)
  11606. (org-clock-update-mode-line))
  11607. (message "%s is now %s" org-effort-property value)))
  11608. (defun org-entry-properties (&optional pom which)
  11609. "Get all properties of the current entry.
  11610. When POM is a buffer position, get all properties from the entry
  11611. there instead.
  11612. This includes the TODO keyword, the tags, time strings for
  11613. deadline, scheduled, and clocking, and any additional properties
  11614. defined in the entry.
  11615. If WHICH is nil or `all', get all properties. If WHICH is
  11616. `special' or `standard', only get that subclass. If WHICH is
  11617. a string, only get that property.
  11618. Return value is an alist. Keys are properties, as upcased
  11619. strings."
  11620. (org-with-point-at pom
  11621. (when (and (derived-mode-p 'org-mode)
  11622. (org-back-to-heading-or-point-min t))
  11623. (catch 'exit
  11624. (let* ((beg (point))
  11625. (specific (and (stringp which) (upcase which)))
  11626. (which (cond ((not specific) which)
  11627. ((member specific org-special-properties) 'special)
  11628. (t 'standard)))
  11629. props)
  11630. ;; Get the special properties, like TODO and TAGS.
  11631. (when (memq which '(nil all special))
  11632. (when (or (not specific) (string= specific "CLOCKSUM"))
  11633. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11634. (when clocksum
  11635. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11636. props)))
  11637. (when specific (throw 'exit props)))
  11638. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11639. (let ((clocksumt (get-text-property (point)
  11640. :org-clock-minutes-today)))
  11641. (when clocksumt
  11642. (push (cons "CLOCKSUM_T"
  11643. (org-duration-from-minutes clocksumt))
  11644. props)))
  11645. (when specific (throw 'exit props)))
  11646. (when (or (not specific) (string= specific "ITEM"))
  11647. (let ((case-fold-search nil))
  11648. (when (looking-at org-complex-heading-regexp)
  11649. (push (cons "ITEM"
  11650. (let ((title (match-string-no-properties 4)))
  11651. (if (org-string-nw-p title)
  11652. (org-remove-tabs title)
  11653. "")))
  11654. props)))
  11655. (when specific (throw 'exit props)))
  11656. (when (or (not specific) (string= specific "TODO"))
  11657. (let ((case-fold-search nil))
  11658. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11659. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11660. (when specific (throw 'exit props)))
  11661. (when (or (not specific) (string= specific "PRIORITY"))
  11662. (push (cons "PRIORITY"
  11663. (if (looking-at org-priority-regexp)
  11664. (match-string-no-properties 2)
  11665. (char-to-string org-priority-default)))
  11666. props)
  11667. (when specific (throw 'exit props)))
  11668. (when (or (not specific) (string= specific "FILE"))
  11669. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11670. props)
  11671. (when specific (throw 'exit props)))
  11672. (when (or (not specific) (string= specific "TAGS"))
  11673. (let ((tags (org-get-tags nil t)))
  11674. (when tags
  11675. (push (cons "TAGS" (org-make-tag-string tags))
  11676. props)))
  11677. (when specific (throw 'exit props)))
  11678. (when (or (not specific) (string= specific "ALLTAGS"))
  11679. (let ((tags (org-get-tags)))
  11680. (when tags
  11681. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11682. props)))
  11683. (when specific (throw 'exit props)))
  11684. (when (or (not specific) (string= specific "BLOCKED"))
  11685. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11686. (when specific (throw 'exit props)))
  11687. (when (or (not specific)
  11688. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11689. (forward-line)
  11690. (when (looking-at-p org-planning-line-re)
  11691. (end-of-line)
  11692. (let ((bol (line-beginning-position))
  11693. ;; Backward compatibility: time keywords used to
  11694. ;; be configurable (before 8.3). Make sure we
  11695. ;; get the correct keyword.
  11696. (key-assoc `(("CLOSED" . ,org-closed-string)
  11697. ("DEADLINE" . ,org-deadline-string)
  11698. ("SCHEDULED" . ,org-scheduled-string))))
  11699. (dolist (pair (if specific (list (assoc specific key-assoc))
  11700. key-assoc))
  11701. (save-excursion
  11702. (when (search-backward (cdr pair) bol t)
  11703. (goto-char (match-end 0))
  11704. (skip-chars-forward " \t")
  11705. (and (looking-at org-ts-regexp-both)
  11706. (push (cons (car pair)
  11707. (match-string-no-properties 0))
  11708. props)))))))
  11709. (when specific (throw 'exit props)))
  11710. (when (or (not specific)
  11711. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11712. (let ((find-ts
  11713. (lambda (end ts)
  11714. ;; Fix next time-stamp before END. TS is the
  11715. ;; list of time-stamps found so far.
  11716. (let ((ts ts)
  11717. (regexp (cond
  11718. ((string= specific "TIMESTAMP")
  11719. org-ts-regexp)
  11720. ((string= specific "TIMESTAMP_IA")
  11721. org-ts-regexp-inactive)
  11722. ((assoc "TIMESTAMP_IA" ts)
  11723. org-ts-regexp)
  11724. ((assoc "TIMESTAMP" ts)
  11725. org-ts-regexp-inactive)
  11726. (t org-ts-regexp-both))))
  11727. (catch 'next
  11728. (while (re-search-forward regexp end t)
  11729. (backward-char)
  11730. (let ((object (org-element-context)))
  11731. ;; Accept to match timestamps in node
  11732. ;; properties, too.
  11733. (when (memq (org-element-type object)
  11734. '(node-property timestamp))
  11735. (let ((type
  11736. (org-element-property :type object)))
  11737. (cond
  11738. ((and (memq type '(active active-range))
  11739. (not (equal specific "TIMESTAMP_IA")))
  11740. (unless (assoc "TIMESTAMP" ts)
  11741. (push (cons "TIMESTAMP"
  11742. (org-element-property
  11743. :raw-value object))
  11744. ts)
  11745. (when specific (throw 'exit ts))))
  11746. ((and (memq type '(inactive inactive-range))
  11747. (not (string= specific "TIMESTAMP")))
  11748. (unless (assoc "TIMESTAMP_IA" ts)
  11749. (push (cons "TIMESTAMP_IA"
  11750. (org-element-property
  11751. :raw-value object))
  11752. ts)
  11753. (when specific (throw 'exit ts))))))
  11754. ;; Both timestamp types are found,
  11755. ;; move to next part.
  11756. (when (= (length ts) 2) (throw 'next ts)))))
  11757. ts)))))
  11758. (goto-char beg)
  11759. ;; First look for timestamps within headline.
  11760. (let ((ts (funcall find-ts (line-end-position) nil)))
  11761. (if (= (length ts) 2) (setq props (nconc ts props))
  11762. ;; Then find timestamps in the section, skipping
  11763. ;; planning line.
  11764. (let ((end (save-excursion (outline-next-heading))))
  11765. (forward-line)
  11766. (when (looking-at-p org-planning-line-re) (forward-line))
  11767. (setq props (nconc (funcall find-ts end ts) props))))))))
  11768. ;; Get the standard properties, like :PROP:.
  11769. (when (memq which '(nil all standard))
  11770. ;; If we are looking after a specific property, delegate
  11771. ;; to `org-entry-get', which is faster. However, make an
  11772. ;; exception for "CATEGORY", since it can be also set
  11773. ;; through keywords (i.e. #+CATEGORY).
  11774. (if (and specific (not (equal specific "CATEGORY")))
  11775. (let ((value (org-entry-get beg specific nil t)))
  11776. (throw 'exit (and value (list (cons specific value)))))
  11777. (let ((range (org-get-property-block beg)))
  11778. (when range
  11779. (let ((end (cdr range)) seen-base)
  11780. (goto-char (car range))
  11781. ;; Unlike to `org--update-property-plist', we
  11782. ;; handle the case where base values is found
  11783. ;; after its extension. We also forbid standard
  11784. ;; properties to be named as special properties.
  11785. (while (re-search-forward org-property-re end t)
  11786. (let* ((key (upcase (match-string-no-properties 2)))
  11787. (extendp (string-match-p "\\+\\'" key))
  11788. (key-base (if extendp (substring key 0 -1) key))
  11789. (value (match-string-no-properties 3)))
  11790. (cond
  11791. ((member-ignore-case key-base org-special-properties))
  11792. (extendp
  11793. (setq props
  11794. (org--update-property-plist key value props)))
  11795. ((member key seen-base))
  11796. (t (push key seen-base)
  11797. (let ((p (assoc-string key props t)))
  11798. (if p (setcdr p (concat value " " (cdr p)))
  11799. (push (cons key value) props))))))))))))
  11800. (unless (assoc "CATEGORY" props)
  11801. (push (cons "CATEGORY" (org-get-category beg)) props)
  11802. (when (string= specific "CATEGORY") (throw 'exit props)))
  11803. ;; Return value.
  11804. props)))))
  11805. (defun org--property-local-values (property literal-nil)
  11806. "Return value for PROPERTY in current entry.
  11807. Value is a list whose car is the base value for PROPERTY and cdr
  11808. a list of accumulated values. Return nil if neither is found in
  11809. the entry. Also return nil when PROPERTY is set to \"nil\",
  11810. unless LITERAL-NIL is non-nil."
  11811. (let ((range (org-get-property-block)))
  11812. (when range
  11813. (goto-char (car range))
  11814. (let* ((case-fold-search t)
  11815. (end (cdr range))
  11816. (value
  11817. ;; Base value.
  11818. (save-excursion
  11819. (let ((v (and (re-search-forward
  11820. (org-re-property property nil t) end t)
  11821. (match-string-no-properties 3))))
  11822. (list (if literal-nil v (org-not-nil v)))))))
  11823. ;; Find additional values.
  11824. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11825. (while (re-search-forward property+ end t)
  11826. (push (match-string-no-properties 3) value)))
  11827. ;; Return final values.
  11828. (and (not (equal value '(nil))) (nreverse value))))))
  11829. (defun org--property-global-or-keyword-value (property literal-nil)
  11830. "Return value for PROPERTY as defined by global properties or by keyword.
  11831. Return value is a string. Return nil if property is not set
  11832. globally or by keyword. Also return nil when PROPERTY is set to
  11833. \"nil\", unless LITERAL-NIL is non-nil."
  11834. (let ((global
  11835. (cdr (or (assoc-string property org-keyword-properties t)
  11836. (assoc-string property org-global-properties t)
  11837. (assoc-string property org-global-properties-fixed t)))))
  11838. (if literal-nil global (org-not-nil global))))
  11839. (defun org-entry-get (pom property &optional inherit literal-nil)
  11840. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11841. If INHERIT is non-nil and the entry does not have the property,
  11842. then also check higher levels of the hierarchy. If INHERIT is
  11843. the symbol `selective', use inheritance only if the setting in
  11844. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11845. If the property is present but empty, the return value is the
  11846. empty string. If the property is not present at all, nil is
  11847. returned. In any other case, return the value as a string.
  11848. Search is case-insensitive.
  11849. If LITERAL-NIL is set, return the string value \"nil\" as
  11850. a string, do not interpret it as the list atom nil. This is used
  11851. for inheritance when a \"nil\" value can supersede a non-nil
  11852. value higher up the hierarchy."
  11853. (org-with-point-at pom
  11854. (cond
  11855. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11856. ;; We need a special property. Use `org-entry-properties' to
  11857. ;; retrieve it, but specify the wanted property.
  11858. (cdr (assoc-string property (org-entry-properties nil property))))
  11859. ((and inherit
  11860. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11861. (org-entry-get-with-inheritance property literal-nil))
  11862. (t
  11863. (let* ((local (org--property-local-values property literal-nil))
  11864. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11865. (if literal-nil value (org-not-nil value)))))))
  11866. (defun org-property-or-variable-value (var &optional inherit)
  11867. "Check if there is a property fixing the value of VAR.
  11868. If yes, return this value. If not, return the current value of the variable."
  11869. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11870. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11871. (read prop)
  11872. (symbol-value var))))
  11873. (defun org-entry-delete (pom property)
  11874. "Delete PROPERTY from entry at point-or-marker POM.
  11875. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11876. non-nil when a property was removed."
  11877. (org-with-point-at pom
  11878. (pcase (org-get-property-block)
  11879. (`(,begin . ,origin)
  11880. (let* ((end (copy-marker origin))
  11881. (re (org-re-property
  11882. (concat (regexp-quote property) "\\+?") t t)))
  11883. (goto-char begin)
  11884. (while (re-search-forward re end t)
  11885. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11886. ;; If drawer is empty, remove it altogether.
  11887. (when (= begin end)
  11888. (delete-region (line-beginning-position 0)
  11889. (line-beginning-position 2)))
  11890. ;; Return non-nil if some property was removed.
  11891. (prog1 (/= end origin) (set-marker end nil))))
  11892. (_ nil))))
  11893. ;; Multi-values properties are properties that contain multiple values
  11894. ;; These values are assumed to be single words, separated by whitespace.
  11895. (defun org-entry-add-to-multivalued-property (pom property value)
  11896. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11897. (let* ((old (org-entry-get pom property))
  11898. (values (and old (split-string old))))
  11899. (setq value (org-entry-protect-space value))
  11900. (unless (member value values)
  11901. (setq values (append values (list value)))
  11902. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11903. (defun org-entry-remove-from-multivalued-property (pom property value)
  11904. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11905. (let* ((old (org-entry-get pom property))
  11906. (values (and old (split-string old))))
  11907. (setq value (org-entry-protect-space value))
  11908. (when (member value values)
  11909. (setq values (delete value values))
  11910. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11911. (defun org-entry-member-in-multivalued-property (pom property value)
  11912. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11913. (let* ((old (org-entry-get pom property))
  11914. (values (and old (split-string old))))
  11915. (setq value (org-entry-protect-space value))
  11916. (member value values)))
  11917. (defun org-entry-get-multivalued-property (pom property)
  11918. "Return a list of values in a multivalued property."
  11919. (let* ((value (org-entry-get pom property))
  11920. (values (and value (split-string value))))
  11921. (mapcar #'org-entry-restore-space values)))
  11922. (defun org-entry-put-multivalued-property (pom property &rest values)
  11923. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11924. VALUES should be a list of strings. Spaces will be protected."
  11925. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11926. (let* ((value (org-entry-get pom property))
  11927. (values (and value (split-string value))))
  11928. (mapcar #'org-entry-restore-space values)))
  11929. (defun org-entry-protect-space (s)
  11930. "Protect spaces and newline in string S."
  11931. (while (string-match " " s)
  11932. (setq s (replace-match "%20" t t s)))
  11933. (while (string-match "\n" s)
  11934. (setq s (replace-match "%0A" t t s)))
  11935. s)
  11936. (defun org-entry-restore-space (s)
  11937. "Restore spaces and newline in string S."
  11938. (while (string-match "%20" s)
  11939. (setq s (replace-match " " t t s)))
  11940. (while (string-match "%0A" s)
  11941. (setq s (replace-match "\n" t t s)))
  11942. s)
  11943. (defvar org-entry-property-inherited-from (make-marker)
  11944. "Marker pointing to the entry from where a property was inherited.
  11945. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11946. location of the entry where the inheritance search matched. If there was
  11947. no match, the marker will point nowhere.
  11948. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11949. is set.")
  11950. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11951. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11952. The search will stop at the first ancestor which has the property defined.
  11953. If the value found is \"nil\", return nil to show that the property
  11954. should be considered as undefined (this is the meaning of nil here).
  11955. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11956. (move-marker org-entry-property-inherited-from nil)
  11957. (org-with-wide-buffer
  11958. (let (value)
  11959. (catch 'exit
  11960. (while t
  11961. (let ((v (org--property-local-values property literal-nil)))
  11962. (when v
  11963. (setq value
  11964. (concat (mapconcat #'identity (delq nil v) " ")
  11965. (and value " ")
  11966. value)))
  11967. (cond
  11968. ((car v)
  11969. (org-back-to-heading-or-point-min t)
  11970. (move-marker org-entry-property-inherited-from (point))
  11971. (throw 'exit nil))
  11972. ((org-up-heading-or-point-min))
  11973. (t
  11974. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11975. (cond ((not global))
  11976. (value (setq value (concat global " " value)))
  11977. (t (setq value global))))
  11978. (throw 'exit nil))))))
  11979. (if literal-nil value (org-not-nil value)))))
  11980. (defvar org-property-changed-functions nil
  11981. "Hook called when the value of a property has changed.
  11982. Each hook function should accept two arguments, the name of the property
  11983. and the new value.")
  11984. (defun org-entry-put (pom property value)
  11985. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11986. If the value is nil, it is converted to the empty string. If it
  11987. is not a string, an error is raised. Also raise an error on
  11988. invalid property names.
  11989. PROPERTY can be any regular property (see
  11990. `org-special-properties'). It can also be \"TODO\",
  11991. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11992. For the last two properties, VALUE may have any of the special
  11993. values \"earlier\" and \"later\". The function then increases or
  11994. decreases scheduled or deadline date by one day."
  11995. (cond ((null value) (setq value ""))
  11996. ((not (stringp value)) (error "Properties values should be strings"))
  11997. ((not (org--valid-property-p property))
  11998. (user-error "Invalid property name: \"%s\"" property)))
  11999. (org-no-read-only
  12000. (org-with-point-at pom
  12001. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12002. (org-back-to-heading-or-point-min t)
  12003. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12004. (let ((beg (point)))
  12005. (cond
  12006. ((equal property "TODO")
  12007. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12008. ((not (member value org-todo-keywords-1))
  12009. (user-error "\"%s\" is not a valid TODO state" value)))
  12010. (org-todo value)
  12011. (org-align-tags))
  12012. ((equal property "PRIORITY")
  12013. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12014. (org-align-tags))
  12015. ((equal property "SCHEDULED")
  12016. (forward-line)
  12017. (if (and (looking-at-p org-planning-line-re)
  12018. (re-search-forward
  12019. org-scheduled-time-regexp (line-end-position) t))
  12020. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12021. ((string= value "later") (org-timestamp-change 1 'day))
  12022. ((string= value "") (org-schedule '(4)))
  12023. (t (org-schedule nil value)))
  12024. (if (member value '("earlier" "later" ""))
  12025. (call-interactively #'org-schedule)
  12026. (org-schedule nil value))))
  12027. ((equal property "DEADLINE")
  12028. (forward-line)
  12029. (if (and (looking-at-p org-planning-line-re)
  12030. (re-search-forward
  12031. org-deadline-time-regexp (line-end-position) t))
  12032. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12033. ((string= value "later") (org-timestamp-change 1 'day))
  12034. ((string= value "") (org-deadline '(4)))
  12035. (t (org-deadline nil value)))
  12036. (if (member value '("earlier" "later" ""))
  12037. (call-interactively #'org-deadline)
  12038. (org-deadline nil value))))
  12039. ((member property org-special-properties)
  12040. (error "The %s property cannot be set with `org-entry-put'" property))
  12041. (t
  12042. (let* ((range (org-get-property-block beg 'force))
  12043. (end (cdr range))
  12044. (case-fold-search t))
  12045. (goto-char (car range))
  12046. (if (re-search-forward (org-re-property property nil t) end t)
  12047. (progn (delete-region (match-beginning 0) (match-end 0))
  12048. (goto-char (match-beginning 0)))
  12049. (goto-char end)
  12050. (insert "\n")
  12051. (backward-char))
  12052. (insert ":" property ":")
  12053. (when value (insert " " value))
  12054. (org-indent-line)))))
  12055. (run-hook-with-args 'org-property-changed-functions property value))))
  12056. (defun org-buffer-property-keys (&optional specials defaults columns)
  12057. "Get all property keys in the current buffer.
  12058. When SPECIALS is non-nil, also list the special properties that
  12059. reflect things like tags and TODO state.
  12060. When DEFAULTS is non-nil, also include properties that has
  12061. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12062. DESCRIPTION, LOCATION, and LOGGING and others.
  12063. When COLUMNS in non-nil, also include property names given in
  12064. COLUMN formats in the current buffer."
  12065. (let ((case-fold-search t)
  12066. (props (append
  12067. (and specials org-special-properties)
  12068. (and defaults (cons org-effort-property org-default-properties))
  12069. ;; Get property names from #+PROPERTY keywords as well
  12070. (mapcar (lambda (s)
  12071. (nth 0 (split-string s)))
  12072. (cdar (org-collect-keywords '("PROPERTY")))))))
  12073. (org-with-wide-buffer
  12074. (goto-char (point-min))
  12075. (while (re-search-forward org-property-start-re nil t)
  12076. (catch :skip
  12077. (let ((range (org-get-property-block)))
  12078. (unless range (throw :skip nil))
  12079. (goto-char (car range))
  12080. (let ((begin (car range))
  12081. (end (cdr range)))
  12082. ;; Make sure that found property block is not located
  12083. ;; before current point, as it would generate an infloop.
  12084. ;; It can happen, for example, in the following
  12085. ;; situation:
  12086. ;;
  12087. ;; * Headline
  12088. ;; :PROPERTIES:
  12089. ;; ...
  12090. ;; :END:
  12091. ;; *************** Inlinetask
  12092. ;; #+BEGIN_EXAMPLE
  12093. ;; :PROPERTIES:
  12094. ;; #+END_EXAMPLE
  12095. ;;
  12096. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12097. (while (< (point) end)
  12098. (let ((p (progn (looking-at org-property-re)
  12099. (match-string-no-properties 2))))
  12100. ;; Only add true property name, not extension symbol.
  12101. (push (if (not (string-match-p "\\+\\'" p)) p
  12102. (substring p 0 -1))
  12103. props))
  12104. (forward-line))))
  12105. (outline-next-heading)))
  12106. (when columns
  12107. (goto-char (point-min))
  12108. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12109. (let ((element (org-element-at-point)))
  12110. (when (memq (org-element-type element) '(keyword node-property))
  12111. (let ((value (org-element-property :value element))
  12112. (start 0))
  12113. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12114. \\(?:{[^}]+}\\)?"
  12115. value start)
  12116. (setq start (match-end 0))
  12117. (let ((p (match-string-no-properties 1 value)))
  12118. (unless (member-ignore-case p org-special-properties)
  12119. (push p props))))))))))
  12120. (sort (delete-dups
  12121. (append props
  12122. ;; for each xxx_ALL property, make sure the bare
  12123. ;; xxx property is also included
  12124. (delq nil (mapcar (lambda (p)
  12125. (and (string-match-p "._ALL\\'" p)
  12126. (substring p 0 -4)))
  12127. props))))
  12128. (lambda (a b) (string< (upcase a) (upcase b))))))
  12129. (defun org-property-values (key)
  12130. "List all non-nil values of property KEY in current buffer."
  12131. (org-with-wide-buffer
  12132. (goto-char (point-min))
  12133. (let ((case-fold-search t)
  12134. (re (org-re-property key))
  12135. values)
  12136. (while (re-search-forward re nil t)
  12137. (push (org-entry-get (point) key) values))
  12138. (delete-dups values))))
  12139. (defun org-insert-property-drawer ()
  12140. "Insert a property drawer into the current entry.
  12141. Do nothing if the drawer already exists. The newly created
  12142. drawer is immediately hidden."
  12143. (org-with-wide-buffer
  12144. ;; Set point to the position where the drawer should be inserted.
  12145. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12146. (org-back-to-heading-or-point-min t)
  12147. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12148. (if (org-before-first-heading-p)
  12149. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12150. (progn
  12151. (forward-line)
  12152. (when (looking-at-p org-planning-line-re) (forward-line))))
  12153. (unless (looking-at-p org-property-drawer-re)
  12154. ;; Make sure we start editing a line from current entry, not from
  12155. ;; next one. It prevents extending text properties or overlays
  12156. ;; belonging to the latter.
  12157. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12158. (let ((begin (if (bobp) (point) (1+ (point))))
  12159. (inhibit-read-only t))
  12160. (unless (bobp) (insert "\n"))
  12161. (insert ":PROPERTIES:\n:END:")
  12162. (org-flag-region (line-end-position 0) (point) t 'outline)
  12163. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12164. (org-indent-region begin (point))))))
  12165. (defun org-insert-drawer (&optional arg drawer)
  12166. "Insert a drawer at point.
  12167. When optional argument ARG is non-nil, insert a property drawer.
  12168. Optional argument DRAWER, when non-nil, is a string representing
  12169. drawer's name. Otherwise, the user is prompted for a name.
  12170. If a region is active, insert the drawer around that region
  12171. instead.
  12172. Point is left between drawer's boundaries."
  12173. (interactive "P")
  12174. (let* ((drawer (if arg "PROPERTIES"
  12175. (or drawer (read-from-minibuffer "Drawer: ")))))
  12176. (cond
  12177. ;; With C-u, fall back on `org-insert-property-drawer'
  12178. (arg (org-insert-property-drawer))
  12179. ;; Check validity of suggested drawer's name.
  12180. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12181. (user-error "Invalid drawer name"))
  12182. ;; With an active region, insert a drawer at point.
  12183. ((not (org-region-active-p))
  12184. (progn
  12185. (unless (bolp) (insert "\n"))
  12186. (insert (format ":%s:\n\n:END:\n" drawer))
  12187. (forward-line -2)))
  12188. ;; Otherwise, insert the drawer at point
  12189. (t
  12190. (let ((rbeg (region-beginning))
  12191. (rend (copy-marker (region-end))))
  12192. (unwind-protect
  12193. (progn
  12194. (goto-char rbeg)
  12195. (beginning-of-line)
  12196. (when (save-excursion
  12197. (re-search-forward org-outline-regexp-bol rend t))
  12198. (user-error "Drawers cannot contain headlines"))
  12199. ;; Position point at the beginning of the first
  12200. ;; non-blank line in region. Insert drawer's opening
  12201. ;; there, then indent it.
  12202. (org-skip-whitespace)
  12203. (beginning-of-line)
  12204. (insert ":" drawer ":\n")
  12205. (forward-line -1)
  12206. (indent-for-tab-command)
  12207. ;; Move point to the beginning of the first blank line
  12208. ;; after the last non-blank line in region. Insert
  12209. ;; drawer's closing, then indent it.
  12210. (goto-char rend)
  12211. (skip-chars-backward " \r\t\n")
  12212. (insert "\n:END:")
  12213. (deactivate-mark t)
  12214. (indent-for-tab-command)
  12215. (unless (eolp) (insert "\n")))
  12216. ;; Clear marker, whatever the outcome of insertion is.
  12217. (set-marker rend nil)))))))
  12218. (defvar org-property-set-functions-alist nil
  12219. "Property set function alist.
  12220. Each entry should have the following format:
  12221. (PROPERTY . READ-FUNCTION)
  12222. The read function will be called with the same argument as
  12223. `org-completing-read'.")
  12224. (defun org-set-property-function (property)
  12225. "Get the function that should be used to set PROPERTY.
  12226. This is computed according to `org-property-set-functions-alist'."
  12227. (or (cdr (assoc property org-property-set-functions-alist))
  12228. 'org-completing-read))
  12229. (defun org-read-property-value (property &optional pom default)
  12230. "Read value for PROPERTY, as a string.
  12231. When optional argument POM is non-nil, completion uses additional
  12232. information, i.e., allowed or existing values at point or marker
  12233. POM.
  12234. Optional argument DEFAULT provides a default value for PROPERTY."
  12235. (let* ((completion-ignore-case t)
  12236. (allowed
  12237. (or (org-property-get-allowed-values nil property 'table)
  12238. (and pom (org-property-get-allowed-values pom property 'table))))
  12239. (current (org-entry-get nil property))
  12240. (prompt (format "%s value%s: "
  12241. property
  12242. (if (org-string-nw-p current)
  12243. (format " [%s]" current)
  12244. "")))
  12245. (set-function (org-set-property-function property)))
  12246. (org-trim
  12247. (if allowed
  12248. (funcall set-function
  12249. prompt allowed nil
  12250. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12251. default nil default)
  12252. (let ((all (mapcar #'list
  12253. (append (org-property-values property)
  12254. (and pom
  12255. (org-with-point-at pom
  12256. (org-property-values property)))))))
  12257. (funcall set-function prompt all nil nil "" nil current))))))
  12258. (defvar org-last-set-property nil)
  12259. (defvar org-last-set-property-value nil)
  12260. (defun org-read-property-name ()
  12261. "Read a property name."
  12262. (let ((completion-ignore-case t)
  12263. (default-prop (or (and (org-at-property-p)
  12264. (match-string-no-properties 2))
  12265. org-last-set-property)))
  12266. (org-completing-read
  12267. (concat "Property"
  12268. (if default-prop (concat " [" default-prop "]") "")
  12269. ": ")
  12270. (mapcar #'list (org-buffer-property-keys nil t t))
  12271. nil nil nil nil default-prop)))
  12272. (defun org-set-property-and-value (use-last)
  12273. "Allow to set [PROPERTY]: [value] direction from prompt.
  12274. When use-default, don't even ask, just use the last
  12275. \"[PROPERTY]: [value]\" string from the history."
  12276. (interactive "P")
  12277. (let* ((completion-ignore-case t)
  12278. (pv (or (and use-last org-last-set-property-value)
  12279. (org-completing-read
  12280. "Enter a \"[Property]: [value]\" pair: "
  12281. nil nil nil nil nil
  12282. org-last-set-property-value)))
  12283. prop val)
  12284. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12285. (setq prop (match-string 1 pv)
  12286. val (match-string 2 pv))
  12287. (org-set-property prop val))))
  12288. (defun org-set-property (property value)
  12289. "In the current entry, set PROPERTY to VALUE.
  12290. When called interactively, this will prompt for a property name, offering
  12291. completion on existing and default properties. And then it will prompt
  12292. for a value, offering completion either on allowed values (via an inherited
  12293. xxx_ALL property) or on existing values in other instances of this property
  12294. in the current file.
  12295. Throw an error when trying to set a property with an invalid name."
  12296. (interactive (list nil nil))
  12297. (let ((property (or property (org-read-property-name))))
  12298. ;; `org-entry-put' also makes the following check, but this one
  12299. ;; avoids polluting `org-last-set-property' and
  12300. ;; `org-last-set-property-value' needlessly.
  12301. (unless (org--valid-property-p property)
  12302. (user-error "Invalid property name: \"%s\"" property))
  12303. (let ((value (or value (org-read-property-value property)))
  12304. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12305. (setq org-last-set-property property)
  12306. (setq org-last-set-property-value (concat property ": " value))
  12307. ;; Possibly postprocess the inserted value:
  12308. (when fn (setq value (funcall fn value)))
  12309. (unless (equal (org-entry-get nil property) value)
  12310. (org-entry-put nil property value)))))
  12311. (defun org-find-property (property &optional value)
  12312. "Find first entry in buffer that sets PROPERTY.
  12313. When optional argument VALUE is non-nil, only consider an entry
  12314. if it contains PROPERTY set to this value. If PROPERTY should be
  12315. explicitly set to nil, use string \"nil\" for VALUE.
  12316. Return position where the entry begins, or nil if there is no
  12317. such entry. If narrowing is in effect, only search the visible
  12318. part of the buffer."
  12319. (save-excursion
  12320. (goto-char (point-min))
  12321. (let ((case-fold-search t)
  12322. (re (org-re-property property nil (not value) value)))
  12323. (catch 'exit
  12324. (while (re-search-forward re nil t)
  12325. (when (if value (org-at-property-p)
  12326. (org-entry-get (point) property nil t))
  12327. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12328. (point)))))))))
  12329. (defun org-delete-property (property)
  12330. "In the current entry, delete PROPERTY."
  12331. (interactive
  12332. (let* ((completion-ignore-case t)
  12333. (cat (org-entry-get (point) "CATEGORY"))
  12334. (props0 (org-entry-properties nil 'standard))
  12335. (props (if cat props0
  12336. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12337. (prop (if (< 1 (length props))
  12338. (completing-read "Property: " props nil t)
  12339. (caar props))))
  12340. (list prop)))
  12341. (if (not property)
  12342. (message "No property to delete in this entry")
  12343. (org-entry-delete nil property)
  12344. (message "Property \"%s\" deleted" property)))
  12345. (defun org-delete-property-globally (property)
  12346. "Remove PROPERTY globally, from all entries.
  12347. This function ignores narrowing, if any."
  12348. (interactive
  12349. (let* ((completion-ignore-case t)
  12350. (prop (completing-read
  12351. "Globally remove property: "
  12352. (mapcar #'list (org-buffer-property-keys)))))
  12353. (list prop)))
  12354. (org-with-wide-buffer
  12355. (goto-char (point-min))
  12356. (let ((count 0)
  12357. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12358. (while (re-search-forward re nil t)
  12359. (when (org-entry-delete (point) property) (cl-incf count)))
  12360. (message "Property \"%s\" removed from %d entries" property count))))
  12361. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12362. (defun org-compute-property-at-point ()
  12363. "Compute the property at point.
  12364. This looks for an enclosing column format, extracts the operator and
  12365. then applies it to the property in the column format's scope."
  12366. (interactive)
  12367. (unless (org-at-property-p)
  12368. (user-error "Not at a property"))
  12369. (let ((prop (match-string-no-properties 2)))
  12370. (org-columns-get-format-and-top-level)
  12371. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12372. (user-error "No operator defined for property %s" prop))
  12373. (org-columns-compute prop)))
  12374. (defvar org-property-allowed-value-functions nil
  12375. "Hook for functions supplying allowed values for a specific property.
  12376. The functions must take a single argument, the name of the property, and
  12377. return a flat list of allowed values. If \":ETC\" is one of
  12378. the values, this means that these values are intended as defaults for
  12379. completion, but that other values should be allowed too.
  12380. The functions must return nil if they are not responsible for this
  12381. property.")
  12382. (defun org-property-get-allowed-values (pom property &optional table)
  12383. "Get allowed values for the property PROPERTY.
  12384. When TABLE is non-nil, return an alist that can directly be used for
  12385. completion."
  12386. (let (vals)
  12387. (cond
  12388. ((equal property "TODO")
  12389. (setq vals (org-with-point-at pom
  12390. (append org-todo-keywords-1 '("")))))
  12391. ((equal property "PRIORITY")
  12392. (let ((n org-priority-lowest))
  12393. (while (>= n org-priority-highest)
  12394. (push (char-to-string n) vals)
  12395. (setq n (1- n)))))
  12396. ((equal property "CATEGORY"))
  12397. ((member property org-special-properties))
  12398. ((setq vals (run-hook-with-args-until-success
  12399. 'org-property-allowed-value-functions property)))
  12400. (t
  12401. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12402. (when (and vals (string-match "\\S-" vals))
  12403. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12404. (setq vals (mapcar (lambda (x)
  12405. (cond ((stringp x) x)
  12406. ((numberp x) (number-to-string x))
  12407. ((symbolp x) (symbol-name x))
  12408. (t "???")))
  12409. vals)))))
  12410. (when (member ":ETC" vals)
  12411. (setq vals (remove ":ETC" vals))
  12412. (org-add-props (car vals) '(org-unrestricted t)))
  12413. (if table (mapcar 'list vals) vals)))
  12414. (defun org-property-previous-allowed-value (&optional _previous)
  12415. "Switch to the next allowed value for this property."
  12416. (interactive)
  12417. (org-property-next-allowed-value t))
  12418. (defun org-property-next-allowed-value (&optional previous)
  12419. "Switch to the next allowed value for this property."
  12420. (interactive)
  12421. (unless (org-at-property-p)
  12422. (user-error "Not at a property"))
  12423. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12424. (key (match-string 2))
  12425. (value (match-string 3))
  12426. (allowed (or (org-property-get-allowed-values (point) key)
  12427. (and (member value '("[ ]" "[-]" "[X]"))
  12428. '("[ ]" "[X]"))))
  12429. (heading (save-match-data (nth 4 (org-heading-components))))
  12430. nval)
  12431. (unless allowed
  12432. (user-error "Allowed values for this property have not been defined"))
  12433. (when previous (setq allowed (reverse allowed)))
  12434. (when (member value allowed)
  12435. (setq nval (car (cdr (member value allowed)))))
  12436. (setq nval (or nval (car allowed)))
  12437. (when (equal nval value)
  12438. (user-error "Only one allowed value for this property"))
  12439. (org-at-property-p)
  12440. (replace-match (concat " :" key ": " nval) t t)
  12441. (org-indent-line)
  12442. (beginning-of-line 1)
  12443. (skip-chars-forward " \t")
  12444. (when (equal prop org-effort-property)
  12445. (org-refresh-property
  12446. '((effort . identity)
  12447. (effort-minutes . org-duration-to-minutes))
  12448. nval)
  12449. (when (string= org-clock-current-task heading)
  12450. (setq org-clock-effort nval)
  12451. (org-clock-update-mode-line)))
  12452. (run-hook-with-args 'org-property-changed-functions key nval)))
  12453. (defun org-find-olp (path &optional this-buffer)
  12454. "Return a marker pointing to the entry at outline path OLP.
  12455. If anything goes wrong, throw an error, and if you need to do
  12456. something based on this error, you can catch it with
  12457. `condition-case'.
  12458. If THIS-BUFFER is set, the outline path does not contain a file,
  12459. only headings."
  12460. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12461. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12462. (level 1)
  12463. (lmin 1)
  12464. (lmax 1)
  12465. end found flevel)
  12466. (unless buffer (error "File not found :%s" file))
  12467. (with-current-buffer buffer
  12468. (unless (derived-mode-p 'org-mode)
  12469. (error "Buffer %s needs to be in Org mode" buffer))
  12470. (org-with-wide-buffer
  12471. (goto-char (point-min))
  12472. (dolist (heading path)
  12473. (let ((re (format org-complex-heading-regexp-format
  12474. (regexp-quote heading)))
  12475. (cnt 0))
  12476. (while (re-search-forward re end t)
  12477. (setq level (- (match-end 1) (match-beginning 1)))
  12478. (when (and (>= level lmin) (<= level lmax))
  12479. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12480. (when (= cnt 0)
  12481. (error "Heading not found on level %d: %s" lmax heading))
  12482. (when (> cnt 1)
  12483. (error "Heading not unique on level %d: %s" lmax heading))
  12484. (goto-char found)
  12485. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12486. (setq end (save-excursion (org-end-of-subtree t t)))))
  12487. (when (org-at-heading-p)
  12488. (point-marker))))))
  12489. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12490. "Find node HEADING in BUFFER.
  12491. Return a marker to the heading if it was found, or nil if not.
  12492. If POS-ONLY is set, return just the position instead of a marker.
  12493. The heading text must match exact, but it may have a TODO keyword,
  12494. a priority cookie and tags in the standard locations."
  12495. (with-current-buffer (or buffer (current-buffer))
  12496. (org-with-wide-buffer
  12497. (goto-char (point-min))
  12498. (let (case-fold-search)
  12499. (when (re-search-forward
  12500. (format org-complex-heading-regexp-format
  12501. (regexp-quote heading)) nil t)
  12502. (if pos-only
  12503. (match-beginning 0)
  12504. (move-marker (make-marker) (match-beginning 0))))))))
  12505. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12506. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12507. When the target headline is found, return a marker to this location."
  12508. (let ((files (directory-files (or dir default-directory)
  12509. t "\\`[^.#].*\\.org\\'"))
  12510. visiting m buffer)
  12511. (catch 'found
  12512. (dolist (file files)
  12513. (message "trying %s" file)
  12514. (setq visiting (org-find-base-buffer-visiting file))
  12515. (setq buffer (or visiting (find-file-noselect file)))
  12516. (setq m (org-find-exact-headline-in-buffer
  12517. heading buffer))
  12518. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12519. (and m (throw 'found m))))))
  12520. (defun org-find-entry-with-id (ident)
  12521. "Locate the entry that contains the ID property with exact value IDENT.
  12522. IDENT can be a string, a symbol or a number, this function will search for
  12523. the string representation of it.
  12524. Return the position where this entry starts, or nil if there is no such entry."
  12525. (interactive "sID: ")
  12526. (let ((id (cond
  12527. ((stringp ident) ident)
  12528. ((symbolp ident) (symbol-name ident))
  12529. ((numberp ident) (number-to-string ident))
  12530. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12531. (org-with-wide-buffer (org-find-property "ID" id))))
  12532. ;;;; Timestamps
  12533. (defvar org-last-changed-timestamp nil)
  12534. (defvar org-last-inserted-timestamp nil
  12535. "The last time stamp inserted with `org-insert-time-stamp'.")
  12536. (defun org-time-stamp (arg &optional inactive)
  12537. "Prompt for a date/time and insert a time stamp.
  12538. If the user specifies a time like HH:MM or if this command is
  12539. called with at least one prefix argument, the time stamp contains
  12540. the date and the time. Otherwise, only the date is included.
  12541. All parts of a date not specified by the user are filled in from
  12542. the timestamp at point, if any, or the current date/time
  12543. otherwise.
  12544. If there is already a timestamp at the cursor, it is replaced.
  12545. With two universal prefix arguments, insert an active timestamp
  12546. with the current time without prompting the user.
  12547. When called from Lisp, the timestamp is inactive if INACTIVE is
  12548. non-nil."
  12549. (interactive "P")
  12550. (let* ((ts (cond
  12551. ((org-at-date-range-p t)
  12552. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12553. ((org-at-timestamp-p 'lax) (match-string 0))))
  12554. ;; Default time is either the timestamp at point or today.
  12555. ;; When entering a range, only the range start is considered.
  12556. (default-time (and ts (org-time-string-to-time ts)))
  12557. (default-input (and ts (org-get-compact-tod ts)))
  12558. (repeater (and ts
  12559. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12560. (match-string 0 ts)))
  12561. org-time-was-given
  12562. org-end-time-was-given
  12563. (time
  12564. (if (equal arg '(16)) (current-time)
  12565. ;; Preserve `this-command' and `last-command'.
  12566. (let ((this-command this-command)
  12567. (last-command last-command))
  12568. (org-read-date
  12569. arg 'totime nil nil default-time default-input
  12570. inactive)))))
  12571. (cond
  12572. ((and ts
  12573. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12574. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12575. (insert "--")
  12576. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12577. (ts
  12578. ;; Make sure we're on a timestamp. When in the middle of a date
  12579. ;; range, move arbitrarily to range end.
  12580. (unless (org-at-timestamp-p 'lax)
  12581. (skip-chars-forward "-")
  12582. (org-at-timestamp-p 'lax))
  12583. (replace-match "")
  12584. (setq org-last-changed-timestamp
  12585. (org-insert-time-stamp
  12586. time (or org-time-was-given arg)
  12587. inactive nil nil (list org-end-time-was-given)))
  12588. (when repeater
  12589. (backward-char)
  12590. (insert " " repeater)
  12591. (setq org-last-changed-timestamp
  12592. (concat (substring org-last-inserted-timestamp 0 -1)
  12593. " " repeater ">")))
  12594. (message "Timestamp updated"))
  12595. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12596. (t (org-insert-time-stamp
  12597. time (or org-time-was-given arg) inactive nil nil
  12598. (list org-end-time-was-given))))))
  12599. ;; FIXME: can we use this for something else, like computing time differences?
  12600. (defun org-get-compact-tod (s)
  12601. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12602. (let* ((t1 (match-string 1 s))
  12603. (h1 (string-to-number (match-string 2 s)))
  12604. (m1 (string-to-number (match-string 3 s)))
  12605. (t2 (and (match-end 4) (match-string 5 s)))
  12606. (h2 (and t2 (string-to-number (match-string 6 s))))
  12607. (m2 (and t2 (string-to-number (match-string 7 s))))
  12608. dh dm)
  12609. (if (not t2)
  12610. t1
  12611. (setq dh (- h2 h1) dm (- m2 m1))
  12612. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12613. (concat t1 "+" (number-to-string dh)
  12614. (and (/= 0 dm) (format ":%02d" dm)))))))
  12615. (defun org-time-stamp-inactive (&optional arg)
  12616. "Insert an inactive time stamp.
  12617. An inactive time stamp is enclosed in square brackets instead of
  12618. angle brackets. It is inactive in the sense that it does not
  12619. trigger agenda entries. So these are more for recording a
  12620. certain time/date.
  12621. If the user specifies a time like HH:MM or if this command is called with
  12622. at least one prefix argument, the time stamp contains the date and the time.
  12623. Otherwise, only the date is included.
  12624. When called with two universal prefix arguments, insert an inactive time stamp
  12625. with the current time without prompting the user."
  12626. (interactive "P")
  12627. (org-time-stamp arg 'inactive))
  12628. (defvar org-date-ovl (make-overlay 1 1))
  12629. (overlay-put org-date-ovl 'face 'org-date-selected)
  12630. (delete-overlay org-date-ovl)
  12631. (defvar org-ans1) ; dynamically scoped parameter
  12632. (defvar org-ans2) ; dynamically scoped parameter
  12633. (defvar org-plain-time-of-day-regexp) ; defined below
  12634. (defvar org-overriding-default-time nil) ; dynamically scoped
  12635. (defvar org-read-date-overlay nil)
  12636. (defvar org-read-date-history nil)
  12637. (defvar org-read-date-final-answer nil)
  12638. (defvar org-read-date-analyze-futurep nil)
  12639. (defvar org-read-date-analyze-forced-year nil)
  12640. (defvar org-read-date-inactive)
  12641. (defvar org-def)
  12642. (defvar org-defdecode)
  12643. (defvar org-with-time)
  12644. (defvar calendar-setup) ; Dynamically scoped.
  12645. (defun org-read-date (&optional with-time to-time from-string prompt
  12646. default-time default-input inactive)
  12647. "Read a date, possibly a time, and make things smooth for the user.
  12648. The prompt will suggest to enter an ISO date, but you can also enter anything
  12649. which will at least partially be understood by `parse-time-string'.
  12650. Unrecognized parts of the date will default to the current day, month, year,
  12651. hour and minute. If this command is called to replace a timestamp at point,
  12652. or to enter the second timestamp of a range, the default time is taken
  12653. from the existing stamp. Furthermore, the command prefers the future,
  12654. so if you are giving a date where the year is not given, and the day-month
  12655. combination is already past in the current year, it will assume you
  12656. mean next year. For details, see the manual. A few examples:
  12657. 3-2-5 --> 2003-02-05
  12658. feb 15 --> currentyear-02-15
  12659. 2/15 --> currentyear-02-15
  12660. sep 12 9 --> 2009-09-12
  12661. 12:45 --> today 12:45
  12662. 22 sept 0:34 --> currentyear-09-22 0:34
  12663. 12 --> currentyear-currentmonth-12
  12664. Fri --> nearest Friday after today
  12665. -Tue --> last Tuesday
  12666. etc.
  12667. Furthermore you can specify a relative date by giving, as the *first* thing
  12668. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12669. change in days weeks, months, years.
  12670. With a single plus or minus, the date is relative to today. With a double
  12671. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12672. +4d --> four days from today
  12673. +4 --> same as above
  12674. +2w --> two weeks from today
  12675. ++5 --> five days from default date
  12676. The function understands only English month and weekday abbreviations.
  12677. While prompting, a calendar is popped up - you can also select the
  12678. date with the mouse (button 1). The calendar shows a period of three
  12679. months. To scroll it to other months, use the keys `>' and `<'.
  12680. If you don't like the calendar, turn it off with
  12681. (setq org-read-date-popup-calendar nil)
  12682. With optional argument TO-TIME, the date will immediately be converted
  12683. to an internal time.
  12684. With an optional argument WITH-TIME, the prompt will suggest to
  12685. also insert a time. Note that when WITH-TIME is not set, you can
  12686. still enter a time, and this function will inform the calling routine
  12687. about this change. The calling routine may then choose to change the
  12688. format used to insert the time stamp into the buffer to include the time.
  12689. With optional argument FROM-STRING, read from this string instead from
  12690. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12691. the time/date that is used for everything that is not specified by the
  12692. user."
  12693. (require 'parse-time)
  12694. (let* ((org-with-time with-time)
  12695. (org-time-stamp-rounding-minutes
  12696. (if (equal org-with-time '(16))
  12697. '(0 0)
  12698. org-time-stamp-rounding-minutes))
  12699. (ct (org-current-time))
  12700. (org-def (or org-overriding-default-time default-time ct))
  12701. (org-defdecode (decode-time org-def))
  12702. (cur-frame (selected-frame))
  12703. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12704. (calendar-setup
  12705. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12706. (calendar-move-hook nil)
  12707. (calendar-view-diary-initially-flag nil)
  12708. (calendar-view-holidays-initially-flag nil)
  12709. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12710. ;; Rationalize `org-def' and `org-defdecode', if required.
  12711. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12712. (setf (nth 2 org-defdecode) -1)
  12713. (setf (nth 1 org-defdecode) 59)
  12714. (setq org-def (apply #'encode-time org-defdecode))
  12715. (setq org-defdecode (decode-time org-def)))
  12716. (let* ((timestr (format-time-string
  12717. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12718. org-def))
  12719. (prompt (concat (if prompt (concat prompt " ") "")
  12720. (format "Date+time [%s]: " timestr))))
  12721. (cond
  12722. (from-string (setq ans from-string))
  12723. (org-read-date-popup-calendar
  12724. (save-excursion
  12725. (save-window-excursion
  12726. (calendar)
  12727. (when (eq calendar-setup 'calendar-only)
  12728. (setq cal-frame
  12729. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12730. (select-frame cal-frame))
  12731. (org-eval-in-calendar '(setq cursor-type nil) t)
  12732. (unwind-protect
  12733. (progn
  12734. (calendar-forward-day (- (time-to-days org-def)
  12735. (calendar-absolute-from-gregorian
  12736. (calendar-current-date))))
  12737. (org-eval-in-calendar nil t)
  12738. (let* ((old-map (current-local-map))
  12739. (map (copy-keymap calendar-mode-map))
  12740. (minibuffer-local-map
  12741. (copy-keymap org-read-date-minibuffer-local-map)))
  12742. (org-defkey map (kbd "RET") 'org-calendar-select)
  12743. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12744. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12745. (unwind-protect
  12746. (progn
  12747. (use-local-map map)
  12748. (setq org-read-date-inactive inactive)
  12749. (add-hook 'post-command-hook 'org-read-date-display)
  12750. (setq org-ans0
  12751. (read-string prompt
  12752. default-input
  12753. 'org-read-date-history
  12754. nil))
  12755. ;; org-ans0: from prompt
  12756. ;; org-ans1: from mouse click
  12757. ;; org-ans2: from calendar motion
  12758. (setq ans
  12759. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12760. (remove-hook 'post-command-hook 'org-read-date-display)
  12761. (use-local-map old-map)
  12762. (when org-read-date-overlay
  12763. (delete-overlay org-read-date-overlay)
  12764. (setq org-read-date-overlay nil)))))
  12765. (bury-buffer "*Calendar*")
  12766. (when cal-frame
  12767. (delete-frame cal-frame)
  12768. (select-frame-set-input-focus cur-frame))))))
  12769. (t ; Naked prompt only
  12770. (unwind-protect
  12771. (setq ans (read-string prompt default-input
  12772. 'org-read-date-history timestr))
  12773. (when org-read-date-overlay
  12774. (delete-overlay org-read-date-overlay)
  12775. (setq org-read-date-overlay nil))))))
  12776. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12777. (when org-read-date-analyze-forced-year
  12778. (message "Year was forced into %s"
  12779. (if org-read-date-force-compatible-dates
  12780. "compatible range (1970-2037)"
  12781. "range representable on this machine"))
  12782. (ding))
  12783. (setq final (apply #'encode-time final))
  12784. (setq org-read-date-final-answer ans)
  12785. (if to-time
  12786. final
  12787. ;; This round-trip gets rid of 34th of August and stuff like that....
  12788. (setq final (decode-time final))
  12789. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12790. (format "%04d-%02d-%02d %02d:%02d"
  12791. (nth 5 final) (nth 4 final) (nth 3 final)
  12792. (nth 2 final) (nth 1 final))
  12793. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12794. (defun org-read-date-display ()
  12795. "Display the current date prompt interpretation in the minibuffer."
  12796. (when org-read-date-display-live
  12797. (when org-read-date-overlay
  12798. (delete-overlay org-read-date-overlay))
  12799. (when (minibufferp (current-buffer))
  12800. (save-excursion
  12801. (end-of-line 1)
  12802. (while (not (equal (buffer-substring
  12803. (max (point-min) (- (point) 4)) (point))
  12804. " "))
  12805. (insert " ")))
  12806. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12807. " " (or org-ans1 org-ans2)))
  12808. (org-end-time-was-given nil)
  12809. (f (org-read-date-analyze ans org-def org-defdecode))
  12810. (fmts (if org-display-custom-times
  12811. org-time-stamp-custom-formats
  12812. org-time-stamp-formats))
  12813. (fmt (if (or org-with-time
  12814. (and (boundp 'org-time-was-given) org-time-was-given))
  12815. (cdr fmts)
  12816. (car fmts)))
  12817. (txt (format-time-string fmt (apply #'encode-time f)))
  12818. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12819. (txt (concat "=> " txt)))
  12820. (when (and org-end-time-was-given
  12821. (string-match org-plain-time-of-day-regexp txt))
  12822. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12823. org-end-time-was-given
  12824. (substring txt (match-end 0)))))
  12825. (when org-read-date-analyze-futurep
  12826. (setq txt (concat txt " (=>F)")))
  12827. (setq org-read-date-overlay
  12828. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12829. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12830. (defun org-read-date-analyze (ans def defdecode)
  12831. "Analyze the combined answer of the date prompt."
  12832. ;; FIXME: cleanup and comment
  12833. (let ((org-def def)
  12834. (org-defdecode defdecode)
  12835. (nowdecode (decode-time))
  12836. delta deltan deltaw deltadef year month day
  12837. hour minute second wday pm h2 m2 tl wday1
  12838. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12839. (setq org-read-date-analyze-futurep nil
  12840. org-read-date-analyze-forced-year nil)
  12841. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12842. (setq ans "+0"))
  12843. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12844. (setq ans (replace-match "" t t ans)
  12845. deltan (car delta)
  12846. deltaw (nth 1 delta)
  12847. deltadef (nth 2 delta)))
  12848. ;; Check if there is an iso week date in there. If yes, store the
  12849. ;; info and postpone interpreting it until the rest of the parsing
  12850. ;; is done.
  12851. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12852. (setq iso-year (when (match-end 1)
  12853. (org-small-year-to-year
  12854. (string-to-number (match-string 1 ans))))
  12855. iso-weekday (when (match-end 3)
  12856. (string-to-number (match-string 3 ans)))
  12857. iso-week (string-to-number (match-string 2 ans)))
  12858. (setq ans (replace-match "" t t ans)))
  12859. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12860. (when (string-match
  12861. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12862. (setq year (if (match-end 2)
  12863. (string-to-number (match-string 2 ans))
  12864. (progn (setq kill-year t)
  12865. (string-to-number (format-time-string "%Y"))))
  12866. month (string-to-number (match-string 3 ans))
  12867. day (string-to-number (match-string 4 ans)))
  12868. (setq year (org-small-year-to-year year))
  12869. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12870. t nil ans)))
  12871. ;; Help matching dotted european dates
  12872. (when (string-match
  12873. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12874. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12875. (setq kill-year t)
  12876. (string-to-number (format-time-string "%Y")))
  12877. day (string-to-number (match-string 1 ans))
  12878. month (string-to-number (match-string 2 ans))
  12879. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12880. t nil ans)))
  12881. ;; Help matching american dates, like 5/30 or 5/30/7
  12882. (when (string-match
  12883. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12884. (setq year (if (match-end 4)
  12885. (string-to-number (match-string 4 ans))
  12886. (progn (setq kill-year t)
  12887. (string-to-number (format-time-string "%Y"))))
  12888. month (string-to-number (match-string 1 ans))
  12889. day (string-to-number (match-string 2 ans)))
  12890. (setq year (org-small-year-to-year year))
  12891. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12892. t nil ans)))
  12893. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12894. ;; If there is a time with am/pm, and *no* time without it, we convert
  12895. ;; so that matching will be successful.
  12896. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12897. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12898. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12899. (setq hour (string-to-number (match-string 1 ans))
  12900. minute (if (match-end 3)
  12901. (string-to-number (match-string 3 ans))
  12902. 0)
  12903. pm (equal ?p
  12904. (string-to-char (downcase (match-string 4 ans)))))
  12905. (if (and (= hour 12) (not pm))
  12906. (setq hour 0)
  12907. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12908. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12909. t t ans))))
  12910. ;; Help matching HHhMM times, similarly as for am/pm times.
  12911. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12912. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12913. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12914. (setq hour (if (match-end 1)
  12915. (string-to-number (match-string 1 ans))
  12916. 0)
  12917. minute (if (match-end 2)
  12918. (string-to-number (match-string 2 ans))
  12919. 0))
  12920. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12921. t t ans))))
  12922. ;; Check if a time range is given as a duration
  12923. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12924. (setq hour (string-to-number (match-string 1 ans))
  12925. h2 (+ hour (string-to-number (match-string 3 ans)))
  12926. minute (string-to-number (match-string 2 ans))
  12927. m2 (+ minute (if (match-end 5) (string-to-number
  12928. (match-string 5 ans))0)))
  12929. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12930. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12931. t t ans)))
  12932. ;; Check if there is a time range
  12933. (when (boundp 'org-end-time-was-given)
  12934. (setq org-time-was-given nil)
  12935. (when (and (string-match org-plain-time-of-day-regexp ans)
  12936. (match-end 8))
  12937. (setq org-end-time-was-given (match-string 8 ans))
  12938. (setq ans (concat (substring ans 0 (match-beginning 7))
  12939. (substring ans (match-end 7))))))
  12940. (setq tl (parse-time-string ans)
  12941. day (or (nth 3 tl) (nth 3 org-defdecode))
  12942. month
  12943. (cond ((nth 4 tl))
  12944. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12945. ;; Day was specified. Make sure DAY+MONTH
  12946. ;; combination happens in the future.
  12947. ((nth 3 tl)
  12948. (setq futurep t)
  12949. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12950. (nth 4 nowdecode)))
  12951. (t (nth 4 org-defdecode)))
  12952. year
  12953. (cond ((and (not kill-year) (nth 5 tl)))
  12954. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12955. ;; Month was guessed in the future and is at least
  12956. ;; equal to NOWDECODE's. Fix year accordingly.
  12957. (futurep
  12958. (if (or (> month (nth 4 nowdecode))
  12959. (>= day (nth 3 nowdecode)))
  12960. (nth 5 nowdecode)
  12961. (1+ (nth 5 nowdecode))))
  12962. ;; Month was specified. Make sure MONTH+YEAR
  12963. ;; combination happens in the future.
  12964. ((nth 4 tl)
  12965. (setq futurep t)
  12966. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12967. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12968. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12969. (t (nth 5 nowdecode))))
  12970. (t (nth 5 org-defdecode)))
  12971. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12972. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12973. second (or (nth 0 tl) 0)
  12974. wday (nth 6 tl))
  12975. (when (and (eq org-read-date-prefer-future 'time)
  12976. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12977. (equal day (nth 3 nowdecode))
  12978. (equal month (nth 4 nowdecode))
  12979. (equal year (nth 5 nowdecode))
  12980. (nth 2 tl)
  12981. (or (< (nth 2 tl) (nth 2 nowdecode))
  12982. (and (= (nth 2 tl) (nth 2 nowdecode))
  12983. (nth 1 tl)
  12984. (< (nth 1 tl) (nth 1 nowdecode)))))
  12985. (setq day (1+ day)
  12986. futurep t))
  12987. ;; Special date definitions below
  12988. (cond
  12989. (iso-week
  12990. ;; There was an iso week
  12991. (require 'cal-iso)
  12992. (setq futurep nil)
  12993. (setq year (or iso-year year)
  12994. day (or iso-weekday wday 1)
  12995. wday nil ; to make sure that the trigger below does not match
  12996. iso-date (calendar-gregorian-from-absolute
  12997. (calendar-iso-to-absolute
  12998. (list iso-week day year))))
  12999. ; FIXME: Should we also push ISO weeks into the future?
  13000. ; (when (and org-read-date-prefer-future
  13001. ; (not iso-year)
  13002. ; (< (calendar-absolute-from-gregorian iso-date)
  13003. ; (time-to-days nil)))
  13004. ; (setq year (1+ year)
  13005. ; iso-date (calendar-gregorian-from-absolute
  13006. ; (calendar-iso-to-absolute
  13007. ; (list iso-week day year)))))
  13008. (setq month (car iso-date)
  13009. year (nth 2 iso-date)
  13010. day (nth 1 iso-date)))
  13011. (deltan
  13012. (setq futurep nil)
  13013. (unless deltadef
  13014. (let ((now (decode-time)))
  13015. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13016. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13017. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13018. ((equal deltaw "m") (setq month (+ month deltan)))
  13019. ((equal deltaw "y") (setq year (+ year deltan)))))
  13020. ((and wday (not (nth 3 tl)))
  13021. ;; Weekday was given, but no day, so pick that day in the week
  13022. ;; on or after the derived date.
  13023. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13024. (unless (equal wday wday1)
  13025. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13026. (when (and (boundp 'org-time-was-given)
  13027. (nth 2 tl))
  13028. (setq org-time-was-given t))
  13029. (when (< year 100) (setq year (+ 2000 year)))
  13030. ;; Check of the date is representable
  13031. (if org-read-date-force-compatible-dates
  13032. (progn
  13033. (when (< year 1970)
  13034. (setq year 1970 org-read-date-analyze-forced-year t))
  13035. (when (> year 2037)
  13036. (setq year 2037 org-read-date-analyze-forced-year t)))
  13037. (condition-case nil
  13038. (ignore (encode-time second minute hour day month year))
  13039. (error
  13040. (setq year (nth 5 org-defdecode))
  13041. (setq org-read-date-analyze-forced-year t))))
  13042. (setq org-read-date-analyze-futurep futurep)
  13043. (list second minute hour day month year)))
  13044. (defvar parse-time-weekdays)
  13045. (defun org-read-date-get-relative (s today default)
  13046. "Check string S for special relative date string.
  13047. TODAY and DEFAULT are internal times, for today and for a default.
  13048. Return shift list (N what def-flag)
  13049. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13050. N is the number of WHATs to shift.
  13051. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13052. the DEFAULT date rather than TODAY."
  13053. (require 'parse-time)
  13054. (when (and
  13055. (string-match
  13056. (concat
  13057. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13058. "\\([0-9]+\\)?"
  13059. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13060. "\\([ \t]\\|$\\)") s)
  13061. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13062. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13063. (string-to-char (substring (match-string 1 s) -1))
  13064. ?+))
  13065. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13066. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13067. (what (if (match-end 3) (match-string 3 s) "d"))
  13068. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13069. (date (if rel default today))
  13070. (wday (nth 6 (decode-time date)))
  13071. delta)
  13072. (if wday1
  13073. (progn
  13074. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13075. (when (= delta 0) (setq delta 7))
  13076. (when (= dir ?-)
  13077. (setq delta (- delta 7))
  13078. (when (= delta 0) (setq delta -7)))
  13079. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13080. (list delta "d" rel))
  13081. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13082. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13083. "Turn a user-specified date into the internal representation.
  13084. The internal representation needed by the calendar is (month day year).
  13085. This is a wrapper to handle the brain-dead convention in calendar that
  13086. user function argument order change dependent on argument order."
  13087. (pcase calendar-date-style
  13088. (`american (list arg1 arg2 arg3))
  13089. (`european (list arg2 arg1 arg3))
  13090. (`iso (list arg2 arg3 arg1))))
  13091. (defun org-eval-in-calendar (form &optional keepdate)
  13092. "Eval FORM in the calendar window and return to current window.
  13093. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13094. (let ((sf (selected-frame))
  13095. (sw (selected-window)))
  13096. (select-window (get-buffer-window "*Calendar*" t))
  13097. (eval form)
  13098. (when (and (not keepdate) (calendar-cursor-to-date))
  13099. (let* ((date (calendar-cursor-to-date))
  13100. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13101. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13102. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13103. (select-window sw)
  13104. (select-frame-set-input-focus sf)))
  13105. (defun org-calendar-select ()
  13106. "Return to `org-read-date' with the date currently selected.
  13107. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13108. (interactive)
  13109. (when (calendar-cursor-to-date)
  13110. (let* ((date (calendar-cursor-to-date))
  13111. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13112. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13113. (when (active-minibuffer-window) (exit-minibuffer))))
  13114. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13115. "Insert a date stamp for the date given by the internal TIME.
  13116. See `format-time-string' for the format of TIME.
  13117. WITH-HM means use the stamp format that includes the time of the day.
  13118. INACTIVE means use square brackets instead of angular ones, so that the
  13119. stamp will not contribute to the agenda.
  13120. PRE and POST are optional strings to be inserted before and after the
  13121. stamp.
  13122. The command returns the inserted time stamp."
  13123. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13124. stamp)
  13125. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13126. (insert-before-markers (or pre ""))
  13127. (when (listp extra)
  13128. (setq extra (car extra))
  13129. (if (and (stringp extra)
  13130. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13131. (setq extra (format "-%02d:%02d"
  13132. (string-to-number (match-string 1 extra))
  13133. (string-to-number (match-string 2 extra))))
  13134. (setq extra nil)))
  13135. (when extra
  13136. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13137. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13138. (insert-before-markers (or post ""))
  13139. (setq org-last-inserted-timestamp stamp)))
  13140. (defun org-toggle-time-stamp-overlays ()
  13141. "Toggle the use of custom time stamp formats."
  13142. (interactive)
  13143. (setq org-display-custom-times (not org-display-custom-times))
  13144. (unless org-display-custom-times
  13145. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13146. (while (setq p (next-single-property-change p 'display))
  13147. (when (and (get-text-property p 'display)
  13148. (eq (get-text-property p 'face) 'org-date))
  13149. (remove-text-properties
  13150. p (setq p (next-single-property-change p 'display))
  13151. '(display t))))
  13152. (set-buffer-modified-p bmp)))
  13153. (org-restart-font-lock)
  13154. (setq org-table-may-need-update t)
  13155. (if org-display-custom-times
  13156. (message "Time stamps are overlaid with custom format")
  13157. (message "Time stamp overlays removed")))
  13158. (defun org-display-custom-time (beg end)
  13159. "Overlay modified time stamp format over timestamp between BEG and END."
  13160. (let* ((ts (buffer-substring beg end))
  13161. t1 with-hm tf time str (off 0))
  13162. (save-match-data
  13163. (setq t1 (org-parse-time-string ts t))
  13164. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13165. (setq off (- (match-end 0) (match-beginning 0)))))
  13166. (setq end (- end off))
  13167. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13168. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13169. time (org-fix-decoded-time t1)
  13170. str (org-add-props
  13171. (format-time-string
  13172. (substring tf 1 -1) (apply 'encode-time time))
  13173. nil 'mouse-face 'highlight))
  13174. (put-text-property beg end 'display str)))
  13175. (defun org-fix-decoded-time (time)
  13176. "Set 0 instead of nil for the first 6 elements of time.
  13177. Don't touch the rest."
  13178. (let ((n 0))
  13179. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13180. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13181. "Difference between TIMESTAMP-STRING and now in days.
  13182. If SECONDS is non-nil, return the difference in seconds."
  13183. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13184. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13185. (funcall fdiff nil))))
  13186. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13187. "Is the time in TIMESTAMP-STRING close to the current date?"
  13188. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13189. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13190. (not (org-entry-is-done-p))))
  13191. (defun org-get-wdays (ts &optional delay zero-delay)
  13192. "Get the deadline lead time appropriate for timestring TS.
  13193. When DELAY is non-nil, get the delay time for scheduled items
  13194. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13195. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13196. don't try to find the delay cookie in the scheduled timestamp."
  13197. (let ((tv (if delay org-scheduled-delay-days
  13198. org-deadline-warning-days)))
  13199. (cond
  13200. ((or (and delay (< tv 0))
  13201. (and delay zero-delay (<= tv 0))
  13202. (and (not delay) (<= tv 0)))
  13203. ;; Enforce this value no matter what
  13204. (- tv))
  13205. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13206. ;; lead time is specified.
  13207. (floor (* (string-to-number (match-string 1 ts))
  13208. (cdr (assoc (match-string 2 ts)
  13209. '(("d" . 1) ("w" . 7)
  13210. ("m" . 30.4) ("y" . 365.25)
  13211. ("h" . 0.041667)))))))
  13212. ;; go for the default.
  13213. (t tv))))
  13214. (defun org-calendar-select-mouse (ev)
  13215. "Return to `org-read-date' with the date currently selected.
  13216. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13217. (interactive "e")
  13218. (mouse-set-point ev)
  13219. (when (calendar-cursor-to-date)
  13220. (let* ((date (calendar-cursor-to-date))
  13221. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13222. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13223. (when (active-minibuffer-window) (exit-minibuffer))))
  13224. (defun org-check-deadlines (ndays)
  13225. "Check if there are any deadlines due or past due.
  13226. A deadline is considered due if it happens within `org-deadline-warning-days'
  13227. days from today's date. If the deadline appears in an entry marked DONE,
  13228. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13229. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13230. are shown."
  13231. (interactive "P")
  13232. (let* ((org-warn-days
  13233. (cond
  13234. ((equal ndays '(4)) 100000)
  13235. (ndays (prefix-numeric-value ndays))
  13236. (t (abs org-deadline-warning-days))))
  13237. (case-fold-search nil)
  13238. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13239. (callback
  13240. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13241. (message "%d deadlines past-due or due within %d days"
  13242. (org-occur regexp nil callback)
  13243. org-warn-days)))
  13244. (defsubst org-re-timestamp (type)
  13245. "Return a regexp for timestamp TYPE.
  13246. Allowed values for TYPE are:
  13247. all: all timestamps
  13248. active: only active timestamps (<...>)
  13249. inactive: only inactive timestamps ([...])
  13250. scheduled: only scheduled timestamps
  13251. deadline: only deadline timestamps
  13252. closed: only closed time-stamps
  13253. When TYPE is nil, fall back on returning a regexp that matches
  13254. both scheduled and deadline timestamps."
  13255. (cl-case type
  13256. (all org-ts-regexp-both)
  13257. (active org-ts-regexp)
  13258. (inactive org-ts-regexp-inactive)
  13259. (scheduled org-scheduled-time-regexp)
  13260. (deadline org-deadline-time-regexp)
  13261. (closed org-closed-time-regexp)
  13262. (otherwise
  13263. (concat "\\<"
  13264. (regexp-opt (list org-deadline-string org-scheduled-string))
  13265. " *<\\([^>]+\\)>"))))
  13266. (defun org-check-before-date (d)
  13267. "Check if there are deadlines or scheduled entries before date D."
  13268. (interactive (list (org-read-date)))
  13269. (let* ((case-fold-search nil)
  13270. (regexp (org-re-timestamp org-ts-type))
  13271. (ts-type org-ts-type)
  13272. (callback
  13273. (lambda ()
  13274. (let ((match (match-string 1)))
  13275. (and (if (memq ts-type '(active inactive all))
  13276. (eq (org-element-type (save-excursion
  13277. (backward-char)
  13278. (org-element-context)))
  13279. 'timestamp)
  13280. (org-at-planning-p))
  13281. (time-less-p
  13282. (org-time-string-to-time match)
  13283. (org-time-string-to-time d)))))))
  13284. (message "%d entries before %s"
  13285. (org-occur regexp nil callback)
  13286. d)))
  13287. (defun org-check-after-date (d)
  13288. "Check if there are deadlines or scheduled entries after date D."
  13289. (interactive (list (org-read-date)))
  13290. (let* ((case-fold-search nil)
  13291. (regexp (org-re-timestamp org-ts-type))
  13292. (ts-type org-ts-type)
  13293. (callback
  13294. (lambda ()
  13295. (let ((match (match-string 1)))
  13296. (and (if (memq ts-type '(active inactive all))
  13297. (eq (org-element-type (save-excursion
  13298. (backward-char)
  13299. (org-element-context)))
  13300. 'timestamp)
  13301. (org-at-planning-p))
  13302. (not (time-less-p
  13303. (org-time-string-to-time match)
  13304. (org-time-string-to-time d))))))))
  13305. (message "%d entries after %s"
  13306. (org-occur regexp nil callback)
  13307. d)))
  13308. (defun org-check-dates-range (start-date end-date)
  13309. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13310. (interactive (list (org-read-date nil nil nil "Range starts")
  13311. (org-read-date nil nil nil "Range end")))
  13312. (let ((case-fold-search nil)
  13313. (regexp (org-re-timestamp org-ts-type))
  13314. (callback
  13315. (let ((type org-ts-type))
  13316. (lambda ()
  13317. (let ((match (match-string 1)))
  13318. (and
  13319. (if (memq type '(active inactive all))
  13320. (eq (org-element-type (save-excursion
  13321. (backward-char)
  13322. (org-element-context)))
  13323. 'timestamp)
  13324. (org-at-planning-p))
  13325. (not (time-less-p
  13326. (org-time-string-to-time match)
  13327. (org-time-string-to-time start-date)))
  13328. (time-less-p
  13329. (org-time-string-to-time match)
  13330. (org-time-string-to-time end-date))))))))
  13331. (message "%d entries between %s and %s"
  13332. (org-occur regexp nil callback) start-date end-date)))
  13333. (defun org-evaluate-time-range (&optional to-buffer)
  13334. "Evaluate a time range by computing the difference between start and end.
  13335. Normally the result is just printed in the echo area, but with prefix arg
  13336. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13337. If the time range is actually in a table, the result is inserted into the
  13338. next column.
  13339. For time difference computation, a year is assumed to be exactly 365
  13340. days in order to avoid rounding problems."
  13341. (interactive "P")
  13342. (or
  13343. (org-clock-update-time-maybe)
  13344. (save-excursion
  13345. (unless (org-at-date-range-p t)
  13346. (goto-char (point-at-bol))
  13347. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13348. (unless (org-at-date-range-p t)
  13349. (user-error "Not at a time-stamp range, and none found in current line")))
  13350. (let* ((ts1 (match-string 1))
  13351. (ts2 (match-string 2))
  13352. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13353. (match-end (match-end 0))
  13354. (time1 (org-time-string-to-time ts1))
  13355. (time2 (org-time-string-to-time ts2))
  13356. (diff (abs (float-time (time-subtract time2 time1))))
  13357. (negative (time-less-p time2 time1))
  13358. ;; (ys (floor (* 365 24 60 60)))
  13359. (ds (* 24 60 60))
  13360. (hs (* 60 60))
  13361. (fy "%dy %dd %02d:%02d")
  13362. (fy1 "%dy %dd")
  13363. (fd "%dd %02d:%02d")
  13364. (fd1 "%dd")
  13365. (fh "%02d:%02d")
  13366. y d h m align)
  13367. (if havetime
  13368. (setq ; y (floor diff ys) diff (mod diff ys)
  13369. y 0
  13370. d (floor diff ds) diff (mod diff ds)
  13371. h (floor diff hs) diff (mod diff hs)
  13372. m (floor diff 60))
  13373. (setq ; y (floor diff ys) diff (mod diff ys)
  13374. y 0
  13375. d (round diff ds)
  13376. h 0 m 0))
  13377. (if (not to-buffer)
  13378. (message "%s" (org-make-tdiff-string y d h m))
  13379. (if (org-at-table-p)
  13380. (progn
  13381. (goto-char match-end)
  13382. (setq align t)
  13383. (and (looking-at " *|") (goto-char (match-end 0))))
  13384. (goto-char match-end))
  13385. (when (looking-at
  13386. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13387. (replace-match ""))
  13388. (when negative (insert " -"))
  13389. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13390. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13391. (insert " " (format fh h m))))
  13392. (when align (org-table-align))
  13393. (message "Time difference inserted")))))
  13394. (defun org-make-tdiff-string (y d h m)
  13395. (let ((fmt "")
  13396. (l nil))
  13397. (when (> y 0)
  13398. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13399. (push y l))
  13400. (when (> d 0)
  13401. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13402. (push d l))
  13403. (when (> h 0)
  13404. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13405. (push h l))
  13406. (when (> m 0)
  13407. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13408. (push m l))
  13409. (apply 'format fmt (nreverse l))))
  13410. (defun org-time-string-to-time (s)
  13411. "Convert timestamp string S into internal time."
  13412. (apply #'encode-time (org-parse-time-string s)))
  13413. (defun org-time-string-to-seconds (s)
  13414. "Convert a timestamp string S into a number of seconds."
  13415. (float-time (org-time-string-to-time s)))
  13416. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13417. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13418. "Convert time stamp S to an absolute day number.
  13419. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13420. stamp, get the closest date to DAYNR. If PREFER is
  13421. `past' (respectively `future') return a date past (respectively
  13422. after) or equal to DAYNR.
  13423. POS is the location of time stamp S, as a buffer position in
  13424. BUFFER.
  13425. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13426. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13427. signaled."
  13428. (cond
  13429. ((string-match "\\`%%\\((.*)\\)" s)
  13430. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13431. ;; only able to match individual dates. If it fails, raise an
  13432. ;; error.
  13433. (if (and daynr
  13434. (org-diary-sexp-entry
  13435. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13436. daynr
  13437. (signal 'org-diary-sexp-no-match (list s))))
  13438. (daynr (org-closest-date s daynr prefer))
  13439. (t (time-to-days
  13440. (condition-case errdata
  13441. (org-time-string-to-time s)
  13442. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13443. s
  13444. (if (not (and buffer pos)) ""
  13445. (format-message " at %d in buffer `%s'" pos buffer))
  13446. (cdr errdata))))))))
  13447. (defun org-days-to-iso-week (days)
  13448. "Return the ISO week number."
  13449. (require 'cal-iso)
  13450. (car (calendar-iso-from-absolute days)))
  13451. (defun org-small-year-to-year (year)
  13452. "Convert 2-digit years into 4-digit years.
  13453. YEAR is expanded into one of the 30 next years, if possible, or
  13454. into a past one. Any year larger than 99 is returned unchanged."
  13455. (if (>= year 100) year
  13456. (let* ((current (string-to-number (format-time-string "%Y")))
  13457. (century (/ current 100))
  13458. (offset (- year (% current 100))))
  13459. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13460. ((> offset -70) (+ (* century 100) year))
  13461. (t (+ (* (1+ century) 100) year))))))
  13462. (defun org-time-from-absolute (d)
  13463. "Return the time corresponding to date D.
  13464. D may be an absolute day number, or a calendar-type list (month day year)."
  13465. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13466. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13467. (defvar org-agenda-current-date)
  13468. (defun org-calendar-holiday ()
  13469. "List of holidays, for Diary display in Org mode."
  13470. (require 'holidays)
  13471. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13472. (and hl (mapconcat #'identity hl "; "))))
  13473. (defun org-diary-sexp-entry (sexp entry d)
  13474. "Process a SEXP diary ENTRY for date D."
  13475. (require 'diary-lib)
  13476. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13477. ;; dynamically.
  13478. (let* ((sexp `(let ((entry ,entry)
  13479. (date ',d))
  13480. ,(car (read-from-string sexp))))
  13481. (result (if calendar-debug-sexp (eval sexp)
  13482. (condition-case nil
  13483. (eval sexp)
  13484. (error
  13485. (beep)
  13486. (message "Bad sexp at line %d in %s: %s"
  13487. (org-current-line)
  13488. (buffer-file-name) sexp)
  13489. (sleep-for 2))))))
  13490. (cond ((stringp result) (split-string result "; "))
  13491. ((and (consp result)
  13492. (not (consp (cdr result)))
  13493. (stringp (cdr result))) (cdr result))
  13494. ((and (consp result)
  13495. (stringp (car result))) result)
  13496. (result entry))))
  13497. (defun org-diary-to-ical-string (frombuf)
  13498. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13499. This uses the icalendar.el library."
  13500. (let* ((tmpdir temporary-file-directory)
  13501. (tmpfile (make-temp-name
  13502. (expand-file-name "orgics" tmpdir)))
  13503. buf rtn b e)
  13504. (with-current-buffer frombuf
  13505. (icalendar-export-region (point-min) (point-max) tmpfile)
  13506. (setq buf (find-buffer-visiting tmpfile))
  13507. (set-buffer buf)
  13508. (goto-char (point-min))
  13509. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13510. (setq b (match-beginning 0)))
  13511. (goto-char (point-max))
  13512. (when (re-search-backward "^END:VEVENT" nil t)
  13513. (setq e (match-end 0)))
  13514. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13515. (kill-buffer buf)
  13516. (delete-file tmpfile)
  13517. rtn))
  13518. (defun org-closest-date (start current prefer)
  13519. "Return closest date to CURRENT starting from START.
  13520. CURRENT and START are both time stamps.
  13521. When PREFER is `past', return a date that is either CURRENT or
  13522. past. When PREFER is `future', return a date that is either
  13523. CURRENT or future.
  13524. Only time stamps with a repeater are modified. Any other time
  13525. stamp stay unchanged. In any case, return value is an absolute
  13526. day number."
  13527. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13528. ;; No repeater. Do not shift time stamp.
  13529. (time-to-days (org-time-string-to-time start))
  13530. (let ((value (string-to-number (match-string 1 start)))
  13531. (type (match-string 2 start)))
  13532. (if (= 0 value)
  13533. ;; Repeater with a 0-value is considered as void.
  13534. (time-to-days (org-time-string-to-time start))
  13535. (let* ((base (org-date-to-gregorian start))
  13536. (target (org-date-to-gregorian current))
  13537. (sday (calendar-absolute-from-gregorian base))
  13538. (cday (calendar-absolute-from-gregorian target))
  13539. n1 n2)
  13540. ;; If START is already past CURRENT, just return START.
  13541. (if (<= cday sday) sday
  13542. ;; Compute closest date before (N1) and closest date past
  13543. ;; (N2) CURRENT.
  13544. (pcase type
  13545. ("h"
  13546. (let ((missing-hours
  13547. (mod (+ (- (* 24 (- cday sday))
  13548. (nth 2 (org-parse-time-string start)))
  13549. org-extend-today-until)
  13550. value)))
  13551. (setf n1 (if (= missing-hours 0) cday
  13552. (- cday (1+ (/ missing-hours 24)))))
  13553. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13554. ((or "d" "w")
  13555. (let ((value (if (equal type "w") (* 7 value) value)))
  13556. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13557. (setf n2 (+ n1 value))))
  13558. ("m"
  13559. (let* ((add-months
  13560. (lambda (d n)
  13561. ;; Add N months to gregorian date D, i.e.,
  13562. ;; a list (MONTH DAY YEAR). Return a valid
  13563. ;; gregorian date.
  13564. (let ((m (+ (nth 0 d) n)))
  13565. (list (mod m 12)
  13566. (nth 1 d)
  13567. (+ (/ m 12) (nth 2 d))))))
  13568. (months ; Complete months to TARGET.
  13569. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13570. (- (nth 0 target) (nth 0 base))
  13571. ;; If START's day is greater than
  13572. ;; TARGET's, remove incomplete month.
  13573. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13574. value)
  13575. value))
  13576. (before (funcall add-months base months)))
  13577. (setf n1 (calendar-absolute-from-gregorian before))
  13578. (setf n2
  13579. (calendar-absolute-from-gregorian
  13580. (funcall add-months before value)))))
  13581. (_
  13582. (let* ((d (nth 1 base))
  13583. (m (nth 0 base))
  13584. (y (nth 2 base))
  13585. (years ; Complete years to TARGET.
  13586. (* (/ (- (nth 2 target)
  13587. y
  13588. ;; If START's month and day are
  13589. ;; greater than TARGET's, remove
  13590. ;; incomplete year.
  13591. (if (or (> (nth 0 target) m)
  13592. (and (= (nth 0 target) m)
  13593. (> (nth 1 target) d)))
  13594. 0
  13595. 1))
  13596. value)
  13597. value))
  13598. (before (list m d (+ y years))))
  13599. (setf n1 (calendar-absolute-from-gregorian before))
  13600. (setf n2 (calendar-absolute-from-gregorian
  13601. (list m d (+ (nth 2 before) value)))))))
  13602. ;; Handle PREFER parameter, if any.
  13603. (cond
  13604. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13605. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13606. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13607. (defun org-date-to-gregorian (d)
  13608. "Turn any specification of date D into a Gregorian date for the calendar."
  13609. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13610. ((and (listp d) (= (length d) 3)) d)
  13611. ((stringp d)
  13612. (let ((d (org-parse-time-string d)))
  13613. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13614. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13615. (defun org-timestamp-up (&optional arg)
  13616. "Increase the date item at the cursor by one.
  13617. If the cursor is on the year, change the year. If it is on the month,
  13618. the day or the time, change that. If the cursor is on the enclosing
  13619. bracket, change the timestamp type.
  13620. With prefix ARG, change by that many units."
  13621. (interactive "p")
  13622. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13623. (defun org-timestamp-down (&optional arg)
  13624. "Decrease the date item at the cursor by one.
  13625. If the cursor is on the year, change the year. If it is on the month,
  13626. the day or the time, change that. If the cursor is on the enclosing
  13627. bracket, change the timestamp type.
  13628. With prefix ARG, change by that many units."
  13629. (interactive "p")
  13630. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13631. (defun org-timestamp-up-day (&optional arg)
  13632. "Increase the date in the time stamp by one day.
  13633. With prefix ARG, change that many days."
  13634. (interactive "p")
  13635. (if (and (not (org-at-timestamp-p 'lax))
  13636. (org-at-heading-p))
  13637. (org-todo 'up)
  13638. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13639. (defun org-timestamp-down-day (&optional arg)
  13640. "Decrease the date in the time stamp by one day.
  13641. With prefix ARG, change that many days."
  13642. (interactive "p")
  13643. (if (and (not (org-at-timestamp-p 'lax))
  13644. (org-at-heading-p))
  13645. (org-todo 'down)
  13646. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13647. (defun org-at-timestamp-p (&optional extended)
  13648. "Non-nil if point is inside a timestamp.
  13649. By default, the function only consider syntactically valid active
  13650. timestamps. However, the caller may have a broader definition
  13651. for timestamps. As a consequence, optional argument EXTENDED can
  13652. be set to the following values
  13653. `inactive'
  13654. Include also syntactically valid inactive timestamps.
  13655. `agenda'
  13656. Include timestamps allowed in Agenda, i.e., those in
  13657. properties drawers, planning lines and clock lines.
  13658. `lax'
  13659. Ignore context. The function matches any part of the
  13660. document looking like a timestamp. This includes comments,
  13661. example blocks...
  13662. For backward-compatibility with Org 9.0, every other non-nil
  13663. value is equivalent to `inactive'.
  13664. When at a timestamp, return the position of the point as a symbol
  13665. among `bracket', `after', `year', `month', `hour', `minute',
  13666. `day' or a number of character from the last know part of the
  13667. time stamp. If diary sexp timestamps, any point inside the timestamp
  13668. is considered `day' (i.e. only `bracket', `day', and `after' return
  13669. values are possible).
  13670. When matching, the match groups are the following:
  13671. group 1: year, if any
  13672. group 2: month, if any
  13673. group 3: day number, if any
  13674. group 4: day name, if any
  13675. group 5: hours, if any
  13676. group 6: minutes, if any"
  13677. (let* ((regexp
  13678. (if extended
  13679. (if (eq extended 'agenda)
  13680. (rx-to-string
  13681. `(or (regexp ,org-ts-regexp3)
  13682. (regexp ,org-element--timestamp-regexp)))
  13683. org-ts-regexp3)
  13684. org-ts-regexp2))
  13685. (pos (point))
  13686. (match?
  13687. (let ((boundaries (org-in-regexp regexp)))
  13688. (save-match-data
  13689. (cond ((null boundaries) nil)
  13690. ((eq extended 'lax) t)
  13691. (t
  13692. (or (and (eq extended 'agenda)
  13693. (or (org-at-planning-p)
  13694. (org-at-property-p)
  13695. (and (bound-and-true-p
  13696. org-agenda-include-inactive-timestamps)
  13697. (org-at-clock-log-p))))
  13698. (eq 'timestamp
  13699. (save-excursion
  13700. (when (= pos (cdr boundaries)) (forward-char -1))
  13701. (org-element-type (org-element-context)))))))))))
  13702. (cond
  13703. ((not match?) nil)
  13704. ((= pos (match-beginning 0)) 'bracket)
  13705. ;; Distinguish location right before the closing bracket from
  13706. ;; right after it.
  13707. ((= pos (1- (match-end 0))) 'bracket)
  13708. ((= pos (match-end 0)) 'after)
  13709. ((org-pos-in-match-range pos 2) 'year)
  13710. ((org-pos-in-match-range pos 3) 'month)
  13711. ((org-pos-in-match-range pos 7) 'hour)
  13712. ((org-pos-in-match-range pos 8) 'minute)
  13713. ((or (org-pos-in-match-range pos 4)
  13714. (org-pos-in-match-range pos 5)) 'day)
  13715. ((and (or (match-end 8) (match-end 5))
  13716. (> pos (or (match-end 8) (match-end 5)))
  13717. (< pos (match-end 0)))
  13718. (- pos (or (match-end 8) (match-end 5))))
  13719. (t 'day))))
  13720. (defun org-toggle-timestamp-type ()
  13721. "Toggle the type (<active> or [inactive]) of a time stamp."
  13722. (interactive)
  13723. (when (org-at-timestamp-p 'lax)
  13724. (let ((beg (match-beginning 0)) (end (match-end 0))
  13725. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13726. (save-excursion
  13727. (goto-char beg)
  13728. (while (re-search-forward "[][<>]" end t)
  13729. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13730. t t)))
  13731. (message "Timestamp is now %sactive"
  13732. (if (equal (char-after beg) ?<) "" "in")))))
  13733. (defun org-at-clock-log-p ()
  13734. "Non-nil if point is on a clock log line."
  13735. (and (org-match-line org-clock-line-re)
  13736. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13737. (defvar org-clock-history) ; defined in org-clock.el
  13738. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13739. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13740. "Change the date in the time stamp at point.
  13741. The date is changed by N times WHAT. WHAT can be `day', `month',
  13742. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13743. position in the timestamp determines what is changed.
  13744. When optional argument UPDOWN is non-nil, minutes are rounded
  13745. according to `org-time-stamp-rounding-minutes'.
  13746. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13747. \"--2d\"."
  13748. (let ((origin (point))
  13749. (timestamp? (org-at-timestamp-p 'lax))
  13750. origin-cat
  13751. with-hm inactive
  13752. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13753. extra rem
  13754. ts time time0 fixnext clrgx)
  13755. (unless timestamp? (user-error "Not at a timestamp"))
  13756. (if (and (not what) (eq timestamp? 'bracket))
  13757. (org-toggle-timestamp-type)
  13758. ;; Point isn't on brackets. Remember the part of the time-stamp
  13759. ;; the point was in. Indeed, size of time-stamps may change,
  13760. ;; but point must be kept in the same category nonetheless.
  13761. (setq origin-cat timestamp?)
  13762. (when (and (not what) (not (eq timestamp? 'day))
  13763. org-display-custom-times
  13764. (get-text-property (point) 'display)
  13765. (not (get-text-property (1- (point)) 'display)))
  13766. (setq timestamp? 'day))
  13767. (setq timestamp? (or what timestamp?)
  13768. inactive (= (char-after (match-beginning 0)) ?\[)
  13769. ts (match-string 0))
  13770. (replace-match "")
  13771. (when (string-match
  13772. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13773. ts)
  13774. (setq extra (match-string 1 ts))
  13775. (when suppress-tmp-delay
  13776. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13777. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13778. (setq with-hm t))
  13779. (setq time0 (org-parse-time-string ts))
  13780. (when (and updown
  13781. (eq timestamp? 'minute)
  13782. (not current-prefix-arg))
  13783. ;; This looks like s-up and s-down. Change by one rounding step.
  13784. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13785. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13786. (setcar (cdr time0) (+ (nth 1 time0)
  13787. (if (> n 0) (- rem) (- dm rem))))))
  13788. (setq time
  13789. (apply #'encode-time
  13790. (or (car time0) 0)
  13791. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13792. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13793. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13794. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13795. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13796. (nthcdr 6 time0)))
  13797. (when (and (memq timestamp? '(hour minute))
  13798. extra
  13799. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13800. (setq extra (org-modify-ts-extra
  13801. extra
  13802. (if (eq timestamp? 'hour) 2 5)
  13803. n dm)))
  13804. (when (integerp timestamp?)
  13805. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13806. (when (eq what 'calendar)
  13807. (let ((cal-date (org-get-date-from-calendar)))
  13808. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13809. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13810. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13811. (setcar time0 (or (car time0) 0))
  13812. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13813. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13814. (setq time (apply 'encode-time time0))))
  13815. ;; Insert the new time-stamp, and ensure point stays in the same
  13816. ;; category as before (i.e. not after the last position in that
  13817. ;; category).
  13818. (let ((pos (point)))
  13819. ;; Stay before inserted string. `save-excursion' is of no use.
  13820. (setq org-last-changed-timestamp
  13821. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13822. (goto-char pos))
  13823. (save-match-data
  13824. (looking-at org-ts-regexp3)
  13825. (goto-char
  13826. (pcase origin-cat
  13827. ;; `day' category ends before `hour' if any, or at the end
  13828. ;; of the day name.
  13829. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13830. (`hour (min (match-end 7) origin))
  13831. (`minute (min (1- (match-end 8)) origin))
  13832. ((pred integerp) (min (1- (match-end 0)) origin))
  13833. ;; Point was right after the time-stamp. However, the
  13834. ;; time-stamp length might have changed, so refer to
  13835. ;; (match-end 0) instead.
  13836. (`after (match-end 0))
  13837. ;; `year' and `month' have both fixed size: point couldn't
  13838. ;; have moved into another part.
  13839. (_ origin))))
  13840. ;; Update clock if on a CLOCK line.
  13841. (org-clock-update-time-maybe)
  13842. ;; Maybe adjust the closest clock in `org-clock-history'
  13843. (when org-clock-adjust-closest
  13844. (if (not (and (org-at-clock-log-p)
  13845. (< 1 (length (delq nil (mapcar 'marker-position
  13846. org-clock-history))))))
  13847. (message "No clock to adjust")
  13848. (cond ((save-excursion ; fix previous clock?
  13849. (re-search-backward org-ts-regexp0 nil t)
  13850. (looking-back (concat org-clock-string " \\[")
  13851. (line-beginning-position)))
  13852. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13853. ((save-excursion ; fix next clock?
  13854. (re-search-backward org-ts-regexp0 nil t)
  13855. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13856. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13857. (save-window-excursion
  13858. ;; Find closest clock to point, adjust the previous/next one in history
  13859. (let* ((p (save-excursion (org-back-to-heading t)))
  13860. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13861. (clfixnth
  13862. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13863. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13864. (if (not clfixpos)
  13865. (message "No clock to adjust")
  13866. (save-excursion
  13867. (org-goto-marker-or-bmk clfixpos)
  13868. (org-show-subtree)
  13869. (when (re-search-forward clrgx nil t)
  13870. (goto-char (match-beginning 1))
  13871. (let (org-clock-adjust-closest)
  13872. (org-timestamp-change n timestamp? updown))
  13873. (message "Clock adjusted in %s for heading: %s"
  13874. (file-name-nondirectory (buffer-file-name))
  13875. (org-get-heading t t)))))))))
  13876. ;; Try to recenter the calendar window, if any.
  13877. (when (and org-calendar-follow-timestamp-change
  13878. (get-buffer-window "*Calendar*" t)
  13879. (memq timestamp? '(day month year)))
  13880. (org-recenter-calendar (time-to-days time))))))
  13881. (defun org-modify-ts-extra (s pos n dm)
  13882. "Change the different parts of the lead-time and repeat fields in timestamp."
  13883. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13884. ng h m new rem)
  13885. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13886. (cond
  13887. ((or (org-pos-in-match-range pos 2)
  13888. (org-pos-in-match-range pos 3))
  13889. (setq m (string-to-number (match-string 3 s))
  13890. h (string-to-number (match-string 2 s)))
  13891. (if (org-pos-in-match-range pos 2)
  13892. (setq h (+ h n))
  13893. (setq n (* dm (with-no-warnings (cl-signum n))))
  13894. (unless (= 0 (setq rem (% m dm)))
  13895. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13896. (setq m (+ m n)))
  13897. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13898. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13899. (setq h (mod h 24))
  13900. (setq ng 1 new (format "-%02d:%02d" h m)))
  13901. ((org-pos-in-match-range pos 6)
  13902. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13903. ((org-pos-in-match-range pos 5)
  13904. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13905. ((org-pos-in-match-range pos 9)
  13906. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13907. ((org-pos-in-match-range pos 8)
  13908. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13909. (when ng
  13910. (setq s (concat
  13911. (substring s 0 (match-beginning ng))
  13912. new
  13913. (substring s (match-end ng))))))
  13914. s))
  13915. (defun org-recenter-calendar (d)
  13916. "If the calendar is visible, recenter it to date D."
  13917. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13918. (when cwin
  13919. (let ((calendar-move-hook nil))
  13920. (with-selected-window cwin
  13921. (calendar-goto-date
  13922. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13923. (defun org-goto-calendar (&optional arg)
  13924. "Go to the Emacs calendar at the current date.
  13925. If there is a time stamp in the current line, go to that date.
  13926. A prefix ARG can be used to force the current date."
  13927. (interactive "P")
  13928. (let ((calendar-move-hook nil)
  13929. (calendar-view-holidays-initially-flag nil)
  13930. (calendar-view-diary-initially-flag nil)
  13931. diff)
  13932. (when (or (org-at-timestamp-p 'lax)
  13933. (org-match-line (concat ".*" org-ts-regexp)))
  13934. (let ((d1 (time-to-days nil))
  13935. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13936. (setq diff (- d2 d1))))
  13937. (calendar)
  13938. (calendar-goto-today)
  13939. (when (and diff (not arg)) (calendar-forward-day diff))))
  13940. (defun org-get-date-from-calendar ()
  13941. "Return a list (month day year) of date at point in calendar."
  13942. (with-current-buffer "*Calendar*"
  13943. (save-match-data
  13944. (calendar-cursor-to-date))))
  13945. (defun org-date-from-calendar ()
  13946. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13947. If there is already a time stamp at the cursor position, update it."
  13948. (interactive)
  13949. (if (org-at-timestamp-p 'lax)
  13950. (org-timestamp-change 0 'calendar)
  13951. (let ((cal-date (org-get-date-from-calendar)))
  13952. (org-insert-time-stamp
  13953. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13954. (defcustom org-image-actual-width t
  13955. "When non-nil, use the actual width of images when inlining them.
  13956. When set to a number, use imagemagick (when available) to set the
  13957. image's width to this value.
  13958. When set to a number in a list, try to get the width from any
  13959. #+ATTR.* keyword if it matches a width specification like
  13960. #+ATTR_HTML: :width 300px
  13961. and fall back on that number if none is found.
  13962. When set to nil, try to get the width from an #+ATTR.* keyword
  13963. and fall back on the original width if none is found.
  13964. When set to any other non-nil value, always use the image width.
  13965. This requires Emacs >= 24.1, built with imagemagick support."
  13966. :group 'org-appearance
  13967. :version "24.4"
  13968. :package-version '(Org . "8.0")
  13969. :type '(choice
  13970. (const :tag "Use the image width" t)
  13971. (integer :tag "Use a number of pixels")
  13972. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13973. (const :tag "Use #+ATTR* or don't resize" nil)))
  13974. (defcustom org-agenda-inhibit-startup nil
  13975. "Inhibit startup when preparing agenda buffers.
  13976. When this variable is t, the initialization of the Org agenda
  13977. buffers is inhibited: e.g. the visibility state is not set, the
  13978. tables are not re-aligned, etc."
  13979. :type 'boolean
  13980. :version "24.3"
  13981. :group 'org-agenda)
  13982. (defcustom org-agenda-ignore-properties nil
  13983. "Avoid updating text properties when building the agenda.
  13984. Properties are used to prepare buffers for effort estimates,
  13985. appointments, statistics and subtree-local categories.
  13986. If you don't use these in the agenda, you can add them to this
  13987. list and agenda building will be a bit faster.
  13988. The value is a list, with zero or more of the symbols `effort', `appt',
  13989. `stats' or `category'."
  13990. :type '(set :greedy t
  13991. (const effort)
  13992. (const appt)
  13993. (const stats)
  13994. (const category))
  13995. :version "26.1"
  13996. :package-version '(Org . "8.3")
  13997. :group 'org-agenda)
  13998. ;;;; Files
  13999. (defun org-save-all-org-buffers ()
  14000. "Save all Org buffers without user confirmation."
  14001. (interactive)
  14002. (message "Saving all Org buffers...")
  14003. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  14004. (when (featurep 'org-id) (org-id-locations-save))
  14005. (message "Saving all Org buffers... done"))
  14006. (defun org-revert-all-org-buffers ()
  14007. "Revert all Org buffers.
  14008. Prompt for confirmation when there are unsaved changes.
  14009. Be sure you know what you are doing before letting this function
  14010. overwrite your changes.
  14011. This function is useful in a setup where one tracks Org files
  14012. with a version control system, to revert on one machine after pulling
  14013. changes from another. I believe the procedure must be like this:
  14014. 1. \\[org-save-all-org-buffers]
  14015. 2. Pull changes from the other machine, resolve conflicts
  14016. 3. \\[org-revert-all-org-buffers]"
  14017. (interactive)
  14018. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14019. (user-error "Abort"))
  14020. (save-excursion
  14021. (save-window-excursion
  14022. (dolist (b (buffer-list))
  14023. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14024. (with-current-buffer b buffer-file-name))
  14025. (pop-to-buffer-same-window b)
  14026. (revert-buffer t 'no-confirm)))
  14027. (when (and (featurep 'org-id) org-id-track-globally)
  14028. (org-id-locations-load)))))
  14029. ;;;; Agenda files
  14030. ;;;###autoload
  14031. (defun org-switchb (&optional arg)
  14032. "Switch between Org buffers.
  14033. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14034. With `\\[universal-argument] \\[universal-argument]' \
  14035. prefix, restrict available buffers to agenda files."
  14036. (interactive "P")
  14037. (let ((blist (org-buffer-list
  14038. (cond ((equal arg '(4)) 'files)
  14039. ((equal arg '(16)) 'agenda)))))
  14040. (pop-to-buffer-same-window
  14041. (completing-read "Org buffer: "
  14042. (mapcar #'list (mapcar #'buffer-name blist))
  14043. nil t))))
  14044. (defun org-buffer-list (&optional predicate exclude-tmp)
  14045. "Return a list of Org buffers.
  14046. PREDICATE can be `export', `files' or `agenda'.
  14047. export restrict the list to Export buffers.
  14048. files restrict the list to buffers visiting Org files.
  14049. agenda restrict the list to buffers visiting agenda files.
  14050. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14051. (let* ((bfn nil)
  14052. (agenda-files (and (eq predicate 'agenda)
  14053. (mapcar 'file-truename (org-agenda-files t))))
  14054. (filter
  14055. (cond
  14056. ((eq predicate 'files)
  14057. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14058. ((eq predicate 'export)
  14059. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14060. ((eq predicate 'agenda)
  14061. (lambda (b)
  14062. (with-current-buffer b
  14063. (and (derived-mode-p 'org-mode)
  14064. (setq bfn (buffer-file-name b))
  14065. (member (file-truename bfn) agenda-files)))))
  14066. (t (lambda (b) (with-current-buffer b
  14067. (or (derived-mode-p 'org-mode)
  14068. (string-match "\\*Org .*Export"
  14069. (buffer-name b)))))))))
  14070. (delq nil
  14071. (mapcar
  14072. (lambda(b)
  14073. (if (and (funcall filter b)
  14074. (or (not exclude-tmp)
  14075. (not (string-match "tmp" (buffer-name b)))))
  14076. b
  14077. nil))
  14078. (buffer-list)))))
  14079. (defun org-agenda-files (&optional unrestricted archives)
  14080. "Get the list of agenda files.
  14081. Optional UNRESTRICTED means return the full list even if a restriction
  14082. is currently in place.
  14083. When ARCHIVES is t, include all archive files that are really being
  14084. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14085. `org-agenda-archives-mode' is t."
  14086. (let ((files
  14087. (cond
  14088. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14089. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14090. ((listp org-agenda-files) org-agenda-files)
  14091. (t (error "Invalid value of `org-agenda-files'")))))
  14092. (setq files (apply 'append
  14093. (mapcar (lambda (f)
  14094. (if (file-directory-p f)
  14095. (directory-files
  14096. f t org-agenda-file-regexp)
  14097. (list (expand-file-name f org-directory))))
  14098. files)))
  14099. (when org-agenda-skip-unavailable-files
  14100. (setq files (delq nil
  14101. (mapcar (lambda (file)
  14102. (and (file-readable-p file) file))
  14103. files))))
  14104. (when (or (eq archives t)
  14105. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14106. (setq files (org-add-archive-files files)))
  14107. files))
  14108. (defun org-agenda-file-p (&optional file)
  14109. "Return non-nil, if FILE is an agenda file.
  14110. If FILE is omitted, use the file associated with the current
  14111. buffer."
  14112. (let ((fname (or file (buffer-file-name))))
  14113. (and fname
  14114. (member (file-truename fname)
  14115. (mapcar #'file-truename (org-agenda-files t))))))
  14116. (defun org-edit-agenda-file-list ()
  14117. "Edit the list of agenda files.
  14118. Depending on setup, this either uses customize to edit the variable
  14119. `org-agenda-files', or it visits the file that is holding the list. In the
  14120. latter case, the buffer is set up in a way that saving it automatically kills
  14121. the buffer and restores the previous window configuration."
  14122. (interactive)
  14123. (if (stringp org-agenda-files)
  14124. (let ((cw (current-window-configuration)))
  14125. (find-file org-agenda-files)
  14126. (setq-local org-window-configuration cw)
  14127. (add-hook 'after-save-hook
  14128. (lambda ()
  14129. (set-window-configuration
  14130. (prog1 org-window-configuration
  14131. (kill-buffer (current-buffer))))
  14132. (org-install-agenda-files-menu)
  14133. (message "New agenda file list installed"))
  14134. nil 'local)
  14135. (message "%s" (substitute-command-keys
  14136. "Edit list and finish with \\[save-buffer]")))
  14137. (customize-variable 'org-agenda-files)))
  14138. (defun org-store-new-agenda-file-list (list)
  14139. "Set new value for the agenda file list and save it correctly."
  14140. (if (stringp org-agenda-files)
  14141. (let ((fe (org-read-agenda-file-list t)) b u)
  14142. (while (setq b (find-buffer-visiting org-agenda-files))
  14143. (kill-buffer b))
  14144. (with-temp-file org-agenda-files
  14145. (insert
  14146. (mapconcat
  14147. (lambda (f) ;; Keep un-expanded entries.
  14148. (if (setq u (assoc f fe))
  14149. (cdr u)
  14150. f))
  14151. list "\n")
  14152. "\n")))
  14153. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14154. (org-insert-mode-line-in-empty-file nil))
  14155. (setq org-agenda-files list)
  14156. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14157. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14158. "Read the list of agenda files from a file.
  14159. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14160. filenames, used by `org-store-new-agenda-file-list' to write back
  14161. un-expanded file names."
  14162. (when (file-directory-p org-agenda-files)
  14163. (error "`org-agenda-files' cannot be a single directory"))
  14164. (when (stringp org-agenda-files)
  14165. (with-temp-buffer
  14166. (insert-file-contents org-agenda-files)
  14167. (mapcar
  14168. (lambda (f)
  14169. (let ((e (expand-file-name (substitute-in-file-name f)
  14170. org-directory)))
  14171. (if pair-with-expansion
  14172. (cons e f)
  14173. e)))
  14174. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14175. ;;;###autoload
  14176. (defun org-cycle-agenda-files ()
  14177. "Cycle through the files in `org-agenda-files'.
  14178. If the current buffer visits an agenda file, find the next one in the list.
  14179. If the current buffer does not, find the first agenda file."
  14180. (interactive)
  14181. (let* ((fs (or (org-agenda-files t)
  14182. (user-error "No agenda files")))
  14183. (files (copy-sequence fs))
  14184. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14185. file)
  14186. (when tcf
  14187. (while (and (setq file (pop files))
  14188. (not (equal (file-truename file) tcf)))))
  14189. (find-file (car (or files fs)))
  14190. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14191. (defun org-agenda-file-to-front (&optional to-end)
  14192. "Move/add the current file to the top of the agenda file list.
  14193. If the file is not present in the list, it is added to the front. If it is
  14194. present, it is moved there. With optional argument TO-END, add/move to the
  14195. end of the list."
  14196. (interactive "P")
  14197. (let ((org-agenda-skip-unavailable-files nil)
  14198. (file-alist (mapcar (lambda (x)
  14199. (cons (file-truename x) x))
  14200. (org-agenda-files t)))
  14201. (ctf (file-truename
  14202. (or buffer-file-name
  14203. (user-error "Please save the current buffer to a file"))))
  14204. x had)
  14205. (setq x (assoc ctf file-alist) had x)
  14206. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14207. (if to-end
  14208. (setq file-alist (append (delq x file-alist) (list x)))
  14209. (setq file-alist (cons x (delq x file-alist))))
  14210. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14211. (org-install-agenda-files-menu)
  14212. (message "File %s to %s of agenda file list"
  14213. (if had "moved" "added") (if to-end "end" "front"))))
  14214. (defun org-remove-file (&optional file)
  14215. "Remove current file from the list of files in variable `org-agenda-files'.
  14216. These are the files which are being checked for agenda entries.
  14217. Optional argument FILE means use this file instead of the current."
  14218. (interactive)
  14219. (let* ((org-agenda-skip-unavailable-files nil)
  14220. (file (or file buffer-file-name
  14221. (user-error "Current buffer does not visit a file")))
  14222. (true-file (file-truename file))
  14223. (afile (abbreviate-file-name file))
  14224. (files (delq nil (mapcar
  14225. (lambda (x)
  14226. (unless (equal true-file
  14227. (file-truename x))
  14228. x))
  14229. (org-agenda-files t)))))
  14230. (if (not (= (length files) (length (org-agenda-files t))))
  14231. (progn
  14232. (org-store-new-agenda-file-list files)
  14233. (org-install-agenda-files-menu)
  14234. (message "Removed from Org Agenda list: %s" afile))
  14235. (message "File was not in list: %s (not removed)" afile))))
  14236. (defun org-file-menu-entry (file)
  14237. (vector file (list 'find-file file) t))
  14238. (defun org-check-agenda-file (file)
  14239. "Make sure FILE exists. If not, ask user what to do."
  14240. (unless (file-exists-p file)
  14241. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14242. (abbreviate-file-name file))
  14243. (let ((r (downcase (read-char-exclusive))))
  14244. (cond
  14245. ((equal r ?r)
  14246. (org-remove-file file)
  14247. (throw 'nextfile t))
  14248. (t (user-error "Abort"))))))
  14249. (defun org-get-agenda-file-buffer (file)
  14250. "Get an agenda buffer visiting FILE.
  14251. If the buffer needs to be created, add it to the list of buffers
  14252. which might be released later."
  14253. (let ((buf (org-find-base-buffer-visiting file)))
  14254. (if buf
  14255. buf ; just return it
  14256. ;; Make a new buffer and remember it
  14257. (setq buf (find-file-noselect file))
  14258. (when buf (push buf org-agenda-new-buffers))
  14259. buf)))
  14260. (defun org-release-buffers (blist)
  14261. "Release all buffers in list, asking the user for confirmation when needed.
  14262. When a buffer is unmodified, it is just killed. When modified, it is saved
  14263. \(if the user agrees) and then killed."
  14264. (let (file)
  14265. (dolist (buf blist)
  14266. (setq file (buffer-file-name buf))
  14267. (when (and (buffer-modified-p buf)
  14268. file
  14269. (y-or-n-p (format "Save file %s? " file)))
  14270. (with-current-buffer buf (save-buffer)))
  14271. (kill-buffer buf))))
  14272. (defun org-agenda-prepare-buffers (files)
  14273. "Create buffers for all agenda files, protect archived trees and comments."
  14274. (interactive)
  14275. (let ((pa '(:org-archived t))
  14276. (pc '(:org-comment t))
  14277. (pall '(:org-archived t :org-comment t))
  14278. (inhibit-read-only t)
  14279. (org-inhibit-startup org-agenda-inhibit-startup)
  14280. (rea (org-make-tag-string (list org-archive-tag)))
  14281. re pos)
  14282. (setq org-tag-alist-for-agenda nil
  14283. org-tag-groups-alist-for-agenda nil)
  14284. (save-excursion
  14285. (save-restriction
  14286. (dolist (file files)
  14287. (catch 'nextfile
  14288. (if (bufferp file)
  14289. (set-buffer file)
  14290. (org-check-agenda-file file)
  14291. (set-buffer (org-get-agenda-file-buffer file)))
  14292. (widen)
  14293. (org-set-regexps-and-options 'tags-only)
  14294. (setq pos (point))
  14295. (or (memq 'category org-agenda-ignore-properties)
  14296. (org-refresh-category-properties))
  14297. (or (memq 'stats org-agenda-ignore-properties)
  14298. (org-refresh-stats-properties))
  14299. (or (memq 'effort org-agenda-ignore-properties)
  14300. (org-refresh-effort-properties))
  14301. (or (memq 'appt org-agenda-ignore-properties)
  14302. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14303. (setq org-todo-keywords-for-agenda
  14304. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14305. (setq org-done-keywords-for-agenda
  14306. (append org-done-keywords-for-agenda org-done-keywords))
  14307. (setq org-todo-keyword-alist-for-agenda
  14308. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14309. (setq org-tag-alist-for-agenda
  14310. (org--tag-add-to-alist
  14311. org-tag-alist-for-agenda
  14312. org-current-tag-alist))
  14313. ;; Merge current file's tag groups into global
  14314. ;; `org-tag-groups-alist-for-agenda'.
  14315. (when org-group-tags
  14316. (dolist (alist org-tag-groups-alist)
  14317. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14318. (if old
  14319. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14320. (push alist org-tag-groups-alist-for-agenda)))))
  14321. (with-silent-modifications
  14322. (save-excursion
  14323. (remove-text-properties (point-min) (point-max) pall)
  14324. (when org-agenda-skip-archived-trees
  14325. (goto-char (point-min))
  14326. (while (re-search-forward rea nil t)
  14327. (when (org-at-heading-p t)
  14328. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14329. (goto-char (point-min))
  14330. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14331. (while (re-search-forward re nil t)
  14332. (when (save-match-data (org-in-commented-heading-p t))
  14333. (add-text-properties
  14334. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14335. (goto-char pos)))))
  14336. (setq org-todo-keywords-for-agenda
  14337. (org-uniquify org-todo-keywords-for-agenda))
  14338. (setq org-todo-keyword-alist-for-agenda
  14339. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14340. ;;;; CDLaTeX minor mode
  14341. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14342. "Keymap for the minor `org-cdlatex-mode'.")
  14343. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14344. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14345. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14346. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14347. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14348. (defvar org-cdlatex-texmathp-advice-is-done nil
  14349. "Flag remembering if we have applied the advice to texmathp already.")
  14350. (define-minor-mode org-cdlatex-mode
  14351. "Toggle the minor `org-cdlatex-mode'.
  14352. This mode supports entering LaTeX environment and math in LaTeX fragments
  14353. in Org mode.
  14354. \\{org-cdlatex-mode-map}"
  14355. :lighter " OCDL"
  14356. (when org-cdlatex-mode
  14357. (require 'cdlatex)
  14358. (run-hooks 'cdlatex-mode-hook)
  14359. (cdlatex-compute-tables))
  14360. (unless org-cdlatex-texmathp-advice-is-done
  14361. (setq org-cdlatex-texmathp-advice-is-done t)
  14362. (defadvice texmathp (around org-math-always-on activate)
  14363. "Always return t in Org buffers.
  14364. This is because we want to insert math symbols without dollars even outside
  14365. the LaTeX math segments. If Org mode thinks that point is actually inside
  14366. an embedded LaTeX fragment, let `texmathp' do its job.
  14367. `\\[org-cdlatex-mode-map]'"
  14368. (interactive)
  14369. (let (p)
  14370. (cond
  14371. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14372. ((eq this-command 'cdlatex-math-symbol)
  14373. (setq ad-return-value t
  14374. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14375. (t
  14376. (let ((p (org-inside-LaTeX-fragment-p)))
  14377. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14378. (setq ad-return-value t
  14379. texmathp-why '("Org mode embedded math" . 0))
  14380. (when p ad-do-it)))))))))
  14381. (defun turn-on-org-cdlatex ()
  14382. "Unconditionally turn on `org-cdlatex-mode'."
  14383. (org-cdlatex-mode 1))
  14384. (defun org-try-cdlatex-tab ()
  14385. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14386. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14387. - inside a LaTeX fragment, or
  14388. - after the first word in a line, where an abbreviation expansion could
  14389. insert a LaTeX environment."
  14390. (when org-cdlatex-mode
  14391. (cond
  14392. ;; Before any word on the line: No expansion possible.
  14393. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14394. ;; Just after first word on the line: Expand it. Make sure it
  14395. ;; cannot happen on headlines, though.
  14396. ((save-excursion
  14397. (skip-chars-backward "a-zA-Z0-9*")
  14398. (skip-chars-backward " \t")
  14399. (and (bolp) (not (org-at-heading-p))))
  14400. (cdlatex-tab) t)
  14401. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14402. (defun org-cdlatex-underscore-caret (&optional _arg)
  14403. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14404. Revert to the normal definition outside of these fragments."
  14405. (interactive "P")
  14406. (if (org-inside-LaTeX-fragment-p)
  14407. (call-interactively 'cdlatex-sub-superscript)
  14408. (let (org-cdlatex-mode)
  14409. (call-interactively (key-binding (vector last-input-event))))))
  14410. (defun org-cdlatex-math-modify (&optional _arg)
  14411. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14412. Revert to the normal definition outside of these fragments."
  14413. (interactive "P")
  14414. (if (org-inside-LaTeX-fragment-p)
  14415. (call-interactively 'cdlatex-math-modify)
  14416. (let (org-cdlatex-mode)
  14417. (call-interactively (key-binding (vector last-input-event))))))
  14418. (defun org-cdlatex-environment-indent (&optional environment item)
  14419. "Execute `cdlatex-environment' and indent the inserted environment.
  14420. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14421. The inserted environment is indented to current indentation
  14422. unless point is at the beginning of the line, in which the
  14423. environment remains unintended."
  14424. (interactive)
  14425. ;; cdlatex-environment always return nil. Therefore, capture output
  14426. ;; first and determine if an environment was selected.
  14427. (let* ((beg (point-marker))
  14428. (end (copy-marker (point) t))
  14429. (inserted (progn
  14430. (ignore-errors (cdlatex-environment environment item))
  14431. (< beg end)))
  14432. ;; Figure out how many lines to move forward after the
  14433. ;; environment has been inserted.
  14434. (lines (when inserted
  14435. (save-excursion
  14436. (- (cl-loop while (< beg (point))
  14437. with x = 0
  14438. do (forward-line -1)
  14439. (cl-incf x)
  14440. finally return x)
  14441. (if (progn (goto-char beg)
  14442. (and (progn (skip-chars-forward " \t") (eolp))
  14443. (progn (skip-chars-backward " \t") (bolp))))
  14444. 1 0)))))
  14445. (env (org-trim (delete-and-extract-region beg end))))
  14446. (when inserted
  14447. ;; Get indentation of next line unless at column 0.
  14448. (let ((ind (if (bolp) 0
  14449. (save-excursion
  14450. (org-return t)
  14451. (prog1 (current-indentation)
  14452. (when (progn (skip-chars-forward " \t") (eolp))
  14453. (delete-region beg (point)))))))
  14454. (bol (progn (skip-chars-backward " \t") (bolp))))
  14455. ;; Insert a newline before environment unless at column zero
  14456. ;; to "escape" the current line. Insert a newline if
  14457. ;; something is one the same line as \end{ENVIRONMENT}.
  14458. (insert
  14459. (concat (unless bol "\n") env
  14460. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14461. (unless (zerop ind)
  14462. (save-excursion
  14463. (goto-char beg)
  14464. (while (< (point) end)
  14465. (unless (eolp) (indent-line-to ind))
  14466. (forward-line))))
  14467. (goto-char beg)
  14468. (forward-line lines)
  14469. (indent-line-to ind)))
  14470. (set-marker beg nil)
  14471. (set-marker end nil)))
  14472. ;;;; LaTeX fragments
  14473. (defun org-inside-LaTeX-fragment-p ()
  14474. "Test if point is inside a LaTeX fragment.
  14475. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14476. sequence appearing also before point.
  14477. Even though the matchers for math are configurable, this function assumes
  14478. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14479. delimiters are skipped when they have been removed by customization.
  14480. The return value is nil, or a cons cell with the delimiter and the
  14481. position of this delimiter.
  14482. This function does a reasonably good job, but can locally be fooled by
  14483. for example currency specifications. For example it will assume being in
  14484. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14485. fragments that are properly closed, but during editing, we have to live
  14486. with the uncertainty caused by missing closing delimiters. This function
  14487. looks only before point, not after."
  14488. (catch 'exit
  14489. (let ((pos (point))
  14490. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14491. (lim (progn
  14492. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14493. 'move)
  14494. (point)))
  14495. dd-on str (start 0) m re)
  14496. (goto-char pos)
  14497. (when dodollar
  14498. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14499. re (nth 1 (assoc "$" org-latex-regexps)))
  14500. (while (string-match re str start)
  14501. (cond
  14502. ((= (match-end 0) (length str))
  14503. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14504. ((= (match-end 0) (- (length str) 5))
  14505. (throw 'exit nil))
  14506. (t (setq start (match-end 0))))))
  14507. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14508. (goto-char pos)
  14509. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14510. (and (match-beginning 2) (throw 'exit nil))
  14511. ;; count $$
  14512. (while (re-search-backward "\\$\\$" lim t)
  14513. (setq dd-on (not dd-on)))
  14514. (goto-char pos)
  14515. (when dd-on (cons "$$" m))))))
  14516. (defun org-inside-latex-macro-p ()
  14517. "Is point inside a LaTeX macro or its arguments?"
  14518. (save-match-data
  14519. (org-in-regexp
  14520. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14521. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14522. "Build an overlay between BEG and END using IMAGE file.
  14523. Argument IMAGETYPE is the extension of the displayed image,
  14524. as a string. It defaults to \"png\"."
  14525. (let ((ov (make-overlay beg end))
  14526. (imagetype (or (intern imagetype) 'png)))
  14527. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14528. (overlay-put ov 'evaporate t)
  14529. (overlay-put ov
  14530. 'modification-hooks
  14531. (list (lambda (o _flag _beg _end &optional _l)
  14532. (delete-overlay o))))
  14533. (overlay-put ov
  14534. 'display
  14535. (list 'image :type imagetype :file image :ascent 'center))))
  14536. (defun org-clear-latex-preview (&optional beg end)
  14537. "Remove all overlays with LaTeX fragment images in current buffer.
  14538. When optional arguments BEG and END are non-nil, remove all
  14539. overlays between them instead. Return a non-nil value when some
  14540. overlays were removed, nil otherwise."
  14541. (let ((overlays
  14542. (cl-remove-if-not
  14543. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14544. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14545. (mapc #'delete-overlay overlays)
  14546. overlays))
  14547. (defun org--latex-preview-region (beg end)
  14548. "Preview LaTeX fragments between BEG and END.
  14549. BEG and END are buffer positions."
  14550. (let ((file (buffer-file-name (buffer-base-buffer))))
  14551. (save-excursion
  14552. (org-format-latex
  14553. (concat org-preview-latex-image-directory "org-ltximg")
  14554. beg end
  14555. ;; Emacs cannot overlay images from remote hosts. Create it in
  14556. ;; `temporary-file-directory' instead.
  14557. (if (or (not file) (file-remote-p file))
  14558. temporary-file-directory
  14559. default-directory)
  14560. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14561. (defun org-latex-preview (&optional arg)
  14562. "Toggle preview of the LaTeX fragment at point.
  14563. If the cursor is on a LaTeX fragment, create the image and
  14564. overlay it over the source code, if there is none. Remove it
  14565. otherwise. If there is no fragment at point, display images for
  14566. all fragments in the current section.
  14567. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14568. for all fragments
  14569. in the current section.
  14570. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14571. argument ARG, display image for all
  14572. fragments in the buffer.
  14573. With a `\\[universal-argument] \\[universal-argument] \
  14574. \\[universal-argument]' prefix argument ARG, clear image for all
  14575. fragments in the buffer."
  14576. (interactive "P")
  14577. (cond
  14578. ((not (display-graphic-p)) nil)
  14579. ;; Clear whole buffer.
  14580. ((equal arg '(64))
  14581. (org-clear-latex-preview (point-min) (point-max))
  14582. (message "LaTeX previews removed from buffer"))
  14583. ;; Preview whole buffer.
  14584. ((equal arg '(16))
  14585. (message "Creating LaTeX previews in buffer...")
  14586. (org--latex-preview-region (point-min) (point-max))
  14587. (message "Creating LaTeX previews in buffer... done."))
  14588. ;; Clear current section.
  14589. ((equal arg '(4))
  14590. (org-clear-latex-preview
  14591. (if (org-before-first-heading-p) (point-min)
  14592. (save-excursion
  14593. (org-with-limited-levels (org-back-to-heading t) (point))))
  14594. (org-with-limited-levels (org-entry-end-position))))
  14595. ;; Toggle preview on LaTeX code at point.
  14596. ((let ((datum (org-element-context)))
  14597. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14598. (let ((beg (org-element-property :begin datum))
  14599. (end (org-element-property :end datum)))
  14600. (if (org-clear-latex-preview beg end)
  14601. (message "LaTeX preview removed")
  14602. (message "Creating LaTeX preview...")
  14603. (org--latex-preview-region beg end)
  14604. (message "Creating LaTeX preview... done."))
  14605. t))))
  14606. ;; Preview current section.
  14607. (t
  14608. (let ((beg (if (org-before-first-heading-p) (point-min)
  14609. (save-excursion
  14610. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14611. (end (org-with-limited-levels (org-entry-end-position))))
  14612. (message "Creating LaTeX previews in section...")
  14613. (org--latex-preview-region beg end)
  14614. (message "Creating LaTeX previews in section... done.")))))
  14615. (defun org-format-latex
  14616. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14617. "Replace LaTeX fragments with links to an image.
  14618. The function takes care of creating the replacement image.
  14619. Only consider fragments between BEG and END when those are
  14620. provided.
  14621. When optional argument OVERLAYS is non-nil, display the image on
  14622. top of the fragment instead of replacing it.
  14623. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14624. Some of the options can be changed using the variable
  14625. `org-format-latex-options', which see."
  14626. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14627. (unless (eq processing-type 'verbatim)
  14628. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14629. (cnt 0)
  14630. checkdir-flag)
  14631. (goto-char (or beg (point-min)))
  14632. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14633. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14634. (overlay-recenter (or end (point-max))))
  14635. (while (re-search-forward math-regexp end t)
  14636. (unless (and overlays
  14637. (eq (get-char-property (point) 'org-overlay-type)
  14638. 'org-latex-overlay))
  14639. (let* ((context (org-element-context))
  14640. (type (org-element-type context)))
  14641. (when (memq type '(latex-environment latex-fragment))
  14642. (let ((block-type (eq type 'latex-environment))
  14643. (value (org-element-property :value context))
  14644. (beg (org-element-property :begin context))
  14645. (end (save-excursion
  14646. (goto-char (org-element-property :end context))
  14647. (skip-chars-backward " \r\t\n")
  14648. (point))))
  14649. (cond
  14650. ((eq processing-type 'mathjax)
  14651. ;; Prepare for MathJax processing.
  14652. (if (not (string-match "\\`\\$\\$?" value))
  14653. (goto-char end)
  14654. (delete-region beg end)
  14655. (if (string= (match-string 0 value) "$$")
  14656. (insert "\\[" (substring value 2 -2) "\\]")
  14657. (insert "\\(" (substring value 1 -1) "\\)"))))
  14658. ((eq processing-type 'html)
  14659. (goto-char beg)
  14660. (delete-region beg end)
  14661. (insert (org-format-latex-as-html value)))
  14662. ((assq processing-type org-preview-latex-process-alist)
  14663. ;; Process to an image.
  14664. (cl-incf cnt)
  14665. (goto-char beg)
  14666. (let* ((processing-info
  14667. (cdr (assq processing-type org-preview-latex-process-alist)))
  14668. (face (face-at-point))
  14669. ;; Get the colors from the face at point.
  14670. (fg
  14671. (let ((color (plist-get org-format-latex-options
  14672. :foreground)))
  14673. (if forbuffer
  14674. (cond
  14675. ((eq color 'auto)
  14676. (face-attribute face :foreground nil 'default))
  14677. ((eq color 'default)
  14678. (face-attribute 'default :foreground nil))
  14679. (t color))
  14680. color)))
  14681. (bg
  14682. (let ((color (plist-get org-format-latex-options
  14683. :background)))
  14684. (if forbuffer
  14685. (cond
  14686. ((eq color 'auto)
  14687. (face-attribute face :background nil 'default))
  14688. ((eq color 'default)
  14689. (face-attribute 'default :background nil))
  14690. (t color))
  14691. color)))
  14692. (hash (sha1 (prin1-to-string
  14693. (list org-format-latex-header
  14694. org-latex-default-packages-alist
  14695. org-latex-packages-alist
  14696. org-format-latex-options
  14697. forbuffer value fg bg))))
  14698. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14699. (absprefix (expand-file-name prefix dir))
  14700. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14701. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14702. (sep (and block-type "\n\n"))
  14703. (link (concat sep "[[file:" linkfile "]]" sep))
  14704. (options
  14705. (org-combine-plists
  14706. org-format-latex-options
  14707. `(:foreground ,fg :background ,bg))))
  14708. (when msg (message msg cnt))
  14709. (unless checkdir-flag ; Ensure the directory exists.
  14710. (setq checkdir-flag t)
  14711. (let ((todir (file-name-directory absprefix)))
  14712. (unless (file-directory-p todir)
  14713. (make-directory todir t))))
  14714. (unless (file-exists-p movefile)
  14715. (org-create-formula-image
  14716. value movefile options forbuffer processing-type))
  14717. (if overlays
  14718. (progn
  14719. (dolist (o (overlays-in beg end))
  14720. (when (eq (overlay-get o 'org-overlay-type)
  14721. 'org-latex-overlay)
  14722. (delete-overlay o)))
  14723. (org--make-preview-overlay beg end movefile imagetype)
  14724. (goto-char end))
  14725. (delete-region beg end)
  14726. (insert
  14727. (org-add-props link
  14728. (list 'org-latex-src
  14729. (replace-regexp-in-string "\"" "" value)
  14730. 'org-latex-src-embed-type
  14731. (if block-type 'paragraph 'character)))))))
  14732. ((eq processing-type 'mathml)
  14733. ;; Process to MathML.
  14734. (unless (org-format-latex-mathml-available-p)
  14735. (user-error "LaTeX to MathML converter not configured"))
  14736. (cl-incf cnt)
  14737. (when msg (message msg cnt))
  14738. (goto-char beg)
  14739. (delete-region beg end)
  14740. (insert (org-format-latex-as-mathml
  14741. value block-type prefix dir)))
  14742. (t
  14743. (error "Unknown conversion process %s for LaTeX fragments"
  14744. processing-type)))))))))))
  14745. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14746. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14747. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14748. successful, return the portion between \"<math...> </math>\"
  14749. elements otherwise return nil. When MATHML-FILE is specified,
  14750. write the results in to that file. When invoked as an
  14751. interactive command, prompt for LATEX-FRAG, with initial value
  14752. set to the current active region and echo the results for user
  14753. inspection."
  14754. (interactive (list (let ((frag (when (org-region-active-p)
  14755. (buffer-substring-no-properties
  14756. (region-beginning) (region-end)))))
  14757. (read-string "LaTeX Fragment: " frag nil frag))))
  14758. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14759. (let* ((tmp-in-file
  14760. (let ((file (file-relative-name
  14761. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14762. (write-region latex-frag nil file)
  14763. file))
  14764. (tmp-out-file (file-relative-name
  14765. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14766. (cmd (format-spec
  14767. org-latex-to-mathml-convert-command
  14768. `((?j . ,(and org-latex-to-mathml-jar-file
  14769. (shell-quote-argument
  14770. (expand-file-name
  14771. org-latex-to-mathml-jar-file))))
  14772. (?I . ,(shell-quote-argument tmp-in-file))
  14773. (?i . ,latex-frag)
  14774. (?o . ,(shell-quote-argument tmp-out-file)))))
  14775. mathml shell-command-output)
  14776. (when (called-interactively-p 'any)
  14777. (unless (org-format-latex-mathml-available-p)
  14778. (user-error "LaTeX to MathML converter not configured")))
  14779. (message "Running %s" cmd)
  14780. (setq shell-command-output (shell-command-to-string cmd))
  14781. (setq mathml
  14782. (when (file-readable-p tmp-out-file)
  14783. (with-current-buffer (find-file-noselect tmp-out-file t)
  14784. (goto-char (point-min))
  14785. (when (re-search-forward
  14786. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14787. (regexp-quote
  14788. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14789. nil t)
  14790. (prog1 (match-string 0) (kill-buffer))))))
  14791. (cond
  14792. (mathml
  14793. (setq mathml
  14794. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14795. (when mathml-file
  14796. (write-region mathml nil mathml-file))
  14797. (when (called-interactively-p 'any)
  14798. (message mathml)))
  14799. ((warn "LaTeX to MathML conversion failed")
  14800. (message shell-command-output)))
  14801. (delete-file tmp-in-file)
  14802. (when (file-exists-p tmp-out-file)
  14803. (delete-file tmp-out-file))
  14804. mathml))
  14805. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14806. prefix &optional dir)
  14807. "Use `org-create-math-formula' but check local cache first."
  14808. (let* ((absprefix (expand-file-name prefix dir))
  14809. (print-length nil) (print-level nil)
  14810. (formula-id (concat
  14811. "formula-"
  14812. (sha1
  14813. (prin1-to-string
  14814. (list latex-frag
  14815. org-latex-to-mathml-convert-command)))))
  14816. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14817. (formula-cache-dir (file-name-directory formula-cache)))
  14818. (unless (file-directory-p formula-cache-dir)
  14819. (make-directory formula-cache-dir t))
  14820. (unless (file-exists-p formula-cache)
  14821. (org-create-math-formula latex-frag formula-cache))
  14822. (if (file-exists-p formula-cache)
  14823. ;; Successful conversion. Return the link to MathML file.
  14824. (org-add-props
  14825. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14826. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14827. 'org-latex-src-embed-type (if latex-frag-type
  14828. 'paragraph 'character)))
  14829. ;; Failed conversion. Return the LaTeX fragment verbatim
  14830. latex-frag)))
  14831. (defun org-format-latex-as-html (latex-fragment)
  14832. "Convert LATEX-FRAGMENT to HTML.
  14833. This uses `org-latex-to-html-convert-command', which see."
  14834. (let ((cmd (format-spec org-latex-to-html-convert-command
  14835. `((?i . ,latex-fragment)))))
  14836. (message "Running %s" cmd)
  14837. (shell-command-to-string cmd)))
  14838. (defun org--get-display-dpi ()
  14839. "Get the DPI of the display.
  14840. The function assumes that the display has the same pixel width in
  14841. the horizontal and vertical directions."
  14842. (if (display-graphic-p)
  14843. (round (/ (display-pixel-height)
  14844. (/ (display-mm-height) 25.4)))
  14845. (error "Attempt to calculate the dpi of a non-graphic display")))
  14846. (defun org-create-formula-image
  14847. (string tofile options buffer &optional processing-type)
  14848. "Create an image from LaTeX source using external processes.
  14849. The LaTeX STRING is saved to a temporary LaTeX file, then
  14850. converted to an image file by process PROCESSING-TYPE defined in
  14851. `org-preview-latex-process-alist'. A nil value defaults to
  14852. `org-preview-latex-default-process'.
  14853. The generated image file is eventually moved to TOFILE.
  14854. The OPTIONS argument controls the size, foreground color and
  14855. background color of the generated image.
  14856. When BUFFER non-nil, this function is used for LaTeX previewing.
  14857. Otherwise, it is used to deal with LaTeX snippets showed in
  14858. a HTML file."
  14859. (let* ((processing-type (or processing-type
  14860. org-preview-latex-default-process))
  14861. (processing-info
  14862. (cdr (assq processing-type org-preview-latex-process-alist)))
  14863. (programs (plist-get processing-info :programs))
  14864. (error-message (or (plist-get processing-info :message) ""))
  14865. (image-input-type (plist-get processing-info :image-input-type))
  14866. (image-output-type (plist-get processing-info :image-output-type))
  14867. (post-clean (or (plist-get processing-info :post-clean)
  14868. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14869. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14870. (latex-header
  14871. (or (plist-get processing-info :latex-header)
  14872. (org-latex-make-preamble
  14873. (org-export-get-environment (org-export-get-backend 'latex))
  14874. org-format-latex-header
  14875. 'snippet)))
  14876. (latex-compiler (plist-get processing-info :latex-compiler))
  14877. (image-converter (plist-get processing-info :image-converter))
  14878. (tmpdir temporary-file-directory)
  14879. (texfilebase (make-temp-name
  14880. (expand-file-name "orgtex" tmpdir)))
  14881. (texfile (concat texfilebase ".tex"))
  14882. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14883. '(1.0 . 1.0)))
  14884. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14885. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14886. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14887. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14888. "Black"))
  14889. (bg (or (plist-get options (if buffer :background :html-background))
  14890. "Transparent"))
  14891. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14892. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14893. (dolist (program programs)
  14894. (org-check-external-command program error-message))
  14895. (if (eq fg 'default)
  14896. (setq fg (org-latex-color :foreground))
  14897. (setq fg (org-latex-color-format fg)))
  14898. (setq bg (cond
  14899. ((eq bg 'default) (org-latex-color :background))
  14900. ((string= bg "Transparent") nil)
  14901. (t (org-latex-color-format bg))))
  14902. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14903. (if (string-suffix-p string "\n")
  14904. (aset string (1- (length string)) ?%)
  14905. (setq string (concat string "%")))
  14906. (with-temp-file texfile
  14907. (insert latex-header)
  14908. (insert "\n\\begin{document}\n"
  14909. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14910. (if bg
  14911. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14912. "\n\\pagecolor{bg}%\n")
  14913. "")
  14914. "\n{\\color{fg}\n"
  14915. string
  14916. "\n}\n"
  14917. "\n\\end{document}\n"))
  14918. (let* ((err-msg (format "Please adjust `%s' part of \
  14919. `org-preview-latex-process-alist'."
  14920. processing-type))
  14921. (image-input-file
  14922. (org-compile-file
  14923. texfile latex-compiler image-input-type err-msg log-buf))
  14924. (image-output-file
  14925. (org-compile-file
  14926. image-input-file image-converter image-output-type err-msg log-buf
  14927. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14928. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14929. (copy-file image-output-file tofile 'replace)
  14930. (dolist (e post-clean)
  14931. (when (file-exists-p (concat texfilebase e))
  14932. (delete-file (concat texfilebase e))))
  14933. image-output-file)))
  14934. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14935. "Fill a LaTeX header template TPL.
  14936. In the template, the following place holders will be recognized:
  14937. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14938. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14939. [PACKAGES] \\usepackage statements for PKG
  14940. [NO-PACKAGES] do not include PKG
  14941. [EXTRA] the string EXTRA
  14942. [NO-EXTRA] do not include EXTRA
  14943. For backward compatibility, if both the positive and the negative place
  14944. holder is missing, the positive one (without the \"NO-\") will be
  14945. assumed to be present at the end of the template.
  14946. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14947. EXTRA is a string.
  14948. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14949. (let (rpl (end ""))
  14950. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14951. (setq rpl (if (or (match-end 1) (not def-pkg))
  14952. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14953. tpl (replace-match rpl t t tpl))
  14954. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14955. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14956. (setq rpl (if (or (match-end 1) (not pkg))
  14957. "" (org-latex-packages-to-string pkg snippets-p t))
  14958. tpl (replace-match rpl t t tpl))
  14959. (when pkg (setq end
  14960. (concat end "\n"
  14961. (org-latex-packages-to-string pkg snippets-p)))))
  14962. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14963. (setq rpl (if (or (match-end 1) (not extra))
  14964. "" (concat extra "\n"))
  14965. tpl (replace-match rpl t t tpl))
  14966. (when (and extra (string-match "\\S-" extra))
  14967. (setq end (concat end "\n" extra))))
  14968. (if (string-match "\\S-" end)
  14969. (concat tpl "\n" end)
  14970. tpl)))
  14971. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14972. "Turn an alist of packages into a string with the \\usepackage macros."
  14973. (setq pkg (mapconcat (lambda(p)
  14974. (cond
  14975. ((stringp p) p)
  14976. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14977. (format "%% Package %s omitted" (cadr p)))
  14978. ((equal "" (car p))
  14979. (format "\\usepackage{%s}" (cadr p)))
  14980. (t
  14981. (format "\\usepackage[%s]{%s}"
  14982. (car p) (cadr p)))))
  14983. pkg
  14984. "\n"))
  14985. (if newline (concat pkg "\n") pkg))
  14986. (defun org-dvipng-color (attr)
  14987. "Return a RGB color specification for dvipng."
  14988. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14989. (defun org-dvipng-color-format (color-name)
  14990. "Convert COLOR-NAME to a RGB color value for dvipng."
  14991. (apply #'format "rgb %s %s %s"
  14992. (mapcar 'org-normalize-color
  14993. (color-values color-name))))
  14994. (defun org-latex-color (attr)
  14995. "Return a RGB color for the LaTeX color package."
  14996. (org-latex-color-format (face-attribute 'default attr nil)))
  14997. (defun org-latex-color-format (color-name)
  14998. "Convert COLOR-NAME to a RGB color value."
  14999. (apply #'format "%s,%s,%s"
  15000. (mapcar 'org-normalize-color
  15001. (color-values color-name))))
  15002. (defun org-normalize-color (value)
  15003. "Return string to be used as color value for an RGB component."
  15004. (format "%g" (/ value 65535.0)))
  15005. ;; Image display
  15006. (defvar-local org-inline-image-overlays nil)
  15007. (defun org-toggle-inline-images (&optional include-linked)
  15008. "Toggle the display of inline images.
  15009. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15010. (interactive "P")
  15011. (if org-inline-image-overlays
  15012. (progn
  15013. (org-remove-inline-images)
  15014. (when (called-interactively-p 'interactive)
  15015. (message "Inline image display turned off")))
  15016. (org-display-inline-images include-linked)
  15017. (when (called-interactively-p 'interactive)
  15018. (message (if org-inline-image-overlays
  15019. (format "%d images displayed inline"
  15020. (length org-inline-image-overlays))
  15021. "No images to display inline")))))
  15022. (defun org-redisplay-inline-images ()
  15023. "Assure display of inline images and refresh them."
  15024. (interactive)
  15025. (org-toggle-inline-images)
  15026. (unless org-inline-image-overlays
  15027. (org-toggle-inline-images)))
  15028. ;; For without-x builds.
  15029. (declare-function image-refresh "image" (spec &optional frame))
  15030. (defcustom org-display-remote-inline-images 'skip
  15031. "How to display remote inline images.
  15032. Possible values of this option are:
  15033. skip Don't display remote images.
  15034. download Always download and display remote images.
  15035. cache Display remote images, and open them in separate buffers
  15036. for caching. Silently update the image buffer when a file
  15037. change is detected."
  15038. :group 'org-appearance
  15039. :package-version '(Org . "9.4")
  15040. :type '(choice
  15041. (const :tag "Ignore remote images" skip)
  15042. (const :tag "Always display remote images" download)
  15043. (const :tag "Display and silently update remote images" cache))
  15044. :safe #'symbolp)
  15045. (defun org--create-inline-image (file width)
  15046. "Create image located at FILE, or return nil.
  15047. WIDTH is the width of the image. The image may not be created
  15048. according to the value of `org-display-remote-inline-images'."
  15049. (let* ((remote? (file-remote-p file))
  15050. (file-or-data
  15051. (pcase org-display-remote-inline-images
  15052. ((guard (not remote?)) file)
  15053. (`download (with-temp-buffer
  15054. (set-buffer-multibyte nil)
  15055. (insert-file-contents-literally file)
  15056. (buffer-string)))
  15057. (`cache (let ((revert-without-query '(".")))
  15058. (with-current-buffer (find-file-noselect file)
  15059. (buffer-string))))
  15060. (`skip nil)
  15061. (other
  15062. (message "Invalid value of `org-display-remote-inline-images': %S"
  15063. other)
  15064. nil))))
  15065. (when file-or-data
  15066. (create-image file-or-data
  15067. (and (image-type-available-p 'imagemagick)
  15068. width
  15069. 'imagemagick)
  15070. remote?
  15071. :width width))))
  15072. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15073. "Display inline images.
  15074. An inline image is a link which follows either of these
  15075. conventions:
  15076. 1. Its path is a file with an extension matching return value
  15077. from `image-file-name-regexp' and it has no contents.
  15078. 2. Its description consists in a single link of the previous
  15079. type. In this case, that link must be a well-formed plain
  15080. or angle link, i.e., it must have an explicit \"file\" type.
  15081. Equip each image with the key-map `image-map'.
  15082. When optional argument INCLUDE-LINKED is non-nil, also links with
  15083. a text description part will be inlined. This can be nice for
  15084. a quick look at those images, but it does not reflect what
  15085. exported files will look like.
  15086. When optional argument REFRESH is non-nil, refresh existing
  15087. images between BEG and END. This will create new image displays
  15088. only if necessary.
  15089. BEG and END define the considered part. They default to the
  15090. buffer boundaries with possible narrowing."
  15091. (interactive "P")
  15092. (when (display-graphic-p)
  15093. (unless refresh
  15094. (org-remove-inline-images)
  15095. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15096. (let ((end (or end (point-max))))
  15097. (org-with-point-at (or beg (point-min))
  15098. (let* ((case-fold-search t)
  15099. (file-extension-re (image-file-name-regexp))
  15100. (link-abbrevs (mapcar #'car
  15101. (append org-link-abbrev-alist-local
  15102. org-link-abbrev-alist)))
  15103. ;; Check absolute, relative file names and explicit
  15104. ;; "file:" links. Also check link abbreviations since
  15105. ;; some might expand to "file" links.
  15106. (file-types-re
  15107. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15108. (if (not link-abbrevs) ""
  15109. (concat "\\|" (regexp-opt link-abbrevs))))))
  15110. (while (re-search-forward file-types-re end t)
  15111. (let* ((link (org-element-lineage
  15112. (save-match-data (org-element-context))
  15113. '(link) t))
  15114. (linktype (org-element-property :type link))
  15115. (inner-start (match-beginning 1))
  15116. (path
  15117. (cond
  15118. ;; No link at point; no inline image.
  15119. ((not link) nil)
  15120. ;; File link without a description. Also handle
  15121. ;; INCLUDE-LINKED here since it should have
  15122. ;; precedence over the next case. I.e., if link
  15123. ;; contains filenames in both the path and the
  15124. ;; description, prioritize the path only when
  15125. ;; INCLUDE-LINKED is non-nil.
  15126. ((or (not (org-element-property :contents-begin link))
  15127. include-linked)
  15128. (and (or (equal "file" linktype)
  15129. (equal "attachment" linktype))
  15130. (org-element-property :path link)))
  15131. ;; Link with a description. Check if description
  15132. ;; is a filename. Even if Org doesn't have syntax
  15133. ;; for those -- clickable image -- constructs, fake
  15134. ;; them, as in `org-export-insert-image-links'.
  15135. ((not inner-start) nil)
  15136. (t
  15137. (org-with-point-at inner-start
  15138. (and (looking-at
  15139. (if (char-equal ?< (char-after inner-start))
  15140. org-link-angle-re
  15141. org-link-plain-re))
  15142. ;; File name must fill the whole
  15143. ;; description.
  15144. (= (org-element-property :contents-end link)
  15145. (match-end 0))
  15146. (match-string 2)))))))
  15147. (when (and path (string-match-p file-extension-re path))
  15148. (let ((file (if (equal "attachment" linktype)
  15149. (progn
  15150. (require 'org-attach)
  15151. (ignore-errors (org-attach-expand path)))
  15152. (expand-file-name path))))
  15153. (when (and file (file-exists-p file))
  15154. (let ((width (org-display-inline-image--width link))
  15155. (old (get-char-property-and-overlay
  15156. (org-element-property :begin link)
  15157. 'org-image-overlay)))
  15158. (if (and (car-safe old) refresh)
  15159. (image-refresh (overlay-get (cdr old) 'display))
  15160. (let ((image (org--create-inline-image file width)))
  15161. (when image
  15162. (let ((ov (make-overlay
  15163. (org-element-property :begin link)
  15164. (progn
  15165. (goto-char
  15166. (org-element-property :end link))
  15167. (skip-chars-backward " \t")
  15168. (point)))))
  15169. (overlay-put ov 'display image)
  15170. (overlay-put ov 'face 'default)
  15171. (overlay-put ov 'org-image-overlay t)
  15172. (overlay-put
  15173. ov 'modification-hooks
  15174. (list 'org-display-inline-remove-overlay))
  15175. (when (boundp 'image-map)
  15176. (overlay-put ov 'keymap image-map))
  15177. (push ov org-inline-image-overlays))))))))))))))))
  15178. (defvar visual-fill-column-width) ; Silence compiler warning
  15179. (defun org-display-inline-image--width (link)
  15180. "Determine the display width of the image LINK, in pixels.
  15181. - When `org-image-actual-width' is t, the image's pixel width is used.
  15182. - When `org-image-actual-width' is a number, that value will is used.
  15183. - When `org-image-actual-width' is nil or a list, the first :width attribute
  15184. set (if it exists) is used to set the image width. A width of X% is
  15185. divided by 100.
  15186. If no :width attribute is given and `org-image-actual-width' is a list with
  15187. a number as the car, then that number is used as the default value.
  15188. If the value is a float between 0 and 2, it interpreted as that proportion
  15189. of the text width in the buffer."
  15190. ;; Apply `org-image-actual-width' specifications.
  15191. (cond
  15192. ((eq org-image-actual-width t) nil)
  15193. ((listp org-image-actual-width)
  15194. (let* ((case-fold-search t)
  15195. (par (org-element-lineage link '(paragraph)))
  15196. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  15197. (par-end (org-element-property :post-affiliated par))
  15198. ;; Try to find an attribute providing a :width.
  15199. (attr-width
  15200. (when (and par (org-with-point-at
  15201. (org-element-property :begin par)
  15202. (re-search-forward attr-re par-end t)))
  15203. (match-string 1)))
  15204. (attr-width-val
  15205. (cond
  15206. ((null attr-width) nil)
  15207. ((string-match-p "\\`[0-9.]+%" attr-width)
  15208. (/ (string-to-number attr-width) 100.0))
  15209. (t (string-to-number attr-width))))
  15210. ;; Fallback to `org-image-actual-width' if no explicit width is given.
  15211. (width (or attr-width-val (car org-image-actual-width))))
  15212. (if (and (floatp width) (<= 0.0 width 2.0))
  15213. ;; A float in [0,2] should be interpereted as this portion of
  15214. ;; the text width in the window. This works well with cases like
  15215. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  15216. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  15217. ;; bound as cases such as 1.2\linewidth are feasible.
  15218. (round (* width
  15219. (window-pixel-width)
  15220. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  15221. (or visual-fill-column-width auto-fill-function))
  15222. (when auto-fill-function fill-column)
  15223. (window-text-width))
  15224. (float (window-total-width)))))
  15225. width)))
  15226. ((numberp org-image-actual-width)
  15227. org-image-actual-width)
  15228. (t nil)))
  15229. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15230. "Remove inline-display overlay if a corresponding region is modified."
  15231. (let ((inhibit-modification-hooks t))
  15232. (when (and ov after)
  15233. (delete ov org-inline-image-overlays)
  15234. (delete-overlay ov))))
  15235. (defun org-remove-inline-images ()
  15236. "Remove inline display of images."
  15237. (interactive)
  15238. (mapc #'delete-overlay org-inline-image-overlays)
  15239. (setq org-inline-image-overlays nil))
  15240. (defvar org-self-insert-command-undo-counter 0)
  15241. (defvar org-speed-command nil)
  15242. (defun org-self-insert-command (N)
  15243. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15244. If the cursor is in a table looking at whitespace, the whitespace is
  15245. overwritten, and the table is not marked as requiring realignment."
  15246. (interactive "p")
  15247. (org-check-before-invisible-edit 'insert)
  15248. (cond
  15249. ((and org-use-speed-commands
  15250. (let ((kv (this-command-keys-vector)))
  15251. (setq org-speed-command
  15252. (run-hook-with-args-until-success
  15253. 'org-speed-command-hook
  15254. (make-string 1 (aref kv (1- (length kv))))))))
  15255. (cond
  15256. ((commandp org-speed-command)
  15257. (setq this-command org-speed-command)
  15258. (call-interactively org-speed-command))
  15259. ((functionp org-speed-command)
  15260. (funcall org-speed-command))
  15261. ((and org-speed-command (listp org-speed-command))
  15262. (eval org-speed-command))
  15263. (t (let (org-use-speed-commands)
  15264. (call-interactively 'org-self-insert-command)))))
  15265. ((and
  15266. (= N 1)
  15267. (not (org-region-active-p))
  15268. (org-at-table-p)
  15269. (progn
  15270. ;; Check if we blank the field, and if that triggers align.
  15271. (and (featurep 'org-table)
  15272. org-table-auto-blank-field
  15273. (memq last-command
  15274. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15275. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15276. ;; Got extra space, this field does not determine
  15277. ;; column width.
  15278. (let (org-table-may-need-update) (org-table-blank-field))
  15279. ;; No extra space, this field may determine column
  15280. ;; width.
  15281. (org-table-blank-field)))
  15282. t)
  15283. (looking-at "[^|\n]* |"))
  15284. ;; There is room for insertion without re-aligning the table.
  15285. (self-insert-command N)
  15286. (org-table-with-shrunk-field
  15287. (save-excursion
  15288. (skip-chars-forward "^|")
  15289. ;; Do not delete last space, which is
  15290. ;; `org-table-separator-space', but the regular space before
  15291. ;; it.
  15292. (delete-region (- (point) 2) (1- (point))))))
  15293. (t
  15294. (setq org-table-may-need-update t)
  15295. (self-insert-command N)
  15296. (org-fix-tags-on-the-fly)
  15297. (when org-self-insert-cluster-for-undo
  15298. (if (not (eq last-command 'org-self-insert-command))
  15299. (setq org-self-insert-command-undo-counter 1)
  15300. (if (>= org-self-insert-command-undo-counter 20)
  15301. (setq org-self-insert-command-undo-counter 1)
  15302. (and (> org-self-insert-command-undo-counter 0)
  15303. buffer-undo-list (listp buffer-undo-list)
  15304. (not (cadr buffer-undo-list)) ; remove nil entry
  15305. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15306. (setq org-self-insert-command-undo-counter
  15307. (1+ org-self-insert-command-undo-counter))))))))
  15308. (defun org-check-before-invisible-edit (kind)
  15309. "Check if editing kind KIND would be dangerous with invisible text around.
  15310. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15311. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15312. (when (and org-catch-invisible-edits
  15313. (or (not (boundp 'visible-mode)) (not visible-mode))
  15314. (or (get-char-property (point) 'invisible)
  15315. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15316. ;; OK, we need to take a closer look. Do not consider
  15317. ;; invisibility obtained through text properties (e.g., link
  15318. ;; fontification), as it cannot be toggled.
  15319. (let* ((invisible-at-point
  15320. (pcase (get-char-property-and-overlay (point) 'invisible)
  15321. (`(,_ . ,(and (pred overlayp) o)) o)))
  15322. ;; Assume that point cannot land in the middle of an
  15323. ;; overlay, or between two overlays.
  15324. (invisible-before-point
  15325. (and (not invisible-at-point)
  15326. (not (bobp))
  15327. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15328. (`(,_ . ,(and (pred overlayp) o)) o))))
  15329. (border-and-ok-direction
  15330. (or
  15331. ;; Check if we are acting predictably before invisible
  15332. ;; text.
  15333. (and invisible-at-point
  15334. (memq kind '(insert delete-backward)))
  15335. ;; Check if we are acting predictably after invisible text
  15336. ;; This works not well, and I have turned it off. It seems
  15337. ;; better to always show and stop after invisible text.
  15338. ;; (and (not invisible-at-point) invisible-before-point
  15339. ;; (memq kind '(insert delete)))
  15340. )))
  15341. (when (or invisible-at-point invisible-before-point)
  15342. (when (eq org-catch-invisible-edits 'error)
  15343. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15344. (if (and org-custom-properties-overlays
  15345. (y-or-n-p "Display invisible properties in this buffer? "))
  15346. (org-toggle-custom-properties-visibility)
  15347. ;; Make the area visible
  15348. (save-excursion
  15349. (when invisible-before-point
  15350. (goto-char
  15351. (previous-single-char-property-change (point) 'invisible)))
  15352. ;; Remove whatever overlay is currently making yet-to-be
  15353. ;; edited text invisible. Also remove nested invisibility
  15354. ;; related overlays.
  15355. (delete-overlay (or invisible-at-point invisible-before-point))
  15356. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15357. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15358. (`(,_ . ,(and (pred overlayp) o))
  15359. (delete-overlay o)
  15360. t)))))
  15361. (cond
  15362. ((eq org-catch-invisible-edits 'show)
  15363. ;; That's it, we do the edit after showing
  15364. (message
  15365. "Unfolding invisible region around point before editing")
  15366. (sit-for 1))
  15367. ((and (eq org-catch-invisible-edits 'smart)
  15368. border-and-ok-direction)
  15369. (message "Unfolding invisible region around point before editing"))
  15370. (t
  15371. ;; Don't do the edit, make the user repeat it in full visibility
  15372. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15373. (defun org-fix-tags-on-the-fly ()
  15374. "Align tags in headline at point.
  15375. Unlike `org-align-tags', this function does nothing if point is
  15376. either not currently on a tagged headline or on a tag."
  15377. (when (and (org-match-line org-tag-line-re)
  15378. (< (point) (match-beginning 1)))
  15379. (org-align-tags)))
  15380. (defun org-delete-backward-char (N)
  15381. "Like `delete-backward-char', insert whitespace at field end in tables.
  15382. When deleting backwards, in tables this function will insert whitespace in
  15383. front of the next \"|\" separator, to keep the table aligned. The table will
  15384. still be marked for re-alignment if the field did fill the entire column,
  15385. because, in this case the deletion might narrow the column."
  15386. (interactive "p")
  15387. (save-match-data
  15388. (org-check-before-invisible-edit 'delete-backward)
  15389. (if (and (= N 1)
  15390. (not overwrite-mode)
  15391. (not (org-region-active-p))
  15392. (not (eq (char-before) ?|))
  15393. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15394. (looking-at-p ".*?|")
  15395. (org-at-table-p))
  15396. (progn (forward-char -1) (org-delete-char 1))
  15397. (backward-delete-char N)
  15398. (org-fix-tags-on-the-fly))))
  15399. (defun org-delete-char (N)
  15400. "Like `delete-char', but insert whitespace at field end in tables.
  15401. When deleting characters, in tables this function will insert whitespace in
  15402. front of the next \"|\" separator, to keep the table aligned. The table will
  15403. still be marked for re-alignment if the field did fill the entire column,
  15404. because, in this case the deletion might narrow the column."
  15405. (interactive "p")
  15406. (save-match-data
  15407. (org-check-before-invisible-edit 'delete)
  15408. (cond
  15409. ((or (/= N 1)
  15410. (eq (char-after) ?|)
  15411. (save-excursion (skip-chars-backward " \t") (bolp))
  15412. (not (org-at-table-p)))
  15413. (delete-char N)
  15414. (org-fix-tags-on-the-fly))
  15415. ((looking-at ".\\(.*?\\)|")
  15416. (let* ((update? org-table-may-need-update)
  15417. (noalign (looking-at-p ".*? |")))
  15418. (delete-char 1)
  15419. (org-table-with-shrunk-field
  15420. (save-excursion
  15421. ;; Last space is `org-table-separator-space', so insert
  15422. ;; a regular one before it instead.
  15423. (goto-char (- (match-end 0) 2))
  15424. (insert " ")))
  15425. ;; If there were two spaces at the end, this field does not
  15426. ;; determine the width of the column.
  15427. (when noalign (setq org-table-may-need-update update?))))
  15428. (t
  15429. (delete-char N)))))
  15430. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15431. (put 'org-self-insert-command 'delete-selection
  15432. (lambda ()
  15433. (not (run-hook-with-args-until-success
  15434. 'self-insert-uses-region-functions))))
  15435. (put 'orgtbl-self-insert-command 'delete-selection
  15436. (lambda ()
  15437. (not (run-hook-with-args-until-success
  15438. 'self-insert-uses-region-functions))))
  15439. (put 'org-delete-char 'delete-selection 'supersede)
  15440. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15441. (put 'org-yank 'delete-selection 'yank)
  15442. (put 'org-return 'delete-selection t)
  15443. ;; Make `flyspell-mode' delay after some commands
  15444. (put 'org-self-insert-command 'flyspell-delayed t)
  15445. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15446. (put 'org-delete-char 'flyspell-delayed t)
  15447. (put 'org-delete-backward-char 'flyspell-delayed t)
  15448. ;; Make pabbrev-mode expand after Org mode commands
  15449. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15450. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15451. (defun org-transpose-words ()
  15452. "Transpose words for Org.
  15453. This uses the `org-mode-transpose-word-syntax-table' syntax
  15454. table, which interprets characters in `org-emphasis-alist' as
  15455. word constituents."
  15456. (interactive)
  15457. (with-syntax-table org-mode-transpose-word-syntax-table
  15458. (call-interactively 'transpose-words)))
  15459. (defvar org-ctrl-c-ctrl-c-hook nil
  15460. "Hook for functions attaching themselves to `C-c C-c'.
  15461. This can be used to add additional functionality to the `C-c C-c'
  15462. key which executes context-dependent commands. This hook is run
  15463. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15464. run after the last test.
  15465. Each function will be called with no arguments. The function
  15466. must check if the context is appropriate for it to act. If yes,
  15467. it should do its thing and then return a non-nil value. If the
  15468. context is wrong, just do nothing and return nil.")
  15469. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15470. "Hook for functions attaching themselves to `C-c C-c'.
  15471. This can be used to add additional functionality to the `C-c C-c'
  15472. key which executes context-dependent commands. This hook is run
  15473. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15474. before the first test.
  15475. Each function will be called with no arguments. The function
  15476. must check if the context is appropriate for it to act. If yes,
  15477. it should do its thing and then return a non-nil value. If the
  15478. context is wrong, just do nothing and return nil.")
  15479. (defvar org-tab-first-hook nil
  15480. "Hook for functions to attach themselves to TAB.
  15481. See `org-ctrl-c-ctrl-c-hook' for more information.
  15482. This hook runs as the first action when TAB is pressed, even before
  15483. `org-cycle' messes around with the `outline-regexp' to cater for
  15484. inline tasks and plain list item folding.
  15485. If any function in this hook returns t, any other actions that
  15486. would have been caused by TAB (such as table field motion or visibility
  15487. cycling) will not occur.")
  15488. (defvar org-tab-after-check-for-table-hook nil
  15489. "Hook for functions to attach themselves to TAB.
  15490. See `org-ctrl-c-ctrl-c-hook' for more information.
  15491. This hook runs after it has been established that the cursor is not in a
  15492. table, but before checking if the cursor is in a headline or if global cycling
  15493. should be done.
  15494. If any function in this hook returns t, not other actions like visibility
  15495. cycling will be done.")
  15496. (defvar org-tab-after-check-for-cycling-hook nil
  15497. "Hook for functions to attach themselves to TAB.
  15498. See `org-ctrl-c-ctrl-c-hook' for more information.
  15499. This hook runs after it has been established that not table field motion and
  15500. not visibility should be done because of current context. This is probably
  15501. the place where a package like yasnippets can hook in.")
  15502. (defvar org-tab-before-tab-emulation-hook nil
  15503. "Hook for functions to attach themselves to TAB.
  15504. See `org-ctrl-c-ctrl-c-hook' for more information.
  15505. This hook runs after every other options for TAB have been exhausted, but
  15506. before indentation and \t insertion takes place.")
  15507. (defvar org-metaleft-hook nil
  15508. "Hook for functions attaching themselves to `M-left'.
  15509. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15510. (defvar org-metaright-hook nil
  15511. "Hook for functions attaching themselves to `M-right'.
  15512. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15513. (defvar org-metaup-hook nil
  15514. "Hook for functions attaching themselves to `M-up'.
  15515. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15516. (defvar org-metadown-hook nil
  15517. "Hook for functions attaching themselves to `M-down'.
  15518. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15519. (defvar org-shiftmetaleft-hook nil
  15520. "Hook for functions attaching themselves to `M-S-left'.
  15521. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15522. (defvar org-shiftmetaright-hook nil
  15523. "Hook for functions attaching themselves to `M-S-right'.
  15524. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15525. (defvar org-shiftmetaup-hook nil
  15526. "Hook for functions attaching themselves to `M-S-up'.
  15527. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15528. (defvar org-shiftmetadown-hook nil
  15529. "Hook for functions attaching themselves to `M-S-down'.
  15530. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15531. (defvar org-metareturn-hook nil
  15532. "Hook for functions attaching themselves to `M-RET'.
  15533. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15534. (defvar org-shiftup-hook nil
  15535. "Hook for functions attaching themselves to `S-up'.
  15536. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15537. (defvar org-shiftup-final-hook nil
  15538. "Hook for functions attaching themselves to `S-up'.
  15539. This one runs after all other options except shift-select have been excluded.
  15540. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15541. (defvar org-shiftdown-hook nil
  15542. "Hook for functions attaching themselves to `S-down'.
  15543. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15544. (defvar org-shiftdown-final-hook nil
  15545. "Hook for functions attaching themselves to `S-down'.
  15546. This one runs after all other options except shift-select have been excluded.
  15547. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15548. (defvar org-shiftleft-hook nil
  15549. "Hook for functions attaching themselves to `S-left'.
  15550. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15551. (defvar org-shiftleft-final-hook nil
  15552. "Hook for functions attaching themselves to `S-left'.
  15553. This one runs after all other options except shift-select have been excluded.
  15554. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15555. (defvar org-shiftright-hook nil
  15556. "Hook for functions attaching themselves to `S-right'.
  15557. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15558. (defvar org-shiftright-final-hook nil
  15559. "Hook for functions attaching themselves to `S-right'.
  15560. This one runs after all other options except shift-select have been excluded.
  15561. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15562. (defun org-modifier-cursor-error ()
  15563. "Throw an error, a modified cursor command was applied in wrong context."
  15564. (user-error "This command is active in special context like tables, headlines or items"))
  15565. (defun org-shiftselect-error ()
  15566. "Throw an error because Shift-Cursor command was applied in wrong context."
  15567. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15568. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15569. (user-error "This command works only in special context like headlines or timestamps")))
  15570. (defun org-call-for-shift-select (cmd)
  15571. (let ((this-command-keys-shift-translated t))
  15572. (call-interactively cmd)))
  15573. (defun org-shifttab (&optional arg)
  15574. "Global visibility cycling or move to previous table field.
  15575. Call `org-table-previous-field' within a table.
  15576. When ARG is nil, cycle globally through visibility states.
  15577. When ARG is a numeric prefix, show contents of this level."
  15578. (interactive "P")
  15579. (cond
  15580. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15581. ((integerp arg)
  15582. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15583. (message "Content view to level: %d" arg)
  15584. (org-content (prefix-numeric-value arg2))
  15585. (org-cycle-show-empty-lines t)
  15586. (setq org-cycle-global-status 'overview)
  15587. (run-hook-with-args 'org-cycle-hook 'overview)))
  15588. (t (call-interactively 'org-global-cycle))))
  15589. (defun org-shiftmetaleft ()
  15590. "Promote subtree or delete table column.
  15591. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15592. `org-table-delete-column', depending on context. See the
  15593. individual commands for more information."
  15594. (interactive)
  15595. (cond
  15596. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15597. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15598. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15599. ((if (not (org-region-active-p)) (org-at-item-p)
  15600. (save-excursion (goto-char (region-beginning))
  15601. (org-at-item-p)))
  15602. (call-interactively 'org-outdent-item-tree))
  15603. (t (org-modifier-cursor-error))))
  15604. (defun org-shiftmetaright ()
  15605. "Demote subtree or insert table column.
  15606. Calls `org-demote-subtree', `org-indent-item-tree', or
  15607. `org-table-insert-column', depending on context. See the
  15608. individual commands for more information."
  15609. (interactive)
  15610. (cond
  15611. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15612. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15613. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15614. ((if (not (org-region-active-p)) (org-at-item-p)
  15615. (save-excursion (goto-char (region-beginning))
  15616. (org-at-item-p)))
  15617. (call-interactively 'org-indent-item-tree))
  15618. (t (org-modifier-cursor-error))))
  15619. (defun org-shiftmetaup (&optional _arg)
  15620. "Drag the line at point up.
  15621. In a table, kill the current row.
  15622. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15623. but also adjust the previous clocked item in the clock history.
  15624. Everywhere else, drag the line at point up."
  15625. (interactive "P")
  15626. (cond
  15627. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15628. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15629. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15630. (call-interactively 'org-timestamp-up)))
  15631. (t (call-interactively 'org-drag-line-backward))))
  15632. (defun org-shiftmetadown (&optional _arg)
  15633. "Drag the line at point down.
  15634. In a table, insert an empty row at the current line.
  15635. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15636. but also adjust the previous clocked item in the clock history.
  15637. Everywhere else, drag the line at point down."
  15638. (interactive "P")
  15639. (cond
  15640. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15641. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15642. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15643. (call-interactively 'org-timestamp-down)))
  15644. (t (call-interactively 'org-drag-line-forward))))
  15645. (defsubst org-hidden-tree-error ()
  15646. (user-error
  15647. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15648. (defun org-metaleft (&optional _arg)
  15649. "Promote heading, list item at point or move table column left.
  15650. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15651. depending on context. With no specific context, calls the Emacs
  15652. default `backward-word'. See the individual commands for more
  15653. information.
  15654. This function runs the hook `org-metaleft-hook' as a first step,
  15655. and returns at first non-nil value."
  15656. (interactive "P")
  15657. (cond
  15658. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15659. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15660. ((org-with-limited-levels
  15661. (or (org-at-heading-p)
  15662. (and (org-region-active-p)
  15663. (save-excursion
  15664. (goto-char (region-beginning))
  15665. (org-at-heading-p)))))
  15666. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15667. (call-interactively 'org-do-promote))
  15668. ;; At an inline task.
  15669. ((org-at-heading-p)
  15670. (call-interactively 'org-inlinetask-promote))
  15671. ((or (org-at-item-p)
  15672. (and (org-region-active-p)
  15673. (save-excursion
  15674. (goto-char (region-beginning))
  15675. (org-at-item-p))))
  15676. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15677. (call-interactively 'org-outdent-item))
  15678. (t (call-interactively 'backward-word))))
  15679. (defun org-metaright (&optional _arg)
  15680. "Demote heading, list item at point or move table column right.
  15681. In front of a drawer or a block keyword, indent it correctly.
  15682. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15683. `org-indent-drawer' or `org-indent-block' depending on context.
  15684. With no specific context, calls the Emacs default `forward-word'.
  15685. See the individual commands for more information.
  15686. This function runs the hook `org-metaright-hook' as a first step,
  15687. and returns at first non-nil value."
  15688. (interactive "P")
  15689. (cond
  15690. ((run-hook-with-args-until-success 'org-metaright-hook))
  15691. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15692. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15693. ((org-at-block-p) (call-interactively 'org-indent-block))
  15694. ((org-with-limited-levels
  15695. (or (org-at-heading-p)
  15696. (and (org-region-active-p)
  15697. (save-excursion
  15698. (goto-char (region-beginning))
  15699. (org-at-heading-p)))))
  15700. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15701. (call-interactively 'org-do-demote))
  15702. ;; At an inline task.
  15703. ((org-at-heading-p)
  15704. (call-interactively 'org-inlinetask-demote))
  15705. ((or (org-at-item-p)
  15706. (and (org-region-active-p)
  15707. (save-excursion
  15708. (goto-char (region-beginning))
  15709. (org-at-item-p))))
  15710. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15711. (call-interactively 'org-indent-item))
  15712. (t (call-interactively 'forward-word))))
  15713. (defun org-check-for-hidden (what)
  15714. "Check if there are hidden headlines/items in the current visual line.
  15715. WHAT can be either `headlines' or `items'. If the current line is
  15716. an outline or item heading and it has a folded subtree below it,
  15717. this function returns t, nil otherwise."
  15718. (let ((re (cond
  15719. ((eq what 'headlines) org-outline-regexp-bol)
  15720. ((eq what 'items) (org-item-beginning-re))
  15721. (t (error "This should not happen"))))
  15722. beg end)
  15723. (save-excursion
  15724. (catch 'exit
  15725. (unless (org-region-active-p)
  15726. (setq beg (point-at-bol))
  15727. (beginning-of-line 2)
  15728. (while (and (not (eobp)) ;; this is like `next-line'
  15729. (get-char-property (1- (point)) 'invisible))
  15730. (beginning-of-line 2))
  15731. (setq end (point))
  15732. (goto-char beg)
  15733. (goto-char (point-at-eol))
  15734. (setq end (max end (point)))
  15735. (while (re-search-forward re end t)
  15736. (when (get-char-property (match-beginning 0) 'invisible)
  15737. (throw 'exit t))))
  15738. nil))))
  15739. (defun org-metaup (&optional _arg)
  15740. "Move subtree up or move table row up.
  15741. Calls `org-move-subtree-up' or `org-table-move-row' or
  15742. `org-move-item-up', depending on context. See the individual commands
  15743. for more information."
  15744. (interactive "P")
  15745. (cond
  15746. ((run-hook-with-args-until-success 'org-metaup-hook))
  15747. ((org-region-active-p)
  15748. (let* ((a (save-excursion
  15749. (goto-char (min (region-beginning) (region-end)))
  15750. (line-beginning-position)))
  15751. (b (save-excursion
  15752. (goto-char (max (region-beginning) (region-end)))
  15753. (if (bolp) (1- (point)) (line-end-position))))
  15754. (c (save-excursion
  15755. (goto-char a)
  15756. (move-beginning-of-line 0)
  15757. (point)))
  15758. (d (save-excursion
  15759. (goto-char a)
  15760. (move-end-of-line 0)
  15761. (point))))
  15762. (transpose-regions a b c d)
  15763. (goto-char c)))
  15764. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15765. ((and (featurep 'org-inlinetask)
  15766. (org-inlinetask-in-task-p))
  15767. (org-drag-element-backward))
  15768. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15769. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15770. (t (org-drag-element-backward))))
  15771. (defun org-metadown (&optional _arg)
  15772. "Move subtree down or move table row down.
  15773. Calls `org-move-subtree-down' or `org-table-move-row' or
  15774. `org-move-item-down', depending on context. See the individual
  15775. commands for more information."
  15776. (interactive "P")
  15777. (cond
  15778. ((run-hook-with-args-until-success 'org-metadown-hook))
  15779. ((org-region-active-p)
  15780. (let* ((a (save-excursion
  15781. (goto-char (min (region-beginning) (region-end)))
  15782. (line-beginning-position)))
  15783. (b (save-excursion
  15784. (goto-char (max (region-beginning) (region-end)))
  15785. (if (bolp) (1- (point)) (line-end-position))))
  15786. (c (save-excursion
  15787. (goto-char b)
  15788. (move-beginning-of-line (if (bolp) 1 2))
  15789. (point)))
  15790. (d (save-excursion
  15791. (goto-char b)
  15792. (move-end-of-line (if (bolp) 1 2))
  15793. (point))))
  15794. (transpose-regions a b c d)
  15795. (goto-char d)))
  15796. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15797. ((and (featurep 'org-inlinetask)
  15798. (org-inlinetask-in-task-p))
  15799. (org-drag-element-forward))
  15800. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15801. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15802. (t (org-drag-element-forward))))
  15803. (defun org-shiftup (&optional arg)
  15804. "Act on current element according to context.
  15805. Call `org-timestamp-up' or `org-priority-up', or
  15806. `org-previous-item', or `org-table-move-cell-up'. See the
  15807. individual commands for more information."
  15808. (interactive "P")
  15809. (cond
  15810. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15811. ((and org-support-shift-select (org-region-active-p))
  15812. (org-call-for-shift-select 'previous-line))
  15813. ((org-at-timestamp-p 'lax)
  15814. (call-interactively (if org-edit-timestamp-down-means-later
  15815. 'org-timestamp-down 'org-timestamp-up)))
  15816. ((and (not (eq org-support-shift-select 'always))
  15817. org-priority-enable-commands
  15818. (org-at-heading-p))
  15819. (call-interactively 'org-priority-up))
  15820. ((and (not org-support-shift-select) (org-at-item-p))
  15821. (call-interactively 'org-previous-item))
  15822. ((org-clocktable-try-shift 'up arg))
  15823. ((and (not (eq org-support-shift-select 'always))
  15824. (org-at-table-p))
  15825. (org-table-move-cell-up))
  15826. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15827. (org-support-shift-select
  15828. (org-call-for-shift-select 'previous-line))
  15829. (t (org-shiftselect-error))))
  15830. (defun org-shiftdown (&optional arg)
  15831. "Act on current element according to context.
  15832. Call `org-timestamp-down' or `org-priority-down', or
  15833. `org-next-item', or `org-table-move-cell-down'. See the
  15834. individual commands for more information."
  15835. (interactive "P")
  15836. (cond
  15837. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15838. ((and org-support-shift-select (org-region-active-p))
  15839. (org-call-for-shift-select 'next-line))
  15840. ((org-at-timestamp-p 'lax)
  15841. (call-interactively (if org-edit-timestamp-down-means-later
  15842. 'org-timestamp-up 'org-timestamp-down)))
  15843. ((and (not (eq org-support-shift-select 'always))
  15844. org-priority-enable-commands
  15845. (org-at-heading-p))
  15846. (call-interactively 'org-priority-down))
  15847. ((and (not org-support-shift-select) (org-at-item-p))
  15848. (call-interactively 'org-next-item))
  15849. ((org-clocktable-try-shift 'down arg))
  15850. ((and (not (eq org-support-shift-select 'always))
  15851. (org-at-table-p))
  15852. (org-table-move-cell-down))
  15853. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15854. (org-support-shift-select
  15855. (org-call-for-shift-select 'next-line))
  15856. (t (org-shiftselect-error))))
  15857. (defun org-shiftright (&optional arg)
  15858. "Act on the current element according to context.
  15859. This does one of the following:
  15860. - switch a timestamp at point one day into the future
  15861. - on a headline, switch to the next TODO keyword
  15862. - on an item, switch entire list to the next bullet type
  15863. - on a property line, switch to the next allowed value
  15864. - on a clocktable definition line, move time block into the future
  15865. - in a table, move a single cell right"
  15866. (interactive "P")
  15867. (cond
  15868. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15869. ((and org-support-shift-select (org-region-active-p))
  15870. (org-call-for-shift-select 'forward-char))
  15871. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15872. ((and (not (eq org-support-shift-select 'always))
  15873. (org-at-heading-p))
  15874. (let ((org-inhibit-logging
  15875. (not org-treat-S-cursor-todo-selection-as-state-change))
  15876. (org-inhibit-blocking
  15877. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15878. (org-call-with-arg 'org-todo 'right)))
  15879. ((or (and org-support-shift-select
  15880. (not (eq org-support-shift-select 'always))
  15881. (org-at-item-bullet-p))
  15882. (and (not org-support-shift-select) (org-at-item-p)))
  15883. (org-call-with-arg 'org-cycle-list-bullet nil))
  15884. ((and (not (eq org-support-shift-select 'always))
  15885. (org-at-property-p))
  15886. (call-interactively 'org-property-next-allowed-value))
  15887. ((org-clocktable-try-shift 'right arg))
  15888. ((and (not (eq org-support-shift-select 'always))
  15889. (org-at-table-p))
  15890. (org-table-move-cell-right))
  15891. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15892. (org-support-shift-select
  15893. (org-call-for-shift-select 'forward-char))
  15894. (t (org-shiftselect-error))))
  15895. (defun org-shiftleft (&optional arg)
  15896. "Act on current element according to context.
  15897. This does one of the following:
  15898. - switch a timestamp at point one day into the past
  15899. - on a headline, switch to the previous TODO keyword.
  15900. - on an item, switch entire list to the previous bullet type
  15901. - on a property line, switch to the previous allowed value
  15902. - on a clocktable definition line, move time block into the past
  15903. - in a table, move a single cell left"
  15904. (interactive "P")
  15905. (cond
  15906. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15907. ((and org-support-shift-select (org-region-active-p))
  15908. (org-call-for-shift-select 'backward-char))
  15909. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15910. ((and (not (eq org-support-shift-select 'always))
  15911. (org-at-heading-p))
  15912. (let ((org-inhibit-logging
  15913. (not org-treat-S-cursor-todo-selection-as-state-change))
  15914. (org-inhibit-blocking
  15915. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15916. (org-call-with-arg 'org-todo 'left)))
  15917. ((or (and org-support-shift-select
  15918. (not (eq org-support-shift-select 'always))
  15919. (org-at-item-bullet-p))
  15920. (and (not org-support-shift-select) (org-at-item-p)))
  15921. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15922. ((and (not (eq org-support-shift-select 'always))
  15923. (org-at-property-p))
  15924. (call-interactively 'org-property-previous-allowed-value))
  15925. ((org-clocktable-try-shift 'left arg))
  15926. ((and (not (eq org-support-shift-select 'always))
  15927. (org-at-table-p))
  15928. (org-table-move-cell-left))
  15929. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15930. (org-support-shift-select
  15931. (org-call-for-shift-select 'backward-char))
  15932. (t (org-shiftselect-error))))
  15933. (defun org-shiftcontrolright ()
  15934. "Switch to next TODO set."
  15935. (interactive)
  15936. (cond
  15937. ((and org-support-shift-select (org-region-active-p))
  15938. (org-call-for-shift-select 'forward-word))
  15939. ((and (not (eq org-support-shift-select 'always))
  15940. (org-at-heading-p))
  15941. (org-call-with-arg 'org-todo 'nextset))
  15942. (org-support-shift-select
  15943. (org-call-for-shift-select 'forward-word))
  15944. (t (org-shiftselect-error))))
  15945. (defun org-shiftcontrolleft ()
  15946. "Switch to previous TODO set."
  15947. (interactive)
  15948. (cond
  15949. ((and org-support-shift-select (org-region-active-p))
  15950. (org-call-for-shift-select 'backward-word))
  15951. ((and (not (eq org-support-shift-select 'always))
  15952. (org-at-heading-p))
  15953. (org-call-with-arg 'org-todo 'previousset))
  15954. (org-support-shift-select
  15955. (org-call-for-shift-select 'backward-word))
  15956. (t (org-shiftselect-error))))
  15957. (defun org-shiftcontrolup (&optional n)
  15958. "Change timestamps synchronously up in CLOCK log lines.
  15959. Optional argument N tells to change by that many units."
  15960. (interactive "P")
  15961. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15962. (let (org-support-shift-select)
  15963. (org-clock-timestamps-up n))
  15964. (user-error "Not at a clock log")))
  15965. (defun org-shiftcontroldown (&optional n)
  15966. "Change timestamps synchronously down in CLOCK log lines.
  15967. Optional argument N tells to change by that many units."
  15968. (interactive "P")
  15969. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15970. (let (org-support-shift-select)
  15971. (org-clock-timestamps-down n))
  15972. (user-error "Not at a clock log")))
  15973. (defun org-increase-number-at-point (&optional inc)
  15974. "Increment the number at point.
  15975. With an optional prefix numeric argument INC, increment using
  15976. this numeric value."
  15977. (interactive "p")
  15978. (if (not (number-at-point))
  15979. (user-error "Not on a number")
  15980. (unless inc (setq inc 1))
  15981. (let ((pos (point))
  15982. (beg (skip-chars-backward "-+^/*0-9eE."))
  15983. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15984. (setq nap (buffer-substring-no-properties
  15985. (+ pos beg) (+ pos beg end)))
  15986. (delete-region (+ pos beg) (+ pos beg end))
  15987. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15988. (when (org-at-table-p)
  15989. (org-table-align)
  15990. (org-table-end-of-field 1))))
  15991. (defun org-decrease-number-at-point (&optional inc)
  15992. "Decrement the number at point.
  15993. With an optional prefix numeric argument INC, decrement using
  15994. this numeric value."
  15995. (interactive "p")
  15996. (org-increase-number-at-point (- (or inc 1))))
  15997. (defun org-ctrl-c-ret ()
  15998. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15999. (interactive)
  16000. (cond
  16001. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16002. (t (call-interactively 'org-insert-heading))))
  16003. (defun org-copy-visible (beg end)
  16004. "Copy the visible parts of the region."
  16005. (interactive "r")
  16006. (let ((result ""))
  16007. (while (/= beg end)
  16008. (if (invisible-p beg)
  16009. (setq beg (next-single-char-property-change beg 'invisible nil end))
  16010. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16011. (setq result (concat result (buffer-substring beg next)))
  16012. (setq beg next))))
  16013. (setq deactivate-mark t)
  16014. (kill-new result)
  16015. (message "Visible strings have been copied to the kill ring.")))
  16016. (defun org-copy-special ()
  16017. "Copy region in table or copy current subtree.
  16018. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16019. context. See the individual commands for more information."
  16020. (interactive)
  16021. (call-interactively
  16022. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16023. (defun org-cut-special ()
  16024. "Cut region in table or cut current subtree.
  16025. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16026. context. See the individual commands for more information."
  16027. (interactive)
  16028. (call-interactively
  16029. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16030. (defun org-paste-special (arg)
  16031. "Paste rectangular region into table, or past subtree relative to level.
  16032. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16033. See the individual commands for more information."
  16034. (interactive "P")
  16035. (if (org-at-table-p)
  16036. (org-table-paste-rectangle)
  16037. (org-paste-subtree arg)))
  16038. (defun org-edit-special (&optional arg)
  16039. "Call a special editor for the element at point.
  16040. When at a table, call the formula editor with `org-table-edit-formulas'.
  16041. When in a source code block, call `org-edit-src-code'.
  16042. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16043. When in an export block, call `org-edit-export-block'.
  16044. When in a LaTeX environment, call `org-edit-latex-environment'.
  16045. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  16046. When at a footnote reference, call `org-edit-footnote-reference'.
  16047. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16048. When at an active timestamp, call `org-time-stamp'.
  16049. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16050. On a link, call `ffap' to visit the link at point.
  16051. Otherwise, return a user error."
  16052. (interactive "P")
  16053. (let ((element (org-element-at-point)))
  16054. (barf-if-buffer-read-only)
  16055. (pcase (org-element-type element)
  16056. (`src-block
  16057. (if (not arg) (org-edit-src-code)
  16058. (let* ((info (org-babel-get-src-block-info))
  16059. (lang (nth 0 info))
  16060. (params (nth 2 info))
  16061. (session (cdr (assq :session params))))
  16062. (if (not session) (org-edit-src-code)
  16063. ;; At a source block with a session and function called
  16064. ;; with an ARG: switch to the buffer related to the
  16065. ;; inferior process.
  16066. (switch-to-buffer
  16067. (funcall (intern (concat "org-babel-prep-session:" lang))
  16068. session params))))))
  16069. (`keyword
  16070. (unless (member (org-element-property :key element)
  16071. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  16072. (user-error "No special environment to edit here"))
  16073. (let ((value (org-element-property :value element)))
  16074. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16075. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16076. (or (match-string 1 value)
  16077. (match-string 0 value)))))
  16078. (when (org-url-p file)
  16079. (user-error "Files located with a URL cannot be edited"))
  16080. (org-link-open-from-string
  16081. (format "[[%s]]" (expand-file-name file))))))
  16082. (`table
  16083. (if (eq (org-element-property :type element) 'table.el)
  16084. (org-edit-table.el)
  16085. (call-interactively 'org-table-edit-formulas)))
  16086. ;; Only Org tables contain `table-row' type elements.
  16087. (`table-row (call-interactively 'org-table-edit-formulas))
  16088. (`example-block (org-edit-src-code))
  16089. (`export-block (org-edit-export-block))
  16090. (`fixed-width (org-edit-fixed-width-region))
  16091. (`latex-environment (org-edit-latex-environment))
  16092. (`planning
  16093. (let ((proplist (cadr element)))
  16094. (mapc #'call-interactively
  16095. (remq nil
  16096. (list
  16097. (when (plist-get proplist :deadline) #'org-deadline)
  16098. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16099. (_
  16100. ;; No notable element at point. Though, we may be at a link or
  16101. ;; a footnote reference, which are objects. Thus, scan deeper.
  16102. (let ((context (org-element-context element)))
  16103. (pcase (org-element-type context)
  16104. (`footnote-reference (org-edit-footnote-reference))
  16105. (`inline-src-block (org-edit-inline-src-code))
  16106. (`latex-fragment (org-edit-latex-fragment))
  16107. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16108. (call-interactively #'org-time-stamp-inactive)
  16109. (call-interactively #'org-time-stamp)))
  16110. (`link (call-interactively #'ffap))
  16111. (_ (user-error "No special environment to edit here"))))))))
  16112. (defun org-ctrl-c-ctrl-c (&optional arg)
  16113. "Set tags in headline, or update according to changed information at point.
  16114. This command does many different things, depending on context:
  16115. - If column view is active, in agenda or org buffers, quit it.
  16116. - If there are highlights, remove them.
  16117. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16118. this is what we do.
  16119. - If the cursor is on a statistics cookie, update it.
  16120. - If the cursor is in a headline, in an agenda or an org buffer,
  16121. prompt for tags and insert them into the current line, aligned
  16122. to `org-tags-column'. When called with prefix arg, realign all
  16123. tags in the current buffer.
  16124. - If the cursor is in one of the special #+KEYWORD lines, this
  16125. triggers scanning the buffer for these lines and updating the
  16126. information.
  16127. - If the cursor is inside a table, realign the table. This command
  16128. works even if the automatic table editor has been turned off.
  16129. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16130. the entire table.
  16131. - If the cursor is at a footnote reference or definition, jump to
  16132. the corresponding definition or references, respectively.
  16133. - If the cursor is a the beginning of a dynamic block, update it.
  16134. - If the current buffer is a capture buffer, close note and file it.
  16135. - If the cursor is on a <<<target>>>, update radio targets and
  16136. corresponding links in this buffer.
  16137. - If the cursor is on a numbered item in a plain list, renumber the
  16138. ordered list.
  16139. - If the cursor is on a checkbox, toggle it.
  16140. - If the cursor is on a code block, evaluate it. The variable
  16141. `org-confirm-babel-evaluate' can be used to control prompting
  16142. before code block evaluation, by default every code block
  16143. evaluation requires confirmation. Code block evaluation can be
  16144. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16145. (interactive "P")
  16146. (cond
  16147. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16148. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16149. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16150. (org-remove-occur-highlights)
  16151. (message "Temporary highlights/overlays removed from current buffer"))
  16152. ((and (local-variable-p 'org-finish-function)
  16153. (fboundp org-finish-function))
  16154. (funcall org-finish-function))
  16155. ((org-babel-hash-at-point))
  16156. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16157. (t
  16158. (let* ((context
  16159. (org-element-lineage
  16160. (org-element-context)
  16161. ;; Limit to supported contexts.
  16162. '(babel-call clock dynamic-block footnote-definition
  16163. footnote-reference inline-babel-call inline-src-block
  16164. inlinetask item keyword node-property paragraph
  16165. plain-list planning property-drawer radio-target
  16166. src-block statistics-cookie table table-cell table-row
  16167. timestamp)
  16168. t))
  16169. (radio-list-p (org-at-radio-list-p))
  16170. (type (org-element-type context)))
  16171. ;; For convenience: at the first line of a paragraph on the same
  16172. ;; line as an item, apply function on that item instead.
  16173. (when (eq type 'paragraph)
  16174. (let ((parent (org-element-property :parent context)))
  16175. (when (and (eq (org-element-type parent) 'item)
  16176. (= (line-beginning-position)
  16177. (org-element-property :begin parent)))
  16178. (setq context parent)
  16179. (setq type 'item))))
  16180. ;; Act according to type of element or object at point.
  16181. ;;
  16182. ;; Do nothing on a blank line, except if it is contained in
  16183. ;; a source block. Hence, we first check if point is in such
  16184. ;; a block and then if it is at a blank line.
  16185. (pcase type
  16186. ((or `inline-src-block `src-block)
  16187. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16188. (org-babel-eval-wipe-error-buffer)
  16189. (org-babel-execute-src-block
  16190. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16191. ((guard (org-match-line "[ \t]*$"))
  16192. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16193. (user-error
  16194. (substitute-command-keys
  16195. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16196. ((or `babel-call `inline-babel-call)
  16197. (let ((info (org-babel-lob-get-info context)))
  16198. (when info (org-babel-execute-src-block nil info))))
  16199. (`clock (org-clock-update-time-maybe))
  16200. (`dynamic-block
  16201. (save-excursion
  16202. (goto-char (org-element-property :post-affiliated context))
  16203. (org-update-dblock)))
  16204. (`footnote-definition
  16205. (goto-char (org-element-property :post-affiliated context))
  16206. (call-interactively 'org-footnote-action))
  16207. (`footnote-reference (call-interactively #'org-footnote-action))
  16208. ((or `headline `inlinetask)
  16209. (save-excursion (goto-char (org-element-property :begin context))
  16210. (call-interactively #'org-set-tags-command)))
  16211. (`item
  16212. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16213. ;; unconditionally, whereas `C-u' will toggle its presence.
  16214. ;; Without a universal argument, if the item has a checkbox,
  16215. ;; toggle it. Otherwise repair the list.
  16216. (if (or radio-list-p
  16217. (and (boundp org-list-checkbox-radio-mode)
  16218. org-list-checkbox-radio-mode))
  16219. (org-toggle-radio-button arg)
  16220. (let* ((box (org-element-property :checkbox context))
  16221. (struct (org-element-property :structure context))
  16222. (old-struct (copy-tree struct))
  16223. (parents (org-list-parents-alist struct))
  16224. (prevs (org-list-prevs-alist struct))
  16225. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16226. (org-list-set-checkbox
  16227. (org-element-property :begin context) struct
  16228. (cond ((equal arg '(16)) "[-]")
  16229. ((and (not box) (equal arg '(4))) "[ ]")
  16230. ((or (not box) (equal arg '(4))) nil)
  16231. ((eq box 'on) "[ ]")
  16232. (t "[X]")))
  16233. ;; Mimic `org-list-write-struct' but with grabbing a return
  16234. ;; value from `org-list-struct-fix-box'.
  16235. (org-list-struct-fix-ind struct parents 2)
  16236. (org-list-struct-fix-item-end struct)
  16237. (org-list-struct-fix-bul struct prevs)
  16238. (org-list-struct-fix-ind struct parents)
  16239. (let ((block-item
  16240. (org-list-struct-fix-box struct parents prevs orderedp)))
  16241. (if (and box (equal struct old-struct))
  16242. (if (equal arg '(16))
  16243. (message "Checkboxes already reset")
  16244. (user-error "Cannot toggle this checkbox: %s"
  16245. (if (eq box 'on)
  16246. "all subitems checked"
  16247. "unchecked subitems")))
  16248. (org-list-struct-apply-struct struct old-struct)
  16249. (org-update-checkbox-count-maybe))
  16250. (when block-item
  16251. (message "Checkboxes were removed due to empty box at line %d"
  16252. (org-current-line block-item)))))))
  16253. (`plain-list
  16254. ;; At a plain list, with a double C-u argument, set
  16255. ;; checkboxes of each item to "[-]", whereas a single one
  16256. ;; will toggle their presence according to the state of the
  16257. ;; first item in the list. Without an argument, repair the
  16258. ;; list.
  16259. (if (or radio-list-p
  16260. (and (boundp org-list-checkbox-radio-mode)
  16261. org-list-checkbox-radio-mode))
  16262. (org-toggle-radio-button arg)
  16263. (let* ((begin (org-element-property :contents-begin context))
  16264. (struct (org-element-property :structure context))
  16265. (old-struct (copy-tree struct))
  16266. (first-box (save-excursion
  16267. (goto-char begin)
  16268. (looking-at org-list-full-item-re)
  16269. (match-string-no-properties 3)))
  16270. (new-box (cond ((equal arg '(16)) "[-]")
  16271. ((equal arg '(4)) (unless first-box "[ ]"))
  16272. ((equal first-box "[X]") "[ ]")
  16273. (t "[X]"))))
  16274. (cond
  16275. (arg
  16276. (dolist (pos
  16277. (org-list-get-all-items
  16278. begin struct (org-list-prevs-alist struct)))
  16279. (org-list-set-checkbox pos struct new-box)))
  16280. ((and first-box (eq (point) begin))
  16281. ;; For convenience, when point is at bol on the first
  16282. ;; item of the list and no argument is provided, simply
  16283. ;; toggle checkbox of that item, if any.
  16284. (org-list-set-checkbox begin struct new-box)))
  16285. (when (equal
  16286. (org-list-write-struct
  16287. struct (org-list-parents-alist struct) old-struct)
  16288. old-struct)
  16289. (message "Cannot update this checkbox"))
  16290. (org-update-checkbox-count-maybe))))
  16291. (`keyword
  16292. (let ((org-inhibit-startup-visibility-stuff t)
  16293. (org-startup-align-all-tables nil))
  16294. (when (boundp 'org-table-coordinate-overlays)
  16295. (mapc #'delete-overlay org-table-coordinate-overlays)
  16296. (setq org-table-coordinate-overlays nil))
  16297. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16298. (message "Local setup has been refreshed"))
  16299. ((or `property-drawer `node-property)
  16300. (call-interactively #'org-property-action))
  16301. (`radio-target
  16302. (call-interactively #'org-update-radio-target-regexp))
  16303. (`statistics-cookie
  16304. (call-interactively #'org-update-statistics-cookies))
  16305. ((or `table `table-cell `table-row)
  16306. ;; At a table, generate a plot if on the #+plot line,
  16307. ;; recalculate every field and align it otherwise. Also
  16308. ;; send the table if necessary.
  16309. (cond
  16310. ((and (org-match-line "[ \t]*#\\+plot:")
  16311. (< (point) (org-element-property :post-affiliated context)))
  16312. (org-plot/gnuplot))
  16313. ;; If the table has a `table.el' type, just give up.
  16314. ((eq (org-element-property :type context) 'table.el)
  16315. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16316. Use `\\[org-edit-special]' to edit table.el tables")))
  16317. ;; At a table row or cell, maybe recalculate line but always
  16318. ;; align table.
  16319. ((or (eq type 'table)
  16320. ;; Check if point is at a TBLFM line.
  16321. (and (eq type 'table-row)
  16322. (= (point) (org-element-property :end context))))
  16323. (save-excursion
  16324. (if (org-at-TBLFM-p)
  16325. (progn (require 'org-table)
  16326. (org-table-calc-current-TBLFM))
  16327. (goto-char (org-element-property :contents-begin context))
  16328. (org-call-with-arg 'org-table-recalculate (or arg t))
  16329. (orgtbl-send-table 'maybe))))
  16330. (t
  16331. (org-table-maybe-eval-formula)
  16332. (cond (arg (call-interactively #'org-table-recalculate))
  16333. ((org-table-maybe-recalculate-line))
  16334. (t (org-table-align))))))
  16335. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16336. (org-timestamp-change 0 'day))
  16337. ((and `nil (guard (org-at-heading-p)))
  16338. ;; When point is on an unsupported object type, we can miss
  16339. ;; the fact that it also is at a heading. Handle it here.
  16340. (call-interactively #'org-set-tags-command))
  16341. ((guard
  16342. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16343. (_
  16344. (user-error
  16345. (substitute-command-keys
  16346. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16347. (defun org-mode-restart ()
  16348. "Restart `org-mode'."
  16349. (interactive)
  16350. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16351. (funcall major-mode)
  16352. (hack-local-variables)
  16353. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16354. (org-indent-mode -1))
  16355. (org-reset-file-cache))
  16356. (message "%s restarted" major-mode))
  16357. (defun org-flag-above-first-heading (&optional arg)
  16358. "Hide from bob up to the first heading.
  16359. Move point to the beginning of first heading or end of buffer."
  16360. (goto-char (point-min))
  16361. (unless (org-at-heading-p)
  16362. (outline-next-heading))
  16363. (unless (bobp)
  16364. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16365. (defun org-show-branches-buffer ()
  16366. "Show all branches in the buffer."
  16367. (org-flag-above-first-heading)
  16368. (outline-hide-sublevels 1)
  16369. (unless (eobp)
  16370. (outline-show-branches)
  16371. (while (outline-get-next-sibling)
  16372. (outline-show-branches)))
  16373. (goto-char (point-min)))
  16374. (defun org-kill-note-or-show-branches ()
  16375. "Abort storing current note, or show just branches."
  16376. (interactive)
  16377. (cond (org-finish-function
  16378. (let ((org-note-abort t)) (funcall org-finish-function)))
  16379. ((org-before-first-heading-p)
  16380. (org-show-branches-buffer)
  16381. (org-hide-archived-subtrees (point-min) (point-max)))
  16382. (t
  16383. (let ((beg (progn (org-back-to-heading) (point)))
  16384. (end (save-excursion (org-end-of-subtree t t) (point))))
  16385. (outline-hide-subtree)
  16386. (outline-show-branches)
  16387. (org-hide-archived-subtrees beg end)))))
  16388. (defun org-delete-indentation (&optional arg)
  16389. "Join current line to previous and fix whitespace at join.
  16390. If previous line is a headline add to headline title. Otherwise
  16391. the function calls `delete-indentation'.
  16392. I.e. with a non-nil optional argument, join the line with the
  16393. following one. If there is a region then join the lines in that
  16394. region."
  16395. (interactive "*P")
  16396. (if (save-excursion
  16397. (beginning-of-line (if arg 1 0))
  16398. (let ((case-fold-search nil))
  16399. (looking-at org-complex-heading-regexp)))
  16400. ;; At headline.
  16401. (let ((tags-column (when (match-beginning 5)
  16402. (save-excursion (goto-char (match-beginning 5))
  16403. (current-column))))
  16404. (string (concat " " (progn (when arg (forward-line 1))
  16405. (org-trim (delete-and-extract-region
  16406. (line-beginning-position)
  16407. (line-end-position)))))))
  16408. (unless (bobp) (delete-region (point) (1- (point))))
  16409. (goto-char (or (match-end 4)
  16410. (match-beginning 5)
  16411. (match-end 0)))
  16412. (skip-chars-backward " \t")
  16413. (save-excursion (insert string))
  16414. ;; Adjust alignment of tags.
  16415. (cond
  16416. ((not tags-column)) ;no tags
  16417. (org-auto-align-tags (org-align-tags))
  16418. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16419. (let ((current-prefix-arg arg))
  16420. (call-interactively #'delete-indentation))))
  16421. (defun org-open-line (n)
  16422. "Insert a new row in tables, call `open-line' elsewhere.
  16423. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16424. As a special case, when a document starts with a table, allow to
  16425. call `open-line' on the very first character."
  16426. (interactive "*p")
  16427. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16428. (org-table-insert-row)
  16429. (open-line n)))
  16430. (defun org--newline (indent arg interactive)
  16431. "Call `newline-and-indent' or just `newline'.
  16432. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16433. indent unconditionally; otherwise, call `newline' with ARG and
  16434. INTERACTIVE, which can trigger indentation if
  16435. `electric-indent-mode' is enabled."
  16436. (if indent
  16437. (org-newline-and-indent arg)
  16438. (newline arg interactive)))
  16439. (defun org-return (&optional indent arg interactive)
  16440. "Goto next table row or insert a newline.
  16441. Calls `org-table-next-row' or `newline', depending on context.
  16442. When optional INDENT argument is non-nil, call
  16443. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16444. and INTERACTIVE.
  16445. When `org-return-follows-link' is non-nil and point is on
  16446. a timestamp or a link, call `org-open-at-point'. However, it
  16447. will not happen if point is in a table or on a \"dead\"
  16448. object (e.g., within a comment). In these case, you need to use
  16449. `org-open-at-point' directly."
  16450. (interactive "i\nP\np")
  16451. (let* ((context (if org-return-follows-link (org-element-context)
  16452. (org-element-at-point)))
  16453. (element-type (org-element-type context)))
  16454. (cond
  16455. ;; In a table, call `org-table-next-row'. However, before first
  16456. ;; column or after last one, split the table.
  16457. ((or (and (eq 'table element-type)
  16458. (not (eq 'table.el (org-element-property :type context)))
  16459. (>= (point) (org-element-property :contents-begin context))
  16460. (< (point) (org-element-property :contents-end context)))
  16461. (org-element-lineage context '(table-row table-cell) t))
  16462. (if (or (looking-at-p "[ \t]*$")
  16463. (save-excursion (skip-chars-backward " \t") (bolp)))
  16464. (insert "\n")
  16465. (org-table-justify-field-maybe)
  16466. (call-interactively #'org-table-next-row)))
  16467. ;; On a link or a timestamp, call `org-open-at-point' if
  16468. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16469. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16470. ((and org-return-follows-link
  16471. (or (and (eq 'link element-type)
  16472. ;; Ensure point is not on the white spaces after
  16473. ;; the link.
  16474. (let ((origin (point)))
  16475. (org-with-point-at (org-element-property :end context)
  16476. (skip-chars-backward " \t")
  16477. (> (point) origin))))
  16478. (org-in-regexp org-ts-regexp-both nil t)
  16479. (org-in-regexp org-tsr-regexp-both nil t)
  16480. (org-in-regexp org-link-any-re nil t)))
  16481. (call-interactively #'org-open-at-point))
  16482. ;; Insert newline in heading, but preserve tags.
  16483. ((and (not (bolp))
  16484. (let ((case-fold-search nil))
  16485. (org-match-line org-complex-heading-regexp)))
  16486. ;; At headline. Split line. However, if point is on keyword,
  16487. ;; priority cookie or tags, do not break any of them: add
  16488. ;; a newline after the headline instead.
  16489. (let ((tags-column (and (match-beginning 5)
  16490. (save-excursion (goto-char (match-beginning 5))
  16491. (current-column))))
  16492. (string
  16493. (when (and (match-end 4) (org-point-in-group (point) 4))
  16494. (delete-and-extract-region (point) (match-end 4)))))
  16495. ;; Adjust tag alignment.
  16496. (cond
  16497. ((not (and tags-column string)))
  16498. (org-auto-align-tags (org-align-tags))
  16499. (t (org--align-tags-here tags-column))) ;preserve tags column
  16500. (end-of-line)
  16501. (org-show-entry)
  16502. (org--newline indent arg interactive)
  16503. (when string (save-excursion (insert (org-trim string))))))
  16504. ;; In a list, make sure indenting keeps trailing text within.
  16505. ((and (not (eolp))
  16506. (org-element-lineage context '(item)))
  16507. (let ((trailing-data
  16508. (delete-and-extract-region (point) (line-end-position))))
  16509. (org--newline indent arg interactive)
  16510. (save-excursion (insert trailing-data))))
  16511. (t
  16512. ;; Do not auto-fill when point is in an Org property drawer.
  16513. (let ((auto-fill-function (and (not (org-at-property-p))
  16514. auto-fill-function)))
  16515. (org--newline indent arg interactive))))))
  16516. (defun org-return-and-maybe-indent ()
  16517. "Goto next table row, or insert a newline, maybe indented.
  16518. Call `org-table-next-row' or `org-return', depending on context.
  16519. See the individual commands for more information.
  16520. When inserting a newline, if `org-adapt-indentation' is t:
  16521. indent the line if `electric-indent-mode' is disabled, don't
  16522. indent it if it is enabled."
  16523. (interactive)
  16524. (org-return (not electric-indent-mode)))
  16525. (defun org-ctrl-c-tab (&optional arg)
  16526. "Toggle columns width in a table, or show children.
  16527. Call `org-table-toggle-column-width' if point is in a table.
  16528. Otherwise provide a compact view of the children. ARG is the
  16529. level to hide."
  16530. (interactive "p")
  16531. (cond
  16532. ((org-at-table-p)
  16533. (call-interactively #'org-table-toggle-column-width))
  16534. ((org-before-first-heading-p)
  16535. (save-excursion
  16536. (org-flag-above-first-heading)
  16537. (outline-hide-sublevels (or arg 1))))
  16538. (t
  16539. (outline-hide-subtree)
  16540. (org-show-children arg))))
  16541. (defun org-ctrl-c-star ()
  16542. "Compute table, or change heading status of lines.
  16543. Calls `org-table-recalculate' or `org-toggle-heading',
  16544. depending on context."
  16545. (interactive)
  16546. (cond
  16547. ((org-at-table-p)
  16548. (call-interactively 'org-table-recalculate))
  16549. (t
  16550. ;; Convert all lines in region to list items
  16551. (call-interactively 'org-toggle-heading))))
  16552. (defun org-ctrl-c-minus ()
  16553. "Insert separator line in table or modify bullet status of line.
  16554. Also turns a plain line or a region of lines into list items.
  16555. Calls `org-table-insert-hline', `org-toggle-item', or
  16556. `org-cycle-list-bullet', depending on context."
  16557. (interactive)
  16558. (cond
  16559. ((org-at-table-p)
  16560. (call-interactively 'org-table-insert-hline))
  16561. ((org-region-active-p)
  16562. (call-interactively 'org-toggle-item))
  16563. ((org-in-item-p)
  16564. (call-interactively 'org-cycle-list-bullet))
  16565. (t
  16566. (call-interactively 'org-toggle-item))))
  16567. (defun org-toggle-heading (&optional nstars)
  16568. "Convert headings to normal text, or items or text to headings.
  16569. If there is no active region, only convert the current line.
  16570. With a `\\[universal-argument]' prefix, convert the whole list at
  16571. point into heading.
  16572. In a region:
  16573. - If the first non blank line is a headline, remove the stars
  16574. from all headlines in the region.
  16575. - If it is a normal line, turn each and every normal line (i.e.,
  16576. not an heading or an item) in the region into headings. If you
  16577. want to convert only the first line of this region, use one
  16578. universal prefix argument.
  16579. - If it is a plain list item, turn all plain list items into headings.
  16580. When converting a line into a heading, the number of stars is chosen
  16581. such that the lines become children of the current entry. However,
  16582. when a numeric prefix argument is given, its value determines the
  16583. number of stars to add."
  16584. (interactive "P")
  16585. (let ((skip-blanks
  16586. ;; Return beginning of first non-blank line, starting from
  16587. ;; line at POS.
  16588. (lambda (pos)
  16589. (save-excursion
  16590. (goto-char pos)
  16591. (while (org-at-comment-p) (forward-line))
  16592. (skip-chars-forward " \r\t\n")
  16593. (point-at-bol))))
  16594. beg end toggled)
  16595. ;; Determine boundaries of changes. If a universal prefix has
  16596. ;; been given, put the list in a region. If region ends at a bol,
  16597. ;; do not consider the last line to be in the region.
  16598. (when (and current-prefix-arg (org-at-item-p))
  16599. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16600. (org-mark-element))
  16601. (if (org-region-active-p)
  16602. (setq beg (funcall skip-blanks (region-beginning))
  16603. end (copy-marker (save-excursion
  16604. (goto-char (region-end))
  16605. (if (bolp) (point) (point-at-eol)))))
  16606. (setq beg (funcall skip-blanks (point-at-bol))
  16607. end (copy-marker (point-at-eol))))
  16608. ;; Ensure inline tasks don't count as headings.
  16609. (org-with-limited-levels
  16610. (save-excursion
  16611. (goto-char beg)
  16612. (cond
  16613. ;; Case 1. Started at an heading: de-star headings.
  16614. ((org-at-heading-p)
  16615. (while (< (point) end)
  16616. (when (org-at-heading-p t)
  16617. (looking-at org-outline-regexp) (replace-match "")
  16618. (setq toggled t))
  16619. (forward-line)))
  16620. ;; Case 2. Started at an item: change items into headlines.
  16621. ;; One star will be added by `org-list-to-subtree'.
  16622. ((org-at-item-p)
  16623. (while (< (point) end)
  16624. (when (org-at-item-p)
  16625. ;; Pay attention to cases when region ends before list.
  16626. (let* ((struct (org-list-struct))
  16627. (list-end
  16628. (min (org-list-get-bottom-point struct) (1+ end))))
  16629. (save-restriction
  16630. (narrow-to-region (point) list-end)
  16631. (insert (org-list-to-subtree
  16632. (org-list-to-lisp t)
  16633. (pcase (org-current-level)
  16634. (`nil 1)
  16635. (l (1+ (org-reduced-level l)))))
  16636. "\n")))
  16637. (setq toggled t))
  16638. (forward-line)))
  16639. ;; Case 3. Started at normal text: make every line an heading,
  16640. ;; skipping headlines and items.
  16641. (t (let* ((stars
  16642. (make-string
  16643. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16644. (add-stars
  16645. (cond (nstars "") ; stars from prefix only
  16646. ((equal stars "") "*") ; before first heading
  16647. (org-odd-levels-only "**") ; inside heading, odd
  16648. (t "*"))) ; inside heading, oddeven
  16649. (rpl (concat stars add-stars " "))
  16650. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16651. (while (< (point) (if (equal nstars '(4)) lend end))
  16652. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16653. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16654. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16655. (forward-line)))))))
  16656. (unless toggled (message "Cannot toggle heading from here"))))
  16657. (defun org-meta-return (&optional arg)
  16658. "Insert a new heading or wrap a region in a table.
  16659. Calls `org-insert-heading', `org-insert-item' or
  16660. `org-table-wrap-region', depending on context. When called with
  16661. an argument, unconditionally call `org-insert-heading'."
  16662. (interactive "P")
  16663. (org-check-before-invisible-edit 'insert)
  16664. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16665. (call-interactively (cond (arg #'org-insert-heading)
  16666. ((org-at-table-p) #'org-table-wrap-region)
  16667. ((org-in-item-p) #'org-insert-item)
  16668. (t #'org-insert-heading)))))
  16669. ;;; Menu entries
  16670. (defsubst org-in-subtree-not-table-p ()
  16671. "Are we in a subtree and not in a table?"
  16672. (and (not (org-before-first-heading-p))
  16673. (not (org-at-table-p))))
  16674. ;; Define the Org mode menus
  16675. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16676. `("Org"
  16677. ("Show/Hide"
  16678. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16679. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16680. ["Sparse Tree..." org-sparse-tree t]
  16681. ["Reveal Context" org-reveal t]
  16682. ["Show All" org-show-all t]
  16683. "--"
  16684. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16685. "--"
  16686. ["New Heading" org-insert-heading t]
  16687. ("Navigate Headings"
  16688. ["Up" outline-up-heading t]
  16689. ["Next" outline-next-visible-heading t]
  16690. ["Previous" outline-previous-visible-heading t]
  16691. ["Next Same Level" outline-forward-same-level t]
  16692. ["Previous Same Level" outline-backward-same-level t]
  16693. "--"
  16694. ["Jump" org-goto t])
  16695. ("Edit Structure"
  16696. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16697. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16698. "--"
  16699. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16700. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16701. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16702. "--"
  16703. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16704. "--"
  16705. ["Copy visible text" org-copy-visible t]
  16706. "--"
  16707. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16708. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16709. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16710. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16711. "--"
  16712. ["Sort Region/Children" org-sort t]
  16713. "--"
  16714. ["Convert to odd levels" org-convert-to-odd-levels t]
  16715. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16716. ("Editing"
  16717. ["Emphasis..." org-emphasize t]
  16718. ["Add block structure" org-insert-structure-template t]
  16719. ["Edit Source Example" org-edit-special t]
  16720. "--"
  16721. ["Footnote new/jump" org-footnote-action t]
  16722. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16723. ("Archive"
  16724. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16725. "--"
  16726. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16727. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16728. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16729. "--"
  16730. ("Hyperlinks"
  16731. ["Store Link (Global)" org-store-link t]
  16732. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16733. ["Insert Link" org-insert-link t]
  16734. ["Follow Link" org-open-at-point t]
  16735. "--"
  16736. ["Next link" org-next-link t]
  16737. ["Previous link" org-previous-link t]
  16738. "--"
  16739. ["Descriptive Links"
  16740. org-toggle-link-display
  16741. :style radio
  16742. :selected org-descriptive-links
  16743. ]
  16744. ["Literal Links"
  16745. org-toggle-link-display
  16746. :style radio
  16747. :selected (not org-descriptive-links)])
  16748. "--"
  16749. ("TODO Lists"
  16750. ["TODO/DONE/-" org-todo t]
  16751. ("Select keyword"
  16752. ["Next keyword" org-shiftright (org-at-heading-p)]
  16753. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16754. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16755. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16756. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16757. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16758. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16759. "--"
  16760. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16761. :selected org-enforce-todo-dependencies :style toggle :active t]
  16762. "Settings for tree at point"
  16763. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16764. :selected (org-entry-get nil "ORDERED")
  16765. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16766. ["Do Children parallel" org-toggle-ordered-property :style radio
  16767. :selected (not (org-entry-get nil "ORDERED"))
  16768. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16769. "--"
  16770. ["Set Priority" org-priority t]
  16771. ["Priority Up" org-shiftup t]
  16772. ["Priority Down" org-shiftdown t]
  16773. "--"
  16774. ["Get news from all feeds" org-feed-update-all t]
  16775. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16776. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16777. ("TAGS and Properties"
  16778. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16779. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16780. "--"
  16781. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16782. ["Column view of properties" org-columns t]
  16783. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16784. ("Dates and Scheduling"
  16785. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16786. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16787. ("Change Date"
  16788. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16789. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16790. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16791. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16792. ["Compute Time Range" org-evaluate-time-range t]
  16793. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16794. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16795. "--"
  16796. ["Custom time format" org-toggle-time-stamp-overlays
  16797. :style radio :selected org-display-custom-times]
  16798. "--"
  16799. ["Goto Calendar" org-goto-calendar t]
  16800. ["Date from Calendar" org-date-from-calendar t]
  16801. "--"
  16802. ["Start/Restart Timer" org-timer-start t]
  16803. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16804. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16805. ["Insert Timer String" org-timer t]
  16806. ["Insert Timer Item" org-timer-item t])
  16807. ("Logging work"
  16808. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16809. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16810. ["Clock out" org-clock-out t]
  16811. ["Clock cancel" org-clock-cancel t]
  16812. "--"
  16813. ["Mark as default task" org-clock-mark-default-task t]
  16814. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16815. ["Goto running clock" org-clock-goto t]
  16816. "--"
  16817. ["Display times" org-clock-display t]
  16818. ["Create clock table" org-clock-report t]
  16819. "--"
  16820. ["Record DONE time"
  16821. (progn (setq org-log-done (not org-log-done))
  16822. (message "Switching to %s will %s record a timestamp"
  16823. (car org-done-keywords)
  16824. (if org-log-done "automatically" "not")))
  16825. :style toggle :selected org-log-done])
  16826. "--"
  16827. ["Agenda Command..." org-agenda t]
  16828. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16829. ("File List for Agenda")
  16830. ("Special views current file"
  16831. ["TODO Tree" org-show-todo-tree t]
  16832. ["Check Deadlines" org-check-deadlines t]
  16833. ["Tags/Property tree" org-match-sparse-tree t])
  16834. "--"
  16835. ["Export/Publish..." org-export-dispatch t]
  16836. ("LaTeX"
  16837. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16838. :style toggle :selected org-cdlatex-mode]
  16839. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16840. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16841. ["Modify math symbol" org-cdlatex-math-modify
  16842. (org-inside-LaTeX-fragment-p)]
  16843. ["Insert citation" org-reftex-citation t])
  16844. "--"
  16845. ("Documentation"
  16846. ["Show Version" org-version t]
  16847. ["Info Documentation" org-info t]
  16848. ["Browse Org News" org-browse-news t])
  16849. ("Customize"
  16850. ["Browse Org Group" org-customize t]
  16851. "--"
  16852. ["Expand This Menu" org-create-customize-menu t])
  16853. ["Send bug report" org-submit-bug-report t]
  16854. "--"
  16855. ("Refresh/Reload"
  16856. ["Refresh setup current buffer" org-mode-restart t]
  16857. ["Reload Org (after update)" org-reload t]
  16858. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16859. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16860. '("Table"
  16861. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16862. ["Next Field" org-cycle (org-at-table-p)]
  16863. ["Previous Field" org-shifttab (org-at-table-p)]
  16864. ["Next Row" org-return (org-at-table-p)]
  16865. "--"
  16866. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16867. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16868. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16869. "--"
  16870. ("Column"
  16871. ["Move Column Left" org-metaleft (org-at-table-p)]
  16872. ["Move Column Right" org-metaright (org-at-table-p)]
  16873. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16874. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16875. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16876. ("Row"
  16877. ["Move Row Up" org-metaup (org-at-table-p)]
  16878. ["Move Row Down" org-metadown (org-at-table-p)]
  16879. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16880. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16881. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16882. "--"
  16883. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16884. ("Rectangle"
  16885. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16886. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16887. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16888. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16889. "--"
  16890. ("Calculate"
  16891. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16892. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16893. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16894. "--"
  16895. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16896. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16897. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16898. "--"
  16899. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16900. "--"
  16901. ["Sum Column/Rectangle" org-table-sum
  16902. (or (org-at-table-p) (org-region-active-p))]
  16903. ["Which Column?" org-table-current-column (org-at-table-p)])
  16904. ["Debug Formulas"
  16905. org-table-toggle-formula-debugger
  16906. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16907. ["Show Col/Row Numbers"
  16908. org-table-toggle-coordinate-overlays
  16909. :style toggle
  16910. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16911. "--"
  16912. ["Create" org-table-create (not (org-at-table-p))]
  16913. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16914. ["Import from File" org-table-import (not (org-at-table-p))]
  16915. ["Export to File" org-table-export (org-at-table-p)]
  16916. "--"
  16917. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16918. "--"
  16919. ("Plot"
  16920. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16921. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16922. (defun org-info (&optional node)
  16923. "Read documentation for Org in the info system.
  16924. With optional NODE, go directly to that node."
  16925. (interactive)
  16926. (info (format "(org)%s" (or node ""))))
  16927. (defun org-browse-news ()
  16928. "Browse the news for the latest major release."
  16929. (interactive)
  16930. (browse-url "https://orgmode.org/Changes.html"))
  16931. ;;;###autoload
  16932. (defun org-submit-bug-report ()
  16933. "Submit a bug report on Org via mail.
  16934. Don't hesitate to report any problems or inaccurate documentation.
  16935. If you don't have setup sending mail from (X)Emacs, please copy the
  16936. output buffer into your mail program, as it gives us important
  16937. information about your Org version and configuration."
  16938. (interactive)
  16939. (require 'reporter)
  16940. (defvar reporter-prompt-for-summary-p)
  16941. (org-load-modules-maybe)
  16942. (org-require-autoloaded-modules)
  16943. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16944. (reporter-submit-bug-report
  16945. "emacs-orgmode@gnu.org"
  16946. (org-version nil 'full)
  16947. (let (list)
  16948. (save-window-excursion
  16949. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16950. (delete-other-windows)
  16951. (erase-buffer)
  16952. (insert "You are about to submit a bug report to the Org mailing list.
  16953. If your report is about Org installation, please read this section:
  16954. https://orgmode.org/org.html#Installation
  16955. Please read https://orgmode.org/org.html#Feedback on how to make
  16956. a good report, it will help Org contributors fixing your problem.
  16957. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16958. if the issue you are about to raise has already been dealt with.
  16959. We also would like to add your full Org and Outline configuration
  16960. to the bug report. It will help us debugging the issue.
  16961. *HOWEVER*, some variables you have customized may contain private
  16962. information. The names of customers, colleagues, or friends, might
  16963. appear in the form of file names, tags, todo states or search strings.
  16964. If you answer \"yes\" to the prompt, you might want to check and remove
  16965. such private information before sending the email.")
  16966. (add-text-properties (point-min) (point-max) '(face org-warning))
  16967. (when (yes-or-no-p "Include your Org configuration ")
  16968. (mapatoms
  16969. (lambda (v)
  16970. (and (boundp v)
  16971. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16972. (or (and (symbol-value v)
  16973. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16974. (and
  16975. (get v 'custom-type) (get v 'standard-value)
  16976. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16977. (push v list)))))
  16978. (kill-buffer (get-buffer "*Warn about privacy*"))
  16979. list))
  16980. nil nil
  16981. "Remember to cover the basics, that is, what you expected to happen and
  16982. what in fact did happen. You don't know how to make a good report? See
  16983. https://orgmode.org/manual/Feedback.html#Feedback
  16984. Your bug report will be posted to the Org mailing list.
  16985. ------------------------------------------------------------------------")
  16986. (save-excursion
  16987. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16988. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16989. (defun org-install-agenda-files-menu ()
  16990. "Install agenda file menu."
  16991. (let ((bl (buffer-list)))
  16992. (save-excursion
  16993. (while bl
  16994. (set-buffer (pop bl))
  16995. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16996. (when (derived-mode-p 'org-mode)
  16997. (easy-menu-change
  16998. '("Org") "File List for Agenda"
  16999. (append
  17000. (list
  17001. ["Edit File List" (org-edit-agenda-file-list) t]
  17002. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17003. ["Remove Current File from List" org-remove-file t]
  17004. ["Cycle through agenda files" org-cycle-agenda-files t]
  17005. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17006. "--")
  17007. (mapcar 'org-file-menu-entry
  17008. ;; Prevent initialization from failing.
  17009. (ignore-errors (org-agenda-files t)))))))))
  17010. ;;;; Documentation
  17011. (defun org-require-autoloaded-modules ()
  17012. (interactive)
  17013. (mapc #'require
  17014. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17015. org-table org-timer)))
  17016. ;;;###autoload
  17017. (defun org-reload (&optional uncompiled)
  17018. "Reload all Org Lisp files.
  17019. With prefix arg UNCOMPILED, load the uncompiled versions."
  17020. (interactive "P")
  17021. (require 'loadhist)
  17022. (let* ((org-dir (org-find-library-dir "org"))
  17023. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17024. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17025. (remove-re (format "\\`%s\\'"
  17026. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17027. (feats (delete-dups
  17028. (mapcar 'file-name-sans-extension
  17029. (mapcar 'file-name-nondirectory
  17030. (delq nil
  17031. (mapcar 'feature-file
  17032. features))))))
  17033. (lfeat (append
  17034. (sort
  17035. (setq feats
  17036. (delq nil (mapcar
  17037. (lambda (f)
  17038. (if (and (string-match feature-re f)
  17039. (not (string-match remove-re f)))
  17040. f nil))
  17041. feats)))
  17042. 'string-lessp)
  17043. (list "org-version" "org")))
  17044. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17045. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17046. load-uncore load-misses)
  17047. (setq load-misses
  17048. (delq 't
  17049. (mapcar (lambda (f)
  17050. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17051. (and (string= org-dir contrib-dir)
  17052. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17053. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17054. (push f load-uncore)
  17055. 't)
  17056. f))
  17057. lfeat)))
  17058. (when load-uncore
  17059. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17060. (if (> (length load-uncore) 1) "s were" " was")
  17061. (reverse load-uncore)))
  17062. (if load-misses
  17063. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17064. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17065. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17066. ;;;###autoload
  17067. (defun org-customize ()
  17068. "Call the customize function with org as argument."
  17069. (interactive)
  17070. (org-load-modules-maybe)
  17071. (org-require-autoloaded-modules)
  17072. (customize-browse 'org))
  17073. (defun org-create-customize-menu ()
  17074. "Create a full customization menu for Org mode, insert it into the menu."
  17075. (interactive)
  17076. (org-load-modules-maybe)
  17077. (org-require-autoloaded-modules)
  17078. (easy-menu-change
  17079. '("Org") "Customize"
  17080. `(["Browse Org group" org-customize t]
  17081. "--"
  17082. ,(customize-menu-create 'org)
  17083. ["Set" Custom-set t]
  17084. ["Save" Custom-save t]
  17085. ["Reset to Current" Custom-reset-current t]
  17086. ["Reset to Saved" Custom-reset-saved t]
  17087. ["Reset to Standard Settings" Custom-reset-standard t]))
  17088. (message "\"Org\"-menu now contains full customization menu"))
  17089. ;;;; Miscellaneous stuff
  17090. ;;; Generally useful functions
  17091. (defun org-in-clocktable-p ()
  17092. "Check if the cursor is in a clocktable."
  17093. (let ((pos (point)) start)
  17094. (save-excursion
  17095. (end-of-line 1)
  17096. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17097. (setq start (match-beginning 0))
  17098. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17099. (>= (match-end 0) pos)
  17100. start))))
  17101. (defun org-in-verbatim-emphasis ()
  17102. (save-match-data
  17103. (and (org-in-regexp org-verbatim-re 2)
  17104. (>= (point) (match-beginning 3))
  17105. (<= (point) (match-end 4)))))
  17106. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17107. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17108. (if (and marker (marker-buffer marker)
  17109. (buffer-live-p (marker-buffer marker)))
  17110. (progn
  17111. (pop-to-buffer-same-window (marker-buffer marker))
  17112. (when (or (> marker (point-max)) (< marker (point-min)))
  17113. (widen))
  17114. (goto-char marker)
  17115. (org-show-context 'org-goto))
  17116. (if bookmark
  17117. (bookmark-jump bookmark)
  17118. (error "Cannot find location"))))
  17119. (defun org-quote-csv-field (s)
  17120. "Quote field for inclusion in CSV material."
  17121. (if (string-match "[\",]" s)
  17122. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17123. s))
  17124. (defun org-force-self-insert (N)
  17125. "Needed to enforce self-insert under remapping."
  17126. (interactive "p")
  17127. (self-insert-command N))
  17128. (defun org-quote-vert (s)
  17129. "Replace \"|\" with \"\\vert\"."
  17130. (while (string-match "|" s)
  17131. (setq s (replace-match "\\vert" t t s)))
  17132. s)
  17133. (defun org-uuidgen-p (s)
  17134. "Is S an ID created by UUIDGEN?"
  17135. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17136. (defun org-in-src-block-p (&optional inside element)
  17137. "Whether point is in a code source block.
  17138. When INSIDE is non-nil, don't consider we are within a source
  17139. block when point is at #+BEGIN_SRC or #+END_SRC.
  17140. When ELEMENT is provided, it is considered to be element at point."
  17141. (save-match-data (setq element (or element (org-element-at-point))))
  17142. (when (eq 'src-block (org-element-type element))
  17143. (or (not inside)
  17144. (not (or (= (line-beginning-position)
  17145. (org-element-property :post-affiliated element))
  17146. (= (1+ (line-end-position))
  17147. (- (org-element-property :end element)
  17148. (org-element-property :post-blank element))))))))
  17149. (defun org-context ()
  17150. "Return a list of contexts of the current cursor position.
  17151. If several contexts apply, all are returned.
  17152. Each context entry is a list with a symbol naming the context, and
  17153. two positions indicating start and end of the context. Possible
  17154. contexts are:
  17155. :headline anywhere in a headline
  17156. :headline-stars on the leading stars in a headline
  17157. :todo-keyword on a TODO keyword (including DONE) in a headline
  17158. :tags on the TAGS in a headline
  17159. :priority on the priority cookie in a headline
  17160. :item on the first line of a plain list item
  17161. :item-bullet on the bullet/number of a plain list item
  17162. :checkbox on the checkbox in a plain list item
  17163. :table in an Org table
  17164. :table-special on a special filed in a table
  17165. :table-table in a table.el table
  17166. :clocktable in a clocktable
  17167. :src-block in a source block
  17168. :link on a hyperlink
  17169. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17170. :latex-fragment on a LaTeX fragment
  17171. :latex-preview on a LaTeX fragment with overlaid preview image
  17172. This function expects the position to be visible because it uses font-lock
  17173. faces as a help to recognize the following contexts: :table-special, :link,
  17174. and :keyword."
  17175. (let* ((f (get-text-property (point) 'face))
  17176. (faces (if (listp f) f (list f)))
  17177. (case-fold-search t)
  17178. (p (point)) clist o)
  17179. ;; First the large context
  17180. (cond
  17181. ((org-at-heading-p t)
  17182. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17183. (when (progn
  17184. (beginning-of-line 1)
  17185. (looking-at org-todo-line-tags-regexp))
  17186. (push (org-point-in-group p 1 :headline-stars) clist)
  17187. (push (org-point-in-group p 2 :todo-keyword) clist)
  17188. (push (org-point-in-group p 4 :tags) clist))
  17189. (goto-char p)
  17190. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17191. (when (looking-at "\\[#[A-Z0-9]\\]")
  17192. (push (org-point-in-group p 0 :priority) clist)))
  17193. ((org-at-item-p)
  17194. (push (org-point-in-group p 2 :item-bullet) clist)
  17195. (push (list :item (point-at-bol)
  17196. (save-excursion (org-end-of-item) (point)))
  17197. clist)
  17198. (and (org-at-item-checkbox-p)
  17199. (push (org-point-in-group p 0 :checkbox) clist)))
  17200. ((org-at-table-p)
  17201. (push (list :table (org-table-begin) (org-table-end)) clist)
  17202. (when (memq 'org-formula faces)
  17203. (push (list :table-special
  17204. (previous-single-property-change p 'face)
  17205. (next-single-property-change p 'face))
  17206. clist)))
  17207. ((org-at-table-p 'any)
  17208. (push (list :table-table) clist)))
  17209. (goto-char p)
  17210. (let ((case-fold-search t))
  17211. ;; New the "medium" contexts: clocktables, source blocks
  17212. (cond ((org-in-clocktable-p)
  17213. (push (list :clocktable
  17214. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17215. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17216. (match-beginning 1))
  17217. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17218. (match-end 0)))
  17219. clist))
  17220. ((org-in-src-block-p)
  17221. (push (list :src-block
  17222. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17223. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17224. (match-beginning 1))
  17225. (and (search-forward "#+END_SRC" nil t)
  17226. (match-beginning 0)))
  17227. clist))))
  17228. (goto-char p)
  17229. ;; Now the small context
  17230. (cond
  17231. ((org-at-timestamp-p)
  17232. (push (org-point-in-group p 0 :timestamp) clist))
  17233. ((memq 'org-link faces)
  17234. (push (list :link
  17235. (previous-single-property-change p 'face)
  17236. (next-single-property-change p 'face))
  17237. clist))
  17238. ((memq 'org-special-keyword faces)
  17239. (push (list :keyword
  17240. (previous-single-property-change p 'face)
  17241. (next-single-property-change p 'face))
  17242. clist))
  17243. ((setq o (cl-some
  17244. (lambda (o)
  17245. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17246. o))
  17247. (overlays-at (point))))
  17248. (push (list :latex-fragment
  17249. (overlay-start o) (overlay-end o))
  17250. clist)
  17251. (push (list :latex-preview
  17252. (overlay-start o) (overlay-end o))
  17253. clist))
  17254. ((org-inside-LaTeX-fragment-p)
  17255. ;; FIXME: positions wrong.
  17256. (push (list :latex-fragment (point) (point)) clist)))
  17257. (setq clist (nreverse (delq nil clist)))
  17258. clist))
  17259. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17260. "Non-nil when point is between matches of START-RE and END-RE.
  17261. Also return a non-nil value when point is on one of the matches.
  17262. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17263. buffer positions. Default values are the positions of headlines
  17264. surrounding the point.
  17265. The functions returns a cons cell whose car (resp. cdr) is the
  17266. position before START-RE (resp. after END-RE)."
  17267. (save-match-data
  17268. (let ((pos (point))
  17269. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17270. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17271. beg end)
  17272. (save-excursion
  17273. ;; Point is on a block when on START-RE or if START-RE can be
  17274. ;; found before it...
  17275. (and (or (org-in-regexp start-re)
  17276. (re-search-backward start-re limit-up t))
  17277. (setq beg (match-beginning 0))
  17278. ;; ... and END-RE after it...
  17279. (goto-char (match-end 0))
  17280. (re-search-forward end-re limit-down t)
  17281. (> (setq end (match-end 0)) pos)
  17282. ;; ... without another START-RE in-between.
  17283. (goto-char (match-beginning 0))
  17284. (not (re-search-backward start-re (1+ beg) t))
  17285. ;; Return value.
  17286. (cons beg end))))))
  17287. (defun org-in-block-p (names)
  17288. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17289. NAMES is a list of strings containing names of blocks.
  17290. Return first block name matched, or nil. Beware that in case of
  17291. nested blocks, the returned name may not belong to the closest
  17292. block from point."
  17293. (save-match-data
  17294. (catch 'exit
  17295. (let ((case-fold-search t)
  17296. (lim-up (save-excursion (outline-previous-heading)))
  17297. (lim-down (save-excursion (outline-next-heading))))
  17298. (dolist (name names)
  17299. (let ((n (regexp-quote name)))
  17300. (when (org-between-regexps-p
  17301. (concat "^[ \t]*#\\+begin_" n)
  17302. (concat "^[ \t]*#\\+end_" n)
  17303. lim-up lim-down)
  17304. (throw 'exit n)))))
  17305. nil)))
  17306. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17307. "Call `multi-occur' with buffers for all agenda files."
  17308. (interactive "sOrg-files matching: ")
  17309. (let* ((files (org-agenda-files))
  17310. (tnames (mapcar #'file-truename files))
  17311. (extra org-agenda-text-search-extra-files))
  17312. (when (eq (car extra) 'agenda-archives)
  17313. (setq extra (cdr extra))
  17314. (setq files (org-add-archive-files files)))
  17315. (dolist (f extra)
  17316. (unless (member (file-truename f) tnames)
  17317. (unless (member f files) (setq files (append files (list f))))
  17318. (setq tnames (append tnames (list (file-truename f))))))
  17319. (multi-occur
  17320. (mapcar (lambda (x)
  17321. (with-current-buffer
  17322. ;; FIXME: Why not just (find-file-noselect x)?
  17323. ;; Is it to avoid the "revert buffer" prompt?
  17324. (or (get-file-buffer x) (find-file-noselect x))
  17325. (widen)
  17326. (current-buffer)))
  17327. files)
  17328. regexp)))
  17329. (add-hook 'occur-mode-find-occurrence-hook
  17330. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17331. (defun org-occur-link-in-agenda-files ()
  17332. "Create a link and search for it in the agendas.
  17333. The link is not stored in `org-stored-links', it is just created
  17334. for the search purpose."
  17335. (interactive)
  17336. (let ((link (condition-case nil
  17337. (org-store-link nil)
  17338. (error "Unable to create a link to here"))))
  17339. (org-occur-in-agenda-files (regexp-quote link))))
  17340. (defun org-back-over-empty-lines ()
  17341. "Move backwards over whitespace, to the beginning of the first empty line.
  17342. Returns the number of empty lines passed."
  17343. (let ((pos (point)))
  17344. (if (cdr (assq 'heading org-blank-before-new-entry))
  17345. (skip-chars-backward " \t\n\r")
  17346. (unless (eobp)
  17347. (forward-line -1)))
  17348. (beginning-of-line 2)
  17349. (goto-char (min (point) pos))
  17350. (count-lines (point) pos)))
  17351. ;;; TODO: Only called once, from ox-odt which should probably use
  17352. ;;; org-export-inline-image-p or something.
  17353. (defun org-file-image-p (file)
  17354. "Return non-nil if FILE is an image."
  17355. (save-match-data
  17356. (string-match (image-file-name-regexp) file)))
  17357. (defun org-get-cursor-date (&optional with-time)
  17358. "Return the date at cursor in as a time.
  17359. This works in the calendar and in the agenda, anywhere else it just
  17360. returns the current time.
  17361. If WITH-TIME is non-nil, returns the time of the event at point (in
  17362. the agenda) or the current time of the day; otherwise returns the
  17363. earliest time on the cursor date that Org treats as that date
  17364. (bearing in mind `org-extend-today-until')."
  17365. (let (date day defd tp hod mod)
  17366. (when with-time
  17367. (setq tp (get-text-property (point) 'time))
  17368. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17369. (setq hod (string-to-number (match-string 1 tp))
  17370. mod (string-to-number (match-string 2 tp))))
  17371. (or tp (let ((now (decode-time)))
  17372. (setq hod (nth 2 now)
  17373. mod (nth 1 now)))))
  17374. (cond
  17375. ((eq major-mode 'calendar-mode)
  17376. (setq date (calendar-cursor-to-date)
  17377. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17378. (nth 1 date) (nth 0 date) (nth 2 date))))
  17379. ((eq major-mode 'org-agenda-mode)
  17380. (setq day (get-text-property (point) 'day))
  17381. (when day
  17382. (setq date (calendar-gregorian-from-absolute day)
  17383. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17384. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17385. (or defd (current-time))))
  17386. (defun org-mark-subtree (&optional up)
  17387. "Mark the current subtree.
  17388. This puts point at the start of the current subtree, and mark at
  17389. the end. If a numeric prefix UP is given, move up into the
  17390. hierarchy of headlines by UP levels before marking the subtree."
  17391. (interactive "P")
  17392. (org-with-limited-levels
  17393. (cond ((org-at-heading-p) (beginning-of-line))
  17394. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17395. (t (outline-previous-visible-heading 1))))
  17396. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17397. (if (called-interactively-p 'any)
  17398. (call-interactively 'org-mark-element)
  17399. (org-mark-element)))
  17400. ;;; Indentation
  17401. (defvar org-element-greater-elements)
  17402. (defun org--get-expected-indentation (element contentsp)
  17403. "Expected indentation column for current line, according to ELEMENT.
  17404. ELEMENT is an element containing point. CONTENTSP is non-nil
  17405. when indentation is to be computed according to contents of
  17406. ELEMENT."
  17407. (let ((type (org-element-type element))
  17408. (start (org-element-property :begin element))
  17409. (post-affiliated (org-element-property :post-affiliated element)))
  17410. (org-with-wide-buffer
  17411. (cond
  17412. (contentsp
  17413. (cl-case type
  17414. ((diary-sexp footnote-definition) 0)
  17415. ((headline inlinetask nil)
  17416. (if (not org-adapt-indentation) 0
  17417. (let ((level (org-current-level)))
  17418. (if level (1+ level) 0))))
  17419. ((item plain-list) (org-list-item-body-column post-affiliated))
  17420. (t
  17421. (goto-char start)
  17422. (current-indentation))))
  17423. ((memq type '(headline inlinetask nil))
  17424. (if (org-match-line "[ \t]*$")
  17425. (org--get-expected-indentation element t)
  17426. 0))
  17427. ((memq type '(diary-sexp footnote-definition)) 0)
  17428. ;; First paragraph of a footnote definition or an item.
  17429. ;; Indent like parent.
  17430. ((< (line-beginning-position) start)
  17431. (org--get-expected-indentation
  17432. (org-element-property :parent element) t))
  17433. ;; At first line: indent according to previous sibling, if any,
  17434. ;; ignoring footnote definitions and inline tasks, or parent's
  17435. ;; contents.
  17436. ((and ( = (line-beginning-position) start)
  17437. (eq org-adapt-indentation t))
  17438. (catch 'exit
  17439. (while t
  17440. (if (= (point-min) start) (throw 'exit 0)
  17441. (goto-char (1- start))
  17442. (let* ((previous (org-element-at-point))
  17443. (parent previous))
  17444. (while (and parent (<= (org-element-property :end parent) start))
  17445. (setq previous parent
  17446. parent (org-element-property :parent parent)))
  17447. (cond
  17448. ((not previous) (throw 'exit 0))
  17449. ((> (org-element-property :end previous) start)
  17450. (throw 'exit (org--get-expected-indentation previous t)))
  17451. ((memq (org-element-type previous)
  17452. '(footnote-definition inlinetask))
  17453. (setq start (org-element-property :begin previous)))
  17454. (t (goto-char (org-element-property :begin previous))
  17455. (throw 'exit
  17456. (if (bolp) (current-indentation)
  17457. ;; At first paragraph in an item or
  17458. ;; a footnote definition.
  17459. (org--get-expected-indentation
  17460. (org-element-property :parent previous) t))))))))))
  17461. ;; Otherwise, move to the first non-blank line above.
  17462. (t
  17463. (beginning-of-line)
  17464. (let ((pos (point)))
  17465. (skip-chars-backward " \r\t\n")
  17466. (cond
  17467. ;; Two blank lines end a footnote definition or a plain
  17468. ;; list. When we indent an empty line after them, the
  17469. ;; containing list or footnote definition is over, so it
  17470. ;; qualifies as a previous sibling. Therefore, we indent
  17471. ;; like its first line.
  17472. ((and (memq type '(footnote-definition plain-list))
  17473. (> (count-lines (point) pos) 2))
  17474. (goto-char start)
  17475. (current-indentation))
  17476. ;; Line above is the first one of a paragraph at the
  17477. ;; beginning of an item or a footnote definition. Indent
  17478. ;; like parent.
  17479. ((< (line-beginning-position) start)
  17480. (org--get-expected-indentation
  17481. (org-element-property :parent element) t))
  17482. ;; Line above is the beginning of an element, i.e., point
  17483. ;; was originally on the blank lines between element's start
  17484. ;; and contents.
  17485. ((= (line-beginning-position) post-affiliated)
  17486. (org--get-expected-indentation element t))
  17487. ;; POS is after contents in a greater element. Indent like
  17488. ;; the beginning of the element.
  17489. ((and (memq type org-element-greater-elements)
  17490. (let ((cend (org-element-property :contents-end element)))
  17491. (and cend (<= cend pos))))
  17492. ;; As a special case, if point is at the end of a footnote
  17493. ;; definition or an item, indent like the very last element
  17494. ;; within. If that last element is an item, indent like
  17495. ;; its contents.
  17496. (if (memq type '(footnote-definition item plain-list))
  17497. (let ((last (org-element-at-point)))
  17498. (goto-char pos)
  17499. (org--get-expected-indentation
  17500. last (eq (org-element-type last) 'item)))
  17501. (goto-char start)
  17502. (current-indentation)))
  17503. ;; In any other case, indent like the current line.
  17504. (t (current-indentation)))))
  17505. ;; Finally, no indentation is needed, fall back to 0.
  17506. (t (current-indentation))))))
  17507. (defun org--align-node-property ()
  17508. "Align node property at point.
  17509. Alignment is done according to `org-property-format', which see."
  17510. (when (save-excursion
  17511. (beginning-of-line)
  17512. (looking-at org-property-re))
  17513. (replace-match
  17514. (concat (match-string 4)
  17515. (org-trim
  17516. (format org-property-format (match-string 1) (match-string 3))))
  17517. t t)))
  17518. (defun org-indent-line ()
  17519. "Indent line depending on context.
  17520. Indentation is done according to the following rules:
  17521. - Footnote definitions, diary sexps, headlines and inline tasks
  17522. have to start at column 0.
  17523. - On the very first line of an element, consider, in order, the
  17524. next rules until one matches:
  17525. 1. If there's a sibling element before, ignoring footnote
  17526. definitions and inline tasks, indent like its first line.
  17527. 2. If element has a parent, indent like its contents. More
  17528. precisely, if parent is an item, indent after the bullet.
  17529. Else, indent like parent's first line.
  17530. 3. Otherwise, indent relatively to current level, if
  17531. `org-adapt-indentation' is t, or to left margin.
  17532. - On a blank line at the end of an element, indent according to
  17533. the type of the element. More precisely
  17534. 1. If element is a plain list, an item, or a footnote
  17535. definition, indent like the very last element within.
  17536. 2. If element is a paragraph, indent like its last non blank
  17537. line.
  17538. 3. Otherwise, indent like its very first line.
  17539. - In the code part of a source block, use language major mode
  17540. to indent current line if `org-src-tab-acts-natively' is
  17541. non-nil. If it is nil, do nothing.
  17542. - Otherwise, indent like the first non-blank line above.
  17543. The function doesn't indent an item as it could break the whole
  17544. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17545. `\\[org-shiftmetaright]'.
  17546. Also align node properties according to `org-property-format'."
  17547. (interactive)
  17548. (unless (or (org-at-heading-p)
  17549. (and (eq org-adapt-indentation 'headline-data)
  17550. (not (or (org-at-clock-log-p)
  17551. (org-at-planning-p)))
  17552. (save-excursion
  17553. (beginning-of-line 1)
  17554. (skip-chars-backward "\n")
  17555. (or (org-at-heading-p)
  17556. (looking-back ":END:.*" (point-at-bol))))))
  17557. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17558. (type (org-element-type element)))
  17559. (cond ((and (memq type '(plain-list item))
  17560. (= (line-beginning-position)
  17561. (org-element-property :post-affiliated element)))
  17562. nil)
  17563. ((and (eq type 'latex-environment)
  17564. (>= (point) (org-element-property :post-affiliated element))
  17565. (< (point)
  17566. (org-with-point-at (org-element-property :end element)
  17567. (skip-chars-backward " \t\n")
  17568. (line-beginning-position 2))))
  17569. nil)
  17570. ((and (eq type 'src-block)
  17571. org-src-tab-acts-natively
  17572. (> (line-beginning-position)
  17573. (org-element-property :post-affiliated element))
  17574. (< (line-beginning-position)
  17575. (org-with-point-at (org-element-property :end element)
  17576. (skip-chars-backward " \t\n")
  17577. (line-beginning-position))))
  17578. ;; At the beginning of a blank line, do some preindentation. This
  17579. ;; signals org-src--edit-element to preserve the indentation on exit
  17580. (when (and (looking-at-p "^[[:space:]]*$")
  17581. (not org-src-preserve-indentation))
  17582. (let ((element (org-element-at-point))
  17583. block-content-ind some-ind)
  17584. (org-with-point-at (org-element-property :begin element)
  17585. (setq block-content-ind (+ (current-indentation)
  17586. org-edit-src-content-indentation))
  17587. (forward-line)
  17588. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17589. (backward-char)
  17590. (setq some-ind (if (looking-at-p "#\\+end_src")
  17591. block-content-ind (current-indentation))))
  17592. (indent-line-to (min block-content-ind some-ind))))
  17593. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17594. (t
  17595. (let ((column (org--get-expected-indentation element nil)))
  17596. ;; Preserve current column.
  17597. (if (<= (current-column) (current-indentation))
  17598. (indent-line-to column)
  17599. (save-excursion (indent-line-to column))))
  17600. ;; Align node property. Also preserve current column.
  17601. (when (eq type 'node-property)
  17602. (let ((column (current-column)))
  17603. (org--align-node-property)
  17604. (org-move-to-column column))))))))
  17605. (defun org-indent-region (start end)
  17606. "Indent each non-blank line in the region.
  17607. Called from a program, START and END specify the region to
  17608. indent. The function will not indent contents of example blocks,
  17609. verse blocks and export blocks as leading white spaces are
  17610. assumed to be significant there."
  17611. (interactive "r")
  17612. (save-excursion
  17613. (goto-char start)
  17614. (skip-chars-forward " \r\t\n")
  17615. (unless (eobp) (beginning-of-line))
  17616. (let ((indent-to
  17617. (lambda (ind pos)
  17618. ;; Set IND as indentation for all lines between point and
  17619. ;; POS. Blank lines are ignored. Leave point after POS
  17620. ;; once done.
  17621. (let ((limit (copy-marker pos)))
  17622. (while (< (point) limit)
  17623. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17624. (forward-line))
  17625. (set-marker limit nil))))
  17626. (end (copy-marker end)))
  17627. (while (< (point) end)
  17628. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17629. (let* ((element (org-element-at-point))
  17630. (type (org-element-type element))
  17631. (element-end (copy-marker (org-element-property :end element)))
  17632. (ind (org--get-expected-indentation element nil)))
  17633. (cond
  17634. ;; Element indented as a single block. Example blocks
  17635. ;; preserving indentation are a special case since the
  17636. ;; "contents" must not be indented whereas the block
  17637. ;; boundaries can.
  17638. ((or (memq type '(export-block latex-environment))
  17639. (and (eq type 'example-block)
  17640. (not
  17641. (or org-src-preserve-indentation
  17642. (org-element-property :preserve-indent element)))))
  17643. (let ((offset (- ind (current-indentation))))
  17644. (unless (zerop offset)
  17645. (indent-rigidly (org-element-property :begin element)
  17646. (org-element-property :end element)
  17647. offset)))
  17648. (goto-char element-end))
  17649. ;; Elements indented line wise. Be sure to exclude
  17650. ;; example blocks (preserving indentation) and source
  17651. ;; blocks from this category as they are treated
  17652. ;; specially later.
  17653. ((or (memq type '(paragraph table table-row))
  17654. (not (or (org-element-property :contents-begin element)
  17655. (memq type '(example-block src-block)))))
  17656. (when (eq type 'node-property)
  17657. (org--align-node-property)
  17658. (beginning-of-line))
  17659. (funcall indent-to ind (min element-end end)))
  17660. ;; Elements consisting of three parts: before the
  17661. ;; contents, the contents, and after the contents. The
  17662. ;; contents are treated specially, according to the
  17663. ;; element type, or not indented at all. Other parts are
  17664. ;; indented as a single block.
  17665. (t
  17666. (let* ((post (copy-marker
  17667. (org-element-property :post-affiliated element)))
  17668. (cbeg
  17669. (copy-marker
  17670. (cond
  17671. ((not (org-element-property :contents-begin element))
  17672. ;; Fake contents for source blocks.
  17673. (org-with-wide-buffer
  17674. (goto-char post)
  17675. (line-beginning-position 2)))
  17676. ((memq type '(footnote-definition item plain-list))
  17677. ;; Contents in these elements could start on
  17678. ;; the same line as the beginning of the
  17679. ;; element. Make sure we start indenting
  17680. ;; from the second line.
  17681. (org-with-wide-buffer
  17682. (goto-char post)
  17683. (end-of-line)
  17684. (skip-chars-forward " \r\t\n")
  17685. (if (eobp) (point) (line-beginning-position))))
  17686. (t (org-element-property :contents-begin element)))))
  17687. (cend (copy-marker
  17688. (or (org-element-property :contents-end element)
  17689. ;; Fake contents for source blocks.
  17690. (org-with-wide-buffer
  17691. (goto-char element-end)
  17692. (skip-chars-backward " \r\t\n")
  17693. (line-beginning-position)))
  17694. t)))
  17695. ;; Do not change items indentation individually as it
  17696. ;; might break the list as a whole. On the other
  17697. ;; hand, when at a plain list, indent it as a whole.
  17698. (cond ((eq type 'plain-list)
  17699. (let ((offset (- ind (current-indentation))))
  17700. (unless (zerop offset)
  17701. (indent-rigidly (org-element-property :begin element)
  17702. (org-element-property :end element)
  17703. offset))
  17704. (goto-char cbeg)))
  17705. ((eq type 'item) (goto-char cbeg))
  17706. (t (funcall indent-to ind (min cbeg end))))
  17707. (when (< (point) end)
  17708. (cl-case type
  17709. ((example-block verse-block))
  17710. (src-block
  17711. ;; In a source block, indent source code
  17712. ;; according to language major mode, but only if
  17713. ;; `org-src-tab-acts-natively' is non-nil.
  17714. (when (and (< (point) end) org-src-tab-acts-natively)
  17715. (ignore-errors
  17716. (org-babel-do-in-edit-buffer
  17717. (indent-region (point-min) (point-max))))))
  17718. (t (org-indent-region (point) (min cend end))))
  17719. (goto-char (min cend end))
  17720. (when (< (point) end)
  17721. (funcall indent-to ind (min element-end end))))
  17722. (set-marker post nil)
  17723. (set-marker cbeg nil)
  17724. (set-marker cend nil))))
  17725. (set-marker element-end nil))))
  17726. (set-marker end nil))))
  17727. (defun org-indent-drawer ()
  17728. "Indent the drawer at point."
  17729. (interactive)
  17730. (unless (save-excursion
  17731. (beginning-of-line)
  17732. (looking-at-p org-drawer-regexp))
  17733. (user-error "Not at a drawer"))
  17734. (let ((element (org-element-at-point)))
  17735. (unless (memq (org-element-type element) '(drawer property-drawer))
  17736. (user-error "Not at a drawer"))
  17737. (org-with-wide-buffer
  17738. (org-indent-region (org-element-property :begin element)
  17739. (org-element-property :end element))))
  17740. (message "Drawer at point indented"))
  17741. (defun org-indent-block ()
  17742. "Indent the block at point."
  17743. (interactive)
  17744. (unless (save-excursion
  17745. (beginning-of-line)
  17746. (let ((case-fold-search t))
  17747. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17748. (user-error "Not at a block"))
  17749. (let ((element (org-element-at-point)))
  17750. (unless (memq (org-element-type element)
  17751. '(comment-block center-block dynamic-block example-block
  17752. export-block quote-block special-block
  17753. src-block verse-block))
  17754. (user-error "Not at a block"))
  17755. (org-with-wide-buffer
  17756. (org-indent-region (org-element-property :begin element)
  17757. (org-element-property :end element))))
  17758. (message "Block at point indented"))
  17759. ;;; Filling
  17760. ;; We use our own fill-paragraph and auto-fill functions.
  17761. ;; `org-fill-paragraph' relies on adaptive filling and context
  17762. ;; checking. Appropriate `fill-prefix' is computed with
  17763. ;; `org-adaptive-fill-function'.
  17764. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17765. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17766. ;; `org-adaptive-fill-function' value. Internally,
  17767. ;; `org-comment-line-break-function' breaks the line.
  17768. ;; `org-setup-filling' installs filling and auto-filling related
  17769. ;; variables during `org-mode' initialization.
  17770. (defun org-setup-filling ()
  17771. (require 'org-element)
  17772. ;; Prevent auto-fill from inserting unwanted new items.
  17773. (when (boundp 'fill-nobreak-predicate)
  17774. (setq-local
  17775. fill-nobreak-predicate
  17776. (org-uniquify
  17777. (append fill-nobreak-predicate
  17778. '(org-fill-line-break-nobreak-p
  17779. org-fill-n-macro-as-item-nobreak-p
  17780. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17781. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17782. (setq-local paragraph-start paragraph-ending)
  17783. (setq-local paragraph-separate paragraph-ending))
  17784. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17785. (setq-local auto-fill-inhibit-regexp nil)
  17786. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17787. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17788. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17789. (defun org-fill-line-break-nobreak-p ()
  17790. "Non-nil when a new line at point would create an Org line break."
  17791. (save-excursion
  17792. (skip-chars-backward " \t")
  17793. (skip-chars-backward "\\\\")
  17794. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17795. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17796. "Non-nil when a new line at point would split a timestamp."
  17797. (and (org-at-timestamp-p 'lax)
  17798. (not (looking-at org-ts-regexp-both))))
  17799. (defun org-fill-n-macro-as-item-nobreak-p ()
  17800. "Non-nil when a new line at point would create a new list."
  17801. ;; During export, a "n" macro followed by a dot or a closing
  17802. ;; parenthesis can end up being parsed as a new list item.
  17803. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17804. (defun org-adaptive-fill-function ()
  17805. "Compute a fill prefix for the current line.
  17806. Return fill prefix, as a string, or nil if current line isn't
  17807. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17808. matches in paragraphs or comments, use it."
  17809. (org-with-wide-buffer
  17810. (unless (org-at-heading-p)
  17811. (let* ((p (line-beginning-position))
  17812. (element (save-excursion
  17813. (beginning-of-line)
  17814. (org-element-at-point)))
  17815. (type (org-element-type element))
  17816. (post-affiliated (org-element-property :post-affiliated element)))
  17817. (unless (< p post-affiliated)
  17818. (cl-case type
  17819. (comment
  17820. (save-excursion
  17821. (beginning-of-line)
  17822. (looking-at "[ \t]*")
  17823. (concat (match-string 0) "# ")))
  17824. (footnote-definition "")
  17825. ((item plain-list)
  17826. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17827. (paragraph
  17828. ;; Fill prefix is usually the same as the current line,
  17829. ;; unless the paragraph is at the beginning of an item.
  17830. (let ((parent (org-element-property :parent element)))
  17831. (save-excursion
  17832. (beginning-of-line)
  17833. (cond ((eq (org-element-type parent) 'item)
  17834. (make-string (org-list-item-body-column
  17835. (org-element-property :begin parent))
  17836. ?\s))
  17837. ((and adaptive-fill-regexp
  17838. ;; Locally disable
  17839. ;; `adaptive-fill-function' to let
  17840. ;; `fill-context-prefix' handle
  17841. ;; `adaptive-fill-regexp' variable.
  17842. (let (adaptive-fill-function)
  17843. (fill-context-prefix
  17844. post-affiliated
  17845. (org-element-property :end element)))))
  17846. ((looking-at "[ \t]+") (match-string 0))
  17847. (t "")))))
  17848. (comment-block
  17849. ;; Only fill contents if P is within block boundaries.
  17850. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17851. (forward-line)
  17852. (point)))
  17853. (cend (save-excursion
  17854. (goto-char (org-element-property :end element))
  17855. (skip-chars-backward " \r\t\n")
  17856. (line-beginning-position))))
  17857. (when (and (>= p cbeg) (< p cend))
  17858. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17859. (match-string 0)
  17860. ""))))))))))
  17861. (defun org-fill-element (&optional justify)
  17862. "Fill element at point, when applicable.
  17863. This function only applies to comment blocks, comments, example
  17864. blocks and paragraphs. Also, as a special case, re-align table
  17865. when point is at one.
  17866. If JUSTIFY is non-nil (interactively, with prefix argument),
  17867. justify as well. If `sentence-end-double-space' is non-nil, then
  17868. period followed by one space does not end a sentence, so don't
  17869. break a line there. The variable `fill-column' controls the
  17870. width for filling.
  17871. For convenience, when point is at a plain list, an item or
  17872. a footnote definition, try to fill the first paragraph within."
  17873. (with-syntax-table org-mode-transpose-word-syntax-table
  17874. ;; Move to end of line in order to get the first paragraph within
  17875. ;; a plain list or a footnote definition.
  17876. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17877. ;; First check if point is in a blank line at the beginning of
  17878. ;; the buffer. In that case, ignore filling.
  17879. (cl-case (org-element-type element)
  17880. ;; Use major mode filling function is source blocks.
  17881. (src-block (org-babel-do-in-edit-buffer
  17882. (push-mark (point-min))
  17883. (goto-char (point-max))
  17884. (setq mark-active t)
  17885. (funcall-interactively #'fill-paragraph justify 'region)))
  17886. ;; Align Org tables, leave table.el tables as-is.
  17887. (table-row (org-table-align) t)
  17888. (table
  17889. (when (eq (org-element-property :type element) 'org)
  17890. (save-excursion
  17891. (goto-char (org-element-property :post-affiliated element))
  17892. (org-table-align)))
  17893. t)
  17894. (paragraph
  17895. ;; Paragraphs may contain `line-break' type objects.
  17896. (let ((beg (max (point-min)
  17897. (org-element-property :contents-begin element)))
  17898. (end (min (point-max)
  17899. (org-element-property :contents-end element))))
  17900. ;; Do nothing if point is at an affiliated keyword.
  17901. (if (< (line-end-position) beg) t
  17902. ;; Fill paragraph, taking line breaks into account.
  17903. (save-excursion
  17904. (goto-char beg)
  17905. (let ((cuts (list beg)))
  17906. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17907. (when (eq 'line-break
  17908. (org-element-type
  17909. (save-excursion (backward-char)
  17910. (org-element-context))))
  17911. (push (point) cuts)))
  17912. (dolist (c (delq end cuts))
  17913. (fill-region-as-paragraph c end justify)
  17914. (setq end c))))
  17915. t)))
  17916. ;; Contents of `comment-block' type elements should be
  17917. ;; filled as plain text, but only if point is within block
  17918. ;; markers.
  17919. (comment-block
  17920. (let* ((case-fold-search t)
  17921. (beg (save-excursion
  17922. (goto-char (org-element-property :begin element))
  17923. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17924. (forward-line)
  17925. (point)))
  17926. (end (save-excursion
  17927. (goto-char (org-element-property :end element))
  17928. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17929. (line-beginning-position))))
  17930. (if (or (< (point) beg) (> (point) end)) t
  17931. (fill-region-as-paragraph
  17932. (save-excursion (end-of-line)
  17933. (re-search-backward "^[ \t]*$" beg 'move)
  17934. (line-beginning-position))
  17935. (save-excursion (beginning-of-line)
  17936. (re-search-forward "^[ \t]*$" end 'move)
  17937. (line-beginning-position))
  17938. justify))))
  17939. ;; Fill comments.
  17940. (comment
  17941. (let ((begin (org-element-property :post-affiliated element))
  17942. (end (org-element-property :end element)))
  17943. (when (and (>= (point) begin) (<= (point) end))
  17944. (let ((begin (save-excursion
  17945. (end-of-line)
  17946. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17947. (progn (forward-line) (point))
  17948. begin)))
  17949. (end (save-excursion
  17950. (end-of-line)
  17951. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17952. (1- (line-beginning-position))
  17953. (skip-chars-backward " \r\t\n")
  17954. (line-end-position)))))
  17955. ;; Do not fill comments when at a blank line.
  17956. (when (> end begin)
  17957. (let ((fill-prefix
  17958. (save-excursion
  17959. (beginning-of-line)
  17960. (looking-at "[ \t]*#")
  17961. (let ((comment-prefix (match-string 0)))
  17962. (goto-char (match-end 0))
  17963. (if (looking-at adaptive-fill-regexp)
  17964. (concat comment-prefix (match-string 0))
  17965. (concat comment-prefix " "))))))
  17966. (save-excursion
  17967. (fill-region-as-paragraph begin end justify))))))
  17968. t))
  17969. ;; Ignore every other element.
  17970. (otherwise t)))))
  17971. (defun org-fill-paragraph (&optional justify region)
  17972. "Fill element at point, when applicable.
  17973. This function only applies to comment blocks, comments, example
  17974. blocks and paragraphs. Also, as a special case, re-align table
  17975. when point is at one.
  17976. For convenience, when point is at a plain list, an item or
  17977. a footnote definition, try to fill the first paragraph within.
  17978. If JUSTIFY is non-nil (interactively, with prefix argument),
  17979. justify as well. If `sentence-end-double-space' is non-nil, then
  17980. period followed by one space does not end a sentence, so don't
  17981. break a line there. The variable `fill-column' controls the
  17982. width for filling.
  17983. The REGION argument is non-nil if called interactively; in that
  17984. case, if Transient Mark mode is enabled and the mark is active,
  17985. fill each of the elements in the active region, instead of just
  17986. filling the current element."
  17987. (interactive (progn
  17988. (barf-if-buffer-read-only)
  17989. (list (when current-prefix-arg 'full) t)))
  17990. (let ((hash (and (not (buffer-modified-p))
  17991. (org-buffer-hash))))
  17992. (cond
  17993. ((and region transient-mark-mode mark-active
  17994. (not (eq (region-beginning) (region-end))))
  17995. (let ((origin (point-marker))
  17996. (start (region-beginning)))
  17997. (unwind-protect
  17998. (progn
  17999. (goto-char (region-end))
  18000. (skip-chars-backward " \t\n")
  18001. (while (> (point) start)
  18002. (org-fill-element justify)
  18003. (org-backward-paragraph)))
  18004. (goto-char origin)
  18005. (set-marker origin nil))))
  18006. (t
  18007. (save-excursion
  18008. (when (org-match-line "[ \t]*$")
  18009. (skip-chars-forward " \t\n"))
  18010. (org-fill-element justify))))
  18011. ;; If we didn't change anything in the buffer (and the buffer was
  18012. ;; previously unmodified), then flip the modification status back
  18013. ;; to "unchanged".
  18014. (when (and hash (equal hash (org-buffer-hash)))
  18015. (set-buffer-modified-p nil))
  18016. ;; Return non-nil.
  18017. t))
  18018. (defun org-auto-fill-function ()
  18019. "Auto-fill function."
  18020. ;; Check if auto-filling is meaningful.
  18021. (let ((fc (current-fill-column)))
  18022. (when (and fc (> (current-column) fc))
  18023. (let* ((fill-prefix (org-adaptive-fill-function))
  18024. ;; Enforce empty fill prefix, if required. Otherwise, it
  18025. ;; will be computed again.
  18026. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18027. (when fill-prefix (do-auto-fill))))))
  18028. (defun org-comment-line-break-function (&optional soft)
  18029. "Break line at point and indent, continuing comment if within one.
  18030. The inserted newline is marked hard if variable
  18031. `use-hard-newlines' is true, unless optional argument SOFT is
  18032. non-nil."
  18033. (if soft (insert-and-inherit ?\n) (newline 1))
  18034. (save-excursion (forward-char -1) (delete-horizontal-space))
  18035. (delete-horizontal-space)
  18036. (indent-to-left-margin)
  18037. (insert-before-markers-and-inherit fill-prefix))
  18038. ;;; Fixed Width Areas
  18039. (defun org-toggle-fixed-width ()
  18040. "Toggle fixed-width markup.
  18041. Add or remove fixed-width markup on current line, whenever it
  18042. makes sense. Return an error otherwise.
  18043. If a region is active and if it contains only fixed-width areas
  18044. or blank lines, remove all fixed-width markup in it. If the
  18045. region contains anything else, convert all non-fixed-width lines
  18046. to fixed-width ones.
  18047. Blank lines at the end of the region are ignored unless the
  18048. region only contains such lines."
  18049. (interactive)
  18050. (if (not (org-region-active-p))
  18051. ;; No region:
  18052. ;;
  18053. ;; Remove fixed width marker only in a fixed-with element.
  18054. ;;
  18055. ;; Add fixed width maker in paragraphs, in blank lines after
  18056. ;; elements or at the beginning of a headline or an inlinetask,
  18057. ;; and before any one-line elements (e.g., a clock).
  18058. (progn
  18059. (beginning-of-line)
  18060. (let* ((element (org-element-at-point))
  18061. (type (org-element-type element)))
  18062. (cond
  18063. ((and (eq type 'fixed-width)
  18064. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18065. (replace-match
  18066. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18067. ((and (memq type '(babel-call clock comment diary-sexp headline
  18068. horizontal-rule keyword paragraph
  18069. planning))
  18070. (<= (org-element-property :post-affiliated element) (point)))
  18071. (skip-chars-forward " \t")
  18072. (insert ": "))
  18073. ((and (looking-at-p "[ \t]*$")
  18074. (or (eq type 'inlinetask)
  18075. (save-excursion
  18076. (skip-chars-forward " \r\t\n")
  18077. (<= (org-element-property :end element) (point)))))
  18078. (delete-region (point) (line-end-position))
  18079. (org-indent-line)
  18080. (insert ": "))
  18081. (t (user-error "Cannot insert a fixed-width line here")))))
  18082. ;; Region active.
  18083. (let* ((begin (save-excursion
  18084. (goto-char (region-beginning))
  18085. (line-beginning-position)))
  18086. (end (copy-marker
  18087. (save-excursion
  18088. (goto-char (region-end))
  18089. (unless (eolp) (beginning-of-line))
  18090. (if (save-excursion (re-search-backward "\\S-" begin t))
  18091. (progn (skip-chars-backward " \r\t\n") (point))
  18092. (point)))))
  18093. (all-fixed-width-p
  18094. (catch 'not-all-p
  18095. (save-excursion
  18096. (goto-char begin)
  18097. (skip-chars-forward " \r\t\n")
  18098. (when (eobp) (throw 'not-all-p nil))
  18099. (while (< (point) end)
  18100. (let ((element (org-element-at-point)))
  18101. (if (eq (org-element-type element) 'fixed-width)
  18102. (goto-char (org-element-property :end element))
  18103. (throw 'not-all-p nil))))
  18104. t))))
  18105. (if all-fixed-width-p
  18106. (save-excursion
  18107. (goto-char begin)
  18108. (while (< (point) end)
  18109. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18110. (replace-match
  18111. "" nil nil nil
  18112. (if (= (line-end-position) (match-end 0)) 0 1)))
  18113. (forward-line)))
  18114. (let ((min-ind (point-max)))
  18115. ;; Find minimum indentation across all lines.
  18116. (save-excursion
  18117. (goto-char begin)
  18118. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18119. (setq min-ind 0)
  18120. (catch 'zerop
  18121. (while (< (point) end)
  18122. (unless (looking-at-p "[ \t]*$")
  18123. (let ((ind (current-indentation)))
  18124. (setq min-ind (min min-ind ind))
  18125. (when (zerop ind) (throw 'zerop t))))
  18126. (forward-line)))))
  18127. ;; Loop over all lines and add fixed-width markup everywhere
  18128. ;; but in fixed-width lines.
  18129. (save-excursion
  18130. (goto-char begin)
  18131. (while (< (point) end)
  18132. (cond
  18133. ((org-at-heading-p)
  18134. (insert ": ")
  18135. (forward-line)
  18136. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18137. (insert ":")
  18138. (forward-line)))
  18139. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18140. (let* ((element (org-element-at-point))
  18141. (element-end (org-element-property :end element)))
  18142. (if (eq (org-element-type element) 'fixed-width)
  18143. (progn (goto-char element-end)
  18144. (skip-chars-backward " \r\t\n")
  18145. (forward-line))
  18146. (let ((limit (min end element-end)))
  18147. (while (< (point) limit)
  18148. (org-move-to-column min-ind t)
  18149. (insert ": ")
  18150. (forward-line))))))
  18151. (t
  18152. (org-move-to-column min-ind t)
  18153. (insert ": ")
  18154. (forward-line)))))))
  18155. (set-marker end nil))))
  18156. ;;; Blocks
  18157. (defun org-block-map (function &optional start end)
  18158. "Call FUNCTION at the head of all source blocks in the current buffer.
  18159. Optional arguments START and END can be used to limit the range."
  18160. (let ((start (or start (point-min)))
  18161. (end (or end (point-max))))
  18162. (save-excursion
  18163. (goto-char start)
  18164. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18165. (save-excursion
  18166. (save-match-data
  18167. (goto-char (match-beginning 0))
  18168. (funcall function)))))))
  18169. (defun org-next-block (arg &optional backward block-regexp)
  18170. "Jump to the next block.
  18171. With a prefix argument ARG, jump forward ARG many blocks.
  18172. When BACKWARD is non-nil, jump to the previous block.
  18173. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18174. Match data is set according to this regexp when the function
  18175. returns.
  18176. Return point at beginning of the opening line of found block.
  18177. Throw an error if no block is found."
  18178. (interactive "p")
  18179. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18180. (case-fold-search t)
  18181. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18182. (count (or arg 1))
  18183. (origin (point))
  18184. last-element)
  18185. (if backward (beginning-of-line) (end-of-line))
  18186. (while (and (> count 0) (funcall search-fn re nil t))
  18187. (let ((element (save-excursion
  18188. (goto-char (match-beginning 0))
  18189. (save-match-data (org-element-at-point)))))
  18190. (when (and (memq (org-element-type element)
  18191. '(center-block comment-block dynamic-block
  18192. example-block export-block quote-block
  18193. special-block src-block verse-block))
  18194. (<= (match-beginning 0)
  18195. (org-element-property :post-affiliated element)))
  18196. (setq last-element element)
  18197. (cl-decf count))))
  18198. (if (= count 0)
  18199. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18200. (save-match-data (org-show-context)))
  18201. (goto-char origin)
  18202. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18203. (defun org-previous-block (arg &optional block-regexp)
  18204. "Jump to the previous block.
  18205. With a prefix argument ARG, jump backward ARG many source blocks.
  18206. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18207. (interactive "p")
  18208. (org-next-block arg t block-regexp))
  18209. ;;; Comments
  18210. ;; Org comments syntax is quite complex. It requires the entire line
  18211. ;; to be just a comment. Also, even with the right syntax at the
  18212. ;; beginning of line, some elements (e.g., verse-block or
  18213. ;; example-block) don't accept comments. Usual Emacs comment commands
  18214. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18215. ;; Org still relies on 'comment-dwim', but cannot trust
  18216. ;; 'comment-only-p'. So, 'comment-region-function' and
  18217. ;; 'uncomment-region-function' both point
  18218. ;; to 'org-comment-or-uncomment-region'. Eventually,
  18219. ;; 'org-insert-comment' takes care of insertion of comments at the
  18220. ;; beginning of line.
  18221. ;; 'org-setup-comments-handling' install comments related variables
  18222. ;; during 'org-mode' initialization.
  18223. (defun org-setup-comments-handling ()
  18224. (interactive)
  18225. (setq-local comment-use-syntax nil)
  18226. (setq-local comment-start "# ")
  18227. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18228. (setq-local comment-insert-comment-function 'org-insert-comment)
  18229. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18230. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18231. (defun org-insert-comment ()
  18232. "Insert an empty comment above current line.
  18233. If the line is empty, insert comment at its beginning. When
  18234. point is within a source block, comment according to the related
  18235. major mode."
  18236. (if (let ((element (org-element-at-point)))
  18237. (and (eq (org-element-type element) 'src-block)
  18238. (< (save-excursion
  18239. (goto-char (org-element-property :post-affiliated element))
  18240. (line-end-position))
  18241. (point))
  18242. (> (save-excursion
  18243. (goto-char (org-element-property :end element))
  18244. (skip-chars-backward " \r\t\n")
  18245. (line-beginning-position))
  18246. (point))))
  18247. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18248. (beginning-of-line)
  18249. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18250. (open-line 1))
  18251. (org-indent-line)
  18252. (insert "# ")))
  18253. (defvar comment-empty-lines) ; From newcomment.el.
  18254. (defun org-comment-or-uncomment-region (beg end &rest _)
  18255. "Comment or uncomment each non-blank line in the region.
  18256. Uncomment each non-blank line between BEG and END if it only
  18257. contains commented lines. Otherwise, comment them. If region is
  18258. strictly within a source block, use appropriate comment syntax."
  18259. (if (let ((element (org-element-at-point)))
  18260. (and (eq (org-element-type element) 'src-block)
  18261. (< (save-excursion
  18262. (goto-char (org-element-property :post-affiliated element))
  18263. (line-end-position))
  18264. beg)
  18265. (>= (save-excursion
  18266. (goto-char (org-element-property :end element))
  18267. (skip-chars-backward " \r\t\n")
  18268. (line-beginning-position))
  18269. end)))
  18270. ;; Translate region boundaries for the Org buffer to the source
  18271. ;; buffer.
  18272. (let ((offset (- end beg)))
  18273. (save-excursion
  18274. (goto-char beg)
  18275. (org-babel-do-in-edit-buffer
  18276. (comment-or-uncomment-region (point) (+ offset (point))))))
  18277. (save-restriction
  18278. ;; Restrict region
  18279. (narrow-to-region (save-excursion (goto-char beg)
  18280. (skip-chars-forward " \r\t\n" end)
  18281. (line-beginning-position))
  18282. (save-excursion (goto-char end)
  18283. (skip-chars-backward " \r\t\n" beg)
  18284. (line-end-position)))
  18285. (let ((uncommentp
  18286. ;; UNCOMMENTP is non-nil when every non blank line between
  18287. ;; BEG and END is a comment.
  18288. (save-excursion
  18289. (goto-char (point-min))
  18290. (while (and (not (eobp))
  18291. (let ((element (org-element-at-point)))
  18292. (and (eq (org-element-type element) 'comment)
  18293. (goto-char (min (point-max)
  18294. (org-element-property
  18295. :end element)))))))
  18296. (eobp))))
  18297. (if uncommentp
  18298. ;; Only blank lines and comments in region: uncomment it.
  18299. (save-excursion
  18300. (goto-char (point-min))
  18301. (while (not (eobp))
  18302. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18303. (replace-match "" nil nil nil 1))
  18304. (forward-line)))
  18305. ;; Comment each line in region.
  18306. (let ((min-indent (point-max)))
  18307. ;; First find the minimum indentation across all lines.
  18308. (save-excursion
  18309. (goto-char (point-min))
  18310. (while (and (not (eobp)) (not (zerop min-indent)))
  18311. (unless (looking-at "[ \t]*$")
  18312. (setq min-indent (min min-indent (current-indentation))))
  18313. (forward-line)))
  18314. ;; Then loop over all lines.
  18315. (save-excursion
  18316. (goto-char (point-min))
  18317. (while (not (eobp))
  18318. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18319. ;; Don't get fooled by invisible text (e.g. link path)
  18320. ;; when moving to column MIN-INDENT.
  18321. (let ((buffer-invisibility-spec nil))
  18322. (org-move-to-column min-indent t))
  18323. (insert comment-start))
  18324. (forward-line)))))))))
  18325. (defun org-comment-dwim (_arg)
  18326. "Call the comment command you mean.
  18327. Call `org-toggle-comment' if on a heading, otherwise call
  18328. `comment-dwim', within a source edit buffer if needed."
  18329. (interactive "*P")
  18330. (cond ((org-at-heading-p)
  18331. (call-interactively #'org-toggle-comment))
  18332. ((org-in-src-block-p)
  18333. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18334. (t (call-interactively #'comment-dwim))))
  18335. ;;; Timestamps API
  18336. ;; This section contains tools to operate on, or create, timestamp
  18337. ;; objects, as returned by, e.g. `org-element-context'.
  18338. (defun org-timestamp-from-string (s)
  18339. "Convert Org timestamp S, as a string, into a timestamp object.
  18340. Return nil if S is not a valid timestamp string."
  18341. (when (org-string-nw-p s)
  18342. (with-temp-buffer
  18343. (save-excursion (insert s))
  18344. (org-element-timestamp-parser))))
  18345. (defun org-timestamp-from-time (time &optional with-time inactive)
  18346. "Convert a time value into a timestamp object.
  18347. TIME is an Emacs internal time representation, as returned, e.g.,
  18348. by `current-time'.
  18349. When optional argument WITH-TIME is non-nil, return a timestamp
  18350. object with a time part, i.e., with hours and minutes.
  18351. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18352. return an active timestamp."
  18353. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18354. (org-element-create 'timestamp
  18355. (list :type (if inactive 'inactive 'active)
  18356. :year-start year
  18357. :month-start month
  18358. :day-start day
  18359. :hour-start (and with-time hour)
  18360. :minute-start (and with-time minute)))))
  18361. (defun org-timestamp-to-time (timestamp &optional end)
  18362. "Convert TIMESTAMP object into an Emacs internal time value.
  18363. Use end of date range or time range when END is non-nil.
  18364. Otherwise, use its start."
  18365. (apply #'encode-time 0
  18366. (mapcar
  18367. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18368. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18369. '(:minute-start :hour-start :day-start :month-start
  18370. :year-start)))))
  18371. (defun org-timestamp-has-time-p (timestamp)
  18372. "Non-nil when TIMESTAMP has a time specified."
  18373. (org-element-property :hour-start timestamp))
  18374. (defun org-timestamp-format (timestamp format &optional end utc)
  18375. "Format a TIMESTAMP object into a string.
  18376. FORMAT is a format specifier to be passed to
  18377. `format-time-string'.
  18378. When optional argument END is non-nil, use end of date-range or
  18379. time-range, if possible.
  18380. When optional argument UTC is non-nil, time is be expressed as
  18381. Universal Time."
  18382. (format-time-string format (org-timestamp-to-time timestamp end)
  18383. (and utc t)))
  18384. (defun org-timestamp-split-range (timestamp &optional end)
  18385. "Extract a TIMESTAMP object from a date or time range.
  18386. END, when non-nil, means extract the end of the range.
  18387. Otherwise, extract its start.
  18388. Return a new timestamp object."
  18389. (let ((type (org-element-property :type timestamp)))
  18390. (if (memq type '(active inactive diary)) timestamp
  18391. (let ((split-ts (org-element-copy timestamp)))
  18392. ;; Set new type.
  18393. (org-element-put-property
  18394. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18395. ;; Copy start properties over end properties if END is
  18396. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18397. (let ((p-alist '((:minute-start . :minute-end)
  18398. (:hour-start . :hour-end)
  18399. (:day-start . :day-end)
  18400. (:month-start . :month-end)
  18401. (:year-start . :year-end))))
  18402. (dolist (p-cell p-alist)
  18403. (org-element-put-property
  18404. split-ts
  18405. (funcall (if end #'car #'cdr) p-cell)
  18406. (org-element-property
  18407. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18408. ;; Eventually refresh `:raw-value'.
  18409. (org-element-put-property split-ts :raw-value nil)
  18410. (org-element-put-property
  18411. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18412. (defun org-timestamp-translate (timestamp &optional boundary)
  18413. "Translate TIMESTAMP object to custom format.
  18414. Format string is defined in `org-time-stamp-custom-formats',
  18415. which see.
  18416. When optional argument BOUNDARY is non-nil, it is either the
  18417. symbol `start' or `end'. In this case, only translate the
  18418. starting or ending part of TIMESTAMP if it is a date or time
  18419. range. Otherwise, translate both parts.
  18420. Return timestamp as-is if `org-display-custom-times' is nil or if
  18421. it has a `diary' type."
  18422. (let ((type (org-element-property :type timestamp)))
  18423. (if (or (not org-display-custom-times) (eq type 'diary))
  18424. (org-element-interpret-data timestamp)
  18425. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18426. org-time-stamp-custom-formats)))
  18427. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18428. (concat (org-timestamp-format timestamp fmt)
  18429. "--"
  18430. (org-timestamp-format timestamp fmt t))
  18431. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18432. ;;; Other stuff
  18433. (defvar reftex-docstruct-symbol)
  18434. (defvar org--rds)
  18435. (defun org-reftex-citation ()
  18436. "Use `reftex-citation' to insert a citation into the buffer.
  18437. This looks for a line like
  18438. #+BIBLIOGRAPHY: foo plain option:-d
  18439. and derives from it that foo.bib is the bibliography file relevant
  18440. for this document. It then installs the necessary environment for RefTeX
  18441. to work in this buffer and calls `reftex-citation' to insert a citation
  18442. into the buffer.
  18443. Export of such citations to both LaTeX and HTML is handled by the contributed
  18444. package ox-bibtex by Taru Karttunen."
  18445. (interactive)
  18446. (let ((reftex-docstruct-symbol 'org--rds)
  18447. org--rds bib)
  18448. (org-with-wide-buffer
  18449. (let ((case-fold-search t)
  18450. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18451. (if (not (save-excursion
  18452. (or (re-search-forward re nil t)
  18453. (re-search-backward re nil t))))
  18454. (user-error "No bibliography defined in file")
  18455. (setq bib (concat (match-string 1) ".bib")
  18456. org--rds (list (list 'bib bib))))))
  18457. (call-interactively 'reftex-citation)))
  18458. ;;;; Functions extending outline functionality
  18459. (defun org-beginning-of-line (&optional n)
  18460. "Go to the beginning of the current visible line.
  18461. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18462. symbol `reversed', on the first attempt move to where the
  18463. headline text starts, and only move to beginning of line when the
  18464. cursor is already before the start of the text of the headline.
  18465. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18466. start of the text on the second attempt.
  18467. With argument N not nil or 1, move forward N - 1 lines first."
  18468. (interactive "^p")
  18469. (let ((origin (point))
  18470. (special (pcase org-special-ctrl-a/e
  18471. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18472. deactivate-mark)
  18473. ;; First move to a visible line.
  18474. (if (bound-and-true-p visual-line-mode)
  18475. (beginning-of-visual-line n)
  18476. (move-beginning-of-line n)
  18477. ;; `move-beginning-of-line' may leave point after invisible
  18478. ;; characters if line starts with such of these (e.g., with
  18479. ;; a link at column 0). Really move to the beginning of the
  18480. ;; current visible line.
  18481. (beginning-of-line))
  18482. (cond
  18483. ;; No special behavior. Point is already at the beginning of
  18484. ;; a line, logical or visual.
  18485. ((not special))
  18486. ;; `beginning-of-visual-line' left point before logical beginning
  18487. ;; of line: point is at the beginning of a visual line. Bail
  18488. ;; out.
  18489. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18490. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18491. ;; At a headline, special position is before the title, but
  18492. ;; after any TODO keyword or priority cookie.
  18493. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18494. (line-end-position)))
  18495. (bol (point)))
  18496. (if (eq special 'reversed)
  18497. (when (and (= origin bol) (eq last-command this-command))
  18498. (goto-char refpos))
  18499. (when (or (> origin refpos) (= origin bol))
  18500. (goto-char refpos)))))
  18501. ((and (looking-at org-list-full-item-re)
  18502. (memq (org-element-type (save-match-data (org-element-at-point)))
  18503. '(item plain-list)))
  18504. ;; Set special position at first white space character after
  18505. ;; bullet, and check-box, if any.
  18506. (let ((after-bullet
  18507. (let ((box (match-end 3)))
  18508. (cond ((not box) (match-end 1))
  18509. ((eq (char-after box) ?\s) (1+ box))
  18510. (t box)))))
  18511. (if (eq special 'reversed)
  18512. (when (and (= (point) origin) (eq last-command this-command))
  18513. (goto-char after-bullet))
  18514. (when (or (> origin after-bullet) (= (point) origin))
  18515. (goto-char after-bullet)))))
  18516. ;; No special context. Point is already at beginning of line.
  18517. (t nil))))
  18518. (defun org-end-of-line (&optional n)
  18519. "Go to the end of the line, but before ellipsis, if any.
  18520. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18521. symbol `reversed', ignore tags on the first attempt, and only
  18522. move to after the tags when the cursor is already beyond the end
  18523. of the headline.
  18524. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18525. on the second attempt.
  18526. With argument N not nil or 1, move forward N - 1 lines first."
  18527. (interactive "^p")
  18528. (let ((origin (point))
  18529. (special (pcase org-special-ctrl-a/e
  18530. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18531. deactivate-mark)
  18532. ;; First move to a visible line.
  18533. (if (bound-and-true-p visual-line-mode)
  18534. (beginning-of-visual-line n)
  18535. (move-beginning-of-line n))
  18536. (cond
  18537. ;; At a headline, with tags.
  18538. ((and special
  18539. (save-excursion
  18540. (beginning-of-line)
  18541. (let ((case-fold-search nil))
  18542. (looking-at org-complex-heading-regexp)))
  18543. (match-end 5))
  18544. (let ((tags (save-excursion
  18545. (goto-char (match-beginning 5))
  18546. (skip-chars-backward " \t")
  18547. (point)))
  18548. (visual-end (and (bound-and-true-p visual-line-mode)
  18549. (save-excursion
  18550. (end-of-visual-line)
  18551. (point)))))
  18552. ;; If `end-of-visual-line' brings us before end of line or
  18553. ;; even tags, i.e., the headline spans over multiple visual
  18554. ;; lines, move there.
  18555. (cond ((and visual-end
  18556. (< visual-end tags)
  18557. (<= origin visual-end))
  18558. (goto-char visual-end))
  18559. ((eq special 'reversed)
  18560. (if (and (= origin (line-end-position))
  18561. (eq this-command last-command))
  18562. (goto-char tags)
  18563. (end-of-line)))
  18564. (t
  18565. (if (or (< origin tags) (= origin (line-end-position)))
  18566. (goto-char tags)
  18567. (end-of-line))))))
  18568. ((bound-and-true-p visual-line-mode)
  18569. (let ((bol (line-beginning-position)))
  18570. (end-of-visual-line)
  18571. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18572. ;; end of a line, backtrack and use `end-of-line' instead.
  18573. (when (/= bol (line-beginning-position))
  18574. (goto-char bol)
  18575. (end-of-line))))
  18576. (t (end-of-line)))))
  18577. (defun org-backward-sentence (&optional _arg)
  18578. "Go to beginning of sentence, or beginning of table field.
  18579. This will call `backward-sentence' or `org-table-beginning-of-field',
  18580. depending on context."
  18581. (interactive)
  18582. (let* ((element (org-element-at-point))
  18583. (contents-begin (org-element-property :contents-begin element))
  18584. (table (org-element-lineage element '(table) t)))
  18585. (if (and table
  18586. (> (point) contents-begin)
  18587. (<= (point) (org-element-property :contents-end table)))
  18588. (call-interactively #'org-table-beginning-of-field)
  18589. (save-restriction
  18590. (when (and contents-begin
  18591. (< (point-min) contents-begin)
  18592. (> (point) contents-begin))
  18593. (narrow-to-region contents-begin
  18594. (org-element-property :contents-end element)))
  18595. (call-interactively #'backward-sentence)))))
  18596. (defun org-forward-sentence (&optional _arg)
  18597. "Go to end of sentence, or end of table field.
  18598. This will call `forward-sentence' or `org-table-end-of-field',
  18599. depending on context."
  18600. (interactive)
  18601. (if (and (org-at-heading-p)
  18602. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18603. (save-restriction
  18604. (narrow-to-region (line-beginning-position) (line-end-position))
  18605. (call-interactively #'forward-sentence))
  18606. (let* ((element (org-element-at-point))
  18607. (contents-end (org-element-property :contents-end element))
  18608. (table (org-element-lineage element '(table) t)))
  18609. (if (and table
  18610. (>= (point) (org-element-property :contents-begin table))
  18611. (< (point) contents-end))
  18612. (call-interactively #'org-table-end-of-field)
  18613. (save-restriction
  18614. (when (and contents-end
  18615. (> (point-max) contents-end)
  18616. ;; Skip blank lines between elements.
  18617. (< (org-element-property :end element)
  18618. (save-excursion (goto-char contents-end)
  18619. (skip-chars-forward " \r\t\n"))))
  18620. (narrow-to-region (org-element-property :contents-begin element)
  18621. contents-end))
  18622. ;; End of heading is considered as the end of a sentence.
  18623. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18624. (call-interactively #'forward-sentence)))))))
  18625. (defun org-kill-line (&optional _arg)
  18626. "Kill line, to tags or end of line."
  18627. (interactive)
  18628. (cond
  18629. ((or (not org-special-ctrl-k)
  18630. (bolp)
  18631. (not (org-at-heading-p)))
  18632. (when (and (get-char-property (line-end-position) 'invisible)
  18633. org-ctrl-k-protect-subtree
  18634. (or (eq org-ctrl-k-protect-subtree 'error)
  18635. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18636. (user-error
  18637. (substitute-command-keys
  18638. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18639. (call-interactively
  18640. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18641. ((org-match-line org-tag-line-re)
  18642. (let ((end (save-excursion
  18643. (goto-char (match-beginning 1))
  18644. (skip-chars-backward " \t")
  18645. (point))))
  18646. (if (<= end (point)) ;on tags part
  18647. (kill-region (point) (line-end-position))
  18648. (kill-region (point) end)))
  18649. ;; Only align tags when we are still on a heading:
  18650. (if (org-at-heading-p) (org-align-tags)))
  18651. (t (kill-region (point) (line-end-position)))))
  18652. (defun org-yank (&optional arg)
  18653. "Yank. If the kill is a subtree, treat it specially.
  18654. This command will look at the current kill and check if is a single
  18655. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18656. cursor is at the beginning of a line or after the stars of a currently
  18657. empty headline, then the yank is handled specially. How exactly depends
  18658. on the value of the following variables.
  18659. `org-yank-folded-subtrees'
  18660. By default, this variable is non-nil, which results in
  18661. subtree(s) being folded after insertion, except if doing so
  18662. would swallow text after the yanked text.
  18663. `org-yank-adjusted-subtrees'
  18664. When non-nil (the default value is nil), the subtree will be
  18665. promoted or demoted in order to fit into the local outline tree
  18666. structure, which means that the level will be adjusted so that it
  18667. becomes the smaller one of the two *visible* surrounding headings.
  18668. Any prefix to this command will cause `yank' to be called directly with
  18669. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18670. will just
  18671. plainly yank the text as it is.
  18672. \[1] The test checks if the first non-white line is a heading
  18673. and if there are no other headings with fewer stars."
  18674. (interactive "P")
  18675. (org-yank-generic 'yank arg))
  18676. (defun org-yank-generic (command arg)
  18677. "Perform some yank-like command.
  18678. This function implements the behavior described in the `org-yank'
  18679. documentation. However, it has been generalized to work for any
  18680. interactive command with similar behavior."
  18681. ;; pretend to be command COMMAND
  18682. (setq this-command command)
  18683. (if arg
  18684. (call-interactively command)
  18685. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18686. (and (org-kill-is-subtree-p)
  18687. (or (bolp)
  18688. (and (looking-at "[ \t]*$")
  18689. (string-match
  18690. "\\`\\*+\\'"
  18691. (buffer-substring (point-at-bol) (point)))))))
  18692. swallowp)
  18693. (cond
  18694. ((and subtreep org-yank-folded-subtrees)
  18695. (let ((beg (point))
  18696. end)
  18697. (if (and subtreep org-yank-adjusted-subtrees)
  18698. (org-paste-subtree nil nil 'for-yank)
  18699. (call-interactively command))
  18700. (setq end (point))
  18701. (goto-char beg)
  18702. (when (and (bolp) subtreep
  18703. (not (setq swallowp
  18704. (org-yank-folding-would-swallow-text beg end))))
  18705. (org-with-limited-levels
  18706. (or (looking-at org-outline-regexp)
  18707. (re-search-forward org-outline-regexp-bol end t))
  18708. (while (and (< (point) end) (looking-at org-outline-regexp))
  18709. (org-flag-subtree t)
  18710. (org-cycle-show-empty-lines 'folded)
  18711. (condition-case nil
  18712. (outline-forward-same-level 1)
  18713. (error (goto-char end))))))
  18714. (when swallowp
  18715. (message
  18716. "Inserted text not folded because that would swallow text"))
  18717. (goto-char end)
  18718. (skip-chars-forward " \t\n\r")
  18719. (beginning-of-line 1)
  18720. (push-mark beg 'nomsg)))
  18721. ((and subtreep org-yank-adjusted-subtrees)
  18722. (let ((beg (point-at-bol)))
  18723. (org-paste-subtree nil nil 'for-yank)
  18724. (push-mark beg 'nomsg)))
  18725. (t
  18726. (call-interactively command))))))
  18727. (defun org-yank-folding-would-swallow-text (beg end)
  18728. "Would `hide-subtree' at BEG swallow any text after END?"
  18729. (let (level)
  18730. (org-with-limited-levels
  18731. (save-excursion
  18732. (goto-char beg)
  18733. (when (or (looking-at org-outline-regexp)
  18734. (re-search-forward org-outline-regexp-bol end t))
  18735. (setq level (org-outline-level)))
  18736. (goto-char end)
  18737. (skip-chars-forward " \t\r\n\v\f")
  18738. (not (or (eobp)
  18739. (and (bolp) (looking-at-p org-outline-regexp)
  18740. (<= (org-outline-level) level))))))))
  18741. (defun org-back-to-heading (&optional invisible-ok)
  18742. "Call `outline-back-to-heading', but provide a better error message."
  18743. (condition-case nil
  18744. (outline-back-to-heading invisible-ok)
  18745. (error
  18746. (user-error "Before first headline at position %d in buffer %s"
  18747. (point) (current-buffer)))))
  18748. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18749. "Go back to heading or first point in buffer.
  18750. If point is before first heading go to first point in buffer
  18751. instead of back to heading."
  18752. (condition-case nil
  18753. (outline-back-to-heading invisible-ok)
  18754. (error
  18755. (goto-char (point-min)))))
  18756. (defun org-before-first-heading-p ()
  18757. "Before first heading?"
  18758. (org-with-limited-levels
  18759. (save-excursion
  18760. (end-of-line)
  18761. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18762. (defun org-at-heading-p (&optional _)
  18763. "Non-nil when on a headline."
  18764. (outline-on-heading-p t))
  18765. (defun org-in-commented-heading-p (&optional no-inheritance)
  18766. "Non-nil if point is under a commented heading.
  18767. This function also checks ancestors of the current headline,
  18768. unless optional argument NO-INHERITANCE is non-nil."
  18769. (cond
  18770. ((org-before-first-heading-p) nil)
  18771. ((let ((headline (nth 4 (org-heading-components))))
  18772. (and headline
  18773. (let ((case-fold-search nil))
  18774. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18775. headline)))))
  18776. (no-inheritance nil)
  18777. (t
  18778. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18779. (defun org-in-archived-heading-p (&optional no-inheritance)
  18780. "Non-nil if point is under an archived heading.
  18781. This function also checks ancestors of the current headline,
  18782. unless optional argument NO-INHERITANCE is non-nil."
  18783. (cond
  18784. ((org-before-first-heading-p) nil)
  18785. ((let ((tags (org-get-tags nil 'local)))
  18786. (and tags
  18787. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18788. (no-inheritance nil)
  18789. (t
  18790. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18791. (defun org-at-comment-p nil
  18792. "Return t if cursor is in a commented line."
  18793. (save-excursion
  18794. (save-match-data
  18795. (beginning-of-line)
  18796. (looking-at org-comment-regexp))))
  18797. (defun org-at-keyword-p nil
  18798. "Return t if cursor is at a keyword-line."
  18799. (save-excursion
  18800. (move-beginning-of-line 1)
  18801. (looking-at org-keyword-regexp)))
  18802. (defun org-at-drawer-p nil
  18803. "Return t if cursor is at a drawer keyword."
  18804. (save-excursion
  18805. (move-beginning-of-line 1)
  18806. (looking-at org-drawer-regexp)))
  18807. (defun org-at-block-p nil
  18808. "Return t if cursor is at a block keyword."
  18809. (save-excursion
  18810. (move-beginning-of-line 1)
  18811. (looking-at org-block-regexp)))
  18812. (defun org-point-at-end-of-empty-headline ()
  18813. "If point is at the end of an empty headline, return t, else nil.
  18814. If the heading only contains a TODO keyword, it is still considered
  18815. empty."
  18816. (let ((case-fold-search nil))
  18817. (and (looking-at "[ \t]*$")
  18818. org-todo-line-regexp
  18819. (save-excursion
  18820. (beginning-of-line)
  18821. (looking-at org-todo-line-regexp)
  18822. (string= (match-string 3) "")))))
  18823. (defun org-at-heading-or-item-p ()
  18824. (or (org-at-heading-p) (org-at-item-p)))
  18825. (defun org-up-heading-all (arg)
  18826. "Move to the heading line of which the present line is a subheading.
  18827. This function considers both visible and invisible heading lines.
  18828. With argument, move up ARG levels."
  18829. (outline-up-heading arg t))
  18830. (defvar-local org--up-heading-cache nil
  18831. "Buffer-local `org-up-heading-safe' cache.")
  18832. (defvar-local org--up-heading-cache-tick nil
  18833. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18834. (defun org-up-heading-safe ()
  18835. "Move to the heading line of which the present line is a subheading.
  18836. This version will not throw an error. It will return the level of the
  18837. headline found, or nil if no higher level is found.
  18838. Also, this function will be a lot faster than `outline-up-heading',
  18839. because it relies on stars being the outline starters. This can really
  18840. make a significant difference in outlines with very many siblings."
  18841. (when (ignore-errors (org-back-to-heading t))
  18842. (let (level-cache)
  18843. (unless org--up-heading-cache
  18844. (setq org--up-heading-cache (make-hash-table)))
  18845. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18846. (setq level-cache (gethash (point) org--up-heading-cache)))
  18847. (when (<= (point-min) (car level-cache) (point-max))
  18848. ;; Parent is inside accessible part of the buffer.
  18849. (progn (goto-char (car level-cache))
  18850. (cdr level-cache)))
  18851. ;; Buffer modified. Invalidate cache.
  18852. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18853. (setq-local org--up-heading-cache-tick
  18854. (buffer-chars-modified-tick))
  18855. (clrhash org--up-heading-cache))
  18856. (let* ((level-up (1- (funcall outline-level)))
  18857. (pos (point))
  18858. (result (and (> level-up 0)
  18859. (re-search-backward
  18860. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18861. (funcall outline-level))))
  18862. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18863. result)))))
  18864. (defun org-up-heading-or-point-min ()
  18865. "Move to the heading line of which the present is a subheading, or point-min.
  18866. This version is needed to make point-min behave like a virtual
  18867. heading of level 0 for property-inheritance. It will return the
  18868. level of the headline found (down to 0) or nil if already at a
  18869. point before the first headline or at point-min."
  18870. (when (ignore-errors (org-back-to-heading t))
  18871. (if (< 1 (funcall outline-level))
  18872. (org-up-heading-safe)
  18873. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18874. (defun org-first-sibling-p ()
  18875. "Is this heading the first child of its parents?"
  18876. (interactive)
  18877. (let ((re org-outline-regexp-bol)
  18878. level l)
  18879. (unless (org-at-heading-p t)
  18880. (user-error "Not at a heading"))
  18881. (setq level (funcall outline-level))
  18882. (save-excursion
  18883. (if (not (re-search-backward re nil t))
  18884. t
  18885. (setq l (funcall outline-level))
  18886. (< l level)))))
  18887. (defun org-goto-sibling (&optional previous)
  18888. "Goto the next sibling, even if it is invisible.
  18889. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18890. when a sibling was found. When none is found, return nil and don't
  18891. move point."
  18892. (let ((fun (if previous 're-search-backward 're-search-forward))
  18893. (pos (point))
  18894. (re org-outline-regexp-bol)
  18895. level l)
  18896. (when (ignore-errors (org-back-to-heading t))
  18897. (setq level (funcall outline-level))
  18898. (catch 'exit
  18899. (or previous (forward-char 1))
  18900. (while (funcall fun re nil t)
  18901. (setq l (funcall outline-level))
  18902. (when (< l level) (goto-char pos) (throw 'exit nil))
  18903. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18904. (goto-char pos)
  18905. nil))))
  18906. (defun org-show-siblings ()
  18907. "Show all siblings of the current headline."
  18908. (save-excursion
  18909. (while (org-goto-sibling) (org-flag-heading nil)))
  18910. (save-excursion
  18911. (while (org-goto-sibling 'previous)
  18912. (org-flag-heading nil))))
  18913. (defun org-goto-first-child ()
  18914. "Goto the first child, even if it is invisible.
  18915. Return t when a child was found. Otherwise don't move point and
  18916. return nil."
  18917. (let (level (pos (point)) (re org-outline-regexp-bol))
  18918. (when (org-back-to-heading-or-point-min t)
  18919. (setq level (org-outline-level))
  18920. (forward-char 1)
  18921. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18922. (progn (goto-char (match-beginning 0)) t)
  18923. (goto-char pos) nil))))
  18924. (defun org-show-hidden-entry ()
  18925. "Show an entry where even the heading is hidden."
  18926. (save-excursion
  18927. (org-show-entry)))
  18928. (defun org-flag-heading (flag &optional entry)
  18929. "Flag the current heading. FLAG non-nil means make invisible.
  18930. When ENTRY is non-nil, show the entire entry."
  18931. (save-excursion
  18932. (org-back-to-heading t)
  18933. ;; Check if we should show the entire entry
  18934. (if (not entry)
  18935. (org-flag-region
  18936. (line-end-position 0) (line-end-position) flag 'outline)
  18937. (org-show-entry)
  18938. (save-excursion
  18939. (and (outline-next-heading)
  18940. (org-flag-heading nil))))))
  18941. (defun org-get-next-sibling ()
  18942. "Move to next heading of the same level, and return point.
  18943. If there is no such heading, return nil.
  18944. This is like outline-next-sibling, but invisible headings are ok."
  18945. (let ((level (funcall outline-level)))
  18946. (outline-next-heading)
  18947. (while (and (not (eobp)) (> (funcall outline-level) level))
  18948. (outline-next-heading))
  18949. (unless (or (eobp) (< (funcall outline-level) level))
  18950. (point))))
  18951. (defun org-get-previous-sibling ()
  18952. "Move to previous heading of the same level, and return point.
  18953. If there is no such heading, return nil."
  18954. (let ((opoint (point))
  18955. (level (funcall outline-level)))
  18956. (outline-previous-heading)
  18957. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18958. (while (and (> (funcall outline-level) level)
  18959. (not (bobp)))
  18960. (outline-previous-heading))
  18961. (unless (< (funcall outline-level) level)
  18962. (point)))))
  18963. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18964. "Goto to the end of a subtree."
  18965. ;; This contains an exact copy of the original function, but it uses
  18966. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18967. ;; trees and before first headline. And is uses an invisible-ok argument.
  18968. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18969. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18970. ;; with many children and grandchildren etc, this can be much faster
  18971. ;; than the outline version.
  18972. (org-back-to-heading-or-point-min invisible-ok)
  18973. (let ((first t)
  18974. (level (funcall outline-level)))
  18975. (cond ((= level 0)
  18976. (goto-char (point-max)))
  18977. ((and (derived-mode-p 'org-mode) (< level 1000))
  18978. ;; A true heading (not a plain list item), in Org
  18979. ;; This means we can easily find the end by looking
  18980. ;; only for the right number of stars. Using a regexp to do
  18981. ;; this is so much faster than using a Lisp loop.
  18982. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18983. (forward-char 1)
  18984. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18985. (t
  18986. ;; something else, do it the slow way
  18987. (while (and (not (eobp))
  18988. (or first (> (funcall outline-level) level)))
  18989. (setq first nil)
  18990. (outline-next-heading))))
  18991. (unless to-heading
  18992. (when (memq (preceding-char) '(?\n ?\^M))
  18993. ;; Go to end of line before heading
  18994. (forward-char -1)
  18995. (when (memq (preceding-char) '(?\n ?\^M))
  18996. ;; leave blank line before heading
  18997. (forward-char -1)))))
  18998. (point))
  18999. (defun org-end-of-meta-data (&optional full)
  19000. "Skip planning line and properties drawer in current entry.
  19001. When optional argument FULL is t, also skip planning information,
  19002. clocking lines and any kind of drawer.
  19003. When FULL is non-nil but not t, skip planning information,
  19004. properties, clocking lines and logbook drawers."
  19005. (org-back-to-heading t)
  19006. (forward-line)
  19007. ;; Skip planning information.
  19008. (when (looking-at-p org-planning-line-re) (forward-line))
  19009. ;; Skip property drawer.
  19010. (when (looking-at org-property-drawer-re)
  19011. (goto-char (match-end 0))
  19012. (forward-line))
  19013. ;; When FULL is not nil, skip more.
  19014. (when (and full (not (org-at-heading-p)))
  19015. (catch 'exit
  19016. (let ((end (save-excursion (outline-next-heading) (point)))
  19017. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19018. (while (not (eobp))
  19019. (cond ;; Skip clock lines.
  19020. ((looking-at-p re) (forward-line))
  19021. ;; Skip logbook drawer.
  19022. ((looking-at-p org-logbook-drawer-re)
  19023. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19024. (forward-line)
  19025. (throw 'exit t)))
  19026. ;; When FULL is t, skip regular drawer too.
  19027. ((and (eq full t) (looking-at-p org-drawer-regexp))
  19028. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19029. (forward-line)
  19030. (throw 'exit t)))
  19031. (t (throw 'exit t))))))))
  19032. (defun org--line-fully-invisible-p ()
  19033. "Return non-nil if the current line is fully invisible."
  19034. (let ((line-beg (line-beginning-position))
  19035. (line-pos (1- (line-end-position)))
  19036. (is-invisible t))
  19037. (while (and (< line-beg line-pos) is-invisible)
  19038. (setq is-invisible (org-invisible-p line-pos))
  19039. (setq line-pos (1- line-pos)))
  19040. is-invisible))
  19041. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19042. "Move forward to the ARG'th subheading at same level as this one.
  19043. Stop at the first and last subheadings of a superior heading.
  19044. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19045. non-nil it will also look at invisible ones."
  19046. (interactive "p")
  19047. (let ((backward? (and arg (< arg 0))))
  19048. (if (org-before-first-heading-p)
  19049. (if backward? (goto-char (point-min)) (outline-next-heading))
  19050. (org-back-to-heading invisible-ok)
  19051. (unless backward? (end-of-line)) ;do not match current headline
  19052. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19053. (f (if backward? #'re-search-backward #'re-search-forward))
  19054. (count (if arg (abs arg) 1))
  19055. (result (point)))
  19056. (while (and (> count 0)
  19057. (funcall f org-outline-regexp-bol nil 'move))
  19058. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19059. (cond ((< l level) (setq count 0))
  19060. ((and (= l level)
  19061. (or invisible-ok
  19062. ;; FIXME: See commit a700fadd72 and the
  19063. ;; related discussion on why using
  19064. ;; `org--line-fully-invisible-p' is needed
  19065. ;; here, which is to serve the needs of an
  19066. ;; external package. If the change is
  19067. ;; wrong regarding Org itself, it should
  19068. ;; be removed.
  19069. (not (org--line-fully-invisible-p))))
  19070. (cl-decf count)
  19071. (when (= l level) (setq result (point)))))))
  19072. (goto-char result))
  19073. (beginning-of-line))))
  19074. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19075. "Move backward to the ARG'th subheading at same level as this one.
  19076. Stop at the first and last subheadings of a superior heading."
  19077. (interactive "p")
  19078. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19079. (defun org-next-visible-heading (arg)
  19080. "Move to the next visible heading line.
  19081. With ARG, repeats or can move backward if negative."
  19082. (interactive "p")
  19083. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19084. (if (< arg 0)
  19085. (beginning-of-line)
  19086. (end-of-line))
  19087. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19088. (unless (bobp)
  19089. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19090. (`(outline . ,o)
  19091. (goto-char (overlay-start o))
  19092. (re-search-backward regexp nil :move))
  19093. (_ nil))))
  19094. (cl-incf arg))
  19095. (while (and (> arg 0) (re-search-forward regexp nil t))
  19096. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19097. (`(outline . ,o)
  19098. (goto-char (overlay-end o))
  19099. (re-search-forward regexp nil :move))
  19100. (_
  19101. (end-of-line)
  19102. nil))) ;leave the loop
  19103. (cl-decf arg))
  19104. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19105. (defun org-previous-visible-heading (arg)
  19106. "Move to the previous visible heading.
  19107. With ARG, repeats or can move forward if negative."
  19108. (interactive "p")
  19109. (org-next-visible-heading (- arg)))
  19110. (defun org-forward-paragraph (&optional arg)
  19111. "Move forward by a paragraph, or equivalent, unit.
  19112. With argument ARG, do it ARG times;
  19113. a negative argument ARG = -N means move backward N paragraphs.
  19114. The function moves point between two structural
  19115. elements (paragraphs, tables, lists, etc.).
  19116. It also provides the following special moves for convenience:
  19117. - on a table or a property drawer, move to its beginning;
  19118. - on comment, example, export, source and verse blocks, stop
  19119. at blank lines;
  19120. - skip consecutive clocks, diary S-exps, and keywords."
  19121. (interactive "^p")
  19122. (unless arg (setq arg 1))
  19123. (if (< arg 0) (org-backward-paragraph (- arg))
  19124. (while (and (> arg 0) (not (eobp)))
  19125. (org--forward-paragraph-once)
  19126. (cl-decf arg))
  19127. ;; Return moves left.
  19128. arg))
  19129. (defun org-backward-paragraph (&optional arg)
  19130. "Move backward by a paragraph, or equivalent, unit.
  19131. With argument ARG, do it ARG times;
  19132. a negative argument ARG = -N means move forward N paragraphs.
  19133. The function moves point between two structural
  19134. elements (paragraphs, tables, lists, etc.).
  19135. It also provides the following special moves for convenience:
  19136. - on a table or a property drawer, move to its beginning;
  19137. - on comment, example, export, source and verse blocks, stop
  19138. at blank lines;
  19139. - skip consecutive clocks, diary S-exps, and keywords."
  19140. (interactive "^p")
  19141. (unless arg (setq arg 1))
  19142. (if (< arg 0) (org-forward-paragraph (- arg))
  19143. (while (and (> arg 0) (not (bobp)))
  19144. (org--backward-paragraph-once)
  19145. (cl-decf arg))
  19146. ;; Return moves left.
  19147. arg))
  19148. (defun org--paragraph-at-point ()
  19149. "Return paragraph, or equivalent, element at point.
  19150. Paragraph element at point is the element at point, with the
  19151. following special cases:
  19152. - treat table rows (resp. node properties) as the table
  19153. \(resp. property drawer) containing them.
  19154. - treat plain lists with an item every line as a whole.
  19155. - treat consecutive keywords, clocks, and diary-sexps as a single
  19156. block.
  19157. Function may return a real element, or a pseudo-element with type
  19158. `pseudo-paragraph'."
  19159. (let* ((e (org-element-at-point))
  19160. (type (org-element-type e))
  19161. ;; If we need to fake a new pseudo-element, triplet is
  19162. ;;
  19163. ;; (BEG END PARENT)
  19164. ;;
  19165. ;; where BEG and END are element boundaries, and PARENT the
  19166. ;; element containing it, or nil.
  19167. (triplet
  19168. (cond
  19169. ((memq type '(table property-drawer))
  19170. (list (org-element-property :begin e)
  19171. (org-element-property :end e)
  19172. (org-element-property :parent e)))
  19173. ((memq type '(node-property table-row))
  19174. (let ((e (org-element-property :parent e)))
  19175. (list (org-element-property :begin e)
  19176. (org-element-property :end e)
  19177. (org-element-property :parent e))))
  19178. ((memq type '(clock diary-sexp keyword))
  19179. (let* ((regexp (pcase type
  19180. (`clock org-clock-line-re)
  19181. (`diary-sexp "%%(")
  19182. (_ org-keyword-regexp)))
  19183. (end (if (< 0 (org-element-property :post-blank e))
  19184. (org-element-property :end e)
  19185. (org-with-wide-buffer
  19186. (forward-line)
  19187. (while (looking-at regexp) (forward-line))
  19188. (skip-chars-forward " \t\n")
  19189. (line-beginning-position))))
  19190. (begin (org-with-point-at (org-element-property :begin e)
  19191. (while (and (not (bobp)) (looking-at regexp))
  19192. (forward-line -1))
  19193. ;; We may have gotten one line too far.
  19194. (if (looking-at regexp)
  19195. (point)
  19196. (line-beginning-position 2)))))
  19197. (list begin end (org-element-property :parent e))))
  19198. ;; Find the full plain list containing point, the check it
  19199. ;; contains exactly one line per item.
  19200. ((let ((l (org-element-lineage e '(plain-list) t)))
  19201. (while (memq (org-element-type (org-element-property :parent l))
  19202. '(item plain-list))
  19203. (setq l (org-element-property :parent l)))
  19204. (and l
  19205. (org-with-point-at (org-element-property :post-affiliated l)
  19206. (forward-line (length (org-element-property :structure l)))
  19207. (= (point) (org-element-property :contents-end l)))
  19208. ;; Return value.
  19209. (list (org-element-property :begin l)
  19210. (org-element-property :end l)
  19211. (org-element-property :parent l)))))
  19212. (t nil)))) ;no triplet: return element
  19213. (pcase triplet
  19214. (`(,b ,e ,p)
  19215. (org-element-create
  19216. 'pseudo-paragraph
  19217. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19218. (_ e))))
  19219. (defun org--forward-paragraph-once ()
  19220. "Move forward to end of paragraph or equivalent, once.
  19221. See `org-forward-paragraph'."
  19222. (interactive)
  19223. (save-restriction
  19224. (widen)
  19225. (skip-chars-forward " \t\n")
  19226. (cond
  19227. ((eobp) nil)
  19228. ;; When inside a folded part, move out of it.
  19229. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19230. (`(,(or `outline `org-hide-block) . ,o)
  19231. (goto-char (overlay-end o))
  19232. (forward-line)
  19233. t)
  19234. (_ nil)))
  19235. (t
  19236. (let* ((element (org--paragraph-at-point))
  19237. (type (org-element-type element))
  19238. (contents-begin (org-element-property :contents-begin element))
  19239. (end (org-element-property :end element))
  19240. (post-affiliated (org-element-property :post-affiliated element)))
  19241. (cond
  19242. ((eq type 'plain-list)
  19243. (forward-char)
  19244. (org--forward-paragraph-once))
  19245. ;; If the element is folded, skip it altogether.
  19246. ((pcase (org-with-point-at post-affiliated
  19247. (get-char-property-and-overlay (line-end-position)
  19248. 'invisible))
  19249. (`(,(or `outline `org-hide-block) . ,o)
  19250. (goto-char (overlay-end o))
  19251. (forward-line)
  19252. t)
  19253. (_ nil)))
  19254. ;; At a greater element, move inside.
  19255. ((and contents-begin
  19256. (> contents-begin (point))
  19257. (not (eq type 'paragraph)))
  19258. (goto-char contents-begin)
  19259. ;; Items and footnote definitions contents may not start at
  19260. ;; the beginning of the line. In this case, skip until the
  19261. ;; next paragraph.
  19262. (cond
  19263. ((not (bolp)) (org--forward-paragraph-once))
  19264. ((org-previous-line-empty-p) (forward-line -1))
  19265. (t nil)))
  19266. ;; Move between empty lines in some blocks.
  19267. ((memq type '(comment-block example-block export-block src-block
  19268. verse-block))
  19269. (let ((contents-start
  19270. (org-with-point-at post-affiliated
  19271. (line-beginning-position 2))))
  19272. (if (< (point) contents-start)
  19273. (goto-char contents-start)
  19274. (let ((contents-end
  19275. (org-with-point-at end
  19276. (skip-chars-backward " \t\n")
  19277. (line-beginning-position))))
  19278. (cond
  19279. ((>= (point) contents-end)
  19280. (goto-char end)
  19281. (skip-chars-backward " \t\n")
  19282. (forward-line))
  19283. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19284. (forward-line -1))
  19285. (t nil))))))
  19286. (t
  19287. ;; Move to element's end.
  19288. (goto-char end)
  19289. (skip-chars-backward " \t\n")
  19290. (forward-line))))))))
  19291. (defun org--backward-paragraph-once ()
  19292. "Move backward to start of paragraph or equivalent, once.
  19293. See `org-backward-paragraph'."
  19294. (interactive)
  19295. (save-restriction
  19296. (widen)
  19297. (cond
  19298. ((bobp) nil)
  19299. ;; Blank lines at the beginning of the buffer.
  19300. ((and (org-match-line "^[ \t]*$")
  19301. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19302. (goto-char (point-min)))
  19303. ;; When inside a folded part, move out of it.
  19304. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19305. (`(,(or `outline `org-hide-block) . ,o)
  19306. (goto-char (1- (overlay-start o)))
  19307. (org--backward-paragraph-once)
  19308. t)
  19309. (_ nil)))
  19310. (t
  19311. (let* ((element (org--paragraph-at-point))
  19312. (type (org-element-type element))
  19313. (begin (org-element-property :begin element))
  19314. (post-affiliated (org-element-property :post-affiliated element))
  19315. (contents-end (org-element-property :contents-end element))
  19316. (end (org-element-property :end element))
  19317. (parent (org-element-property :parent element))
  19318. (reach
  19319. ;; Move to the visible empty line above position P, or
  19320. ;; to position P. Return t.
  19321. (lambda (p)
  19322. (goto-char p)
  19323. (when (and (org-previous-line-empty-p)
  19324. (let ((end (line-end-position 0)))
  19325. (or (= end (point-min))
  19326. (not (org-invisible-p (1- end))))))
  19327. (forward-line -1))
  19328. t)))
  19329. (cond
  19330. ;; Already at the beginning of an element.
  19331. ((= begin (point))
  19332. (cond
  19333. ;; There is a blank line above. Move there.
  19334. ((and (org-previous-line-empty-p)
  19335. (let ((lep (line-end-position 0)))
  19336. ;; When the first headline start at point 2, don't choke while
  19337. ;; checking with `org-invisible-p'.
  19338. (or (= lep 1)
  19339. (not (org-invisible-p (1- (line-end-position 0)))))))
  19340. (forward-line -1))
  19341. ;; At the beginning of the first element within a greater
  19342. ;; element. Move to the beginning of the greater element.
  19343. ((and parent (= begin (org-element-property :contents-begin parent)))
  19344. (funcall reach (org-element-property :begin parent)))
  19345. ;; Since we have to move anyway, find the beginning
  19346. ;; position of the element above.
  19347. (t
  19348. (forward-char -1)
  19349. (org--backward-paragraph-once))))
  19350. ;; Skip paragraphs at the very beginning of footnote
  19351. ;; definitions or items.
  19352. ((and (eq type 'paragraph)
  19353. (org-with-point-at begin (not (bolp))))
  19354. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19355. ;; If the element is folded, skip it altogether.
  19356. ((org-with-point-at post-affiliated
  19357. (org-invisible-p (line-end-position) t))
  19358. (funcall reach begin))
  19359. ;; At the end of a greater element, move inside.
  19360. ((and contents-end
  19361. (<= contents-end (point))
  19362. (not (eq type 'paragraph)))
  19363. (cond
  19364. ((memq type '(footnote-definition plain-list))
  19365. (skip-chars-backward " \t\n")
  19366. (org--backward-paragraph-once))
  19367. ((= contents-end (point))
  19368. (forward-char -1)
  19369. (org--backward-paragraph-once))
  19370. (t
  19371. (goto-char contents-end))))
  19372. ;; Move between empty lines in some blocks.
  19373. ((and (memq type '(comment-block example-block export-block src-block
  19374. verse-block))
  19375. (let ((contents-start
  19376. (org-with-point-at post-affiliated
  19377. (line-beginning-position 2))))
  19378. (when (> (point) contents-start)
  19379. (let ((contents-end
  19380. (org-with-point-at end
  19381. (skip-chars-backward " \t\n")
  19382. (line-beginning-position))))
  19383. (if (> (point) contents-end)
  19384. (progn (goto-char contents-end) t)
  19385. (skip-chars-backward " \t\n" begin)
  19386. (re-search-backward "^[ \t]*\n" contents-start :move)
  19387. t))))))
  19388. ;; Move to element's start.
  19389. (t
  19390. (funcall reach begin))))))))
  19391. (defun org-forward-element ()
  19392. "Move forward by one element.
  19393. Move to the next element at the same level, when possible."
  19394. (interactive)
  19395. (cond ((eobp) (user-error "Cannot move further down"))
  19396. ((org-with-limited-levels (org-at-heading-p))
  19397. (let ((origin (point)))
  19398. (goto-char (org-end-of-subtree nil t))
  19399. (unless (org-with-limited-levels (org-at-heading-p))
  19400. (goto-char origin)
  19401. (user-error "Cannot move further down"))))
  19402. (t
  19403. (let* ((elem (org-element-at-point))
  19404. (end (org-element-property :end elem))
  19405. (parent (org-element-property :parent elem)))
  19406. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19407. (goto-char (org-element-property :end parent)))
  19408. ((integer-or-marker-p end) (goto-char end))
  19409. (t (message "No element at point")))))))
  19410. (defun org-backward-element ()
  19411. "Move backward by one element.
  19412. Move to the previous element at the same level, when possible."
  19413. (interactive)
  19414. (cond ((bobp) (user-error "Cannot move further up"))
  19415. ((org-with-limited-levels (org-at-heading-p))
  19416. ;; At a headline, move to the previous one, if any, or stay
  19417. ;; here.
  19418. (let ((origin (point)))
  19419. (org-with-limited-levels (org-backward-heading-same-level 1))
  19420. ;; When current headline has no sibling above, move to its
  19421. ;; parent.
  19422. (when (= (point) origin)
  19423. (or (org-with-limited-levels (org-up-heading-safe))
  19424. (progn (goto-char origin)
  19425. (user-error "Cannot move further up"))))))
  19426. (t
  19427. (let* ((elem (org-element-at-point))
  19428. (beg (org-element-property :begin elem)))
  19429. (cond
  19430. ;; Move to beginning of current element if point isn't
  19431. ;; there already.
  19432. ((null beg) (message "No element at point"))
  19433. ((/= (point) beg) (goto-char beg))
  19434. (t (goto-char beg)
  19435. (skip-chars-backward " \r\t\n")
  19436. (unless (bobp)
  19437. (let ((prev (org-element-at-point)))
  19438. (goto-char (org-element-property :begin prev))
  19439. (while (and (setq prev (org-element-property :parent prev))
  19440. (<= (org-element-property :end prev) beg))
  19441. (goto-char (org-element-property :begin prev)))))))))))
  19442. (defun org-up-element ()
  19443. "Move to upper element."
  19444. (interactive)
  19445. (if (org-with-limited-levels (org-at-heading-p))
  19446. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19447. (let* ((elem (org-element-at-point))
  19448. (parent (org-element-property :parent elem)))
  19449. (if parent (goto-char (org-element-property :begin parent))
  19450. (if (org-with-limited-levels (org-before-first-heading-p))
  19451. (user-error "No surrounding element")
  19452. (org-with-limited-levels (org-back-to-heading)))))))
  19453. (defun org-down-element ()
  19454. "Move to inner element."
  19455. (interactive)
  19456. (let ((element (org-element-at-point)))
  19457. (cond
  19458. ((memq (org-element-type element) '(plain-list table))
  19459. (goto-char (org-element-property :contents-begin element))
  19460. (forward-char))
  19461. ((memq (org-element-type element) org-element-greater-elements)
  19462. ;; If contents are hidden, first disclose them.
  19463. (when (org-invisible-p (line-end-position)) (org-cycle))
  19464. (goto-char (or (org-element-property :contents-begin element)
  19465. (user-error "No content for this element"))))
  19466. (t (user-error "No inner element")))))
  19467. (defun org-drag-element-backward ()
  19468. "Move backward element at point."
  19469. (interactive)
  19470. (let ((elem (or (org-element-at-point)
  19471. (user-error "No element at point"))))
  19472. (if (eq (org-element-type elem) 'headline)
  19473. ;; Preserve point when moving a whole tree, even if point was
  19474. ;; on blank lines below the headline.
  19475. (let ((offset (skip-chars-backward " \t\n")))
  19476. (unwind-protect (org-move-subtree-up)
  19477. (forward-char (- offset))))
  19478. (let ((prev-elem
  19479. (save-excursion
  19480. (goto-char (org-element-property :begin elem))
  19481. (skip-chars-backward " \r\t\n")
  19482. (unless (bobp)
  19483. (let* ((beg (org-element-property :begin elem))
  19484. (prev (org-element-at-point))
  19485. (up prev))
  19486. (while (and (setq up (org-element-property :parent up))
  19487. (<= (org-element-property :end up) beg))
  19488. (setq prev up))
  19489. prev)))))
  19490. ;; Error out if no previous element or previous element is
  19491. ;; a parent of the current one.
  19492. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19493. (user-error "Cannot drag element backward")
  19494. (let ((pos (point)))
  19495. (org-element-swap-A-B prev-elem elem)
  19496. (goto-char (+ (org-element-property :begin prev-elem)
  19497. (- pos (org-element-property :begin elem))))))))))
  19498. (defun org-drag-element-forward ()
  19499. "Move forward element at point."
  19500. (interactive)
  19501. (let* ((pos (point))
  19502. (elem (or (org-element-at-point)
  19503. (user-error "No element at point"))))
  19504. (when (= (point-max) (org-element-property :end elem))
  19505. (user-error "Cannot drag element forward"))
  19506. (goto-char (org-element-property :end elem))
  19507. (let ((next-elem (org-element-at-point)))
  19508. (when (or (org-element-nested-p elem next-elem)
  19509. (and (eq (org-element-type next-elem) 'headline)
  19510. (not (eq (org-element-type elem) 'headline))))
  19511. (goto-char pos)
  19512. (user-error "Cannot drag element forward"))
  19513. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19514. ;; body's length (without final blanks) and by the length of
  19515. ;; blanks between ELEM and NEXT-ELEM.
  19516. (let ((size-next (- (save-excursion
  19517. (goto-char (org-element-property :end next-elem))
  19518. (skip-chars-backward " \r\t\n")
  19519. (forward-line)
  19520. ;; Small correction if buffer doesn't end
  19521. ;; with a newline character.
  19522. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19523. (org-element-property :begin next-elem)))
  19524. (size-blank (- (org-element-property :end elem)
  19525. (save-excursion
  19526. (goto-char (org-element-property :end elem))
  19527. (skip-chars-backward " \r\t\n")
  19528. (forward-line)
  19529. (point)))))
  19530. (org-element-swap-A-B elem next-elem)
  19531. (goto-char (+ pos size-next size-blank))))))
  19532. (defun org-drag-line-forward (arg)
  19533. "Drag the line at point ARG lines forward."
  19534. (interactive "p")
  19535. (dotimes (_ (abs arg))
  19536. (let ((c (current-column)))
  19537. (if (< 0 arg)
  19538. (progn
  19539. (beginning-of-line 2)
  19540. (transpose-lines 1)
  19541. (beginning-of-line 0))
  19542. (transpose-lines 1)
  19543. (beginning-of-line -1))
  19544. (org-move-to-column c))))
  19545. (defun org-drag-line-backward (arg)
  19546. "Drag the line at point ARG lines backward."
  19547. (interactive "p")
  19548. (org-drag-line-forward (- arg)))
  19549. (defun org-mark-element ()
  19550. "Put point at beginning of this element, mark at end.
  19551. Interactively, if this command is repeated or (in Transient Mark
  19552. mode) if the mark is active, it marks the next element after the
  19553. ones already marked."
  19554. (interactive)
  19555. (let (deactivate-mark)
  19556. (if (and (called-interactively-p 'any)
  19557. (or (and (eq last-command this-command) (mark t))
  19558. (and transient-mark-mode mark-active)))
  19559. (set-mark
  19560. (save-excursion
  19561. (goto-char (mark))
  19562. (goto-char (org-element-property :end (org-element-at-point)))
  19563. (point)))
  19564. (let ((element (org-element-at-point)))
  19565. (end-of-line)
  19566. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19567. (goto-char (org-element-property :begin element))))))
  19568. (defun org-narrow-to-element ()
  19569. "Narrow buffer to current element."
  19570. (interactive)
  19571. (let ((elem (org-element-at-point)))
  19572. (cond
  19573. ((eq (car elem) 'headline)
  19574. (narrow-to-region
  19575. (org-element-property :begin elem)
  19576. (org-element-property :end elem)))
  19577. ((memq (car elem) org-element-greater-elements)
  19578. (narrow-to-region
  19579. (org-element-property :contents-begin elem)
  19580. (org-element-property :contents-end elem)))
  19581. (t
  19582. (narrow-to-region
  19583. (org-element-property :begin elem)
  19584. (org-element-property :end elem))))))
  19585. (defun org-transpose-element ()
  19586. "Transpose current and previous elements, keeping blank lines between.
  19587. Point is moved after both elements."
  19588. (interactive)
  19589. (org-skip-whitespace)
  19590. (let ((end (org-element-property :end (org-element-at-point))))
  19591. (org-drag-element-backward)
  19592. (goto-char end)))
  19593. (defun org-unindent-buffer ()
  19594. "Un-indent the visible part of the buffer.
  19595. Relative indentation (between items, inside blocks, etc.) isn't
  19596. modified."
  19597. (interactive)
  19598. (unless (eq major-mode 'org-mode)
  19599. (user-error "Cannot un-indent a buffer not in Org mode"))
  19600. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19601. (unindent-tree
  19602. (lambda (contents)
  19603. (dolist (element (reverse contents))
  19604. (if (memq (org-element-type element) '(headline section))
  19605. (funcall unindent-tree (org-element-contents element))
  19606. (save-excursion
  19607. (save-restriction
  19608. (narrow-to-region
  19609. (org-element-property :begin element)
  19610. (org-element-property :end element))
  19611. (org-do-remove-indentation))))))))
  19612. (funcall unindent-tree (org-element-contents parse-tree))))
  19613. (defun org-make-options-regexp (kwds &optional extra)
  19614. "Make a regular expression for keyword lines.
  19615. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19616. when non-nil, is a regexp matching keywords names."
  19617. (concat "^[ \t]*#\\+\\("
  19618. (regexp-opt kwds)
  19619. (and extra (concat (and kwds "\\|") extra))
  19620. "\\):[ \t]*\\(.*\\)"))
  19621. ;;; Conveniently switch to Info nodes
  19622. (defun org-info-find-node (&optional nodename)
  19623. "Find Info documentation NODENAME or Org documentation according context.
  19624. Started from `gnus-info-find-node'."
  19625. (interactive)
  19626. (Info-goto-node
  19627. (or nodename
  19628. (let ((default-org-info-node "(org) Top"))
  19629. (cond
  19630. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19631. ((eq 'org-mode major-mode)
  19632. (let* ((context (org-element-at-point))
  19633. (element-info-nodes ; compare to `org-element-all-elements'.
  19634. `((babel-call . "(org) Evaluating Code Blocks")
  19635. (center-block . "(org) Paragraphs")
  19636. (clock . ,default-org-info-node)
  19637. (comment . "(org) Comment Lines")
  19638. (comment-block . "(org) Comment Lines")
  19639. (diary-sexp . ,default-org-info-node)
  19640. (drawer . "(org) Drawers")
  19641. (dynamic-block . "(org) Dynamic Blocks")
  19642. (example-block . "(org) Literal Examples")
  19643. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19644. (fixed-width . ,default-org-info-node)
  19645. (footnote-definition . "(org) Creating Footnotes")
  19646. (headline . "(org) Document Structure")
  19647. (horizontal-rule . "(org) Built-in Table Editor")
  19648. (inlinetask . ,default-org-info-node)
  19649. (item . "(org) Plain Lists")
  19650. (keyword . "(org) Per-file keywords")
  19651. (latex-environment . "(org) LaTeX Export")
  19652. (node-property . "(org) Properties and Columns")
  19653. (paragraph . "(org) Paragraphs")
  19654. (plain-list . "(org) Plain Lists")
  19655. (planning . "(org) Deadlines and Scheduling")
  19656. (property-drawer . "(org) Properties and Columns")
  19657. (quote-block . "(org) Paragraphs")
  19658. (section . ,default-org-info-node)
  19659. (special-block . ,default-org-info-node)
  19660. (src-block . "(org) Working with Source Code")
  19661. (table . "(org) Tables")
  19662. (table-row . "(org) Tables")
  19663. (verse-block . "(org) Paragraphs"))))
  19664. (or (cdr (assoc (car context) element-info-nodes))
  19665. default-org-info-node)))
  19666. (t default-org-info-node))))))
  19667. ;;; Finish up
  19668. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19669. (lambda () (add-hook 'change-major-mode-hook
  19670. 'org-show-all 'append 'local)))
  19671. (provide 'org)
  19672. (run-hooks 'org-load-hook)
  19673. ;;; org.el ends here