org.el 783 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4-dev
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  111. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  112. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  113. (declare-function org-clock-cancel "org-clock" ())
  114. (declare-function org-clock-display "org-clock" (&optional arg))
  115. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  116. (declare-function org-clock-goto "org-clock" (&optional select))
  117. (declare-function org-clock-in "org-clock" (&optional select start-time))
  118. (declare-function org-clock-in-last "org-clock" (&optional arg))
  119. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  120. (declare-function org-clock-out-if-current "org-clock" ())
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-quit "org-colview" ())
  131. (declare-function org-columns-insert-dblock "org-colview" ())
  132. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  133. (declare-function org-element-at-point "org-element" ())
  134. (declare-function org-element-cache-refresh "org-element" (pos))
  135. (declare-function org-element-cache-reset "org-element" (&optional all))
  136. (declare-function org-element-contents "org-element" (element))
  137. (declare-function org-element-context "org-element" (&optional element))
  138. (declare-function org-element-copy "org-element" (datum))
  139. (declare-function org-element-create "org-element" (type &optional props &rest children))
  140. (declare-function org-element-interpret-data "org-element" (data))
  141. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  142. (declare-function org-element-link-parser "org-element" ())
  143. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  144. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  145. (declare-function org-element-property "org-element" (property element))
  146. (declare-function org-element-put-property "org-element" (element property value))
  147. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  148. (declare-function org-element-timestamp-parser "org-element" ())
  149. (declare-function org-element-type "org-element" (element))
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-id-find-id-file "org-id" (id))
  157. (declare-function org-id-get-create "org-id" (&optional force))
  158. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  159. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  160. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  161. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  162. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  163. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  164. (declare-function org-timer "org-timer" (&optional restart no-insert))
  165. (declare-function org-timer-item "org-timer" (&optional arg))
  166. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  167. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  168. (declare-function org-timer-start "org-timer" (&optional offset))
  169. (declare-function org-timer-stop "org-timer" ())
  170. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  171. (declare-function org-update-radio-target-regexp "ol" ())
  172. (defvar ffap-url-regexp)
  173. (defvar org-element-paragraph-separate)
  174. (defvar org-indent-indentation-per-level)
  175. (defvar org-radio-target-regexp)
  176. (defvar org-target-link-regexp)
  177. (defvar org-target-regexp)
  178. ;; load languages based on value of `org-babel-load-languages'
  179. (defvar org-babel-load-languages)
  180. ;;;###autoload
  181. (defun org-babel-do-load-languages (sym value)
  182. "Load the languages defined in `org-babel-load-languages'."
  183. (set-default sym value)
  184. (dolist (pair org-babel-load-languages)
  185. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  186. (if active
  187. (require (intern (concat "ob-" lang)))
  188. (fmakunbound
  189. (intern (concat "org-babel-execute:" lang)))
  190. (fmakunbound
  191. (intern (concat "org-babel-expand-body:" lang)))))))
  192. ;;;###autoload
  193. (defun org-babel-load-file (file &optional compile)
  194. "Load Emacs Lisp source code blocks in the Org FILE.
  195. This function exports the source code using `org-babel-tangle'
  196. and then loads the resulting file using `load-file'. With
  197. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  198. byte-compiled before it is loaded."
  199. (interactive "fFile to load: \nP")
  200. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  201. ;; Tangle only if the Org file is newer than the Elisp file.
  202. (unless (org-file-newer-than-p
  203. tangled-file
  204. (file-attribute-modification-time
  205. (file-attributes (file-truename file))))
  206. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  207. (if compile
  208. (progn
  209. (byte-compile-file tangled-file 'load)
  210. (message "Compiled and loaded %s" tangled-file))
  211. (load-file tangled-file)
  212. (message "Loaded %s" tangled-file))))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. \\<org-mode-map>
  216. This list can be used to load support for any of the languages
  217. below. Each language will depend on a different set of system
  218. executables and/or Emacs modes.
  219. When a language is \"loaded\", code blocks in that language can
  220. be evaluated with `org-babel-execute-src-block', which is bound
  221. by default to \\[org-ctrl-c-ctrl-c].
  222. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  223. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  224. default, only Emacs Lisp is loaded, since it has no specific
  225. requirement."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Keyword
  326. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  327. "Regular expression for keyword-lines")
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. \\<org-mode-map>
  345. A deadline is this string, followed by a time stamp. It must be
  346. a word, terminated by a colon. You can insert a schedule keyword
  347. and a timestamp with `\\[org-deadline]'.")
  348. (defvar org-scheduled-string "SCHEDULED:"
  349. "String to mark scheduled TODO entries.
  350. \\<org-mode-map>
  351. A schedule is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-schedule]'.")
  354. (defconst org-ds-keyword-length
  355. (+ 2
  356. (apply #'max
  357. (mapcar #'length
  358. (list org-deadline-string org-scheduled-string
  359. org-clock-string org-closed-string))))
  360. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  361. (defconst org-planning-line-re
  362. (concat "^[ \t]*"
  363. (regexp-opt
  364. (list org-closed-string org-deadline-string org-scheduled-string)
  365. t))
  366. "Matches a line with planning info.
  367. Matched keyword is in group 1.")
  368. (defconst org-clock-line-re
  369. (concat "^[ \t]*" org-clock-string)
  370. "Matches a line with clock info.")
  371. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  372. "Matches the DEADLINE keyword.")
  373. (defconst org-deadline-time-regexp
  374. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  375. "Matches the DEADLINE keyword together with a time stamp.")
  376. (defconst org-deadline-time-hour-regexp
  377. (concat "\\<" org-deadline-string
  378. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  379. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  380. (defconst org-deadline-line-regexp
  381. (concat "\\<\\(" org-deadline-string "\\).*")
  382. "Matches the DEADLINE keyword and the rest of the line.")
  383. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  384. "Matches the SCHEDULED keyword.")
  385. (defconst org-scheduled-time-regexp
  386. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  387. "Matches the SCHEDULED keyword together with a time stamp.")
  388. (defconst org-scheduled-time-hour-regexp
  389. (concat "\\<" org-scheduled-string
  390. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  391. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  392. (defconst org-closed-time-regexp
  393. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  394. "Matches the CLOSED keyword together with a time stamp.")
  395. (defconst org-keyword-time-regexp
  396. (concat "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string
  399. org-clock-string)
  400. t)
  401. " *[[<]\\([^]>]+\\)[]>]")
  402. "Matches any of the 4 keywords, together with the time stamp.")
  403. (defconst org-keyword-time-not-clock-regexp
  404. (concat
  405. "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string) t)
  408. " *[[<]\\([^]>]+\\)[]>]")
  409. "Matches any of the 3 keywords, together with the time stamp.")
  410. (defconst org-maybe-keyword-time-regexp
  411. (concat "\\(\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string
  414. org-clock-string)
  415. t)
  416. "\\)?"
  417. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  418. "\\|"
  419. "<%%([^\r\n>]*>\\)")
  420. "Matches a timestamp, possibly preceded by a keyword.")
  421. (defconst org-all-time-keywords
  422. (mapcar (lambda (w) (substring w 0 -1))
  423. (list org-scheduled-string org-deadline-string
  424. org-clock-string org-closed-string))
  425. "List of time keywords.")
  426. ;;;; Drawer
  427. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  428. "Matches first or last line of a hidden block.
  429. Group 1 contains drawer's name or \"END\".")
  430. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  431. "Regular expression matching the first line of a property drawer.")
  432. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  433. "Regular expression matching the last line of a property drawer.")
  434. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  435. "Regular expression matching the first line of a clock drawer.")
  436. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a clock drawer.")
  438. (defconst org-logbook-drawer-re
  439. (concat "^[ \t]*:LOGBOOK:[ \t]*\n"
  440. "\\(?:[ \t]*.*\\(?: .*\\)?[ \t]*\n\\)*?"
  441. "[ \t]*:END:[ \t]*$")
  442. "Matches an entire LOGBOOK drawer.")
  443. (defconst org-property-drawer-re
  444. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  445. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  446. "[ \t]*:END:[ \t]*$")
  447. "Matches an entire property drawer.")
  448. (defconst org-clock-drawer-re
  449. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  450. org-clock-drawer-end-re "\\)\n?")
  451. "Matches an entire clock drawer.")
  452. ;;;; Headline
  453. (defconst org-heading-keyword-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline with some keyword.
  456. This regexp will match the headline of any node which has the
  457. exact keyword that is put into the format. The keyword isn't in
  458. any group by default, but the stars and the body are.")
  459. (defconst org-heading-keyword-maybe-regexp-format
  460. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  461. "Printf format for a regexp matching a headline, possibly with some keyword.
  462. This regexp can match any headline with the specified keyword, or
  463. without a keyword. The keyword isn't in any group by default,
  464. but the stars and the body are.")
  465. (defconst org-archive-tag "ARCHIVE"
  466. "The tag that marks a subtree as archived.
  467. An archived subtree does not open during visibility cycling, and does
  468. not contribute to the agenda listings.")
  469. (defconst org-tag-re "[[:alnum:]_@#%]+"
  470. "Regexp matching a single tag.")
  471. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  472. "Regexp matching the tag group at the end of a line, with leading spaces.
  473. Tags are stored in match group 1. Match group 2 stores the tags
  474. without the enclosing colons.")
  475. (defconst org-tag-line-re
  476. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  477. "Regexp matching tags in a headline.
  478. Tags are stored in match group 1. Match group 2 stores the tags
  479. without the enclosing colons.")
  480. (eval-and-compile
  481. (defconst org-comment-string "COMMENT"
  482. "Entries starting with this keyword will never be exported.
  483. \\<org-mode-map>
  484. An entry can be toggled between COMMENT and normal with
  485. `\\[org-toggle-comment]'."))
  486. ;;;; LaTeX Environments and Fragments
  487. (defconst org-latex-regexps
  488. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  489. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  490. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  491. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  492. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  493. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  494. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  495. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  496. "Regular expressions for matching embedded LaTeX.")
  497. ;;;; Node Property
  498. (defconst org-effort-property "Effort"
  499. "The property that is being used to keep track of effort estimates.
  500. Effort estimates given in this property need to be in the format
  501. defined in org-duration.el.")
  502. ;;;; Timestamp
  503. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  504. "Regular expression for fast time stamp matching.")
  505. (defconst org-ts-regexp-inactive
  506. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  507. "Regular expression for fast inactive time stamp matching.")
  508. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  509. "Regular expression for fast time stamp matching.")
  510. (defconst org-ts-regexp0
  511. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  512. "Regular expression matching time strings for analysis.
  513. This one does not require the space after the date, so it can be used
  514. on a string that terminates immediately after the date.")
  515. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  516. "Regular expression matching time strings for analysis.")
  517. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  518. "Regular expression matching time stamps, with groups.")
  519. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  520. "Regular expression matching time stamps (also [..]), with groups.")
  521. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  522. "Regular expression matching a time stamp range.")
  523. (defconst org-tr-regexp-both
  524. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  525. "Regular expression matching a time stamp range.")
  526. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  527. org-ts-regexp "\\)?")
  528. "Regular expression matching a time stamp or time stamp range.")
  529. (defconst org-tsr-regexp-both
  530. (concat org-ts-regexp-both "\\(--?-?"
  531. org-ts-regexp-both "\\)?")
  532. "Regular expression matching a time stamp or time stamp range.
  533. The time stamps may be either active or inactive.")
  534. (defconst org-repeat-re
  535. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  536. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  537. "Regular expression for specifying repeated events.
  538. After a match, group 1 contains the repeat expression.")
  539. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  540. "Formats for `format-time-string' which are used for time stamps.")
  541. ;;; The custom variables
  542. (defgroup org nil
  543. "Outline-based notes management and organizer."
  544. :tag "Org"
  545. :group 'outlines
  546. :group 'calendar)
  547. (defcustom org-mode-hook nil
  548. "Mode hook for Org mode, run after the mode was turned on."
  549. :group 'org
  550. :type 'hook)
  551. (defcustom org-load-hook nil
  552. "Hook that is run after org.el has been loaded."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-log-buffer-setup-hook nil
  556. "Hook that is run after an Org log buffer is created."
  557. :group 'org
  558. :version "24.1"
  559. :type 'hook)
  560. (defvar org-modules) ; defined below
  561. (defvar org-modules-loaded nil
  562. "Have the modules been loaded already?")
  563. (defun org-load-modules-maybe (&optional force)
  564. "Load all extensions listed in `org-modules'."
  565. (when (or force (not org-modules-loaded))
  566. (dolist (ext org-modules)
  567. (condition-case nil (require ext)
  568. (error (message "Problems while trying to load feature `%s'" ext))))
  569. (setq org-modules-loaded t)))
  570. (defun org-set-modules (var value)
  571. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  572. (set var value)
  573. (when (featurep 'org)
  574. (org-load-modules-maybe 'force)
  575. (org-element-cache-reset 'all)))
  576. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  577. "Modules that should always be loaded together with org.el.
  578. If a description starts with <C>, the file is not part of Emacs
  579. and loading it will require that you have downloaded and properly
  580. installed the Org mode distribution.
  581. You can also use this system to load external packages (i.e. neither Org
  582. core modules, nor modules from the CONTRIB directory). Just add symbols
  583. to the end of the list. If the package is called org-xyz.el, then you need
  584. to add the symbol `xyz', and the package must have a call to:
  585. (provide \\='org-xyz)
  586. For export specific modules, see also `org-export-backends'."
  587. :group 'org
  588. :set 'org-set-modules
  589. :version "26.1"
  590. :package-version '(Org . "9.2")
  591. :type
  592. '(set :greedy t
  593. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  594. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  595. (const :tag " crypt: Encryption of subtrees" org-crypt)
  596. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  597. (const :tag " docview: Links to Docview buffers" ol-docview)
  598. (const :tag " eww: Store link to URL of Eww" ol-eww)
  599. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  600. (const :tag " habit: Track your consistency with habits" org-habit)
  601. (const :tag " id: Global IDs for identifying entries" org-id)
  602. (const :tag " info: Links to Info nodes" ol-info)
  603. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  604. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  605. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  606. (const :tag " mouse: Additional mouse support" org-mouse)
  607. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  608. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  609. (const :tag " tempo: Fast completion for structures" org-tempo)
  610. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  611. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  612. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  613. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  614. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  615. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  616. (const :tag "C collector: Collect properties into tables" org-collector)
  617. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  618. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  619. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  620. (const :tag "C eval: Include command output as text" org-eval)
  621. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  622. (const :tag "C git-link: Links to specific file version" ol-git-link)
  623. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  624. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  625. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  626. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  627. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  628. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  629. (const :tag "C man: Links to man pages in Org mode" ol-man)
  630. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  631. (const :tag "C notify: Notifications for Org mode" org-notify)
  632. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  633. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  634. (const :tag "C registry: A registry for Org links" org-registry)
  635. (const :tag "C screen: Visit screen sessions through links" org-screen)
  636. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  637. (const :tag "C secretary: Team management with Org" org-secretary)
  638. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  639. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  640. (const :tag "C track: Keep up with Org mode development" org-track)
  641. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  642. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  643. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  644. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  645. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  646. (defvar org-export-registered-backends) ; From ox.el.
  647. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  648. (declare-function org-export-backend-name "ox" (backend) t)
  649. (defcustom org-export-backends '(ascii html icalendar latex odt)
  650. "List of export back-ends that should be always available.
  651. If a description starts with <C>, the file is not part of Emacs
  652. and loading it will require that you have downloaded and properly
  653. installed the Org mode distribution.
  654. Unlike to `org-modules', libraries in this list will not be
  655. loaded along with Org, but only once the export framework is
  656. needed.
  657. This variable needs to be set before org.el is loaded. If you
  658. need to make a change while Emacs is running, use the customize
  659. interface or run the following code, where VAL stands for the new
  660. value of the variable, after updating it:
  661. (progn
  662. (setq org-export-registered-backends
  663. (cl-remove-if-not
  664. (lambda (backend)
  665. (let ((name (org-export-backend-name backend)))
  666. (or (memq name val)
  667. (catch \\='parentp
  668. (dolist (b val)
  669. (and (org-export-derived-backend-p b name)
  670. (throw \\='parentp t)))))))
  671. org-export-registered-backends))
  672. (let ((new-list (mapcar #\\='org-export-backend-name
  673. org-export-registered-backends)))
  674. (dolist (backend val)
  675. (cond
  676. ((not (load (format \"ox-%s\" backend) t t))
  677. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  678. backend))
  679. ((not (memq backend new-list)) (push backend new-list))))
  680. (set-default \\='org-export-backends new-list)))
  681. Adding a back-end to this list will also pull the back-end it
  682. depends on, if any."
  683. :group 'org
  684. :group 'org-export
  685. :version "26.1"
  686. :package-version '(Org . "9.0")
  687. :initialize 'custom-initialize-set
  688. :set (lambda (var val)
  689. (if (not (featurep 'ox)) (set-default var val)
  690. ;; Any back-end not required anymore (not present in VAL and not
  691. ;; a parent of any back-end in the new value) is removed from the
  692. ;; list of registered back-ends.
  693. (setq org-export-registered-backends
  694. (cl-remove-if-not
  695. (lambda (backend)
  696. (let ((name (org-export-backend-name backend)))
  697. (or (memq name val)
  698. (catch 'parentp
  699. (dolist (b val)
  700. (and (org-export-derived-backend-p b name)
  701. (throw 'parentp t)))))))
  702. org-export-registered-backends))
  703. ;; Now build NEW-LIST of both new back-ends and required
  704. ;; parents.
  705. (let ((new-list (mapcar #'org-export-backend-name
  706. org-export-registered-backends)))
  707. (dolist (backend val)
  708. (cond
  709. ((not (load (format "ox-%s" backend) t t))
  710. (message "Problems while trying to load export back-end `%s'"
  711. backend))
  712. ((not (memq backend new-list)) (push backend new-list))))
  713. ;; Set VAR to that list with fixed dependencies.
  714. (set-default var new-list))))
  715. :type '(set :greedy t
  716. (const :tag " ascii Export buffer to ASCII format" ascii)
  717. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  718. (const :tag " html Export buffer to HTML format" html)
  719. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  720. (const :tag " latex Export buffer to LaTeX format" latex)
  721. (const :tag " man Export buffer to MAN format" man)
  722. (const :tag " md Export buffer to Markdown format" md)
  723. (const :tag " odt Export buffer to ODT format" odt)
  724. (const :tag " org Export buffer to Org format" org)
  725. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  726. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  727. (const :tag "C deck Export buffer to deck.js presentations" deck)
  728. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  729. (const :tag "C groff Export buffer to Groff format" groff)
  730. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  731. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  732. (const :tag "C s5 Export buffer to s5 presentations" s5)
  733. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  734. (eval-after-load 'ox
  735. '(dolist (backend org-export-backends)
  736. (condition-case nil (require (intern (format "ox-%s" backend)))
  737. (error (message "Problems while trying to load export back-end `%s'"
  738. backend)))))
  739. (defcustom org-support-shift-select nil
  740. "Non-nil means make shift-cursor commands select text when possible.
  741. \\<org-mode-map>
  742. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  743. start selecting a region, or enlarge regions started in this way.
  744. In Org mode, in special contexts, these same keys are used for
  745. other purposes, important enough to compete with shift selection.
  746. Org tries to balance these needs by supporting `shift-select-mode'
  747. outside these special contexts, under control of this variable.
  748. The default of this variable is nil, to avoid confusing behavior. Shifted
  749. cursor keys will then execute Org commands in the following contexts:
  750. - on a headline, changing TODO state (left/right) and priority (up/down)
  751. - on a time stamp, changing the time
  752. - in a plain list item, changing the bullet type
  753. - in a property definition line, switching between allowed values
  754. - in the BEGIN line of a clock table (changing the time block).
  755. Outside these contexts, the commands will throw an error.
  756. When this variable is t and the cursor is not in a special
  757. context, Org mode will support shift-selection for making and
  758. enlarging regions. To make this more effective, the bullet
  759. cycling will no longer happen anywhere in an item line, but only
  760. if the cursor is exactly on the bullet.
  761. If you set this variable to the symbol `always', then the keys
  762. will not be special in headlines, property lines, and item lines,
  763. to make shift selection work there as well. If this is what you
  764. want, you can use the following alternative commands:
  765. `\\[org-todo]' and `\\[org-priority]' \
  766. to change TODO state and priority,
  767. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  768. can be used to switch TODO sets,
  769. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  770. and properties can be edited by hand or in column view.
  771. However, when the cursor is on a timestamp, shift-cursor commands
  772. will still edit the time stamp - this is just too good to give up."
  773. :group 'org
  774. :type '(choice
  775. (const :tag "Never" nil)
  776. (const :tag "When outside special context" t)
  777. (const :tag "Everywhere except timestamps" always)))
  778. (defcustom org-loop-over-headlines-in-active-region nil
  779. "Shall some commands act upon headlines in the active region?
  780. When set to t, some commands will be performed in all headlines
  781. within the active region.
  782. When set to `start-level', some commands will be performed in all
  783. headlines within the active region, provided that these headlines
  784. are of the same level than the first one.
  785. When set to a string, those commands will be performed on the
  786. matching headlines within the active region. Such string must be
  787. a tags/property/todo match as it is used in the agenda tags view.
  788. The list of commands is: `org-schedule', `org-deadline',
  789. `org-todo', `org-set-tags-command', `org-archive-subtree',
  790. `org-archive-set-tag', `org-toggle-archive-tag' and
  791. `org-archive-to-archive-sibling'. The archiving commands skip
  792. already archived entries.
  793. See `org-agenda-loop-over-headlines-in-active-region' for the
  794. equivalent option for agenda views."
  795. :type '(choice (const :tag "Don't loop" nil)
  796. (const :tag "All headlines in active region" t)
  797. (const :tag "In active region, headlines at the same level than the first one" start-level)
  798. (string :tag "Tags/Property/Todo matcher"))
  799. :version "24.1"
  800. :group 'org-todo
  801. :group 'org-archive)
  802. (defcustom org-startup-folded t
  803. "Non-nil means entering Org mode will switch to OVERVIEW.
  804. This can also be configured on a per-file basis by adding one of
  805. the following lines anywhere in the buffer:
  806. #+STARTUP: fold (or `overview', this is equivalent)
  807. #+STARTUP: nofold (or `showall', this is equivalent)
  808. #+STARTUP: content
  809. #+STARTUP: showeverything
  810. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  811. to ignore this option when Org opens agenda files for the first
  812. time."
  813. :group 'org-startup
  814. :type '(choice
  815. (const :tag "nofold: show all" nil)
  816. (const :tag "fold: overview" t)
  817. (const :tag "content: all headlines" content)
  818. (const :tag "show everything, even drawers" showeverything)))
  819. (defcustom org-startup-truncated t
  820. "Non-nil means entering Org mode will set `truncate-lines'.
  821. This is useful since some lines containing links can be very long and
  822. uninteresting. Also tables look terrible when wrapped.
  823. The variable `org-startup-truncated' allows to configure
  824. truncation for Org mode different to the other modes that use the
  825. variable `truncate-lines' and as a shortcut instead of putting
  826. the variable `truncate-lines' into the `org-mode-hook'. If one
  827. wants to configure truncation for Org mode not statically but
  828. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  829. the variable `truncate-lines' has to be used because in such a
  830. case it is too late to set the variable `org-startup-truncated'."
  831. :group 'org-startup
  832. :type 'boolean)
  833. (defcustom org-startup-indented nil
  834. "Non-nil means turn on `org-indent-mode' on startup.
  835. This can also be configured on a per-file basis by adding one of
  836. the following lines anywhere in the buffer:
  837. #+STARTUP: indent
  838. #+STARTUP: noindent"
  839. :group 'org-structure
  840. :type '(choice
  841. (const :tag "Not" nil)
  842. (const :tag "Globally (slow on startup in large files)" t)))
  843. (defcustom org-use-sub-superscripts t
  844. "Non-nil means interpret \"_\" and \"^\" for display.
  845. If you want to control how Org exports those characters, see
  846. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  847. used to be an alias for `org-export-with-sub-superscripts' in
  848. Org <8.0, it is not anymore.
  849. When this option is turned on, you can use TeX-like syntax for
  850. sub- and superscripts within the buffer. Several characters after
  851. \"_\" or \"^\" will be considered as a single item - so grouping
  852. with {} is normally not needed. For example, the following things
  853. will be parsed as single sub- or superscripts:
  854. 10^24 or 10^tau several digits will be considered 1 item.
  855. 10^-12 or 10^-tau a leading sign with digits or a word
  856. x^2-y^3 will be read as x^2 - y^3, because items are
  857. terminated by almost any nonword/nondigit char.
  858. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  859. Still, ambiguity is possible. So when in doubt, use {} to enclose
  860. the sub/superscript. If you set this variable to the symbol `{}',
  861. the braces are *required* in order to trigger interpretations as
  862. sub/superscript. This can be helpful in documents that need \"_\"
  863. frequently in plain text."
  864. :group 'org-startup
  865. :version "24.4"
  866. :package-version '(Org . "8.0")
  867. :type '(choice
  868. (const :tag "Always interpret" t)
  869. (const :tag "Only with braces" {})
  870. (const :tag "Never interpret" nil)))
  871. (defcustom org-startup-with-beamer-mode nil
  872. "Non-nil means turn on `org-beamer-mode' on startup.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: beamer"
  876. :group 'org-startup
  877. :version "24.1"
  878. :type 'boolean)
  879. (defcustom org-startup-align-all-tables nil
  880. "Non-nil means align all tables when visiting a file.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: align
  884. #+STARTUP: noalign"
  885. :group 'org-startup
  886. :type 'boolean)
  887. (defcustom org-startup-shrink-all-tables nil
  888. "Non-nil means shrink all table columns with a width cookie.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: shrink"
  892. :group 'org-startup
  893. :type 'boolean
  894. :version "27.1"
  895. :package-version '(Org . "9.2")
  896. :safe #'booleanp)
  897. (defcustom org-startup-with-inline-images nil
  898. "Non-nil means show inline images when loading a new Org file.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: inlineimages
  902. #+STARTUP: noinlineimages"
  903. :group 'org-startup
  904. :version "24.1"
  905. :type 'boolean)
  906. (defcustom org-startup-with-latex-preview nil
  907. "Non-nil means preview LaTeX fragments when loading a new Org file.
  908. This can also be configured on a per-file basis by adding one of
  909. the following lines anywhere in the buffer:
  910. #+STARTUP: latexpreview
  911. #+STARTUP: nolatexpreview"
  912. :group 'org-startup
  913. :version "24.4"
  914. :package-version '(Org . "8.0")
  915. :type 'boolean)
  916. (defcustom org-insert-mode-line-in-empty-file nil
  917. "Non-nil means insert the first line setting Org mode in empty files.
  918. When the function `org-mode' is called interactively in an empty file, this
  919. normally means that the file name does not automatically trigger Org mode.
  920. To ensure that the file will always be in Org mode in the future, a
  921. line enforcing Org mode will be inserted into the buffer, if this option
  922. has been set."
  923. :group 'org-startup
  924. :type 'boolean)
  925. (defcustom org-ellipsis nil
  926. "The ellipsis to use in the Org mode outline.
  927. When nil, just use the standard three dots. When a non-empty string,
  928. use that string instead.
  929. The change affects only Org mode (which will then use its own display table).
  930. Changing this requires executing `\\[org-mode]' in a buffer to become
  931. effective."
  932. :group 'org-startup
  933. :type '(choice (const :tag "Default" nil)
  934. (string :tag "String" :value "...#"))
  935. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  936. (defvar org-display-table nil
  937. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  938. (defgroup org-keywords nil
  939. "Keywords in Org mode."
  940. :tag "Org Keywords"
  941. :group 'org)
  942. (defcustom org-closed-keep-when-no-todo nil
  943. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  944. :group 'org-todo
  945. :group 'org-keywords
  946. :version "24.4"
  947. :package-version '(Org . "8.0")
  948. :type 'boolean)
  949. (defgroup org-structure nil
  950. "Options concerning the general structure of Org files."
  951. :tag "Org Structure"
  952. :group 'org)
  953. (defgroup org-reveal-location nil
  954. "Options about how to make context of a location visible."
  955. :tag "Org Reveal Location"
  956. :group 'org-structure)
  957. (defcustom org-show-context-detail '((agenda . local)
  958. (bookmark-jump . lineage)
  959. (isearch . lineage)
  960. (default . ancestors))
  961. "Alist between context and visibility span when revealing a location.
  962. \\<org-mode-map>Some actions may move point into invisible
  963. locations. As a consequence, Org always expose a neighborhood
  964. around point. How much is shown depends on the initial action,
  965. or context. Valid contexts are
  966. agenda when exposing an entry from the agenda
  967. org-goto when using the command `org-goto' (`\\[org-goto]')
  968. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  969. tags-tree when constructing a sparse tree based on tags matches
  970. link-search when exposing search matches associated with a link
  971. mark-goto when exposing the jump goal of a mark
  972. bookmark-jump when exposing a bookmark location
  973. isearch when exiting from an incremental search
  974. default default for all contexts not set explicitly
  975. Allowed visibility spans are
  976. minimal show current headline; if point is not on headline,
  977. also show entry
  978. local show current headline, entry and next headline
  979. ancestors show current headline and its direct ancestors; if
  980. point is not on headline, also show entry
  981. lineage show current headline, its direct ancestors and all
  982. their children; if point is not on headline, also show
  983. entry and first child
  984. tree show current headline, its direct ancestors and all
  985. their children; if point is not on headline, also show
  986. entry and all children
  987. canonical show current headline, its direct ancestors along with
  988. their entries and children; if point is not located on
  989. the headline, also show current entry and all children
  990. As special cases, a nil or t value means show all contexts in
  991. `minimal' or `canonical' view, respectively.
  992. Some views can make displayed information very compact, but also
  993. make it harder to edit the location of the match. In such
  994. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  995. more context."
  996. :group 'org-reveal-location
  997. :version "26.1"
  998. :package-version '(Org . "9.0")
  999. :type '(choice
  1000. (const :tag "Canonical" t)
  1001. (const :tag "Minimal" nil)
  1002. (repeat :greedy t :tag "Individual contexts"
  1003. (cons
  1004. (choice :tag "Context"
  1005. (const agenda)
  1006. (const org-goto)
  1007. (const occur-tree)
  1008. (const tags-tree)
  1009. (const link-search)
  1010. (const mark-goto)
  1011. (const bookmark-jump)
  1012. (const isearch)
  1013. (const default))
  1014. (choice :tag "Detail level"
  1015. (const minimal)
  1016. (const local)
  1017. (const ancestors)
  1018. (const lineage)
  1019. (const tree)
  1020. (const canonical))))))
  1021. (defcustom org-indirect-buffer-display 'other-window
  1022. "How should indirect tree buffers be displayed?
  1023. This applies to indirect buffers created with the commands
  1024. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1025. Valid values are:
  1026. current-window Display in the current window
  1027. other-window Just display in another window.
  1028. dedicated-frame Create one new frame, and re-use it each time.
  1029. new-frame Make a new frame each time. Note that in this case
  1030. previously-made indirect buffers are kept, and you need to
  1031. kill these buffers yourself."
  1032. :group 'org-structure
  1033. :group 'org-agenda-windows
  1034. :type '(choice
  1035. (const :tag "In current window" current-window)
  1036. (const :tag "In current frame, other window" other-window)
  1037. (const :tag "Each time a new frame" new-frame)
  1038. (const :tag "One dedicated frame" dedicated-frame)))
  1039. (defconst org-file-apps-gnu
  1040. '((remote . emacs)
  1041. (system . mailcap)
  1042. (t . mailcap))
  1043. "Default file applications on a UNIX or GNU/Linux system.
  1044. See `org-file-apps'.")
  1045. (defconst org-file-apps-macos
  1046. '((remote . emacs)
  1047. (system . "open %s")
  1048. ("ps.gz" . "gv %s")
  1049. ("eps.gz" . "gv %s")
  1050. ("dvi" . "xdvi %s")
  1051. ("fig" . "xfig %s")
  1052. (t . "open %s"))
  1053. "Default file applications on a macOS system.
  1054. The system \"open\" is known as a default, but we use X11 applications
  1055. for some files for which the OS does not have a good default.
  1056. See `org-file-apps'.")
  1057. (defconst org-file-apps-windowsnt
  1058. (list '(remote . emacs)
  1059. (cons 'system (lambda (file _path)
  1060. (with-no-warnings (w32-shell-execute "open" file))))
  1061. (cons t (lambda (file _path)
  1062. (with-no-warnings (w32-shell-execute "open" file)))))
  1063. "Default file applications on a Windows NT system.
  1064. The system \"open\" is used for most files.
  1065. See `org-file-apps'.")
  1066. (defcustom org-file-apps
  1067. '((auto-mode . emacs)
  1068. (directory . emacs)
  1069. ("\\.mm\\'" . default)
  1070. ("\\.x?html?\\'" . default)
  1071. ("\\.pdf\\'" . default))
  1072. "Applications for opening `file:path' items in a document.
  1073. \\<org-mode-map>
  1074. Org mode uses system defaults for different file types, but you
  1075. can use this variable to set the application for a given file
  1076. extension. The entries in this list are cons cells where the car
  1077. identifies files and the cdr the corresponding command.
  1078. Possible values for the file identifier are:
  1079. \"string\" A string as a file identifier can be interpreted in different
  1080. ways, depending on its contents:
  1081. - Alphanumeric characters only:
  1082. Match links with this file extension.
  1083. Example: (\"pdf\" . \"evince %s\")
  1084. to open PDFs with evince.
  1085. - Regular expression: Match links where the
  1086. filename matches the regexp. If you want to
  1087. use groups here, use shy groups.
  1088. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1089. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1090. to open *.html and *.xhtml with firefox.
  1091. - Regular expression which contains (non-shy) groups:
  1092. Match links where the whole link, including \"::\", and
  1093. anything after that, matches the regexp.
  1094. In a custom command string, %1, %2, etc. are replaced with
  1095. the parts of the link that were matched by the groups.
  1096. For backwards compatibility, if a command string is given
  1097. that does not use any of the group matches, this case is
  1098. handled identically to the second one (i.e. match against
  1099. file name only).
  1100. In a custom function, you can access the group matches with
  1101. (match-string n link).
  1102. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1103. \"evince -p %1 %s\")
  1104. to open [[file:document.pdf::5]] with evince at page 5.
  1105. `directory' Matches a directory
  1106. `remote' Matches a remote file, accessible through tramp or efs.
  1107. Remote files most likely should be visited through Emacs
  1108. because external applications cannot handle such paths.
  1109. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1110. so all files Emacs knows how to handle. Using this with
  1111. command `emacs' will open most files in Emacs. Beware that this
  1112. will also open html files inside Emacs, unless you add
  1113. (\"html\" . default) to the list as well.
  1114. `system' The system command to open files, like `open' on Windows
  1115. and macOS, and mailcap under GNU/Linux. This is the command
  1116. that will be selected if you call `org-open-at-point' with a
  1117. double prefix argument (`\\[universal-argument] \
  1118. \\[universal-argument] \\[org-open-at-point]').
  1119. t Default for files not matched by any of the other options.
  1120. Possible values for the command are:
  1121. `emacs' The file will be visited by the current Emacs process.
  1122. `default' Use the default application for this file type, which is the
  1123. association for t in the list, most likely in the system-specific
  1124. part. This can be used to overrule an unwanted setting in the
  1125. system-specific variable.
  1126. `system' Use the system command for opening files, like \"open\".
  1127. This command is specified by the entry whose car is `system'.
  1128. Most likely, the system-specific version of this variable
  1129. does define this command, but you can overrule/replace it
  1130. here.
  1131. `mailcap' Use command specified in the mailcaps.
  1132. string A command to be executed by a shell; %s will be replaced
  1133. by the path to the file.
  1134. function A Lisp function, which will be called with two arguments:
  1135. the file path and the original link string, without the
  1136. \"file:\" prefix.
  1137. For more examples, see the system specific constants
  1138. `org-file-apps-macos'
  1139. `org-file-apps-windowsnt'
  1140. `org-file-apps-gnu'."
  1141. :group 'org
  1142. :package-version '(Org . "9.4")
  1143. :type '(repeat
  1144. (cons (choice :value ""
  1145. (string :tag "Extension")
  1146. (const :tag "System command to open files" system)
  1147. (const :tag "Default for unrecognized files" t)
  1148. (const :tag "Remote file" remote)
  1149. (const :tag "Links to a directory" directory)
  1150. (const :tag "Any files that have Emacs modes"
  1151. auto-mode))
  1152. (choice :value ""
  1153. (const :tag "Visit with Emacs" emacs)
  1154. (const :tag "Use default" default)
  1155. (const :tag "Use the system command" system)
  1156. (string :tag "Command")
  1157. (function :tag "Function")))))
  1158. (defcustom org-open-non-existing-files nil
  1159. "Non-nil means `org-open-file' opens non-existing files.
  1160. When nil, an error is thrown.
  1161. This variable applies only to external applications because they
  1162. might choke on non-existing files. If the link is to a file that
  1163. will be opened in Emacs, the variable is ignored."
  1164. :group 'org
  1165. :type 'boolean
  1166. :safe #'booleanp)
  1167. (defcustom org-open-directory-means-index-dot-org nil
  1168. "When non-nil a link to a directory really means to \"index.org\".
  1169. When nil, following a directory link runs Dired or opens
  1170. a finder/explorer window on that directory."
  1171. :group 'org
  1172. :type 'boolean
  1173. :safe #'booleanp)
  1174. (defcustom org-bookmark-names-plist
  1175. '(:last-capture "org-capture-last-stored"
  1176. :last-refile "org-refile-last-stored"
  1177. :last-capture-marker "org-capture-last-stored-marker")
  1178. "Names for bookmarks automatically set by some Org commands.
  1179. This can provide strings as names for a number of bookmarks Org sets
  1180. automatically. The following keys are currently implemented:
  1181. :last-capture
  1182. :last-capture-marker
  1183. :last-refile
  1184. When a key does not show up in the property list, the corresponding bookmark
  1185. is not set."
  1186. :group 'org-structure
  1187. :type 'plist)
  1188. (defgroup org-cycle nil
  1189. "Options concerning visibility cycling in Org mode."
  1190. :tag "Org Cycle"
  1191. :group 'org-structure)
  1192. (defcustom org-cycle-skip-children-state-if-no-children t
  1193. "Non-nil means skip CHILDREN state in entries that don't have any."
  1194. :group 'org-cycle
  1195. :type 'boolean)
  1196. (defcustom org-cycle-max-level nil
  1197. "Maximum level which should still be subject to visibility cycling.
  1198. Levels higher than this will, for cycling, be treated as text, not a headline.
  1199. When `org-odd-levels-only' is set, a value of N in this variable actually
  1200. means 2N-1 stars as the limiting headline.
  1201. When nil, cycle all levels.
  1202. Note that the limiting level of cycling is also influenced by
  1203. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1204. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1205. than its value."
  1206. :group 'org-cycle
  1207. :type '(choice
  1208. (const :tag "No limit" nil)
  1209. (integer :tag "Maximum level")))
  1210. (defcustom org-hide-block-startup nil
  1211. "Non-nil means entering Org mode will fold all blocks.
  1212. This can also be set in on a per-file basis with
  1213. #+STARTUP: hideblocks
  1214. #+STARTUP: showblocks"
  1215. :group 'org-startup
  1216. :group 'org-cycle
  1217. :type 'boolean)
  1218. (defcustom org-cycle-global-at-bob nil
  1219. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1220. This makes it possible to do global cycling without having to use `S-TAB'
  1221. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1222. line of the buffer
  1223. must not be a headline -- it may be empty or some other text.
  1224. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1225. sure the cursor stays at the beginning of the buffer.
  1226. When this option is nil, don't do anything special at the beginning of
  1227. the buffer."
  1228. :group 'org-cycle
  1229. :type 'boolean)
  1230. (defcustom org-cycle-level-after-item/entry-creation t
  1231. "Non-nil means cycle entry level or item indentation in new empty entries.
  1232. When the cursor is at the end of an empty headline, i.e., with only stars
  1233. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1234. and then all possible ancestor states, before returning to the original state.
  1235. This makes data entry extremely fast: M-RET to create a new headline,
  1236. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1237. When the cursor is at the end of an empty plain list item, one TAB will
  1238. make it a subitem, two or more tabs will back up to make this an item
  1239. higher up in the item hierarchy."
  1240. :group 'org-cycle
  1241. :type 'boolean)
  1242. (defcustom org-cycle-emulate-tab t
  1243. "Where should `org-cycle' emulate TAB.
  1244. nil Never
  1245. white Only in completely white lines
  1246. whitestart Only at the beginning of lines, before the first non-white char
  1247. t Everywhere except in headlines
  1248. exc-hl-bol Everywhere except at the start of a headline
  1249. If TAB is used in a place where it does not emulate TAB, the current subtree
  1250. visibility is cycled."
  1251. :group 'org-cycle
  1252. :type '(choice (const :tag "Never" nil)
  1253. (const :tag "Only in completely white lines" white)
  1254. (const :tag "Before first char in a line" whitestart)
  1255. (const :tag "Everywhere except in headlines" t)
  1256. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1257. (defcustom org-cycle-separator-lines 2
  1258. "Number of empty lines needed to keep an empty line between collapsed trees.
  1259. If you leave an empty line between the end of a subtree and the following
  1260. headline, this empty line is hidden when the subtree is folded.
  1261. Org mode will leave (exactly) one empty line visible if the number of
  1262. empty lines is equal or larger to the number given in this variable.
  1263. So the default 2 means at least 2 empty lines after the end of a subtree
  1264. are needed to produce free space between a collapsed subtree and the
  1265. following headline.
  1266. If the number is negative, and the number of empty lines is at least -N,
  1267. all empty lines are shown.
  1268. Special case: when 0, never leave empty lines in collapsed view."
  1269. :group 'org-cycle
  1270. :type 'integer)
  1271. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1272. (defcustom org-pre-cycle-hook nil
  1273. "Hook that is run before visibility cycling is happening.
  1274. The function(s) in this hook must accept a single argument which indicates
  1275. the new state that will be set right after running this hook. The
  1276. argument is a symbol. Before a global state change, it can have the values
  1277. `overview', `content', or `all'. Before a local state change, it can have
  1278. the values `folded', `children', or `subtree'."
  1279. :group 'org-cycle
  1280. :type 'hook)
  1281. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1282. org-cycle-show-empty-lines
  1283. org-optimize-window-after-visibility-change)
  1284. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1285. The function(s) in this hook must accept a single argument which indicates
  1286. the new state that was set by the most recent `org-cycle' command. The
  1287. argument is a symbol. After a global state change, it can have the values
  1288. `overview', `contents', or `all'. After a local state change, it can have
  1289. the values `folded', `children', or `subtree'."
  1290. :group 'org-cycle
  1291. :type 'hook
  1292. :version "26.1"
  1293. :package-version '(Org . "8.3"))
  1294. (defgroup org-edit-structure nil
  1295. "Options concerning structure editing in Org mode."
  1296. :tag "Org Edit Structure"
  1297. :group 'org-structure)
  1298. (defcustom org-odd-levels-only nil
  1299. "Non-nil means skip even levels and only use odd levels for the outline.
  1300. This has the effect that two stars are being added/taken away in
  1301. promotion/demotion commands. It also influences how levels are
  1302. handled by the exporters.
  1303. Changing it requires restart of `font-lock-mode' to become effective
  1304. for fontification also in regions already fontified.
  1305. You may also set this on a per-file basis by adding one of the following
  1306. lines to the buffer:
  1307. #+STARTUP: odd
  1308. #+STARTUP: oddeven"
  1309. :group 'org-edit-structure
  1310. :group 'org-appearance
  1311. :type 'boolean)
  1312. (defcustom org-adapt-indentation t
  1313. "Non-nil means adapt indentation to outline node level.
  1314. When this variable is set to t, Org assumes that you write
  1315. outlines by indenting text in each node to align with the
  1316. headline (after the stars).
  1317. When this variable is set to 'headline-data, only adapt the
  1318. indentation of the data lines right below the headline, such as
  1319. planning/clock lines and property/logbook drawers.
  1320. The following issues are influenced by this variable:
  1321. - The indentation is increased by one space in a demotion
  1322. command, and decreased by one in a promotion command. However,
  1323. in the latter case, if shifting some line in the entry body
  1324. would alter document structure (e.g., insert a new headline),
  1325. indentation is not changed at all.
  1326. - Property drawers and planning information is inserted indented
  1327. when this variable is set. When nil, they will not be indented.
  1328. - TAB indents a line relative to current level. The lines below
  1329. a headline will be indented when this variable is set to t.
  1330. Note that this is all about true indentation, by adding and
  1331. removing space characters. See also \"org-indent.el\" which does
  1332. level-dependent indentation in a virtual way, i.e. at display
  1333. time in Emacs."
  1334. :group 'org-edit-structure
  1335. :type '(choice
  1336. (const :tag "Adapt indentation for all lines" t)
  1337. (const :tag "Adapt indentation for headline data lines"
  1338. 'headline-data)
  1339. (const :tag "Do not adapt indentation at all" nil))
  1340. :safe #'booleanp)
  1341. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1342. (defcustom org-special-ctrl-a/e nil
  1343. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1344. When t, `C-a' will bring back the cursor to the beginning of the
  1345. headline text, i.e. after the stars and after a possible TODO
  1346. keyword. In an item, this will be the position after bullet and
  1347. check-box, if any. When the cursor is already at that position,
  1348. another `C-a' will bring it to the beginning of the line.
  1349. `C-e' will jump to the end of the headline, ignoring the presence
  1350. of tags in the headline. A second `C-e' will then jump to the
  1351. true end of the line, after any tags. This also means that, when
  1352. this variable is non-nil, `C-e' also will never jump beyond the
  1353. end of the heading of a folded section, i.e. not after the
  1354. ellipses.
  1355. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1356. normally, going to the true line boundary first. Only a directly
  1357. following, identical keypress will bring the cursor to the
  1358. special positions.
  1359. This may also be a cons cell where the behavior for `C-a' and
  1360. `C-e' is set separately."
  1361. :group 'org-edit-structure
  1362. :type '(choice
  1363. (const :tag "off" nil)
  1364. (const :tag "on: after stars/bullet and before tags first" t)
  1365. (const :tag "reversed: true line boundary first" reversed)
  1366. (cons :tag "Set C-a and C-e separately"
  1367. (choice :tag "Special C-a"
  1368. (const :tag "off" nil)
  1369. (const :tag "on: after stars/bullet first" t)
  1370. (const :tag "reversed: before stars/bullet first" reversed))
  1371. (choice :tag "Special C-e"
  1372. (const :tag "off" nil)
  1373. (const :tag "on: before tags first" t)
  1374. (const :tag "reversed: after tags first" reversed)))))
  1375. (defcustom org-special-ctrl-k nil
  1376. "Non-nil means `C-k' will behave specially in headlines.
  1377. When nil, `C-k' will call the default `kill-line' command.
  1378. When t, the following will happen while the cursor is in the headline:
  1379. - When the cursor is at the beginning of a headline, kill the entire
  1380. line and possible the folded subtree below the line.
  1381. - When in the middle of the headline text, kill the headline up to the tags.
  1382. - When after the headline text, kill the tags."
  1383. :group 'org-edit-structure
  1384. :type 'boolean)
  1385. (defcustom org-ctrl-k-protect-subtree nil
  1386. "Non-nil means, do not delete a hidden subtree with C-k.
  1387. When set to the symbol `error', simply throw an error when C-k is
  1388. used to kill (part-of) a headline that has hidden text behind it.
  1389. Any other non-nil value will result in a query to the user, if it is
  1390. OK to kill that hidden subtree. When nil, kill without remorse."
  1391. :group 'org-edit-structure
  1392. :version "24.1"
  1393. :type '(choice
  1394. (const :tag "Do not protect hidden subtrees" nil)
  1395. (const :tag "Protect hidden subtrees with a security query" t)
  1396. (const :tag "Never kill a hidden subtree with C-k" error)))
  1397. (defcustom org-special-ctrl-o t
  1398. "Non-nil means, make `C-o' insert a row in tables."
  1399. :group 'org-edit-structure
  1400. :type 'boolean)
  1401. (defcustom org-catch-invisible-edits nil
  1402. "Check if in invisible region before inserting or deleting a character.
  1403. Valid values are:
  1404. nil Do not check, so just do invisible edits.
  1405. error Throw an error and do nothing.
  1406. show Make point visible, and do the requested edit.
  1407. show-and-error Make point visible, then throw an error and abort the edit.
  1408. smart Make point visible, and do insertion/deletion if it is
  1409. adjacent to visible text and the change feels predictable.
  1410. Never delete a previously invisible character or add in the
  1411. middle or right after an invisible region. Basically, this
  1412. allows insertion and backward-delete right before ellipses.
  1413. FIXME: maybe in this case we should not even show?"
  1414. :group 'org-edit-structure
  1415. :version "24.1"
  1416. :type '(choice
  1417. (const :tag "Do not check" nil)
  1418. (const :tag "Throw error when trying to edit" error)
  1419. (const :tag "Unhide, but do not do the edit" show-and-error)
  1420. (const :tag "Show invisible part and do the edit" show)
  1421. (const :tag "Be smart and do the right thing" smart)))
  1422. (defcustom org-yank-folded-subtrees t
  1423. "Non-nil means when yanking subtrees, fold them.
  1424. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1425. it starts with a heading and all other headings in it are either children
  1426. or siblings, then fold all the subtrees. However, do this only if no
  1427. text after the yank would be swallowed into a folded tree by this action."
  1428. :group 'org-edit-structure
  1429. :type 'boolean)
  1430. (defcustom org-yank-adjusted-subtrees nil
  1431. "Non-nil means when yanking subtrees, adjust the level.
  1432. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1433. this function for details."
  1434. :group 'org-edit-structure
  1435. :type 'boolean)
  1436. (defcustom org-M-RET-may-split-line '((default . t))
  1437. "Non-nil means M-RET will split the line at the cursor position.
  1438. When nil, it will go to the end of the line before making a
  1439. new line.
  1440. You may also set this option in a different way for different
  1441. contexts. Valid contexts are:
  1442. headline when creating a new headline
  1443. item when creating a new item
  1444. table in a table field
  1445. default the value to be used for all contexts not explicitly
  1446. customized"
  1447. :group 'org-structure
  1448. :group 'org-table
  1449. :type '(choice
  1450. (const :tag "Always" t)
  1451. (const :tag "Never" nil)
  1452. (repeat :greedy t :tag "Individual contexts"
  1453. (cons
  1454. (choice :tag "Context"
  1455. (const headline)
  1456. (const item)
  1457. (const table)
  1458. (const default))
  1459. (boolean)))))
  1460. (defcustom org-insert-heading-respect-content nil
  1461. "Non-nil means insert new headings after the current subtree.
  1462. \\<org-mode-map>
  1463. When nil, the new heading is created directly after the current line.
  1464. The commands `\\[org-insert-heading-respect-content]' and \
  1465. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1466. for the duration of the command."
  1467. :group 'org-structure
  1468. :type 'boolean)
  1469. (defcustom org-blank-before-new-entry '((heading . auto)
  1470. (plain-list-item . auto))
  1471. "Should `org-insert-heading' leave a blank line before new heading/item?
  1472. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1473. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1474. which case Org will look at the surrounding headings/items and try to
  1475. make an intelligent decision whether to insert a blank line or not."
  1476. :group 'org-edit-structure
  1477. :type '(list
  1478. (cons (const heading)
  1479. (choice (const :tag "Never" nil)
  1480. (const :tag "Always" t)
  1481. (const :tag "Auto" auto)))
  1482. (cons (const plain-list-item)
  1483. (choice (const :tag "Never" nil)
  1484. (const :tag "Always" t)
  1485. (const :tag "Auto" auto)))))
  1486. (defcustom org-insert-heading-hook nil
  1487. "Hook being run after inserting a new heading."
  1488. :group 'org-edit-structure
  1489. :type 'hook)
  1490. (defgroup org-sparse-trees nil
  1491. "Options concerning sparse trees in Org mode."
  1492. :tag "Org Sparse Trees"
  1493. :group 'org-structure)
  1494. (defcustom org-highlight-sparse-tree-matches t
  1495. "Non-nil means highlight all matches that define a sparse tree.
  1496. The highlights will automatically disappear the next time the buffer is
  1497. changed by an edit command."
  1498. :group 'org-sparse-trees
  1499. :type 'boolean)
  1500. (defcustom org-remove-highlights-with-change t
  1501. "Non-nil means any change to the buffer will remove temporary highlights.
  1502. \\<org-mode-map>\
  1503. Such highlights are created by `org-occur' and `org-clock-display'.
  1504. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1505. to get rid of the highlights.
  1506. The highlights created by `org-latex-preview' always need
  1507. `\\[org-latex-preview]' to be removed."
  1508. :group 'org-sparse-trees
  1509. :group 'org-time
  1510. :type 'boolean)
  1511. (defcustom org-occur-case-fold-search t
  1512. "Non-nil means `org-occur' should be case-insensitive.
  1513. If set to `smart' the search will be case-insensitive only if it
  1514. doesn't specify any upper case character."
  1515. :group 'org-sparse-trees
  1516. :version "26.1"
  1517. :type '(choice
  1518. (const :tag "Case-sensitive" nil)
  1519. (const :tag "Case-insensitive" t)
  1520. (const :tag "Case-insensitive for lower case searches only" smart)))
  1521. (defcustom org-occur-hook '(org-first-headline-recenter)
  1522. "Hook that is run after `org-occur' has constructed a sparse tree.
  1523. This can be used to recenter the window to show as much of the structure
  1524. as possible."
  1525. :group 'org-sparse-trees
  1526. :type 'hook)
  1527. (defcustom org-self-insert-cluster-for-undo nil
  1528. "Non-nil means cluster self-insert commands for undo when possible.
  1529. If this is set, then, like in the Emacs command loop, 20 consecutive
  1530. characters will be undone together.
  1531. This is configurable, because there is some impact on typing performance."
  1532. :group 'org-table
  1533. :type 'boolean)
  1534. (defvaralias 'org-activate-links 'org-highlight-links)
  1535. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1536. "Types of links that should be highlighted in Org files.
  1537. This is a list of symbols, each one of them leading to the
  1538. highlighting of a certain link type.
  1539. You can still open links that are not highlighted.
  1540. In principle, it does not hurt to turn on highlighting for all
  1541. link types. There may be a small gain when turning off unused
  1542. link types. The types are:
  1543. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1544. angle Links in angular brackets that may contain whitespace like
  1545. <bbdb:Carsten Dominik>.
  1546. plain Plain links in normal text, no whitespace, like http://google.com.
  1547. radio Text that is matched by a radio target, see manual for details.
  1548. tag Tag settings in a headline (link to tag search).
  1549. date Time stamps (link to calendar).
  1550. footnote Footnote labels.
  1551. If you set this variable during an Emacs session, use `org-mode-restart'
  1552. in the Org buffer so that the change takes effect."
  1553. :group 'org-appearance
  1554. :type '(set :greedy t
  1555. (const :tag "Double bracket links" bracket)
  1556. (const :tag "Angular bracket links" angle)
  1557. (const :tag "Plain text links" plain)
  1558. (const :tag "Radio target matches" radio)
  1559. (const :tag "Tags" tag)
  1560. (const :tag "Timestamps" date)
  1561. (const :tag "Footnotes" footnote)))
  1562. (defcustom org-mark-ring-length 4
  1563. "Number of different positions to be recorded in the ring.
  1564. Changing this requires a restart of Emacs to work correctly."
  1565. :group 'org-link-follow
  1566. :type 'integer)
  1567. (defgroup org-todo nil
  1568. "Options concerning TODO items in Org mode."
  1569. :tag "Org TODO"
  1570. :group 'org)
  1571. (defgroup org-progress nil
  1572. "Options concerning Progress logging in Org mode."
  1573. :tag "Org Progress"
  1574. :group 'org-time)
  1575. (defvar org-todo-interpretation-widgets
  1576. '((:tag "Sequence (cycling hits every state)" sequence)
  1577. (:tag "Type (cycling directly to DONE)" type))
  1578. "The available interpretation symbols for customizing `org-todo-keywords'.
  1579. Interested libraries should add to this list.")
  1580. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1581. "List of TODO entry keyword sequences and their interpretation.
  1582. \\<org-mode-map>This is a list of sequences.
  1583. Each sequence starts with a symbol, either `sequence' or `type',
  1584. indicating if the keywords should be interpreted as a sequence of
  1585. action steps, or as different types of TODO items. The first
  1586. keywords are states requiring action - these states will select a headline
  1587. for inclusion into the global TODO list Org produces. If one of the
  1588. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1589. signify that no further action is necessary. If \"|\" is not found,
  1590. the last keyword is treated as the only DONE state of the sequence.
  1591. The command `\\[org-todo]' cycles an entry through these states, and one
  1592. additional state where no keyword is present. For details about this
  1593. cycling, see the manual.
  1594. TODO keywords and interpretation can also be set on a per-file basis with
  1595. the special #+SEQ_TODO and #+TYP_TODO lines.
  1596. Each keyword can optionally specify a character for fast state selection
  1597. \(in combination with the variable `org-use-fast-todo-selection')
  1598. and specifiers for state change logging, using the same syntax that
  1599. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1600. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1601. indicates to record a time stamp each time this state is selected.
  1602. Each keyword may also specify if a timestamp or a note should be
  1603. recorded when entering or leaving the state, by adding additional
  1604. characters in the parenthesis after the keyword. This looks like this:
  1605. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1606. record only the time of the state change. With X and Y being either
  1607. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1608. Y when leaving the state if and only if the *target* state does not
  1609. define X. You may omit any of the fast-selection key or X or /Y,
  1610. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1611. For backward compatibility, this variable may also be just a list
  1612. of keywords. In this case the interpretation (sequence or type) will be
  1613. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1614. :group 'org-todo
  1615. :group 'org-keywords
  1616. :type '(choice
  1617. (repeat :tag "Old syntax, just keywords"
  1618. (string :tag "Keyword"))
  1619. (repeat :tag "New syntax"
  1620. (cons
  1621. (choice
  1622. :tag "Interpretation"
  1623. ;;Quick and dirty way to see
  1624. ;;`org-todo-interpretations'. This takes the
  1625. ;;place of item arguments
  1626. :convert-widget
  1627. (lambda (widget)
  1628. (widget-put widget
  1629. :args (mapcar
  1630. (lambda (x)
  1631. (widget-convert
  1632. (cons 'const x)))
  1633. org-todo-interpretation-widgets))
  1634. widget))
  1635. (repeat
  1636. (string :tag "Keyword"))))))
  1637. (defvar-local org-todo-keywords-1 nil
  1638. "All TODO and DONE keywords active in a buffer.")
  1639. (defvar org-todo-keywords-for-agenda nil)
  1640. (defvar org-done-keywords-for-agenda nil)
  1641. (defvar org-todo-keyword-alist-for-agenda nil)
  1642. (defvar org-tag-alist-for-agenda nil
  1643. "Alist of all tags from all agenda files.")
  1644. (defvar org-tag-groups-alist-for-agenda nil
  1645. "Alist of all groups tags from all current agenda files.")
  1646. (defvar-local org-tag-groups-alist nil)
  1647. (defvar org-agenda-contributing-files nil)
  1648. (defvar-local org-current-tag-alist nil
  1649. "Alist of all tag groups in current buffer.
  1650. This variable takes into consideration `org-tag-alist',
  1651. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1652. (defvar-local org-not-done-keywords nil)
  1653. (defvar-local org-done-keywords nil)
  1654. (defvar-local org-todo-heads nil)
  1655. (defvar-local org-todo-sets nil)
  1656. (defvar-local org-todo-log-states nil)
  1657. (defvar-local org-todo-kwd-alist nil)
  1658. (defvar-local org-todo-key-alist nil)
  1659. (defvar-local org-todo-key-trigger nil)
  1660. (defcustom org-todo-interpretation 'sequence
  1661. "Controls how TODO keywords are interpreted.
  1662. This variable is in principle obsolete and is only used for
  1663. backward compatibility, if the interpretation of todo keywords is
  1664. not given already in `org-todo-keywords'. See that variable for
  1665. more information."
  1666. :group 'org-todo
  1667. :group 'org-keywords
  1668. :type '(choice (const sequence)
  1669. (const type)))
  1670. (defcustom org-use-fast-todo-selection 'auto
  1671. "\\<org-mode-map>\
  1672. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1673. This variable describes if and under what circumstances the cycling
  1674. mechanism for TODO keywords will be replaced by a single-key, direct
  1675. selection scheme, where the choices are displayed in a little window.
  1676. When nil, fast selection is never used. This means that the command
  1677. will always switch to the next state.
  1678. When it is the symbol `auto', fast selection is whenever selection
  1679. keys have been defined.
  1680. `expert' is like `auto', but no special window with the keyword
  1681. will be shown, choices will only be listed in the prompt.
  1682. In all cases, the special interface is only used if access keys have
  1683. actually been assigned by the user, i.e. if keywords in the configuration
  1684. are followed by a letter in parenthesis, like TODO(t)."
  1685. :group 'org-todo
  1686. :set (lambda (var val)
  1687. (cond
  1688. ((eq var t) (set var 'auto))
  1689. ((eq var 'prefix) (set var nil))
  1690. (t (set var val))))
  1691. :type '(choice
  1692. (const :tag "Never" nil)
  1693. (const :tag "Automatically, when key letter have been defined" auto)
  1694. (const :tag "Automatically, but don't show the selection window" expert)))
  1695. (defcustom org-provide-todo-statistics t
  1696. "Non-nil means update todo statistics after insert and toggle.
  1697. ALL-HEADLINES means update todo statistics by including headlines
  1698. with no TODO keyword as well, counting them as not done.
  1699. A list of TODO keywords means the same, but skip keywords that are
  1700. not in this list.
  1701. When set to a list of two lists, the first list contains keywords
  1702. to consider as TODO keywords, the second list contains keywords
  1703. to consider as DONE keywords.
  1704. When this is set, todo statistics is updated in the parent of the
  1705. current entry each time a todo state is changed."
  1706. :group 'org-todo
  1707. :type '(choice
  1708. (const :tag "Yes, only for TODO entries" t)
  1709. (const :tag "Yes, including all entries" all-headlines)
  1710. (repeat :tag "Yes, for TODOs in this list"
  1711. (string :tag "TODO keyword"))
  1712. (list :tag "Yes, for TODOs and DONEs in these lists"
  1713. (repeat (string :tag "TODO keyword"))
  1714. (repeat (string :tag "DONE keyword")))
  1715. (other :tag "No TODO statistics" nil)))
  1716. (defcustom org-hierarchical-todo-statistics t
  1717. "Non-nil means TODO statistics covers just direct children.
  1718. When nil, all entries in the subtree are considered.
  1719. This has only an effect if `org-provide-todo-statistics' is set.
  1720. To set this to nil for only a single subtree, use a COOKIE_DATA
  1721. property and include the word \"recursive\" into the value."
  1722. :group 'org-todo
  1723. :type 'boolean)
  1724. (defcustom org-after-todo-state-change-hook nil
  1725. "Hook which is run after the state of a TODO item was changed.
  1726. The new state (a string with a TODO keyword, or nil) is available in the
  1727. Lisp variable `org-state'."
  1728. :group 'org-todo
  1729. :type 'hook)
  1730. (defvar org-blocker-hook nil
  1731. "Hook for functions that are allowed to block a state change.
  1732. Functions in this hook should not modify the buffer.
  1733. Each function gets as its single argument a property list,
  1734. see `org-trigger-hook' for more information about this list.
  1735. If any of the functions in this hook returns nil, the state change
  1736. is blocked.")
  1737. (defvar org-trigger-hook nil
  1738. "Hook for functions that are triggered by a state change.
  1739. Each function gets as its single argument a property list with at
  1740. least the following elements:
  1741. (:type type-of-change :position pos-at-entry-start
  1742. :from old-state :to new-state)
  1743. Depending on the type, more properties may be present.
  1744. This mechanism is currently implemented for:
  1745. TODO state changes
  1746. ------------------
  1747. :type todo-state-change
  1748. :from previous state (keyword as a string), or nil, or a symbol
  1749. `todo' or `done', to indicate the general type of state.
  1750. :to new state, like in :from")
  1751. (defcustom org-enforce-todo-dependencies nil
  1752. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1753. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1754. be blocked if any prior sibling is not yet done.
  1755. Finally, if the parent is blocked because of ordered siblings of its own,
  1756. the child will also be blocked."
  1757. :set (lambda (var val)
  1758. (set var val)
  1759. (if val
  1760. (add-hook 'org-blocker-hook
  1761. 'org-block-todo-from-children-or-siblings-or-parent)
  1762. (remove-hook 'org-blocker-hook
  1763. 'org-block-todo-from-children-or-siblings-or-parent)))
  1764. :group 'org-todo
  1765. :type 'boolean)
  1766. (defcustom org-enforce-todo-checkbox-dependencies nil
  1767. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1768. When this is nil, checkboxes have no influence on switching TODO states.
  1769. When non-nil, you first need to check off all check boxes before the TODO
  1770. entry can be switched to DONE.
  1771. This variable needs to be set before org.el is loaded, and you need to
  1772. restart Emacs after a change to make the change effective. The only way
  1773. to change it while Emacs is running is through the customize interface."
  1774. :set (lambda (var val)
  1775. (set var val)
  1776. (if val
  1777. (add-hook 'org-blocker-hook
  1778. 'org-block-todo-from-checkboxes)
  1779. (remove-hook 'org-blocker-hook
  1780. 'org-block-todo-from-checkboxes)))
  1781. :group 'org-todo
  1782. :type 'boolean)
  1783. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1784. "Non-nil means inserting a TODO heading is treated as state change.
  1785. So when the command `\\[org-insert-todo-heading]' is used, state change
  1786. logging will apply if appropriate. When nil, the new TODO item will
  1787. be inserted directly, and no logging will take place."
  1788. :group 'org-todo
  1789. :type 'boolean)
  1790. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1791. "Non-nil means switching TODO states with S-cursor counts as state change.
  1792. This is the default behavior. However, setting this to nil allows a
  1793. convenient way to select a TODO state and bypass any logging associated
  1794. with that."
  1795. :group 'org-todo
  1796. :type 'boolean)
  1797. (defcustom org-todo-state-tags-triggers nil
  1798. "Tag changes that should be triggered by TODO state changes.
  1799. This is a list. Each entry is
  1800. (state-change (tag . flag) .......)
  1801. State-change can be a string with a state, and empty string to indicate the
  1802. state that has no TODO keyword, or it can be one of the symbols `todo'
  1803. or `done', meaning any not-done or done state, respectively."
  1804. :group 'org-todo
  1805. :group 'org-tags
  1806. :type '(repeat
  1807. (cons (choice :tag "When changing to"
  1808. (const :tag "Not-done state" todo)
  1809. (const :tag "Done state" done)
  1810. (string :tag "State"))
  1811. (repeat
  1812. (cons :tag "Tag action"
  1813. (string :tag "Tag")
  1814. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1815. (defcustom org-log-done nil
  1816. "Information to record when a task moves to the DONE state.
  1817. Possible values are:
  1818. nil Don't add anything, just change the keyword
  1819. time Add a time stamp to the task
  1820. note Prompt for a note and add it with template `org-log-note-headings'
  1821. This option can also be set with on a per-file-basis with
  1822. #+STARTUP: nologdone
  1823. #+STARTUP: logdone
  1824. #+STARTUP: lognotedone
  1825. You can have local logging settings for a subtree by setting the LOGGING
  1826. property to one or more of these keywords."
  1827. :group 'org-todo
  1828. :group 'org-progress
  1829. :type '(choice
  1830. (const :tag "No logging" nil)
  1831. (const :tag "Record CLOSED timestamp" time)
  1832. (const :tag "Record CLOSED timestamp with note." note)))
  1833. ;; Normalize old uses of org-log-done.
  1834. (cond
  1835. ((eq org-log-done t) (setq org-log-done 'time))
  1836. ((and (listp org-log-done) (memq 'done org-log-done))
  1837. (setq org-log-done 'note)))
  1838. (defcustom org-log-reschedule nil
  1839. "Information to record when the scheduling date of a task is modified.
  1840. Possible values are:
  1841. nil Don't add anything, just change the date
  1842. time Add a time stamp to the task
  1843. note Prompt for a note and add it with template `org-log-note-headings'
  1844. This option can also be set with on a per-file-basis with
  1845. #+STARTUP: nologreschedule
  1846. #+STARTUP: logreschedule
  1847. #+STARTUP: lognotereschedule
  1848. You can have local logging settings for a subtree by setting the LOGGING
  1849. property to one or more of these keywords.
  1850. This variable has an effect when calling `org-schedule' or
  1851. `org-agenda-schedule' only."
  1852. :group 'org-todo
  1853. :group 'org-progress
  1854. :type '(choice
  1855. (const :tag "No logging" nil)
  1856. (const :tag "Record timestamp" time)
  1857. (const :tag "Record timestamp with note" note)))
  1858. (defcustom org-log-redeadline nil
  1859. "Information to record when the deadline date of a task is modified.
  1860. Possible values are:
  1861. nil Don't add anything, just change the date
  1862. time Add a time stamp to the task
  1863. note Prompt for a note and add it with template `org-log-note-headings'
  1864. This option can also be set with on a per-file-basis with
  1865. #+STARTUP: nologredeadline
  1866. #+STARTUP: logredeadline
  1867. #+STARTUP: lognoteredeadline
  1868. You can have local logging settings for a subtree by setting the LOGGING
  1869. property to one or more of these keywords.
  1870. This variable has an effect when calling `org-deadline' or
  1871. `org-agenda-deadline' only."
  1872. :group 'org-todo
  1873. :group 'org-progress
  1874. :type '(choice
  1875. (const :tag "No logging" nil)
  1876. (const :tag "Record timestamp" time)
  1877. (const :tag "Record timestamp with note." note)))
  1878. (defcustom org-log-note-clock-out nil
  1879. "Non-nil means record a note when clocking out of an item.
  1880. This can also be configured on a per-file basis by adding one of
  1881. the following lines anywhere in the buffer:
  1882. #+STARTUP: lognoteclock-out
  1883. #+STARTUP: nolognoteclock-out"
  1884. :group 'org-todo
  1885. :group 'org-progress
  1886. :type 'boolean)
  1887. (defcustom org-log-done-with-time t
  1888. "Non-nil means the CLOSED time stamp will contain date and time.
  1889. When nil, only the date will be recorded."
  1890. :group 'org-progress
  1891. :type 'boolean)
  1892. (defcustom org-log-note-headings
  1893. '((done . "CLOSING NOTE %t")
  1894. (state . "State %-12s from %-12S %t")
  1895. (note . "Note taken on %t")
  1896. (reschedule . "Rescheduled from %S on %t")
  1897. (delschedule . "Not scheduled, was %S on %t")
  1898. (redeadline . "New deadline from %S on %t")
  1899. (deldeadline . "Removed deadline, was %S on %t")
  1900. (refile . "Refiled on %t")
  1901. (clock-out . ""))
  1902. "Headings for notes added to entries.
  1903. The value is an alist, with the car being a symbol indicating the
  1904. note context, and the cdr is the heading to be used. The heading
  1905. may also be the empty string. The following placeholders can be
  1906. used:
  1907. %t a time stamp.
  1908. %T an active time stamp instead the default inactive one
  1909. %d a short-format time stamp.
  1910. %D an active short-format time stamp.
  1911. %s the new TODO state or time stamp (inactive), in double quotes.
  1912. %S the old TODO state or time stamp (inactive), in double quotes.
  1913. %u the user name.
  1914. %U full user name.
  1915. In fact, it is not a good idea to change the `state' entry,
  1916. because Agenda Log mode depends on the format of these entries."
  1917. :group 'org-todo
  1918. :group 'org-progress
  1919. :type '(list :greedy t
  1920. (cons (const :tag "Heading when closing an item" done) string)
  1921. (cons (const :tag
  1922. "Heading when changing todo state (todo sequence only)"
  1923. state) string)
  1924. (cons (const :tag "Heading when just taking a note" note) string)
  1925. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1926. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1927. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1928. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1929. (cons (const :tag "Heading when refiling" refile) string)
  1930. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1931. (unless (assq 'note org-log-note-headings)
  1932. (push '(note . "%t") org-log-note-headings))
  1933. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1934. (defcustom org-log-into-drawer nil
  1935. "Non-nil means insert state change notes and time stamps into a drawer.
  1936. When nil, state changes notes will be inserted after the headline and
  1937. any scheduling and clock lines, but not inside a drawer.
  1938. The value of this variable should be the name of the drawer to use.
  1939. LOGBOOK is proposed as the default drawer for this purpose, you can
  1940. also set this to a string to define the drawer of your choice.
  1941. A value of t is also allowed, representing \"LOGBOOK\".
  1942. A value of t or nil can also be set with on a per-file-basis with
  1943. #+STARTUP: logdrawer
  1944. #+STARTUP: nologdrawer
  1945. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1946. will be ignored.
  1947. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1948. a subtree.
  1949. Do not check directly this variable in a Lisp program. Call
  1950. function `org-log-into-drawer' instead."
  1951. :group 'org-todo
  1952. :group 'org-progress
  1953. :type '(choice
  1954. (const :tag "Not into a drawer" nil)
  1955. (const :tag "LOGBOOK" t)
  1956. (string :tag "Other")))
  1957. (defun org-log-into-drawer ()
  1958. "Name of the log drawer, as a string, or nil.
  1959. This is the value of `org-log-into-drawer'. However, if the
  1960. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1961. be used instead of the default value."
  1962. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1963. (cond ((equal p "nil") nil)
  1964. ((equal p "t") "LOGBOOK")
  1965. ((stringp p) p)
  1966. (p "LOGBOOK")
  1967. ((stringp org-log-into-drawer) org-log-into-drawer)
  1968. (org-log-into-drawer "LOGBOOK"))))
  1969. (defcustom org-log-state-notes-insert-after-drawers nil
  1970. "Non-nil means insert state change notes after any drawers in entry.
  1971. Only the drawers that *immediately* follow the headline and the
  1972. deadline/scheduled line are skipped.
  1973. When nil, insert notes right after the heading and perhaps the line
  1974. with deadline/scheduling if present.
  1975. This variable will have no effect if `org-log-into-drawer' is
  1976. set."
  1977. :group 'org-todo
  1978. :group 'org-progress
  1979. :type 'boolean)
  1980. (defcustom org-log-states-order-reversed t
  1981. "Non-nil means the latest state note will be directly after heading.
  1982. When nil, the state change notes will be ordered according to time.
  1983. This option can also be set with on a per-file-basis with
  1984. #+STARTUP: logstatesreversed
  1985. #+STARTUP: nologstatesreversed"
  1986. :group 'org-todo
  1987. :group 'org-progress
  1988. :type 'boolean)
  1989. (defcustom org-todo-repeat-to-state nil
  1990. "The TODO state to which a repeater should return the repeating task.
  1991. By default this is the first task of a TODO sequence or the
  1992. previous state of a TYPE_TODO set. But you can specify to use
  1993. the previous state in a TODO sequence or a string.
  1994. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1995. entry, which has precedence over this option."
  1996. :group 'org-todo
  1997. :version "24.1"
  1998. :type '(choice (const :tag "Use the previous TODO state" t)
  1999. (const :tag "Use the head of the TODO sequence" nil)
  2000. (string :tag "Use a specific TODO state")))
  2001. (defcustom org-log-repeat 'time
  2002. "Non-nil means record moving through the DONE state when triggering repeat.
  2003. An auto-repeating task is immediately switched back to TODO when
  2004. marked DONE. If you are not logging state changes (by adding \"@\"
  2005. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2006. record a closing note, there will be no record of the task moving
  2007. through DONE. This variable forces taking a note anyway.
  2008. nil Don't force a record
  2009. time Record a time stamp
  2010. note Prompt for a note and add it with template `org-log-note-headings'
  2011. This option can also be set with on a per-file-basis with
  2012. #+STARTUP: nologrepeat
  2013. #+STARTUP: logrepeat
  2014. #+STARTUP: lognoterepeat
  2015. You can have local logging settings for a subtree by setting the LOGGING
  2016. property to one or more of these keywords."
  2017. :group 'org-todo
  2018. :group 'org-progress
  2019. :type '(choice
  2020. (const :tag "Don't force a record" nil)
  2021. (const :tag "Force recording the DONE state" time)
  2022. (const :tag "Force recording a note with the DONE state" note)))
  2023. (defcustom org-todo-repeat-hook nil
  2024. "Hook that is run after a task has been repeated."
  2025. :package-version '(Org . "9.2")
  2026. :group 'org-todo
  2027. :type 'hook)
  2028. (defgroup org-priorities nil
  2029. "Priorities in Org mode."
  2030. :tag "Org Priorities"
  2031. :group 'org-todo)
  2032. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2033. (defcustom org-priority-enable-commands t
  2034. "Non-nil means priority commands are active.
  2035. When nil, these commands will be disabled, so that you never accidentally
  2036. set a priority."
  2037. :group 'org-priorities
  2038. :type 'boolean)
  2039. (defvaralias 'org-highest-priority 'org-priority-highest)
  2040. (defcustom org-priority-highest ?A
  2041. "The highest priority of TODO items.
  2042. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2043. Must be smaller than `org-priority-lowest'."
  2044. :group 'org-priorities
  2045. :type '(choice
  2046. (character :tag "Character")
  2047. (integer :tag "Integer (< 65)")))
  2048. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2049. (defcustom org-priority-lowest ?C
  2050. "The lowest priority of TODO items.
  2051. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2052. Must be higher than `org-priority-highest'."
  2053. :group 'org-priorities
  2054. :type '(choice
  2055. (character :tag "Character")
  2056. (integer :tag "Integer (< 65)")))
  2057. (defvaralias 'org-default-priority 'org-priority-default)
  2058. (defcustom org-priority-default ?B
  2059. "The default priority of TODO items.
  2060. This is the priority an item gets if no explicit priority is given.
  2061. When starting to cycle on an empty priority the first step in the cycle
  2062. depends on `org-priority-start-cycle-with-default'. The resulting first
  2063. step priority must not exceed the range from `org-priority-highest' to
  2064. `org-priority-lowest' which means that `org-priority-default' has to be
  2065. in this range exclusive or inclusive to the range boundaries. Else the
  2066. first step refuses to set the default and the second will fall back on
  2067. (depending on the command used) the highest or lowest priority."
  2068. :group 'org-priorities
  2069. :type '(choice
  2070. (character :tag "Character")
  2071. (integer :tag "Integer (< 65)")))
  2072. (defcustom org-priority-start-cycle-with-default t
  2073. "Non-nil means start with default priority when starting to cycle.
  2074. When this is nil, the first step in the cycle will be (depending on the
  2075. command used) one higher or lower than the default priority.
  2076. See also `org-priority-default'."
  2077. :group 'org-priorities
  2078. :type 'boolean)
  2079. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2080. (defcustom org-priority-get-priority-function nil
  2081. "Function to extract the priority from a string.
  2082. The string is normally the headline. If this is nil, Org
  2083. computes the priority from the priority cookie like [#A] in the
  2084. headline. It returns an integer, increasing by 1000 for each
  2085. priority level.
  2086. The user can set a different function here, which should take a
  2087. string as an argument and return the numeric priority."
  2088. :group 'org-priorities
  2089. :version "24.1"
  2090. :type '(choice
  2091. (const nil)
  2092. (function)))
  2093. (defgroup org-time nil
  2094. "Options concerning time stamps and deadlines in Org mode."
  2095. :tag "Org Time"
  2096. :group 'org)
  2097. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2098. "Number of minutes to round time stamps to.
  2099. \\<org-mode-map>\
  2100. These are two values, the first applies when first creating a time stamp.
  2101. The second applies when changing it with the commands `S-up' and `S-down'.
  2102. When changing the time stamp, this means that it will change in steps
  2103. of N minutes, as given by the second value.
  2104. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2105. numbers should be factors of 60, so for example 5, 10, 15.
  2106. When this is larger than 1, you can still force an exact time stamp by using
  2107. a double prefix argument to a time stamp command like \
  2108. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2109. and by using a prefix arg to `S-up/down' to specify the exact number
  2110. of minutes to shift."
  2111. :group 'org-time
  2112. :get (lambda (var) ; Make sure both elements are there
  2113. (if (integerp (default-value var))
  2114. (list (default-value var) 5)
  2115. (default-value var)))
  2116. :type '(list
  2117. (integer :tag "when inserting times")
  2118. (integer :tag "when modifying times")))
  2119. ;; Normalize old customizations of this variable.
  2120. (when (integerp org-time-stamp-rounding-minutes)
  2121. (setq org-time-stamp-rounding-minutes
  2122. (list org-time-stamp-rounding-minutes
  2123. org-time-stamp-rounding-minutes)))
  2124. (defcustom org-display-custom-times nil
  2125. "Non-nil means overlay custom formats over all time stamps.
  2126. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2127. To turn this on on a per-file basis, insert anywhere in the file:
  2128. #+STARTUP: customtime"
  2129. :group 'org-time
  2130. :set 'set-default
  2131. :type 'sexp)
  2132. (make-variable-buffer-local 'org-display-custom-times)
  2133. (defcustom org-time-stamp-custom-formats
  2134. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2135. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2136. These are overlaid over the default ISO format if the variable
  2137. `org-display-custom-times' is set. Time like %H:%M should be at the
  2138. end of the second format. The custom formats are also honored by export
  2139. commands, if custom time display is turned on at the time of export."
  2140. :group 'org-time
  2141. :type 'sexp)
  2142. (defun org-time-stamp-format (&optional long inactive)
  2143. "Get the right format for a time string."
  2144. (let ((f (if long (cdr org-time-stamp-formats)
  2145. (car org-time-stamp-formats))))
  2146. (if inactive
  2147. (concat "[" (substring f 1 -1) "]")
  2148. f)))
  2149. (defcustom org-deadline-warning-days 14
  2150. "Number of days before expiration during which a deadline becomes active.
  2151. This variable governs the display in sparse trees and in the agenda.
  2152. When 0 or negative, it means use this number (the absolute value of it)
  2153. even if a deadline has a different individual lead time specified.
  2154. Custom commands can set this variable in the options section."
  2155. :group 'org-time
  2156. :group 'org-agenda-daily/weekly
  2157. :type 'integer)
  2158. (defcustom org-scheduled-delay-days 0
  2159. "Number of days before a scheduled item becomes active.
  2160. This variable governs the display in sparse trees and in the agenda.
  2161. The default value (i.e. 0) means: don't delay scheduled item.
  2162. When negative, it means use this number (the absolute value of it)
  2163. even if a scheduled item has a different individual delay time
  2164. specified.
  2165. Custom commands can set this variable in the options section."
  2166. :group 'org-time
  2167. :group 'org-agenda-daily/weekly
  2168. :version "24.4"
  2169. :package-version '(Org . "8.0")
  2170. :type 'integer)
  2171. (defcustom org-read-date-prefer-future t
  2172. "Non-nil means assume future for incomplete date input from user.
  2173. This affects the following situations:
  2174. 1. The user gives a month but not a year.
  2175. For example, if it is April and you enter \"feb 2\", this will be read
  2176. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2177. 2. The user gives a day, but no month.
  2178. For example, if today is the 15th, and you enter \"3\", Org will read
  2179. this as the third of *next* month. However, if you enter \"17\",
  2180. it will be considered as *this* month.
  2181. If you set this variable to the symbol `time', then also the following
  2182. will work:
  2183. 3. If the user gives a time.
  2184. If the time is before now, it will be interpreted as tomorrow.
  2185. Currently none of this works for ISO week specifications.
  2186. When this option is nil, the current day, month and year will always be
  2187. used as defaults.
  2188. See also `org-agenda-jump-prefer-future'."
  2189. :group 'org-time
  2190. :type '(choice
  2191. (const :tag "Never" nil)
  2192. (const :tag "Check month and day" t)
  2193. (const :tag "Check month, day, and time" time)))
  2194. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2195. "Should the agenda jump command prefer the future for incomplete dates?
  2196. The default is to do the same as configured in `org-read-date-prefer-future'.
  2197. But you can also set a deviating value here.
  2198. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2199. :group 'org-agenda
  2200. :group 'org-time
  2201. :version "24.1"
  2202. :type '(choice
  2203. (const :tag "Use org-read-date-prefer-future"
  2204. org-read-date-prefer-future)
  2205. (const :tag "Never" nil)
  2206. (const :tag "Always" t)))
  2207. (defcustom org-read-date-force-compatible-dates t
  2208. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2209. Depending on the system Emacs is running on, certain dates cannot
  2210. be represented with the type used internally to represent time.
  2211. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2212. correctly. Some systems allow for earlier dates, some for later,
  2213. some for both. One way to find out is to insert any date into an
  2214. Org buffer, putting the cursor on the year and hitting S-up and
  2215. S-down to test the range.
  2216. When this variable is set to t, the date/time prompt will not let
  2217. you specify dates outside the 1970-2037 range, so it is certain that
  2218. these dates will work in whatever version of Emacs you are
  2219. running, and also that you can move a file from one Emacs implementation
  2220. to another. Whenever Org is forcing the year for you, it will display
  2221. a message and beep.
  2222. When this variable is nil, Org will check if the date is
  2223. representable in the specific Emacs implementation you are using.
  2224. If not, it will force a year, usually the current year, and beep
  2225. to remind you. Currently this setting is not recommended because
  2226. the likelihood that you will open your Org files in an Emacs that
  2227. has limited date range is not negligible.
  2228. A workaround for this problem is to use diary sexp dates for time
  2229. stamps outside of this range."
  2230. :group 'org-time
  2231. :version "24.1"
  2232. :type 'boolean)
  2233. (defcustom org-read-date-display-live t
  2234. "Non-nil means display current interpretation of date prompt live.
  2235. This display will be in an overlay, in the minibuffer."
  2236. :group 'org-time
  2237. :type 'boolean)
  2238. (defvaralias 'org-popup-calendar-for-date-prompt
  2239. 'org-read-date-popup-calendar)
  2240. (defcustom org-read-date-popup-calendar t
  2241. "Non-nil means pop up a calendar when prompting for a date.
  2242. In the calendar, the date can be selected with mouse-1. However, the
  2243. minibuffer will also be active, and you can simply enter the date as well.
  2244. When nil, only the minibuffer will be available."
  2245. :group 'org-time
  2246. :type 'boolean)
  2247. (defcustom org-extend-today-until 0
  2248. "The hour when your day really ends. Must be an integer.
  2249. This has influence for the following applications:
  2250. - When switching the agenda to \"today\". If it is still earlier than
  2251. the time given here, the day recognized as TODAY is actually yesterday.
  2252. - When a date is read from the user and it is still before the time given
  2253. here, the current date and time will be assumed to be yesterday, 23:59.
  2254. Also, timestamps inserted in capture templates follow this rule.
  2255. IMPORTANT: This is a feature whose implementation is and likely will
  2256. remain incomplete. Really, it is only here because past midnight seems to
  2257. be the favorite working time of John Wiegley :-)"
  2258. :group 'org-time
  2259. :type 'integer)
  2260. (defcustom org-use-effective-time nil
  2261. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2262. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2263. \"effective time\" of any timestamps between midnight and 8am will be
  2264. 23:59 of the previous day."
  2265. :group 'org-time
  2266. :version "24.1"
  2267. :type 'boolean)
  2268. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2269. "When non-nil, use the last clock out time for `org-todo'.
  2270. Note that this option has precedence over the combined use of
  2271. `org-use-effective-time' and `org-extend-today-until'."
  2272. :group 'org-time
  2273. :version "24.4"
  2274. :package-version '(Org . "8.0")
  2275. :type 'boolean)
  2276. (defcustom org-edit-timestamp-down-means-later nil
  2277. "Non-nil means S-down will increase the time in a time stamp.
  2278. When nil, S-up will increase."
  2279. :group 'org-time
  2280. :type 'boolean)
  2281. (defcustom org-calendar-follow-timestamp-change t
  2282. "Non-nil means make the calendar window follow timestamp changes.
  2283. When a timestamp is modified and the calendar window is visible, it will be
  2284. moved to the new date."
  2285. :group 'org-time
  2286. :type 'boolean)
  2287. (defgroup org-tags nil
  2288. "Options concerning tags in Org mode."
  2289. :tag "Org Tags"
  2290. :group 'org)
  2291. (defcustom org-tag-alist nil
  2292. "Default tags available in Org files.
  2293. The value of this variable is an alist. Associations either:
  2294. (TAG)
  2295. (TAG . SELECT)
  2296. (SPECIAL)
  2297. where TAG is a tag as a string, SELECT is character, used to
  2298. select that tag through the fast tag selection interface, and
  2299. SPECIAL is one of the following keywords: `:startgroup',
  2300. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2301. `:newline'. These keywords are used to define a hierarchy of
  2302. tags. See manual for details.
  2303. When this variable is nil, Org mode bases tag input on what is
  2304. already in the buffer. The value can be overridden locally by
  2305. using a TAGS keyword, e.g.,
  2306. #+TAGS: tag1 tag2
  2307. See also `org-tag-persistent-alist' to sidestep this behavior."
  2308. :group 'org-tags
  2309. :type '(repeat
  2310. (choice
  2311. (cons :tag "Tag with key"
  2312. (string :tag "Tag name")
  2313. (character :tag "Access char"))
  2314. (list :tag "Tag" (string :tag "Tag name"))
  2315. (const :tag "Start radio group" (:startgroup))
  2316. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2317. (const :tag "Group tags delimiter" (:grouptags))
  2318. (const :tag "End radio group" (:endgroup))
  2319. (const :tag "End tag group, non distinct" (:endgrouptag))
  2320. (const :tag "New line" (:newline)))))
  2321. (defcustom org-tag-persistent-alist nil
  2322. "Tags always available in Org files.
  2323. The value of this variable is an alist. Associations either:
  2324. (TAG)
  2325. (TAG . SELECT)
  2326. (SPECIAL)
  2327. where TAG is a tag as a string, SELECT is a character, used to
  2328. select that tag through the fast tag selection interface, and
  2329. SPECIAL is one of the following keywords: `:startgroup',
  2330. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2331. `:newline'. These keywords are used to define a hierarchy of
  2332. tags. See manual for details.
  2333. Unlike to `org-tag-alist', tags defined in this variable do not
  2334. depend on a local TAGS keyword. Instead, to disable these tags
  2335. on a per-file basis, insert anywhere in the file:
  2336. #+STARTUP: noptag"
  2337. :group 'org-tags
  2338. :type '(repeat
  2339. (choice
  2340. (cons :tag "Tag with key"
  2341. (string :tag "Tag name")
  2342. (character :tag "Access char"))
  2343. (list :tag "Tag" (string :tag "Tag name"))
  2344. (const :tag "Start radio group" (:startgroup))
  2345. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2346. (const :tag "Group tags delimiter" (:grouptags))
  2347. (const :tag "End radio group" (:endgroup))
  2348. (const :tag "End tag group, non distinct" (:endgrouptag))
  2349. (const :tag "New line" (:newline)))))
  2350. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2351. "If non-nil, always offer completion for all tags of all agenda files.
  2352. Setting this variable locally allows for dynamic generation of tag
  2353. completions in capture buffers.
  2354. (add-hook \\='org-capture-mode-hook
  2355. (lambda ()
  2356. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2357. :group 'org-tags
  2358. :version "24.1"
  2359. :type 'boolean)
  2360. (defvar org-file-tags nil
  2361. "List of tags that can be inherited by all entries in the file.
  2362. The tags will be inherited if the variable `org-use-tag-inheritance'
  2363. says they should be.
  2364. This variable is populated from #+FILETAGS lines.")
  2365. (defcustom org-use-fast-tag-selection 'auto
  2366. "Non-nil means use fast tag selection scheme.
  2367. This is a special interface to select and deselect tags with single keys.
  2368. When nil, fast selection is never used.
  2369. When the symbol `auto', fast selection is used if and only if selection
  2370. characters for tags have been configured, either through the variable
  2371. `org-tag-alist' or through a #+TAGS line in the buffer.
  2372. When t, fast selection is always used and selection keys are assigned
  2373. automatically if necessary."
  2374. :group 'org-tags
  2375. :type '(choice
  2376. (const :tag "Always" t)
  2377. (const :tag "Never" nil)
  2378. (const :tag "When selection characters are configured" auto)))
  2379. (defcustom org-fast-tag-selection-single-key nil
  2380. "Non-nil means fast tag selection exits after first change.
  2381. When nil, you have to press RET to exit it.
  2382. During fast tag selection, you can toggle this flag with `C-c'.
  2383. This variable can also have the value `expert'. In this case, the window
  2384. displaying the tags menu is not even shown, until you press C-c again."
  2385. :group 'org-tags
  2386. :type '(choice
  2387. (const :tag "No" nil)
  2388. (const :tag "Yes" t)
  2389. (const :tag "Expert" expert)))
  2390. (defvar org-fast-tag-selection-include-todo nil
  2391. "Non-nil means fast tags selection interface will also offer TODO states.
  2392. This is an undocumented feature, you should not rely on it.")
  2393. (defcustom org-tags-column -77
  2394. "The column to which tags should be indented in a headline.
  2395. If this number is positive, it specifies the column. If it is negative,
  2396. it means that the tags should be flushright to that column. For example,
  2397. -80 works well for a normal 80 character screen.
  2398. When 0, place tags directly after headline text, with only one space in
  2399. between."
  2400. :group 'org-tags
  2401. :type 'integer)
  2402. (defcustom org-auto-align-tags t
  2403. "Non-nil keeps tags aligned when modifying headlines.
  2404. Some operations (i.e. demoting) change the length of a headline and
  2405. therefore shift the tags around. With this option turned on, after
  2406. each such operation the tags are again aligned to `org-tags-column'."
  2407. :group 'org-tags
  2408. :type 'boolean)
  2409. (defcustom org-use-tag-inheritance t
  2410. "Non-nil means tags in levels apply also for sublevels.
  2411. When nil, only the tags directly given in a specific line apply there.
  2412. This may also be a list of tags that should be inherited, or a regexp that
  2413. matches tags that should be inherited. Additional control is possible
  2414. with the variable `org-tags-exclude-from-inheritance' which gives an
  2415. explicit list of tags to be excluded from inheritance, even if the value of
  2416. `org-use-tag-inheritance' would select it for inheritance.
  2417. If this option is t, a match early-on in a tree can lead to a large
  2418. number of matches in the subtree when constructing the agenda or creating
  2419. a sparse tree. If you only want to see the first match in a tree during
  2420. a search, check out the variable `org-tags-match-list-sublevels'."
  2421. :group 'org-tags
  2422. :type '(choice
  2423. (const :tag "Not" nil)
  2424. (const :tag "Always" t)
  2425. (repeat :tag "Specific tags" (string :tag "Tag"))
  2426. (regexp :tag "Tags matched by regexp")))
  2427. (defcustom org-tags-exclude-from-inheritance nil
  2428. "List of tags that should never be inherited.
  2429. This is a way to exclude a few tags from inheritance. For way to do
  2430. the opposite, to actively allow inheritance for selected tags,
  2431. see the variable `org-use-tag-inheritance'."
  2432. :group 'org-tags
  2433. :type '(repeat (string :tag "Tag")))
  2434. (defun org-tag-inherit-p (tag)
  2435. "Check if TAG is one that should be inherited."
  2436. (cond
  2437. ((member tag org-tags-exclude-from-inheritance) nil)
  2438. ((eq org-use-tag-inheritance t) t)
  2439. ((not org-use-tag-inheritance) nil)
  2440. ((stringp org-use-tag-inheritance)
  2441. (string-match org-use-tag-inheritance tag))
  2442. ((listp org-use-tag-inheritance)
  2443. (member tag org-use-tag-inheritance))
  2444. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2445. (defcustom org-tags-match-list-sublevels t
  2446. "Non-nil means list also sublevels of headlines matching a search.
  2447. This variable applies to tags/property searches, and also to stuck
  2448. projects because this search is based on a tags match as well.
  2449. When set to the symbol `indented', sublevels are indented with
  2450. leading dots.
  2451. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2452. the sublevels of a headline matching a tag search often also match
  2453. the same search. Listing all of them can create very long lists.
  2454. Setting this variable to nil causes subtrees of a match to be skipped.
  2455. This variable is semi-obsolete and probably should always be true. It
  2456. is better to limit inheritance to certain tags using the variables
  2457. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2458. :group 'org-tags
  2459. :type '(choice
  2460. (const :tag "No, don't list them" nil)
  2461. (const :tag "Yes, do list them" t)
  2462. (const :tag "List them, indented with leading dots" indented)))
  2463. (defcustom org-tags-sort-function nil
  2464. "When set, tags are sorted using this function as a comparator."
  2465. :group 'org-tags
  2466. :type '(choice
  2467. (const :tag "No sorting" nil)
  2468. (const :tag "Alphabetical" org-string-collate-lessp)
  2469. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2470. (function :tag "Custom function" nil)))
  2471. (defvar org-tags-history nil
  2472. "History of minibuffer reads for tags.")
  2473. (defvar org-last-tags-completion-table nil
  2474. "The last used completion table for tags.")
  2475. (defvar org-after-tags-change-hook nil
  2476. "Hook that is run after the tags in a line have changed.")
  2477. (defgroup org-properties nil
  2478. "Options concerning properties in Org mode."
  2479. :tag "Org Properties"
  2480. :group 'org)
  2481. (defcustom org-property-format "%-10s %s"
  2482. "How property key/value pairs should be formatted by `indent-line'.
  2483. When `indent-line' hits a property definition, it will format the line
  2484. according to this format, mainly to make sure that the values are
  2485. lined-up with respect to each other."
  2486. :group 'org-properties
  2487. :type 'string)
  2488. (defcustom org-properties-postprocess-alist nil
  2489. "Alist of properties and functions to adjust inserted values.
  2490. Elements of this alist must be of the form
  2491. ([string] [function])
  2492. where [string] must be a property name and [function] must be a
  2493. lambda expression: this lambda expression must take one argument,
  2494. the value to adjust, and return the new value as a string.
  2495. For example, this element will allow the property \"Remaining\"
  2496. to be updated wrt the relation between the \"Effort\" property
  2497. and the clock summary:
  2498. ((\"Remaining\" (lambda(value)
  2499. (let ((clocksum (org-clock-sum-current-item))
  2500. (effort (org-duration-to-minutes
  2501. (org-entry-get (point) \"Effort\"))))
  2502. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2503. :group 'org-properties
  2504. :version "24.1"
  2505. :type '(alist :key-type (string :tag "Property")
  2506. :value-type (function :tag "Function")))
  2507. (defcustom org-use-property-inheritance nil
  2508. "Non-nil means properties apply also for sublevels.
  2509. This setting is chiefly used during property searches. Turning it on can
  2510. cause significant overhead when doing a search, which is why it is not
  2511. on by default.
  2512. When nil, only the properties directly given in the current entry count.
  2513. When t, every property is inherited. The value may also be a list of
  2514. properties that should have inheritance, or a regular expression matching
  2515. properties that should be inherited.
  2516. However, note that some special properties use inheritance under special
  2517. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2518. and the properties ending in \"_ALL\" when they are used as descriptor
  2519. for valid values of a property.
  2520. Note for programmers:
  2521. When querying an entry with `org-entry-get', you can control if inheritance
  2522. should be used. By default, `org-entry-get' looks only at the local
  2523. properties. You can request inheritance by setting the inherit argument
  2524. to t (to force inheritance) or to `selective' (to respect the setting
  2525. in this variable)."
  2526. :group 'org-properties
  2527. :type '(choice
  2528. (const :tag "Not" nil)
  2529. (const :tag "Always" t)
  2530. (repeat :tag "Specific properties" (string :tag "Property"))
  2531. (regexp :tag "Properties matched by regexp")))
  2532. (defun org-property-inherit-p (property)
  2533. "Return a non-nil value if PROPERTY should be inherited."
  2534. (cond
  2535. ((eq org-use-property-inheritance t) t)
  2536. ((not org-use-property-inheritance) nil)
  2537. ((stringp org-use-property-inheritance)
  2538. (string-match org-use-property-inheritance property))
  2539. ((listp org-use-property-inheritance)
  2540. (member-ignore-case property org-use-property-inheritance))
  2541. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2542. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2543. "The default column format, if no other format has been defined.
  2544. This variable can be set on the per-file basis by inserting a line
  2545. #+COLUMNS: %25ITEM ....."
  2546. :group 'org-properties
  2547. :type 'string)
  2548. (defcustom org-columns-default-format-for-agenda nil
  2549. "The default column format in an agenda buffer.
  2550. This will be used for column view in the agenda unless a format has
  2551. been set by adding `org-overriding-columns-format' to the local
  2552. settings list of a custom agenda view. When nil, the columns format
  2553. for the first item in the agenda list will be used, or as a fall-back,
  2554. `org-columns-default-format'."
  2555. :group 'org-properties
  2556. :type '(choice
  2557. (const :tag "No default" nil)
  2558. (string :tag "Format string")))
  2559. (defcustom org-columns-ellipses ".."
  2560. "The ellipses to be used when a field in column view is truncated.
  2561. When this is the empty string, as many characters as possible are shown,
  2562. but then there will be no visual indication that the field has been truncated.
  2563. When this is a string of length N, the last N characters of a truncated
  2564. field are replaced by this string. If the column is narrower than the
  2565. ellipses string, only part of the ellipses string will be shown."
  2566. :group 'org-properties
  2567. :type 'string)
  2568. (defconst org-global-properties-fixed
  2569. '(("VISIBILITY_ALL" . "folded children content all")
  2570. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2571. "List of property/value pairs that can be inherited by any entry.
  2572. These are fixed values, for the preset properties. The user variable
  2573. that can be used to add to this list is `org-global-properties'.
  2574. The entries in this list are cons cells where the car is a property
  2575. name and cdr is a string with the value. If the value represents
  2576. multiple items like an \"_ALL\" property, separate the items by
  2577. spaces.")
  2578. (defcustom org-global-properties nil
  2579. "List of property/value pairs that can be inherited by any entry.
  2580. This list will be combined with the constant `org-global-properties-fixed'.
  2581. The entries in this list are cons cells where the car is a property
  2582. name and cdr is a string with the value.
  2583. Buffer local properties are added either by a document property drawer
  2584. :PROPERTIES:
  2585. :NAME: VALUE
  2586. :END:
  2587. or by adding lines like
  2588. #+PROPERTY: NAME VALUE"
  2589. :group 'org-properties
  2590. :type '(repeat
  2591. (cons (string :tag "Property")
  2592. (string :tag "Value"))))
  2593. (defvar-local org-keyword-properties nil
  2594. "List of property/value pairs inherited by any entry.
  2595. Valid for the current buffer. This variable is populated from
  2596. PROPERTY keywords.
  2597. Note that properties are defined also in property drawers.
  2598. Properties defined there take precedence over properties defined
  2599. as keywords.")
  2600. (defgroup org-agenda nil
  2601. "Options concerning agenda views in Org mode."
  2602. :tag "Org Agenda"
  2603. :group 'org)
  2604. (defvar-local org-category nil
  2605. "Variable used by Org files to set a category for agenda display.
  2606. There are multiple ways to set the category. One way is to set
  2607. it in the document property drawer. For example:
  2608. :PROPERTIES:
  2609. :CATEGORY: ELisp
  2610. :END:
  2611. Other ways to define it is as an emacs file variable, for example
  2612. # -*- mode: org; org-category: \"ELisp\"
  2613. or for the file to contain a special line:
  2614. #+CATEGORY: ELisp
  2615. If the file does not specify a category, then file's base name
  2616. is used instead.")
  2617. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2618. (defcustom org-agenda-files nil
  2619. "The files to be used for agenda display.
  2620. If an entry is a directory, all files in that directory that are matched
  2621. by `org-agenda-file-regexp' will be part of the file list.
  2622. If the value of the variable is not a list but a single file name, then
  2623. the list of agenda files is actually stored and maintained in that file,
  2624. one agenda file per line. In this file paths can be given relative to
  2625. `org-directory'. Tilde expansion and environment variable substitution
  2626. are also made.
  2627. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2628. and removed with `\\[org-remove-file]'."
  2629. :group 'org-agenda
  2630. :type '(choice
  2631. (repeat :tag "List of files and directories" file)
  2632. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2633. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2634. "Regular expression to match files for `org-agenda-files'.
  2635. If any element in the list in that variable contains a directory instead
  2636. of a normal file, all files in that directory that are matched by this
  2637. regular expression will be included."
  2638. :group 'org-agenda
  2639. :type 'regexp)
  2640. (defvaralias 'org-agenda-multi-occur-extra-files
  2641. 'org-agenda-text-search-extra-files)
  2642. (defcustom org-agenda-text-search-extra-files nil
  2643. "List of extra files to be searched by text search commands.
  2644. These files will be searched in addition to the agenda files by the
  2645. commands `org-search-view' (`\\[org-agenda] s') \
  2646. and `org-occur-in-agenda-files'.
  2647. Note that these files will only be searched for text search commands,
  2648. not for the other agenda views like todo lists, tag searches or the weekly
  2649. agenda. This variable is intended to list notes and possibly archive files
  2650. that should also be searched by these two commands.
  2651. In fact, if the first element in the list is the symbol `agenda-archives',
  2652. then all archive files of all agenda files will be added to the search
  2653. scope."
  2654. :group 'org-agenda
  2655. :type '(set :greedy t
  2656. (const :tag "Agenda Archives" agenda-archives)
  2657. (repeat :inline t (file))))
  2658. (defcustom org-agenda-skip-unavailable-files nil
  2659. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2660. A nil value means to remove them, after a query, from the list."
  2661. :group 'org-agenda
  2662. :type 'boolean)
  2663. (defgroup org-latex nil
  2664. "Options for embedding LaTeX code into Org mode."
  2665. :tag "Org LaTeX"
  2666. :group 'org)
  2667. (defcustom org-format-latex-options
  2668. '(:foreground default :background default :scale 1.0
  2669. :html-foreground "Black" :html-background "Transparent"
  2670. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2671. "Options for creating images from LaTeX fragments.
  2672. This is a property list with the following properties:
  2673. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2674. `default' means use the foreground of the default face.
  2675. `auto' means use the foreground from the text face.
  2676. :background the background color, or \"Transparent\".
  2677. `default' means use the background of the default face.
  2678. `auto' means use the background from the text face.
  2679. :scale a scaling factor for the size of the images, to get more pixels
  2680. :html-foreground, :html-background, :html-scale
  2681. the same numbers for HTML export.
  2682. :matchers a list indicating which matchers should be used to
  2683. find LaTeX fragments. Valid members of this list are:
  2684. \"begin\" find environments
  2685. \"$1\" find single characters surrounded by $.$
  2686. \"$\" find math expressions surrounded by $...$
  2687. \"$$\" find math expressions surrounded by $$....$$
  2688. \"\\(\" find math expressions surrounded by \\(...\\)
  2689. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2690. :group 'org-latex
  2691. :type 'plist)
  2692. (defcustom org-format-latex-signal-error t
  2693. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2694. When nil, just push out a message."
  2695. :group 'org-latex
  2696. :version "24.1"
  2697. :type 'boolean)
  2698. (defcustom org-latex-to-mathml-jar-file nil
  2699. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2700. Use this to specify additional executable file say a jar file.
  2701. When using MathToWeb as the converter, specify the full-path to
  2702. your mathtoweb.jar file."
  2703. :group 'org-latex
  2704. :version "24.1"
  2705. :type '(choice
  2706. (const :tag "None" nil)
  2707. (file :tag "JAR file" :must-match t)))
  2708. (defcustom org-latex-to-mathml-convert-command nil
  2709. "Command to convert LaTeX fragments to MathML.
  2710. Replace format-specifiers in the command as noted below and use
  2711. `shell-command' to convert LaTeX to MathML.
  2712. %j: Executable file in fully expanded form as specified by
  2713. `org-latex-to-mathml-jar-file'.
  2714. %I: Input LaTeX file in fully expanded form.
  2715. %i: The latex fragment to be converted.
  2716. %o: Output MathML file.
  2717. This command is used by `org-create-math-formula'.
  2718. When using MathToWeb as the converter, set this option to
  2719. \"java -jar %j -unicode -force -df %o %I\".
  2720. When using LaTeXML set this option to
  2721. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2722. :group 'org-latex
  2723. :version "24.1"
  2724. :type '(choice
  2725. (const :tag "None" nil)
  2726. (string :tag "\nShell command")))
  2727. (defcustom org-preview-latex-default-process 'dvipng
  2728. "The default process to convert LaTeX fragments to image files.
  2729. All available processes and theirs documents can be found in
  2730. `org-preview-latex-process-alist', which see."
  2731. :group 'org-latex
  2732. :version "26.1"
  2733. :package-version '(Org . "9.0")
  2734. :type 'symbol)
  2735. (defcustom org-preview-latex-process-alist
  2736. '((dvipng
  2737. :programs ("latex" "dvipng")
  2738. :description "dvi > png"
  2739. :message "you need to install the programs: latex and dvipng."
  2740. :image-input-type "dvi"
  2741. :image-output-type "png"
  2742. :image-size-adjust (1.0 . 1.0)
  2743. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2744. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2745. (dvisvgm
  2746. :programs ("latex" "dvisvgm")
  2747. :description "dvi > svg"
  2748. :message "you need to install the programs: latex and dvisvgm."
  2749. :image-input-type "dvi"
  2750. :image-output-type "svg"
  2751. :image-size-adjust (1.7 . 1.5)
  2752. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2753. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2754. (imagemagick
  2755. :programs ("latex" "convert")
  2756. :description "pdf > png"
  2757. :message "you need to install the programs: latex and imagemagick."
  2758. :image-input-type "pdf"
  2759. :image-output-type "png"
  2760. :image-size-adjust (1.0 . 1.0)
  2761. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2762. :image-converter
  2763. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2764. "Definitions of external processes for LaTeX previewing.
  2765. Org mode can use some external commands to generate TeX snippet's images for
  2766. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2767. `org-create-formula-image' how to call them.
  2768. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2769. PROPERTIES accepts the following attributes:
  2770. :programs list of strings, required programs.
  2771. :description string, describe the process.
  2772. :message string, message it when required programs cannot be found.
  2773. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2774. :image-output-type string, output file type of image converter (e.g., \"png\").
  2775. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2776. image size showed in buffer and the cdr element is for
  2777. HTML file. This option is only useful for process
  2778. developers, users should use variable
  2779. `org-format-latex-options' instead.
  2780. :post-clean list of strings, files matched are to be cleaned up once
  2781. the image is generated. When nil, the files with \".dvi\",
  2782. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2783. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2784. be cleaned up.
  2785. :latex-header list of strings, the LaTeX header of the snippet file.
  2786. When nil, the fallback value is used instead, which is
  2787. controlled by `org-format-latex-header',
  2788. `org-latex-default-packages-alist' and
  2789. `org-latex-packages-alist', which see.
  2790. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2791. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2792. replaced with values defined below.
  2793. :image-converter list of image converter commands strings. Each of them is
  2794. given to the shell and supports any of the following
  2795. place-holders defined below.
  2796. Place-holders used by `:image-converter' and `:latex-compiler':
  2797. %f input file name
  2798. %b base name of input file
  2799. %o base directory of input file
  2800. %O absolute output file name
  2801. Place-holders only used by `:image-converter':
  2802. %D dpi, which is used to adjust image size by some processing commands.
  2803. %S the image size scale ratio, which is used to adjust image size by some
  2804. processing commands."
  2805. :group 'org-latex
  2806. :version "26.1"
  2807. :package-version '(Org . "9.0")
  2808. :type '(alist :tag "LaTeX to image backends"
  2809. :value-type (plist)))
  2810. (defcustom org-preview-latex-image-directory "ltximg/"
  2811. "Path to store latex preview images.
  2812. A relative path here creates many directories relative to the
  2813. processed Org files paths. An absolute path puts all preview
  2814. images at the same place."
  2815. :group 'org-latex
  2816. :version "26.1"
  2817. :package-version '(Org . "9.0")
  2818. :type 'string)
  2819. (defun org-format-latex-mathml-available-p ()
  2820. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2821. (save-match-data
  2822. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2823. org-latex-to-mathml-convert-command)
  2824. (let ((executable (car (split-string
  2825. org-latex-to-mathml-convert-command))))
  2826. (when (executable-find executable)
  2827. (if (string-match
  2828. "%j" org-latex-to-mathml-convert-command)
  2829. (file-readable-p org-latex-to-mathml-jar-file)
  2830. t))))))
  2831. (defcustom org-format-latex-header "\\documentclass{article}
  2832. \\usepackage[usenames]{color}
  2833. \[PACKAGES]
  2834. \[DEFAULT-PACKAGES]
  2835. \\pagestyle{empty} % do not remove
  2836. % The settings below are copied from fullpage.sty
  2837. \\setlength{\\textwidth}{\\paperwidth}
  2838. \\addtolength{\\textwidth}{-3cm}
  2839. \\setlength{\\oddsidemargin}{1.5cm}
  2840. \\addtolength{\\oddsidemargin}{-2.54cm}
  2841. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2842. \\setlength{\\textheight}{\\paperheight}
  2843. \\addtolength{\\textheight}{-\\headheight}
  2844. \\addtolength{\\textheight}{-\\headsep}
  2845. \\addtolength{\\textheight}{-\\footskip}
  2846. \\addtolength{\\textheight}{-3cm}
  2847. \\setlength{\\topmargin}{1.5cm}
  2848. \\addtolength{\\topmargin}{-2.54cm}"
  2849. "The document header used for processing LaTeX fragments.
  2850. It is imperative that this header make sure that no page number
  2851. appears on the page. The package defined in the variables
  2852. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2853. will either replace the placeholder \"[PACKAGES]\" in this
  2854. header, or they will be appended."
  2855. :group 'org-latex
  2856. :type 'string)
  2857. (defun org-set-packages-alist (var val)
  2858. "Set the packages alist and make sure it has 3 elements per entry."
  2859. (set var (mapcar (lambda (x)
  2860. (if (and (consp x) (= (length x) 2))
  2861. (list (car x) (nth 1 x) t)
  2862. x))
  2863. val)))
  2864. (defun org-get-packages-alist (var)
  2865. "Get the packages alist and make sure it has 3 elements per entry."
  2866. (mapcar (lambda (x)
  2867. (if (and (consp x) (= (length x) 2))
  2868. (list (car x) (nth 1 x) t)
  2869. x))
  2870. (default-value var)))
  2871. (defcustom org-latex-default-packages-alist
  2872. '(("AUTO" "inputenc" t ("pdflatex"))
  2873. ("T1" "fontenc" t ("pdflatex"))
  2874. ("" "graphicx" t)
  2875. ("" "grffile" t)
  2876. ("" "longtable" nil)
  2877. ("" "wrapfig" nil)
  2878. ("" "rotating" nil)
  2879. ("normalem" "ulem" t)
  2880. ("" "amsmath" t)
  2881. ("" "textcomp" t)
  2882. ("" "amssymb" t)
  2883. ("" "capt-of" nil)
  2884. ("" "hyperref" nil))
  2885. "Alist of default packages to be inserted in the header.
  2886. Change this only if one of the packages here causes an
  2887. incompatibility with another package you are using.
  2888. The packages in this list are needed by one part or another of
  2889. Org mode to function properly:
  2890. - inputenc, fontenc: for basic font and character selection
  2891. - graphicx: for including images
  2892. - grffile: allow periods and spaces in graphics file names
  2893. - longtable: For multipage tables
  2894. - wrapfig: for figure placement
  2895. - rotating: for sideways figures and tables
  2896. - ulem: for underline and strike-through
  2897. - amsmath: for subscript and superscript and math environments
  2898. - textcomp, amssymb: for various symbols used
  2899. for interpreting the entities in `org-entities'. You can skip
  2900. some of these packages if you don't use any of their symbols.
  2901. - capt-of: for captions outside of floats
  2902. - hyperref: for cross references
  2903. Therefore you should not modify this variable unless you know
  2904. what you are doing. The one reason to change it anyway is that
  2905. you might be loading some other package that conflicts with one
  2906. of the default packages. Each element is either a cell or
  2907. a string.
  2908. A cell is of the format
  2909. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2910. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2911. when compiling LaTeX snippets into images for inclusion into
  2912. non-LaTeX output.
  2913. COMPILERS is a list of compilers that should include the package,
  2914. see `org-latex-compiler'. If the document compiler is not in the
  2915. list, and the list is non-nil, the package will not be inserted
  2916. in the final document.
  2917. A string will be inserted as-is in the header of the document."
  2918. :group 'org-latex
  2919. :group 'org-export-latex
  2920. :set 'org-set-packages-alist
  2921. :get 'org-get-packages-alist
  2922. :version "26.1"
  2923. :package-version '(Org . "8.3")
  2924. :type '(repeat
  2925. (choice
  2926. (list :tag "options/package pair"
  2927. (string :tag "options")
  2928. (string :tag "package")
  2929. (boolean :tag "Snippet")
  2930. (choice
  2931. (const :tag "For all compilers" nil)
  2932. (repeat :tag "Allowed compiler" string)))
  2933. (string :tag "A line of LaTeX"))))
  2934. (defcustom org-latex-packages-alist nil
  2935. "Alist of packages to be inserted in every LaTeX header.
  2936. These will be inserted after `org-latex-default-packages-alist'.
  2937. Each element is either a cell or a string.
  2938. A cell is of the format:
  2939. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2940. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2941. needed when turning LaTeX snippets into images for inclusion into
  2942. non-LaTeX output.
  2943. COMPILERS is a list of compilers that should include the package,
  2944. see `org-latex-compiler'. If the document compiler is not in the
  2945. list, and the list is non-nil, the package will not be inserted
  2946. in the final document.
  2947. A string will be inserted as-is in the header of the document.
  2948. Make sure that you only list packages here which:
  2949. - you want in every file;
  2950. - do not conflict with the setup in `org-format-latex-header';
  2951. - do not conflict with the default packages in
  2952. `org-latex-default-packages-alist'."
  2953. :group 'org-latex
  2954. :group 'org-export-latex
  2955. :set 'org-set-packages-alist
  2956. :get 'org-get-packages-alist
  2957. :type '(repeat
  2958. (choice
  2959. (list :tag "options/package pair"
  2960. (string :tag "options")
  2961. (string :tag "package")
  2962. (boolean :tag "Snippet"))
  2963. (string :tag "A line of LaTeX"))))
  2964. (defgroup org-appearance nil
  2965. "Settings for Org mode appearance."
  2966. :tag "Org Appearance"
  2967. :group 'org)
  2968. (defcustom org-level-color-stars-only nil
  2969. "Non-nil means fontify only the stars in each headline.
  2970. When nil, the entire headline is fontified.
  2971. Changing it requires restart of `font-lock-mode' to become effective
  2972. also in regions already fontified."
  2973. :group 'org-appearance
  2974. :type 'boolean)
  2975. (defcustom org-hide-leading-stars nil
  2976. "Non-nil means hide the first N-1 stars in a headline.
  2977. This works by using the face `org-hide' for these stars. This
  2978. face is white for a light background, and black for a dark
  2979. background. You may have to customize the face `org-hide' to
  2980. make this work.
  2981. Changing it requires restart of `font-lock-mode' to become effective
  2982. also in regions already fontified.
  2983. You may also set this on a per-file basis by adding one of the following
  2984. lines to the buffer:
  2985. #+STARTUP: hidestars
  2986. #+STARTUP: showstars"
  2987. :group 'org-appearance
  2988. :type 'boolean)
  2989. (defcustom org-hidden-keywords nil
  2990. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2991. For example, a value \\='(title) for this list makes the document's title
  2992. appear in the buffer without the initial \"#+TITLE:\" part."
  2993. :group 'org-appearance
  2994. :version "24.1"
  2995. :type '(set (const :tag "#+AUTHOR" author)
  2996. (const :tag "#+DATE" date)
  2997. (const :tag "#+EMAIL" email)
  2998. (const :tag "#+TITLE" title)))
  2999. (defcustom org-custom-properties nil
  3000. "List of properties (as strings) with a special meaning.
  3001. The default use of these custom properties is to let the user
  3002. hide them with `org-toggle-custom-properties-visibility'."
  3003. :group 'org-properties
  3004. :group 'org-appearance
  3005. :version "24.3"
  3006. :type '(repeat (string :tag "Property Name")))
  3007. (defcustom org-fontify-todo-headline nil
  3008. "Non-nil means change the face of a headline if it is marked as TODO.
  3009. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3010. When this is non-nil, the headline after the keyword is set to the
  3011. `org-headline-todo' as an additional indication."
  3012. :group 'org-appearance
  3013. :package-version '(Org . "9.4")
  3014. :type 'boolean
  3015. :safe t)
  3016. (defcustom org-fontify-done-headline nil
  3017. "Non-nil means change the face of a headline if it is marked DONE.
  3018. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3019. When this is non-nil, the headline after the keyword is set to the
  3020. `org-headline-done' as an additional indication."
  3021. :group 'org-appearance
  3022. :type 'boolean)
  3023. (defcustom org-fontify-emphasized-text t
  3024. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3025. Changing this variable requires a restart of Emacs to take effect."
  3026. :group 'org-appearance
  3027. :type 'boolean)
  3028. (defcustom org-fontify-whole-heading-line nil
  3029. "Non-nil means fontify the whole line for headings.
  3030. This is useful when setting a background color for the
  3031. org-level-* faces."
  3032. :group 'org-appearance
  3033. :type 'boolean)
  3034. (defcustom org-fontify-whole-block-delimiter-line t
  3035. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3036. This is useful when setting a background color for the
  3037. org-block-begin-line and org-block-end-line faces."
  3038. :group 'org-appearance
  3039. :type 'boolean)
  3040. (defcustom org-highlight-latex-and-related nil
  3041. "Non-nil means highlight LaTeX related syntax in the buffer.
  3042. When non-nil, the value should be a list containing any of the
  3043. following symbols:
  3044. `native' Highlight LaTeX snippets and environments natively.
  3045. `latex' Highlight LaTeX snippets and environments.
  3046. `script' Highlight subscript and superscript.
  3047. `entities' Highlight entities."
  3048. :group 'org-appearance
  3049. :version "24.4"
  3050. :package-version '(Org . "8.0")
  3051. :type '(choice
  3052. (const :tag "No highlighting" nil)
  3053. (set :greedy t :tag "Highlight"
  3054. (const :tag "LaTeX snippets and environments (native)" native)
  3055. (const :tag "LaTeX snippets and environments" latex)
  3056. (const :tag "Subscript and superscript" script)
  3057. (const :tag "Entities" entities))))
  3058. (defcustom org-hide-emphasis-markers nil
  3059. "Non-nil mean font-lock should hide the emphasis marker characters."
  3060. :group 'org-appearance
  3061. :type 'boolean
  3062. :safe #'booleanp)
  3063. (defcustom org-hide-macro-markers nil
  3064. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3065. :group 'org-appearance
  3066. :type 'boolean)
  3067. (defcustom org-pretty-entities nil
  3068. "Non-nil means show entities as UTF8 characters.
  3069. When nil, the \\name form remains in the buffer."
  3070. :group 'org-appearance
  3071. :version "24.1"
  3072. :type 'boolean)
  3073. (defcustom org-pretty-entities-include-sub-superscripts t
  3074. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3075. :group 'org-appearance
  3076. :version "24.1"
  3077. :type 'boolean)
  3078. (defvar org-emph-re nil
  3079. "Regular expression for matching emphasis.
  3080. After a match, the match groups contain these elements:
  3081. 0 The match of the full regular expression, including the characters
  3082. before and after the proper match
  3083. 1 The character before the proper match, or empty at beginning of line
  3084. 2 The proper match, including the leading and trailing markers
  3085. 3 The leading marker like * or /, indicating the type of highlighting
  3086. 4 The text between the emphasis markers, not including the markers
  3087. 5 The character after the match, empty at the end of a line")
  3088. (defvar org-verbatim-re nil
  3089. "Regular expression for matching verbatim text.")
  3090. (defvar org-emphasis-regexp-components) ; defined just below
  3091. (defvar org-emphasis-alist) ; defined just below
  3092. (defun org-set-emph-re (var val)
  3093. "Set variable and compute the emphasis regular expression."
  3094. (set var val)
  3095. (when (and (boundp 'org-emphasis-alist)
  3096. (boundp 'org-emphasis-regexp-components)
  3097. org-emphasis-alist org-emphasis-regexp-components)
  3098. (pcase-let*
  3099. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3100. (body (if (<= nl 0) body
  3101. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3102. (template
  3103. (format (concat "\\([%s]\\|^\\)" ;before markers
  3104. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3105. "\\([%s]\\|$\\)") ;after markers
  3106. pre border border body border post)))
  3107. (setq org-emph-re (format template "*/_+"))
  3108. (setq org-verbatim-re (format template "=~")))))
  3109. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3110. ;; set this option proved cumbersome. See this message/thread:
  3111. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3112. (defvar org-emphasis-regexp-components
  3113. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3114. "Components used to build the regular expression for emphasis.
  3115. This is a list with five entries. Terminology: In an emphasis string
  3116. like \" *strong word* \", we call the initial space PREMATCH, the final
  3117. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3118. and \"trong wor\" is the body. The different components in this variable
  3119. specify what is allowed/forbidden in each part:
  3120. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3121. post Chars allowed as postmatch. End of line will be allowed too.
  3122. border The chars *forbidden* as border characters.
  3123. body-regexp A regexp like \".\" to match a body character. Don't use
  3124. non-shy groups here, and don't allow newline here.
  3125. newline The maximum number of newlines allowed in an emphasis exp.
  3126. You need to reload Org or to restart Emacs after setting this.")
  3127. (defcustom org-emphasis-alist
  3128. '(("*" bold)
  3129. ("/" italic)
  3130. ("_" underline)
  3131. ("=" org-verbatim verbatim)
  3132. ("~" org-code verbatim)
  3133. ("+" (:strike-through t)))
  3134. "Alist of characters and faces to emphasize text.
  3135. Text starting and ending with a special character will be emphasized,
  3136. for example *bold*, _underlined_ and /italic/. This variable sets the
  3137. marker characters and the face to be used by font-lock for highlighting
  3138. in Org buffers.
  3139. You need to reload Org or to restart Emacs after customizing this."
  3140. :group 'org-appearance
  3141. :set 'org-set-emph-re
  3142. :version "24.4"
  3143. :package-version '(Org . "8.0")
  3144. :type '(repeat
  3145. (list
  3146. (string :tag "Marker character")
  3147. (choice
  3148. (face :tag "Font-lock-face")
  3149. (plist :tag "Face property list"))
  3150. (option (const verbatim)))))
  3151. (defvar org-protecting-blocks '("src" "example" "export")
  3152. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3153. This is needed for font-lock setup.")
  3154. ;;; Functions and variables from their packages
  3155. ;; Declared here to avoid compiler warnings
  3156. (defvar mark-active)
  3157. ;; Various packages
  3158. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3159. (declare-function calendar-forward-day "cal-move" (arg))
  3160. (declare-function calendar-goto-date "cal-move" (date))
  3161. (declare-function calendar-goto-today "cal-move" ())
  3162. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3163. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3164. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3165. (declare-function cdlatex-tab "ext:cdlatex" ())
  3166. (declare-function dired-get-filename
  3167. "dired"
  3168. (&optional localp no-error-if-not-filep))
  3169. (declare-function iswitchb-read-buffer
  3170. "iswitchb"
  3171. (prompt &optional
  3172. default require-match _predicate start matches-set))
  3173. (declare-function org-agenda-change-all-lines
  3174. "org-agenda"
  3175. (newhead hdmarker &optional fixface just-this))
  3176. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3177. "org-agenda"
  3178. (&optional end))
  3179. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3180. (declare-function org-agenda-format-item
  3181. "org-agenda"
  3182. (extra txt &optional level category tags dotime
  3183. remove-re habitp))
  3184. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3185. (declare-function org-agenda-save-markers-for-cut-and-paste
  3186. "org-agenda"
  3187. (beg end))
  3188. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3189. (declare-function org-agenda-skip "org-agenda" ())
  3190. (declare-function org-attach-expand "org-attach" (file))
  3191. (declare-function org-attach-reveal "org-attach" ())
  3192. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3193. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3194. (declare-function org-indent-mode "org-indent" (&optional arg))
  3195. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3196. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3197. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3198. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3199. (declare-function parse-time-string "parse-time" (string))
  3200. (defvar align-mode-rules-list)
  3201. (defvar calc-embedded-close-formula)
  3202. (defvar calc-embedded-open-formula)
  3203. (defvar calc-embedded-open-mode)
  3204. (defvar font-lock-unfontify-region-function)
  3205. (defvar iswitchb-temp-buflist)
  3206. (defvar org-agenda-tags-todo-honor-ignore-options)
  3207. (defvar remember-data-file)
  3208. (defvar texmathp-why)
  3209. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3210. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3211. (declare-function org-resolve-clocks "org-clock"
  3212. (&optional also-non-dangling-p prompt last-valid))
  3213. (defvar org-clock-start-time)
  3214. (defvar org-clock-marker (make-marker)
  3215. "Marker recording the last clock-in.")
  3216. (defvar org-clock-hd-marker (make-marker)
  3217. "Marker recording the last clock-in, but the headline position.")
  3218. (defvar org-clock-heading ""
  3219. "The heading of the current clock entry.")
  3220. (defun org-clock-is-active ()
  3221. "Return the buffer where the clock is currently running.
  3222. Return nil if no clock is running."
  3223. (marker-buffer org-clock-marker))
  3224. (defun org-check-running-clock ()
  3225. "Check if the current buffer contains the running clock.
  3226. If yes, offer to stop it and to save the buffer with the changes."
  3227. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3228. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3229. (buffer-name))))
  3230. (org-clock-out)
  3231. (when (y-or-n-p "Save changed buffer?")
  3232. (save-buffer))))
  3233. (defun org-clocktable-try-shift (dir n)
  3234. "Check if this line starts a clock table, if yes, shift the time block."
  3235. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3236. (org-clocktable-shift dir n)))
  3237. ;;;###autoload
  3238. (defun org-clock-persistence-insinuate ()
  3239. "Set up hooks for clock persistence."
  3240. (require 'org-clock)
  3241. (add-hook 'org-mode-hook 'org-clock-load)
  3242. (add-hook 'kill-emacs-hook 'org-clock-save))
  3243. (defun org-clock-auto-clockout-insinuate ()
  3244. "Set up hook for auto clocking out when Emacs is idle.
  3245. See `org-clock-auto-clockout-timer'.
  3246. This function is meant to be added to the user configuration."
  3247. (require 'org-clock)
  3248. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3249. (defgroup org-archive nil
  3250. "Options concerning archiving in Org mode."
  3251. :tag "Org Archive"
  3252. :group 'org-structure)
  3253. (defcustom org-archive-location "%s_archive::"
  3254. "The location where subtrees should be archived.
  3255. The value of this variable is a string, consisting of two parts,
  3256. separated by a double-colon. The first part is a filename and
  3257. the second part is a headline.
  3258. When the filename is omitted, archiving happens in the same file.
  3259. %s in the filename will be replaced by the current file
  3260. name (without the directory part). Archiving to a different file
  3261. is useful to keep archived entries from contributing to the
  3262. Org Agenda.
  3263. The archived entries will be filed as subtrees of the specified
  3264. headline. When the headline is omitted, the subtrees are simply
  3265. filed away at the end of the file, as top-level entries. Also in
  3266. the heading you can use %s to represent the file name, this can be
  3267. useful when using the same archive for a number of different files.
  3268. Here are a few examples:
  3269. \"%s_archive::\"
  3270. If the current file is Projects.org, archive in file
  3271. Projects.org_archive, as top-level trees. This is the default.
  3272. \"::* Archived Tasks\"
  3273. Archive in the current file, under the top-level headline
  3274. \"* Archived Tasks\".
  3275. \"~/org/archive.org::\"
  3276. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3277. \"~/org/archive.org::* From %s\"
  3278. Archive in file ~/org/archive.org (absolute path), under headlines
  3279. \"From FILENAME\" where file name is the current file name.
  3280. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3281. The \"datetree/\" string is special, signifying to archive
  3282. items to the datetree. Items are placed in either the CLOSED
  3283. date of the item, or the current date if there is no CLOSED date.
  3284. The heading will be a subentry to the current date. There doesn't
  3285. need to be a heading, but there always needs to be a slash after
  3286. datetree. For example, to store archived items directly in the
  3287. datetree, use \"~/org/datetree.org::datetree/\".
  3288. \"basement::** Finished Tasks\"
  3289. Archive in file ./basement (relative path), as level 3 trees
  3290. below the level 2 heading \"** Finished Tasks\".
  3291. You may define it locally by setting an ARCHIVE property. If
  3292. such a property is found in the file or in an entry, and anywhere
  3293. up the hierarchy, it will be used.
  3294. You can also set it for the whole file using the keyword-syntax:
  3295. #+ARCHIVE: basement::** Finished Tasks"
  3296. :group 'org-archive
  3297. :type 'string)
  3298. (defcustom org-agenda-skip-archived-trees t
  3299. "Non-nil means the agenda will skip any items located in archived trees.
  3300. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3301. variable is no longer recommended, you should leave it at the value t.
  3302. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3303. :group 'org-archive
  3304. :group 'org-agenda-skip
  3305. :type 'boolean)
  3306. (defcustom org-columns-skip-archived-trees t
  3307. "Non-nil means ignore archived trees when creating column view."
  3308. :group 'org-archive
  3309. :group 'org-properties
  3310. :type 'boolean)
  3311. (defcustom org-cycle-open-archived-trees nil
  3312. "Non-nil means `org-cycle' will open archived trees.
  3313. An archived tree is a tree marked with the tag ARCHIVE.
  3314. When nil, archived trees will stay folded. You can still open them with
  3315. normal outline commands like `show-all', but not with the cycling commands."
  3316. :group 'org-archive
  3317. :group 'org-cycle
  3318. :type 'boolean)
  3319. (defcustom org-sparse-tree-open-archived-trees nil
  3320. "Non-nil means sparse tree construction shows matches in archived trees.
  3321. When nil, matches in these trees are highlighted, but the trees are kept in
  3322. collapsed state."
  3323. :group 'org-archive
  3324. :group 'org-sparse-trees
  3325. :type 'boolean)
  3326. (defcustom org-sparse-tree-default-date-type nil
  3327. "The default date type when building a sparse tree.
  3328. When this is nil, a date is a scheduled or a deadline timestamp.
  3329. Otherwise, these types are allowed:
  3330. all: all timestamps
  3331. active: only active timestamps (<...>)
  3332. inactive: only inactive timestamps ([...])
  3333. scheduled: only scheduled timestamps
  3334. deadline: only deadline timestamps"
  3335. :type '(choice (const :tag "Scheduled or deadline" nil)
  3336. (const :tag "All timestamps" all)
  3337. (const :tag "Only active timestamps" active)
  3338. (const :tag "Only inactive timestamps" inactive)
  3339. (const :tag "Only scheduled timestamps" scheduled)
  3340. (const :tag "Only deadline timestamps" deadline)
  3341. (const :tag "Only closed timestamps" closed))
  3342. :version "26.1"
  3343. :package-version '(Org . "8.3")
  3344. :group 'org-sparse-trees)
  3345. (defun org-cycle-hide-archived-subtrees (state)
  3346. "Re-hide all archived subtrees after a visibility state change.
  3347. STATE should be one of the symbols listed in the docstring of
  3348. `org-cycle-hook'."
  3349. (when (and (not org-cycle-open-archived-trees)
  3350. (not (memq state '(overview folded))))
  3351. (save-excursion
  3352. (let* ((globalp (memq state '(contents all)))
  3353. (beg (if globalp (point-min) (point)))
  3354. (end (if globalp (point-max) (org-end-of-subtree t))))
  3355. (org-hide-archived-subtrees beg end)
  3356. (goto-char beg)
  3357. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3358. (message "%s" (substitute-command-keys
  3359. "Subtree is archived and stays closed. Use \
  3360. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3361. (defun org-force-cycle-archived ()
  3362. "Cycle subtree even if it is archived."
  3363. (interactive)
  3364. (setq this-command 'org-cycle)
  3365. (let ((org-cycle-open-archived-trees t))
  3366. (call-interactively 'org-cycle)))
  3367. (defun org-hide-archived-subtrees (beg end)
  3368. "Re-hide all archived subtrees after a visibility state change."
  3369. (org-with-wide-buffer
  3370. (let ((case-fold-search nil)
  3371. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3372. (goto-char beg)
  3373. ;; Include headline point is currently on.
  3374. (beginning-of-line)
  3375. (while (and (< (point) end) (re-search-forward re end t))
  3376. (when (member org-archive-tag (org-get-tags nil t))
  3377. (org-flag-subtree t)
  3378. (org-end-of-subtree t))))))
  3379. (defun org-flag-subtree (flag)
  3380. (save-excursion
  3381. (org-back-to-heading t)
  3382. (org-flag-region (line-end-position)
  3383. (progn (org-end-of-subtree t) (point))
  3384. flag
  3385. 'outline)))
  3386. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3387. ;; Declare Column View Code
  3388. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3389. (declare-function org-columns-compute "org-colview" (property))
  3390. ;; Declare ID code
  3391. (declare-function org-id-store-link "org-id")
  3392. (declare-function org-id-locations-load "org-id")
  3393. (declare-function org-id-locations-save "org-id")
  3394. (defvar org-id-track-globally)
  3395. ;;; Variables for pre-computed regular expressions, all buffer local
  3396. (defvar-local org-todo-regexp nil
  3397. "Matches any of the TODO state keywords.
  3398. Since TODO keywords are case-sensitive, `case-fold-search' is
  3399. expected to be bound to nil when matching against this regexp.")
  3400. (defvar-local org-not-done-regexp nil
  3401. "Matches any of the TODO state keywords except the last one.
  3402. Since TODO keywords are case-sensitive, `case-fold-search' is
  3403. expected to be bound to nil when matching against this regexp.")
  3404. (defvar-local org-not-done-heading-regexp nil
  3405. "Matches a TODO headline that is not done.
  3406. Since TODO keywords are case-sensitive, `case-fold-search' is
  3407. expected to be bound to nil when matching against this regexp.")
  3408. (defvar-local org-todo-line-regexp nil
  3409. "Matches a headline and puts TODO state into group 2 if present.
  3410. Since TODO keywords are case-sensitive, `case-fold-search' is
  3411. expected to be bound to nil when matching against this regexp.")
  3412. (defvar-local org-complex-heading-regexp nil
  3413. "Matches a headline and puts everything into groups:
  3414. group 1: Stars
  3415. group 2: The TODO keyword, maybe
  3416. group 3: Priority cookie
  3417. group 4: True headline
  3418. group 5: Tags
  3419. Since TODO keywords are case-sensitive, `case-fold-search' is
  3420. expected to be bound to nil when matching against this regexp.")
  3421. (defvar-local org-complex-heading-regexp-format nil
  3422. "Printf format to make regexp to match an exact headline.
  3423. This regexp will match the headline of any node which has the
  3424. exact headline text that is put into the format, but may have any
  3425. TODO state, priority and tags.")
  3426. (defvar-local org-todo-line-tags-regexp nil
  3427. "Matches a headline and puts TODO state into group 2 if present.
  3428. Also put tags into group 4 if tags are present.")
  3429. (defconst org-plain-time-of-day-regexp
  3430. (concat
  3431. "\\(\\<[012]?[0-9]"
  3432. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3433. "\\(--?"
  3434. "\\(\\<[012]?[0-9]"
  3435. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3436. "\\)?")
  3437. "Regular expression to match a plain time or time range.
  3438. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3439. groups carry important information:
  3440. 0 the full match
  3441. 1 the first time, range or not
  3442. 8 the second time, if it is a range.")
  3443. (defconst org-plain-time-extension-regexp
  3444. (concat
  3445. "\\(\\<[012]?[0-9]"
  3446. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3447. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3448. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3449. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3450. groups carry important information:
  3451. 0 the full match
  3452. 7 hours of duration
  3453. 9 minutes of duration")
  3454. (defconst org-stamp-time-of-day-regexp
  3455. (concat
  3456. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3457. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3458. "\\(--?"
  3459. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3460. "Regular expression to match a timestamp time or time range.
  3461. After a match, the following groups carry important information:
  3462. 0 the full match
  3463. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3464. 2 the first time, range or not
  3465. 4 the second time, if it is a range.")
  3466. (defconst org-startup-options
  3467. '(("fold" org-startup-folded t)
  3468. ("overview" org-startup-folded t)
  3469. ("nofold" org-startup-folded nil)
  3470. ("showall" org-startup-folded nil)
  3471. ("showeverything" org-startup-folded showeverything)
  3472. ("content" org-startup-folded content)
  3473. ("indent" org-startup-indented t)
  3474. ("noindent" org-startup-indented nil)
  3475. ("hidestars" org-hide-leading-stars t)
  3476. ("showstars" org-hide-leading-stars nil)
  3477. ("odd" org-odd-levels-only t)
  3478. ("oddeven" org-odd-levels-only nil)
  3479. ("align" org-startup-align-all-tables t)
  3480. ("noalign" org-startup-align-all-tables nil)
  3481. ("shrink" org-startup-shrink-all-tables t)
  3482. ("inlineimages" org-startup-with-inline-images t)
  3483. ("noinlineimages" org-startup-with-inline-images nil)
  3484. ("latexpreview" org-startup-with-latex-preview t)
  3485. ("nolatexpreview" org-startup-with-latex-preview nil)
  3486. ("customtime" org-display-custom-times t)
  3487. ("logdone" org-log-done time)
  3488. ("lognotedone" org-log-done note)
  3489. ("nologdone" org-log-done nil)
  3490. ("lognoteclock-out" org-log-note-clock-out t)
  3491. ("nolognoteclock-out" org-log-note-clock-out nil)
  3492. ("logrepeat" org-log-repeat state)
  3493. ("lognoterepeat" org-log-repeat note)
  3494. ("logdrawer" org-log-into-drawer t)
  3495. ("nologdrawer" org-log-into-drawer nil)
  3496. ("logstatesreversed" org-log-states-order-reversed t)
  3497. ("nologstatesreversed" org-log-states-order-reversed nil)
  3498. ("nologrepeat" org-log-repeat nil)
  3499. ("logreschedule" org-log-reschedule time)
  3500. ("lognotereschedule" org-log-reschedule note)
  3501. ("nologreschedule" org-log-reschedule nil)
  3502. ("logredeadline" org-log-redeadline time)
  3503. ("lognoteredeadline" org-log-redeadline note)
  3504. ("nologredeadline" org-log-redeadline nil)
  3505. ("logrefile" org-log-refile time)
  3506. ("lognoterefile" org-log-refile note)
  3507. ("nologrefile" org-log-refile nil)
  3508. ("fninline" org-footnote-define-inline t)
  3509. ("nofninline" org-footnote-define-inline nil)
  3510. ("fnlocal" org-footnote-section nil)
  3511. ("fnauto" org-footnote-auto-label t)
  3512. ("fnprompt" org-footnote-auto-label nil)
  3513. ("fnconfirm" org-footnote-auto-label confirm)
  3514. ("fnplain" org-footnote-auto-label plain)
  3515. ("fnadjust" org-footnote-auto-adjust t)
  3516. ("nofnadjust" org-footnote-auto-adjust nil)
  3517. ("constcgs" constants-unit-system cgs)
  3518. ("constSI" constants-unit-system SI)
  3519. ("noptag" org-tag-persistent-alist nil)
  3520. ("hideblocks" org-hide-block-startup t)
  3521. ("nohideblocks" org-hide-block-startup nil)
  3522. ("beamer" org-startup-with-beamer-mode t)
  3523. ("entitiespretty" org-pretty-entities t)
  3524. ("entitiesplain" org-pretty-entities nil))
  3525. "Variable associated with STARTUP options for Org.
  3526. Each element is a list of three items: the startup options (as written
  3527. in the #+STARTUP line), the corresponding variable, and the value to set
  3528. this variable to if the option is found. An optional forth element PUSH
  3529. means to push this value onto the list in the variable.")
  3530. (defcustom org-group-tags t
  3531. "When non-nil (the default), use group tags.
  3532. This can be turned on/off through `org-toggle-tags-groups'."
  3533. :group 'org-tags
  3534. :group 'org-startup
  3535. :type 'boolean)
  3536. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3537. (defun org-toggle-tags-groups ()
  3538. "Toggle support for group tags.
  3539. Support for group tags is controlled by the option
  3540. `org-group-tags', which is non-nil by default."
  3541. (interactive)
  3542. (setq org-group-tags (not org-group-tags))
  3543. (cond ((and (derived-mode-p 'org-agenda-mode)
  3544. org-group-tags)
  3545. (org-agenda-redo))
  3546. ((derived-mode-p 'org-mode)
  3547. (let ((org-inhibit-startup t)) (org-mode))))
  3548. (message "Groups tags support has been turned %s"
  3549. (if org-group-tags "on" "off")))
  3550. (defun org--tag-add-to-alist (alist1 alist2)
  3551. "Merge tags from ALIST1 into ALIST2.
  3552. Duplicates tags outside a group are removed. Keywords and order
  3553. are preserved.
  3554. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3555. See `org-tag-alist' for their structure."
  3556. (cond
  3557. ((null alist2) alist1)
  3558. ((null alist1) alist2)
  3559. (t
  3560. (let ((to-add nil)
  3561. (group-flag nil))
  3562. (dolist (tag-pair alist1)
  3563. (pcase tag-pair
  3564. (`(,(or :startgrouptag :startgroup))
  3565. (setq group-flag t)
  3566. (push tag-pair to-add))
  3567. (`(,(or :endgrouptag :endgroup))
  3568. (setq group-flag nil)
  3569. (push tag-pair to-add))
  3570. (`(,(or :grouptags :newline))
  3571. (push tag-pair to-add))
  3572. (`(,tag . ,_)
  3573. ;; Remove duplicates from ALIST1, unless they are in
  3574. ;; a group. Indeed, it makes sense to have a tag appear in
  3575. ;; multiple groups.
  3576. (when (or group-flag (not (assoc tag alist2)))
  3577. (push tag-pair to-add)))
  3578. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3579. ;; Preserve order of ALIST1.
  3580. (append (nreverse to-add) alist2)))))
  3581. (defun org-set-regexps-and-options (&optional tags-only)
  3582. "Precompute regular expressions used in the current buffer.
  3583. When optional argument TAGS-ONLY is non-nil, only compute tags
  3584. related expressions."
  3585. (when (derived-mode-p 'org-mode)
  3586. (let ((alist (org--setup-collect-keywords
  3587. (org-make-options-regexp
  3588. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3589. (and (not tags-only)
  3590. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3591. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3592. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3593. ;; Startup options. Get this early since it does change
  3594. ;; behavior for other options (e.g., tags).
  3595. (let ((startup (cdr (assq 'startup alist))))
  3596. (dolist (option startup)
  3597. (let ((entry (assoc-string option org-startup-options t)))
  3598. (when entry
  3599. (let ((var (nth 1 entry))
  3600. (val (nth 2 entry)))
  3601. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3602. (unless (listp (symbol-value var))
  3603. (set (make-local-variable var) nil))
  3604. (add-to-list var val)))))))
  3605. (setq-local org-file-tags
  3606. (mapcar #'org-add-prop-inherited
  3607. (cdr (assq 'filetags alist))))
  3608. (setq org-current-tag-alist
  3609. (org--tag-add-to-alist
  3610. org-tag-persistent-alist
  3611. (let ((tags (cdr (assq 'tags alist))))
  3612. (if tags (org-tag-string-to-alist tags)
  3613. org-tag-alist))))
  3614. (setq org-tag-groups-alist
  3615. (org-tag-alist-to-groups org-current-tag-alist))
  3616. (unless tags-only
  3617. ;; Properties.
  3618. (setq-local org-keyword-properties (cdr (assq 'property alist)))
  3619. ;; Archive location.
  3620. (let ((archive (cdr (assq 'archive alist))))
  3621. (when archive (setq-local org-archive-location archive)))
  3622. ;; Category.
  3623. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3624. (when cat
  3625. (setq-local org-category (intern cat))
  3626. (setq-local org-keyword-properties
  3627. (org--update-property-plist
  3628. "CATEGORY" cat org-keyword-properties))))
  3629. ;; Columns.
  3630. (let ((column (cdr (assq 'columns alist))))
  3631. (when column (setq-local org-columns-default-format column)))
  3632. ;; Constants.
  3633. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3634. ;; Link abbreviations.
  3635. (let ((links (cdr (assq 'link alist))))
  3636. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3637. ;; Priorities.
  3638. (let ((priorities (cdr (assq 'priorities alist))))
  3639. (when priorities
  3640. (setq-local org-priority-highest (nth 0 priorities))
  3641. (setq-local org-priority-lowest (nth 1 priorities))
  3642. (setq-local org-priority-default (nth 2 priorities))))
  3643. ;; Scripts.
  3644. (let ((scripts (assq 'scripts alist)))
  3645. (when scripts
  3646. (setq-local org-use-sub-superscripts (cdr scripts))))
  3647. ;; TODO keywords.
  3648. (setq-local org-todo-kwd-alist nil)
  3649. (setq-local org-todo-key-alist nil)
  3650. (setq-local org-todo-key-trigger nil)
  3651. (setq-local org-todo-keywords-1 nil)
  3652. (setq-local org-done-keywords nil)
  3653. (setq-local org-todo-heads nil)
  3654. (setq-local org-todo-sets nil)
  3655. (setq-local org-todo-log-states nil)
  3656. (let ((todo-sequences
  3657. (or (nreverse (cdr (assq 'todo alist)))
  3658. (let ((d (default-value 'org-todo-keywords)))
  3659. (if (not (stringp (car d))) d
  3660. ;; XXX: Backward compatibility code.
  3661. (list (cons org-todo-interpretation d)))))))
  3662. (dolist (sequence todo-sequences)
  3663. (let* ((sequence (or (run-hook-with-args-until-success
  3664. 'org-todo-setup-filter-hook sequence)
  3665. sequence))
  3666. (sequence-type (car sequence))
  3667. (keywords (cdr sequence))
  3668. (sep (member "|" keywords))
  3669. names alist)
  3670. (dolist (k (remove "|" keywords))
  3671. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3672. k)
  3673. (error "Invalid TODO keyword %s" k))
  3674. (let ((name (match-string 1 k))
  3675. (key (match-string 2 k))
  3676. (log (org-extract-log-state-settings k)))
  3677. (push name names)
  3678. (push (cons name (and key (string-to-char key))) alist)
  3679. (when log (push log org-todo-log-states))))
  3680. (let* ((names (nreverse names))
  3681. (done (if sep (org-remove-keyword-keys (cdr sep))
  3682. (last names)))
  3683. (head (car names))
  3684. (tail (list sequence-type head (car done) (org-last done))))
  3685. (add-to-list 'org-todo-heads head 'append)
  3686. (push names org-todo-sets)
  3687. (setq org-done-keywords (append org-done-keywords done nil))
  3688. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3689. (setq org-todo-key-alist
  3690. (append org-todo-key-alist
  3691. (and alist
  3692. (append '((:startgroup))
  3693. (nreverse alist)
  3694. '((:endgroup))))))
  3695. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3696. (setq org-todo-sets (nreverse org-todo-sets)
  3697. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3698. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3699. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3700. ;; Compute the regular expressions and other local variables.
  3701. ;; Using `org-outline-regexp-bol' would complicate them much,
  3702. ;; because of the fixed white space at the end of that string.
  3703. (unless org-done-keywords
  3704. (setq org-done-keywords
  3705. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3706. (setq org-not-done-keywords
  3707. (org-delete-all org-done-keywords
  3708. (copy-sequence org-todo-keywords-1))
  3709. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3710. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3711. org-not-done-heading-regexp
  3712. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3713. org-todo-line-regexp
  3714. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3715. org-complex-heading-regexp
  3716. (concat "^\\(\\*+\\)"
  3717. "\\(?: +" org-todo-regexp "\\)?"
  3718. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3719. "\\(?: +\\(.*?\\)\\)??"
  3720. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3721. "[ \t]*$")
  3722. org-complex-heading-regexp-format
  3723. (concat "^\\(\\*+\\)"
  3724. "\\(?: +" org-todo-regexp "\\)?"
  3725. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3726. "\\(?: +"
  3727. ;; Stats cookies can be stuck to body.
  3728. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3729. "\\(%s\\)"
  3730. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3731. "\\)"
  3732. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3733. "[ \t]*$")
  3734. org-todo-line-tags-regexp
  3735. (concat "^\\(\\*+\\)"
  3736. "\\(?: +" org-todo-regexp "\\)?"
  3737. "\\(?: +\\(.*?\\)\\)??"
  3738. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3739. "[ \t]*$"))
  3740. (org-compute-latex-and-related-regexp)))))
  3741. (defsubst org-priority-to-value (s)
  3742. "Convert priority string S to its numeric value."
  3743. (or (save-match-data
  3744. (and (string-match "\\([0-9]+\\)" s)
  3745. (string-to-number (match-string 1 s))))
  3746. (string-to-char s)))
  3747. (defun org--setup-collect-keywords (regexp &optional files alist)
  3748. "Return setup keywords values as an alist.
  3749. REGEXP matches a subset of setup keywords. FILES is a list of
  3750. file names already visited. It is used to avoid circular setup
  3751. files. ALIST, when non-nil, is the alist computed so far.
  3752. Return value contains the following keys: `archive', `category',
  3753. `columns', `constants', `filetags', `link', `priorities',
  3754. `property', `scripts', `startup', `tags' and `todo'."
  3755. (org-with-wide-buffer
  3756. (goto-char (point-min))
  3757. (let ((case-fold-search t))
  3758. (while (re-search-forward regexp nil t)
  3759. (let ((element (org-element-at-point)))
  3760. (when (eq (org-element-type element) 'keyword)
  3761. (let ((key (org-element-property :key element))
  3762. (value (org-element-property :value element)))
  3763. (cond
  3764. ((equal key "ARCHIVE")
  3765. (when (org-string-nw-p value)
  3766. (push (cons 'archive value) alist)))
  3767. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3768. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3769. ((equal key "CONSTANTS")
  3770. (let* ((constants (assq 'constants alist))
  3771. (store (cdr constants)))
  3772. (dolist (pair (split-string value))
  3773. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3774. pair)
  3775. (let* ((name (match-string 1 pair))
  3776. (value (match-string 2 pair))
  3777. (old (assoc name store)))
  3778. (if old (setcdr old value)
  3779. (push (cons name value) store)))))
  3780. (if constants (setcdr constants store)
  3781. (push (cons 'constants store) alist))))
  3782. ((equal key "FILETAGS")
  3783. (when (org-string-nw-p value)
  3784. (let ((old (assq 'filetags alist))
  3785. (new (apply #'nconc
  3786. (mapcar (lambda (x) (org-split-string x ":"))
  3787. (split-string value)))))
  3788. (if old (setcdr old (append new (cdr old)))
  3789. (push (cons 'filetags new) alist)))))
  3790. ((equal key "LINK")
  3791. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3792. (let ((links (assq 'link alist))
  3793. (pair (cons (match-string-no-properties 1 value)
  3794. (match-string-no-properties 2 value))))
  3795. (if links (push pair (cdr links))
  3796. (push (list 'link pair) alist)))))
  3797. ((equal key "OPTIONS")
  3798. (when (and (org-string-nw-p value)
  3799. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3800. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3801. ((equal key "PRIORITIES")
  3802. (push (cons 'priorities
  3803. (let ((prio (split-string value)))
  3804. (if (< (length prio) 3)
  3805. (list org-priority-highest
  3806. org-priority-lowest
  3807. org-priority-default)
  3808. (mapcar #'org-priority-to-value prio))))
  3809. alist))
  3810. ((equal key "PROPERTY")
  3811. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3812. (let* ((property (assq 'property alist))
  3813. (value (org--update-property-plist
  3814. (match-string-no-properties 1 value)
  3815. (match-string-no-properties 2 value)
  3816. (cdr property))))
  3817. (if property (setcdr property value)
  3818. (push (cons 'property value) alist)))))
  3819. ((equal key "STARTUP")
  3820. (let ((startup (assq 'startup alist)))
  3821. (if startup
  3822. (setcdr startup
  3823. (append (cdr startup) (split-string value)))
  3824. (push (cons 'startup (split-string value)) alist))))
  3825. ((equal key "TAGS")
  3826. (let ((tag-cell (assq 'tags alist)))
  3827. (if tag-cell
  3828. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3829. (push (cons 'tags value) alist))))
  3830. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3831. (let ((todo (assq 'todo alist))
  3832. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3833. (split-string value))))
  3834. (if todo (push value (cdr todo))
  3835. (push (list 'todo value) alist))))
  3836. ((equal key "SETUPFILE")
  3837. (unless buffer-read-only ; Do not check in Gnus messages.
  3838. (let ((f (and (org-string-nw-p value)
  3839. (expand-file-name (org-strip-quotes value)))))
  3840. (when (and f (file-readable-p f) (not (member f files)))
  3841. (with-temp-buffer
  3842. (setq default-directory (file-name-directory f))
  3843. (insert-file-contents f)
  3844. (setq alist
  3845. ;; Fake Org mode to benefit from cache
  3846. ;; without recurring needlessly.
  3847. (let ((major-mode 'org-mode))
  3848. (org--setup-collect-keywords
  3849. regexp (cons f files) alist)))))))))))))))
  3850. alist)
  3851. (defun org-tag-string-to-alist (s)
  3852. "Return tag alist associated to string S.
  3853. S is a value for TAGS keyword or produced with
  3854. `org-tag-alist-to-string'. Return value is an alist suitable for
  3855. `org-tag-alist' or `org-tag-persistent-alist'."
  3856. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3857. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3858. "\\(?:(\\(.\\))\\)?\\'"))
  3859. alist group-flag)
  3860. (dolist (tokens lines (cdr (nreverse alist)))
  3861. (push '(:newline) alist)
  3862. (while tokens
  3863. (let ((token (pop tokens)))
  3864. (pcase token
  3865. ("{"
  3866. (push '(:startgroup) alist)
  3867. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3868. ("}"
  3869. (push '(:endgroup) alist)
  3870. (setq group-flag nil))
  3871. ("["
  3872. (push '(:startgrouptag) alist)
  3873. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3874. ("]"
  3875. (push '(:endgrouptag) alist)
  3876. (setq group-flag nil))
  3877. (":"
  3878. (push '(:grouptags) alist))
  3879. ((guard (string-match tag-re token))
  3880. (let ((tag (match-string 1 token))
  3881. (key (and (match-beginning 2)
  3882. (string-to-char (match-string 2 token)))))
  3883. ;; Push all tags in groups, no matter if they already
  3884. ;; appear somewhere else in the list.
  3885. (when (or group-flag (not (assoc tag alist)))
  3886. (push (cons tag key) alist))))))))))
  3887. (defun org-tag-alist-to-string (alist &optional skip-key)
  3888. "Return tag string associated to ALIST.
  3889. ALIST is an alist, as defined in `org-tag-alist' or
  3890. `org-tag-persistent-alist', or produced with
  3891. `org-tag-string-to-alist'.
  3892. Return value is a string suitable as a value for \"TAGS\"
  3893. keyword.
  3894. When optional argument SKIP-KEY is non-nil, skip selection keys
  3895. next to tags."
  3896. (mapconcat (lambda (token)
  3897. (pcase token
  3898. (`(:startgroup) "{")
  3899. (`(:endgroup) "}")
  3900. (`(:startgrouptag) "[")
  3901. (`(:endgrouptag) "]")
  3902. (`(:grouptags) ":")
  3903. (`(:newline) "\\n")
  3904. ((and
  3905. (guard (not skip-key))
  3906. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3907. (format "%s(%c)" tag key))
  3908. (`(,(and tag (pred stringp)) . ,_) tag)
  3909. (_ (user-error "Invalid tag token: %S" token))))
  3910. alist
  3911. " "))
  3912. (defun org-tag-alist-to-groups (alist)
  3913. "Return group alist from tag ALIST.
  3914. ALIST is an alist, as defined in `org-tag-alist' or
  3915. `org-tag-persistent-alist', or produced with
  3916. `org-tag-string-to-alist'. Return value is an alist following
  3917. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3918. a string, summarizing TAGS, as a list of strings."
  3919. (let (groups group-status current-group)
  3920. (dolist (token alist (nreverse groups))
  3921. (pcase token
  3922. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3923. (`(,(or :endgroup :endgrouptag))
  3924. (when (eq group-status 'append)
  3925. (push (nreverse current-group) groups))
  3926. (setq group-status nil current-group nil))
  3927. (`(:grouptags) (setq group-status 'append))
  3928. ((and `(,tag . ,_) (guard group-status))
  3929. (if (eq group-status 'append) (push tag current-group)
  3930. (setq current-group (list tag))))
  3931. (_ nil)))))
  3932. (defvar org--file-cache (make-hash-table :test #'equal)
  3933. "Hash table to store contents of files referenced via a URL.
  3934. This is the cache of file URLs read using `org-file-contents'.")
  3935. (defun org-reset-file-cache ()
  3936. "Reset the cache of files downloaded by `org-file-contents'."
  3937. (clrhash org--file-cache))
  3938. (defun org-file-url-p (file)
  3939. "Non-nil if FILE is a URL."
  3940. (require 'ffap)
  3941. (string-match-p ffap-url-regexp file))
  3942. (defun org-file-contents (file &optional noerror nocache)
  3943. "Return the contents of FILE, as a string.
  3944. FILE can be a file name or URL.
  3945. If FILE is a URL, download the contents. If the URL contents are
  3946. already cached in the `org--file-cache' hash table, the download step
  3947. is skipped.
  3948. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3949. from file or URL.
  3950. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3951. is available. This option applies only if FILE is a URL."
  3952. (let* ((is-url (org-file-url-p file))
  3953. (cache (and is-url
  3954. (not nocache)
  3955. (gethash file org--file-cache))))
  3956. (cond
  3957. (cache)
  3958. (is-url
  3959. (with-current-buffer (url-retrieve-synchronously file)
  3960. (goto-char (point-min))
  3961. ;; Move point to after the url-retrieve header.
  3962. (search-forward "\n\n" nil :move)
  3963. ;; Search for the success code only in the url-retrieve header.
  3964. (if (save-excursion
  3965. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3966. ;; Update the cache `org--file-cache' and return contents.
  3967. (puthash file
  3968. (buffer-substring-no-properties (point) (point-max))
  3969. org--file-cache)
  3970. (funcall (if noerror #'message #'user-error)
  3971. "Unable to fetch file from %S"
  3972. file))))
  3973. (t
  3974. (with-temp-buffer
  3975. (condition-case nil
  3976. (progn
  3977. (insert-file-contents file)
  3978. (buffer-string))
  3979. (file-error
  3980. (funcall (if noerror #'message #'user-error)
  3981. "Unable to read file %S"
  3982. file))))))))
  3983. (defun org-extract-log-state-settings (x)
  3984. "Extract the log state setting from a TODO keyword string.
  3985. This will extract info from a string like \"WAIT(w@/!)\"."
  3986. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  3987. (let ((kw (match-string 1 x))
  3988. (log1 (and (match-end 3) (match-string 3 x)))
  3989. (log2 (and (match-end 4) (match-string 4 x))))
  3990. (and (or log1 log2)
  3991. (list kw
  3992. (and log1 (if (equal log1 "!") 'time 'note))
  3993. (and log2 (if (equal log2 "!") 'time 'note)))))))
  3994. (defun org-remove-keyword-keys (list)
  3995. "Remove a pair of parenthesis at the end of each string in LIST."
  3996. (mapcar (lambda (x)
  3997. (if (string-match "(.*)$" x)
  3998. (substring x 0 (match-beginning 0))
  3999. x))
  4000. list))
  4001. (defun org-assign-fast-keys (alist)
  4002. "Assign fast keys to a keyword-key alist.
  4003. Respect keys that are already there."
  4004. (let (new e (alt ?0))
  4005. (while (setq e (pop alist))
  4006. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4007. (cdr e)) ;; Key already assigned.
  4008. (push e new)
  4009. (let ((clist (string-to-list (downcase (car e))))
  4010. (used (append new alist)))
  4011. (when (= (car clist) ?@)
  4012. (pop clist))
  4013. (while (and clist (rassoc (car clist) used))
  4014. (pop clist))
  4015. (unless clist
  4016. (while (rassoc alt used)
  4017. (cl-incf alt)))
  4018. (push (cons (car e) (or (car clist) alt)) new))))
  4019. (nreverse new)))
  4020. ;;; Some variables used in various places
  4021. (defvar org-window-configuration nil
  4022. "Used in various places to store a window configuration.")
  4023. (defvar org-selected-window nil
  4024. "Used in various places to store a window configuration.")
  4025. (defvar org-finish-function nil
  4026. "Function to be called when `C-c C-c' is used.
  4027. This is for getting out of special buffers like capture.")
  4028. (defvar org-last-state)
  4029. ;; Defined somewhere in this file, but used before definition.
  4030. (defvar org-entities) ;; defined in org-entities.el
  4031. (defvar org-struct-menu)
  4032. (defvar org-org-menu)
  4033. (defvar org-tbl-menu)
  4034. ;;;; Define the Org mode
  4035. (defun org-before-change-function (_beg _end)
  4036. "Every change indicates that a table might need an update."
  4037. (setq org-table-may-need-update t))
  4038. (defvar org-mode-map)
  4039. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4040. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4041. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4042. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4043. (defvar bidi-paragraph-direction)
  4044. (defvar buffer-face-mode-face)
  4045. (require 'outline)
  4046. ;; Other stuff we need.
  4047. (require 'time-date)
  4048. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4049. (require 'easymenu)
  4050. (autoload 'easy-menu-add "easymenu")
  4051. (require 'overlay)
  4052. (require 'org-entities)
  4053. (require 'org-faces)
  4054. (require 'org-list)
  4055. (require 'org-pcomplete)
  4056. (require 'org-src)
  4057. (require 'org-footnote)
  4058. (require 'org-macro)
  4059. ;; babel
  4060. (require 'ob)
  4061. ;;;###autoload
  4062. (define-derived-mode org-mode outline-mode "Org"
  4063. "Outline-based notes management and organizer, alias
  4064. \"Carsten's outline-mode for keeping track of everything.\"
  4065. Org mode develops organizational tasks around a NOTES file which
  4066. contains information about projects as plain text. Org mode is
  4067. implemented on top of Outline mode, which is ideal to keep the content
  4068. of large files well structured. It supports ToDo items, deadlines and
  4069. time stamps, which magically appear in the diary listing of the Emacs
  4070. calendar. Tables are easily created with a built-in table editor.
  4071. Plain text URL-like links connect to websites, emails (VM), Usenet
  4072. messages (Gnus), BBDB entries, and any files related to the project.
  4073. For printing and sharing of notes, an Org file (or a part of it)
  4074. can be exported as a structured ASCII or HTML file.
  4075. The following commands are available:
  4076. \\{org-mode-map}"
  4077. (org-load-modules-maybe)
  4078. (org-install-agenda-files-menu)
  4079. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4080. (add-to-invisibility-spec '(org-hide-block . t))
  4081. (add-to-invisibility-spec '(org-hide-drawer . t))
  4082. (setq-local outline-regexp org-outline-regexp)
  4083. (setq-local outline-level 'org-outline-level)
  4084. (setq bidi-paragraph-direction 'left-to-right)
  4085. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4086. (unless org-display-table
  4087. (setq org-display-table (make-display-table)))
  4088. (set-display-table-slot
  4089. org-display-table 4
  4090. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4091. org-ellipsis)))
  4092. (setq buffer-display-table org-display-table))
  4093. (org-set-regexps-and-options)
  4094. (org-set-font-lock-defaults)
  4095. (when (and org-tag-faces (not org-tags-special-faces-re))
  4096. ;; tag faces set outside customize.... force initialization.
  4097. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4098. ;; Calc embedded
  4099. (setq-local calc-embedded-open-mode "# ")
  4100. ;; Modify a few syntax entries
  4101. (modify-syntax-entry ?\" "\"")
  4102. (modify-syntax-entry ?\\ "_")
  4103. (modify-syntax-entry ?~ "_")
  4104. (modify-syntax-entry ?< "(>")
  4105. (modify-syntax-entry ?> ")<")
  4106. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4107. ;; Activate before-change-function
  4108. (setq-local org-table-may-need-update t)
  4109. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4110. ;; Check for running clock before killing a buffer
  4111. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4112. ;; Initialize macros templates.
  4113. (org-macro-initialize-templates)
  4114. ;; Initialize radio targets.
  4115. (org-update-radio-target-regexp)
  4116. ;; Indentation.
  4117. (setq-local indent-line-function 'org-indent-line)
  4118. (setq-local indent-region-function 'org-indent-region)
  4119. ;; Filling and auto-filling.
  4120. (org-setup-filling)
  4121. ;; Comments.
  4122. (org-setup-comments-handling)
  4123. ;; Initialize cache.
  4124. (org-element-cache-reset)
  4125. ;; Beginning/end of defun
  4126. (setq-local beginning-of-defun-function 'org-backward-element)
  4127. (setq-local end-of-defun-function
  4128. (lambda ()
  4129. (if (not (org-at-heading-p))
  4130. (org-forward-element)
  4131. (org-forward-element)
  4132. (forward-char -1))))
  4133. ;; Next error for sparse trees
  4134. (setq-local next-error-function 'org-occur-next-match)
  4135. ;; Make commit log messages from Org documents easier.
  4136. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4137. ;; Make sure dependence stuff works reliably, even for users who set it
  4138. ;; too late :-(
  4139. (if org-enforce-todo-dependencies
  4140. (add-hook 'org-blocker-hook
  4141. 'org-block-todo-from-children-or-siblings-or-parent)
  4142. (remove-hook 'org-blocker-hook
  4143. 'org-block-todo-from-children-or-siblings-or-parent))
  4144. (if org-enforce-todo-checkbox-dependencies
  4145. (add-hook 'org-blocker-hook
  4146. 'org-block-todo-from-checkboxes)
  4147. (remove-hook 'org-blocker-hook
  4148. 'org-block-todo-from-checkboxes))
  4149. ;; Align options lines
  4150. (setq-local
  4151. align-mode-rules-list
  4152. '((org-in-buffer-settings
  4153. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4154. (modes . '(org-mode)))))
  4155. ;; Make isearch reveal context
  4156. (setq-local outline-isearch-open-invisible-function
  4157. (lambda (&rest _) (org-show-context 'isearch)))
  4158. ;; Setup the pcomplete hooks
  4159. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4160. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4161. (setq-local pcomplete-default-completion-function #'ignore)
  4162. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4163. (setq-local pcomplete-termination-string "")
  4164. (add-hook 'completion-at-point-functions
  4165. #'pcomplete-completions-at-point nil t)
  4166. (setq-local buffer-face-mode-face 'org-default)
  4167. ;; If empty file that did not turn on Org mode automatically, make
  4168. ;; it to.
  4169. (when (and org-insert-mode-line-in-empty-file
  4170. (called-interactively-p 'any)
  4171. (= (point-min) (point-max)))
  4172. (insert "# -*- mode: org -*-\n\n"))
  4173. (unless org-inhibit-startup
  4174. (org-unmodified
  4175. (when org-startup-with-beamer-mode (org-beamer-mode))
  4176. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4177. (org-table-map-tables
  4178. (cond ((and org-startup-align-all-tables
  4179. org-startup-shrink-all-tables)
  4180. (lambda () (org-table-align) (org-table-shrink)))
  4181. (org-startup-align-all-tables #'org-table-align)
  4182. (t #'org-table-shrink))
  4183. t))
  4184. (when org-startup-with-inline-images (org-display-inline-images))
  4185. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4186. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4187. (when org-startup-truncated (setq truncate-lines t))
  4188. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4189. ;; Activate `org-table-header-line-mode'
  4190. (when org-table-header-line-p
  4191. (org-table-header-line-mode 1))
  4192. ;; Try to set `org-hide' face correctly.
  4193. (let ((foreground (org-find-invisible-foreground)))
  4194. (when foreground
  4195. (set-face-foreground 'org-hide foreground))))
  4196. ;; Update `customize-package-emacs-version-alist'
  4197. (add-to-list 'customize-package-emacs-version-alist
  4198. '(Org ("8.0" . "24.4")
  4199. ("8.1" . "24.4")
  4200. ("8.2" . "24.4")
  4201. ("8.2.7" . "24.4")
  4202. ("8.3" . "26.1")
  4203. ("9.0" . "26.1")
  4204. ("9.1" . "26.1")
  4205. ("9.2" . "27.1")
  4206. ("9.3" . "27.1")))
  4207. (defvar org-mode-transpose-word-syntax-table
  4208. (let ((st (make-syntax-table text-mode-syntax-table)))
  4209. (dolist (c org-emphasis-alist st)
  4210. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4211. (when (fboundp 'abbrev-table-put)
  4212. (abbrev-table-put org-mode-abbrev-table
  4213. :parents (list text-mode-abbrev-table)))
  4214. (defun org-find-invisible-foreground ()
  4215. (let ((candidates (remove
  4216. "unspecified-bg"
  4217. (nconc
  4218. (list (face-background 'default)
  4219. (face-background 'org-default))
  4220. (mapcar
  4221. (lambda (alist)
  4222. (when (boundp alist)
  4223. (cdr (assq 'background-color (symbol-value alist)))))
  4224. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4225. (list (face-foreground 'org-hide))))))
  4226. (car (remove nil candidates))))
  4227. (defun org-current-time (&optional rounding-minutes past)
  4228. "Current time, possibly rounded to ROUNDING-MINUTES.
  4229. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4230. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4231. the rounding returns a past time."
  4232. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4233. (car org-time-stamp-rounding-minutes)))
  4234. (now (current-time)))
  4235. (if (< r 1)
  4236. now
  4237. (let* ((time (decode-time now))
  4238. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4239. (nthcdr 2 time))))
  4240. (if (or (not past) (org-time-less-p res now))
  4241. res
  4242. (org-time-subtract res (* r 60)))))))
  4243. (defun org-today ()
  4244. "Return today date, considering `org-extend-today-until'."
  4245. (time-to-days
  4246. (org-time-since (* 3600 org-extend-today-until))))
  4247. ;;;; Font-Lock stuff, including the activators
  4248. (require 'font-lock)
  4249. (defconst org-match-sexp-depth 3
  4250. "Number of stacked braces for sub/superscript matching.")
  4251. (defun org-create-multibrace-regexp (left right n)
  4252. "Create a regular expression which will match a balanced sexp.
  4253. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4254. as single character strings.
  4255. The regexp returned will match the entire expression including the
  4256. delimiters. It will also define a single group which contains the
  4257. match except for the outermost delimiters. The maximum depth of
  4258. stacked delimiters is N. Escaping delimiters is not possible."
  4259. (let* ((nothing (concat "[^" left right "]*?"))
  4260. (or "\\|")
  4261. (re nothing)
  4262. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4263. (while (> n 1)
  4264. (setq n (1- n)
  4265. re (concat re or next)
  4266. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4267. (concat left "\\(" re "\\)" right)))
  4268. (defconst org-match-substring-regexp
  4269. (concat
  4270. "\\(\\S-\\)\\([_^]\\)\\("
  4271. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4272. "\\|"
  4273. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4274. "\\|"
  4275. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4276. "The regular expression matching a sub- or superscript.")
  4277. (defconst org-match-substring-with-braces-regexp
  4278. (concat
  4279. "\\(\\S-\\)\\([_^]\\)"
  4280. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4281. "The regular expression matching a sub- or superscript, forcing braces.")
  4282. (defvar org-emph-face nil)
  4283. (defun org-do-emphasis-faces (limit)
  4284. "Run through the buffer and emphasize strings."
  4285. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4286. (car org-emphasis-regexp-components))))
  4287. (catch :exit
  4288. (while (re-search-forward quick-re limit t)
  4289. (let* ((marker (match-string 2))
  4290. (verbatim? (member marker '("~" "="))))
  4291. (when (save-excursion
  4292. (goto-char (match-beginning 0))
  4293. (and
  4294. ;; Do not match table hlines.
  4295. (not (and (equal marker "+")
  4296. (org-match-line
  4297. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4298. ;; Do not match headline stars. Do not consider
  4299. ;; stars of a headline as closing marker for bold
  4300. ;; markup either.
  4301. (not (and (equal marker "*")
  4302. (save-excursion
  4303. (forward-char)
  4304. (skip-chars-backward "*")
  4305. (looking-at-p org-outline-regexp-bol))))
  4306. ;; Match full emphasis markup regexp.
  4307. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4308. ;; Do not span over paragraph boundaries.
  4309. (not (string-match-p org-element-paragraph-separate
  4310. (match-string 2)))
  4311. ;; Do not span over cells in table rows.
  4312. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4313. (string-match-p "|" (match-string 4))))))
  4314. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4315. (m (if org-hide-emphasis-markers 4 2)))
  4316. (font-lock-prepend-text-property
  4317. (match-beginning m) (match-end m) 'face face)
  4318. (when verbatim?
  4319. (org-remove-flyspell-overlays-in
  4320. (match-beginning 0) (match-end 0))
  4321. (remove-text-properties (match-beginning 2) (match-end 2)
  4322. '(display t invisible t intangible t)))
  4323. (add-text-properties (match-beginning 2) (match-end 2)
  4324. '(font-lock-multiline t org-emphasis t))
  4325. (when (and org-hide-emphasis-markers
  4326. (not (org-at-comment-p)))
  4327. (add-text-properties (match-end 4) (match-beginning 5)
  4328. '(invisible org-link))
  4329. (add-text-properties (match-beginning 3) (match-end 3)
  4330. '(invisible org-link)))
  4331. (throw :exit t))))))))
  4332. (defun org-emphasize (&optional char)
  4333. "Insert or change an emphasis, i.e. a font like bold or italic.
  4334. If there is an active region, change that region to a new emphasis.
  4335. If there is no region, just insert the marker characters and position
  4336. the cursor between them.
  4337. CHAR should be the marker character. If it is a space, it means to
  4338. remove the emphasis of the selected region.
  4339. If CHAR is not given (for example in an interactive call) it will be
  4340. prompted for."
  4341. (interactive)
  4342. (let ((erc org-emphasis-regexp-components)
  4343. (string "") beg end move s)
  4344. (if (org-region-active-p)
  4345. (setq beg (region-beginning)
  4346. end (region-end)
  4347. string (buffer-substring beg end))
  4348. (setq move t))
  4349. (unless char
  4350. (message "Emphasis marker or tag: [%s]"
  4351. (mapconcat #'car org-emphasis-alist ""))
  4352. (setq char (read-char-exclusive)))
  4353. (if (equal char ?\s)
  4354. (setq s ""
  4355. move nil)
  4356. (unless (assoc (char-to-string char) org-emphasis-alist)
  4357. (user-error "No such emphasis marker: \"%c\"" char))
  4358. (setq s (char-to-string char)))
  4359. (while (and (> (length string) 1)
  4360. (equal (substring string 0 1) (substring string -1))
  4361. (assoc (substring string 0 1) org-emphasis-alist))
  4362. (setq string (substring string 1 -1)))
  4363. (setq string (concat s string s))
  4364. (when beg (delete-region beg end))
  4365. (unless (or (bolp)
  4366. (string-match (concat "[" (nth 0 erc) "\n]")
  4367. (char-to-string (char-before (point)))))
  4368. (insert " "))
  4369. (unless (or (eobp)
  4370. (string-match (concat "[" (nth 1 erc) "\n]")
  4371. (char-to-string (char-after (point)))))
  4372. (insert " ") (backward-char 1))
  4373. (insert string)
  4374. (and move (backward-char 1))))
  4375. (defconst org-nonsticky-props
  4376. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4377. (defsubst org-rear-nonsticky-at (pos)
  4378. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4379. (defun org-activate-links (limit)
  4380. "Add link properties to links.
  4381. This includes angle, plain, and bracket links."
  4382. (catch :exit
  4383. (while (re-search-forward org-link-any-re limit t)
  4384. (let* ((start (match-beginning 0))
  4385. (end (match-end 0))
  4386. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4387. (visible-end (or (match-end 3) (match-end 2)))
  4388. (style (cond ((eq ?< (char-after start)) 'angle)
  4389. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4390. (t 'plain))))
  4391. (when (and (memq style org-highlight-links)
  4392. ;; Do not span over paragraph boundaries.
  4393. (not (string-match-p org-element-paragraph-separate
  4394. (match-string 0)))
  4395. ;; Do not confuse plain links with tags.
  4396. (not (and (eq style 'plain)
  4397. (let ((face (get-text-property
  4398. (max (1- start) (point-min)) 'face)))
  4399. (if (consp face) (memq 'org-tag face)
  4400. (eq 'org-tag face))))))
  4401. (let* ((link-object (save-excursion
  4402. (goto-char start)
  4403. (save-match-data (org-element-link-parser))))
  4404. (link (org-element-property :raw-link link-object))
  4405. (type (org-element-property :type link-object))
  4406. (path (org-element-property :path link-object))
  4407. (properties ;for link's visible part
  4408. (list
  4409. 'face (pcase (org-link-get-parameter type :face)
  4410. ((and (pred functionp) face) (funcall face path))
  4411. ((and (pred facep) face) face)
  4412. ((and (pred consp) face) face) ;anonymous
  4413. (_ 'org-link))
  4414. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4415. 'highlight)
  4416. 'keymap (or (org-link-get-parameter type :keymap)
  4417. org-mouse-map)
  4418. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4419. ((and (pred stringp) echo) echo)
  4420. ((and (pred functionp) echo) echo)
  4421. (_ (concat "LINK: " link)))
  4422. 'htmlize-link (pcase (org-link-get-parameter type
  4423. :htmlize-link)
  4424. ((and (pred functionp) f) (funcall f))
  4425. (_ `(:uri ,link)))
  4426. 'font-lock-multiline t)))
  4427. (org-remove-flyspell-overlays-in start end)
  4428. (org-rear-nonsticky-at end)
  4429. (if (not (eq 'bracket style))
  4430. (add-text-properties start end properties)
  4431. ;; Handle invisible parts in bracket links.
  4432. (remove-text-properties start end '(invisible nil))
  4433. (let ((hidden
  4434. (append `(invisible
  4435. ,(or (org-link-get-parameter type :display)
  4436. 'org-link))
  4437. properties)))
  4438. (add-text-properties start visible-start hidden)
  4439. (add-text-properties visible-start visible-end properties)
  4440. (add-text-properties visible-end end hidden)
  4441. (org-rear-nonsticky-at visible-start)
  4442. (org-rear-nonsticky-at visible-end)))
  4443. (let ((f (org-link-get-parameter type :activate-func)))
  4444. (when (functionp f)
  4445. (funcall f start end path (eq style 'bracket))))
  4446. (throw :exit t))))) ;signal success
  4447. nil))
  4448. (defun org-activate-code (limit)
  4449. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4450. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4451. (remove-text-properties (match-beginning 0) (match-end 0)
  4452. '(display t invisible t intangible t))
  4453. t))
  4454. (defcustom org-src-fontify-natively t
  4455. "When non-nil, fontify code in code blocks.
  4456. See also the `org-block' face."
  4457. :type 'boolean
  4458. :version "26.1"
  4459. :package-version '(Org . "8.3")
  4460. :group 'org-appearance
  4461. :group 'org-babel)
  4462. (defcustom org-allow-promoting-top-level-subtree nil
  4463. "When non-nil, allow promoting a top level subtree.
  4464. The leading star of the top level headline will be replaced
  4465. by a #."
  4466. :type 'boolean
  4467. :version "24.1"
  4468. :group 'org-appearance)
  4469. (defun org-fontify-meta-lines-and-blocks (limit)
  4470. (condition-case nil
  4471. (org-fontify-meta-lines-and-blocks-1 limit)
  4472. (error (message "Org mode fontification error in %S at %d"
  4473. (current-buffer)
  4474. (line-number-at-pos)))))
  4475. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4476. "Fontify #+ lines and blocks."
  4477. (let ((case-fold-search t))
  4478. (when (re-search-forward
  4479. (rx bol (group (zero-or-more blank) "#"
  4480. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4481. space
  4482. eol))
  4483. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4484. (zero-or-more blank)
  4485. (group (group (zero-or-more (not (any " \t\n"))))
  4486. (zero-or-more blank)
  4487. (group (zero-or-more any)))))
  4488. limit t)
  4489. (let ((beg (match-beginning 0))
  4490. (end-of-beginline (match-end 0))
  4491. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4492. (block-end nil) ; will include \n after end of block content
  4493. (lang (match-string 7)) ; the language, if it is an src block
  4494. (bol-after-beginline (line-beginning-position 2))
  4495. (dc1 (downcase (match-string 2)))
  4496. (dc3 (downcase (match-string 3)))
  4497. (whole-blockline org-fontify-whole-block-delimiter-line)
  4498. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4499. (cond
  4500. ((and (match-end 4) (equal dc3 "+begin"))
  4501. ;; Truly a block
  4502. (setq block-type (downcase (match-string 5))
  4503. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4504. (when (re-search-forward
  4505. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4506. (seq (zero-or-more blank)
  4507. "#+end"
  4508. ,(match-string 4)
  4509. word-end
  4510. (zero-or-more any)))))
  4511. nil t) ;; on purpose, we look further than LIMIT
  4512. ;; We do have a matching #+end line
  4513. (setq beg-of-endline (match-beginning 0)
  4514. end-of-endline (match-end 0)
  4515. nl-before-endline (1- (match-beginning 0)))
  4516. (setq block-end (match-beginning 0)) ; includes the final newline.
  4517. (when quoting
  4518. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4519. (remove-text-properties beg end-of-endline
  4520. '(display t invisible t intangible t)))
  4521. (add-text-properties
  4522. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4523. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4524. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4525. (cond
  4526. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4527. (org-src-font-lock-fontify-block lang block-start block-end)
  4528. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4529. (quoting
  4530. (add-text-properties
  4531. bol-after-beginline beg-of-endline
  4532. (list 'face
  4533. (list :inherit
  4534. (let ((face-name
  4535. (intern (format "org-block-%s" lang))))
  4536. (append (and (facep face-name) (list face-name))
  4537. '(org-block)))))))
  4538. ((not org-fontify-quote-and-verse-blocks))
  4539. ((string= block-type "quote")
  4540. (add-face-text-property
  4541. bol-after-beginline beg-of-endline 'org-quote t))
  4542. ((string= block-type "verse")
  4543. (add-face-text-property
  4544. bol-after-beginline beg-of-endline 'org-verse t)))
  4545. ;; Fontify the #+begin and #+end lines of the blocks
  4546. (add-text-properties
  4547. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4548. '(face org-block-begin-line))
  4549. (unless (string-prefix-p "*" (match-string 1))
  4550. (add-text-properties
  4551. beg-of-endline
  4552. (if whole-blockline
  4553. (let ((beg-of-next-line (1+ end-of-endline)))
  4554. (min (point-max) beg-of-next-line))
  4555. (min (point-max) end-of-endline))
  4556. '(face org-block-end-line)))
  4557. t))
  4558. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4559. (org-remove-flyspell-overlays-in
  4560. (match-beginning 0)
  4561. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4562. (add-text-properties
  4563. beg (match-end 3)
  4564. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4565. '(font-lock-fontified t invisible t)
  4566. '(font-lock-fontified t face org-document-info-keyword)))
  4567. (add-text-properties
  4568. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4569. (if (string-equal dc1 "+title:")
  4570. '(font-lock-fontified t face org-document-title)
  4571. '(font-lock-fontified t face org-document-info))))
  4572. ((string-prefix-p "+caption" dc1)
  4573. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4574. (remove-text-properties (match-beginning 0) (match-end 0)
  4575. '(display t invisible t intangible t))
  4576. ;; Handle short captions.
  4577. (save-excursion
  4578. (beginning-of-line)
  4579. (looking-at (rx (group (zero-or-more blank)
  4580. "#+caption"
  4581. (optional "[" (zero-or-more any) "]")
  4582. ":")
  4583. (zero-or-more blank))))
  4584. (add-text-properties (line-beginning-position) (match-end 1)
  4585. '(font-lock-fontified t face org-meta-line))
  4586. (add-text-properties (match-end 0) (line-end-position)
  4587. '(font-lock-fontified t face org-block))
  4588. t)
  4589. ((member dc3 '(" " ""))
  4590. ; Just a comment, the plus was not there
  4591. (org-remove-flyspell-overlays-in beg (match-end 0))
  4592. (add-text-properties
  4593. beg (match-end 0)
  4594. '(font-lock-fontified t face font-lock-comment-face)))
  4595. (t ;; just any other in-buffer setting, but not indented
  4596. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4597. (remove-text-properties (match-beginning 0) (match-end 0)
  4598. '(display t invisible t intangible t))
  4599. (add-text-properties beg (match-end 0)
  4600. '(font-lock-fontified t face org-meta-line))
  4601. t))))))
  4602. (defun org-fontify-drawers (limit)
  4603. "Fontify drawers."
  4604. (when (re-search-forward org-drawer-regexp limit t)
  4605. (add-text-properties
  4606. (line-beginning-position) (line-beginning-position 2)
  4607. '(font-lock-fontified t face org-drawer))
  4608. (org-remove-flyspell-overlays-in
  4609. (line-beginning-position) (line-beginning-position 2))
  4610. t))
  4611. (defun org-fontify-macros (limit)
  4612. "Fontify macros."
  4613. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4614. (let ((begin (match-beginning 0))
  4615. (opening-end (match-beginning 1)))
  4616. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4617. (match-string 1))
  4618. (let ((end (match-end 1))
  4619. (closing-start (match-beginning 1)))
  4620. (add-text-properties
  4621. begin end
  4622. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4623. (org-remove-flyspell-overlays-in begin end)
  4624. (when org-hide-macro-markers
  4625. (add-text-properties begin opening-end '(invisible t))
  4626. (add-text-properties closing-start end '(invisible t)))
  4627. t)))))
  4628. (defun org-fontify-extend-region (beg end _old-len)
  4629. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4630. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4631. (extend (lambda (r1 r2 dir)
  4632. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4633. (replace-regexp-in-string "[][]" r2
  4634. (match-string-no-properties 0)))))
  4635. (re-search-forward (regexp-quote re) nil t dir)))))
  4636. (save-match-data
  4637. (save-excursion
  4638. (goto-char beg)
  4639. (back-to-indentation)
  4640. (cond ((looking-at end-re)
  4641. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4642. ((looking-at begin-re)
  4643. (cons beg (or (funcall extend "end" "]" 1) end)))
  4644. (t (cons beg end)))))))
  4645. (defun org-activate-footnote-links (limit)
  4646. "Add text properties for footnotes."
  4647. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4648. (when fn
  4649. (let* ((beg (nth 1 fn))
  4650. (end (nth 2 fn))
  4651. (label (car fn))
  4652. (referencep (/= (line-beginning-position) beg)))
  4653. (when (and referencep (nth 3 fn))
  4654. (save-excursion
  4655. (goto-char beg)
  4656. (search-forward (or label "fn:"))
  4657. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4658. (add-text-properties beg end
  4659. (list 'mouse-face 'highlight
  4660. 'keymap org-mouse-map
  4661. 'help-echo
  4662. (if referencep "Footnote reference"
  4663. "Footnote definition")
  4664. 'font-lock-fontified t
  4665. 'font-lock-multiline t
  4666. 'face 'org-footnote))))))
  4667. (defun org-activate-dates (limit)
  4668. "Add text properties for dates."
  4669. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4670. (not (equal (char-before (match-beginning 0)) 91)))
  4671. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4672. (add-text-properties (match-beginning 0) (match-end 0)
  4673. (list 'mouse-face 'highlight
  4674. 'keymap org-mouse-map))
  4675. (org-rear-nonsticky-at (match-end 0))
  4676. (when org-display-custom-times
  4677. ;; If it's a date range, activate custom time for second date.
  4678. (when (match-end 3)
  4679. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4680. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4681. t))
  4682. (defun org-activate-target-links (limit)
  4683. "Add text properties for target matches."
  4684. (when org-target-link-regexp
  4685. (let ((case-fold-search t))
  4686. ;; `org-target-link-regexp' matches one character before the
  4687. ;; actual target.
  4688. (unless (bolp) (forward-char -1))
  4689. (when (re-search-forward org-target-link-regexp limit t)
  4690. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4691. (add-text-properties (match-beginning 1) (match-end 1)
  4692. (list 'mouse-face 'highlight
  4693. 'keymap org-mouse-map
  4694. 'help-echo "Radio target link"
  4695. 'org-linked-text t))
  4696. (org-rear-nonsticky-at (match-end 1))
  4697. t))))
  4698. (defvar org-latex-and-related-regexp nil
  4699. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4700. (defun org-compute-latex-and-related-regexp ()
  4701. "Compute regular expression for LaTeX, entities and sub/superscript.
  4702. Result depends on variable `org-highlight-latex-and-related'."
  4703. (let ((re-sub
  4704. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4705. ((eq org-use-sub-superscripts '{})
  4706. (list org-match-substring-with-braces-regexp))
  4707. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4708. (re-latex
  4709. (when (or (memq 'latex org-highlight-latex-and-related)
  4710. (memq 'native org-highlight-latex-and-related))
  4711. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4712. (delq nil
  4713. (mapcar (lambda (x)
  4714. (and (member (car x) matchers) (nth 1 x)))
  4715. org-latex-regexps)))))
  4716. (re-entities
  4717. (when (memq 'entities org-highlight-latex-and-related)
  4718. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4719. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4720. (setq-local org-latex-and-related-regexp
  4721. (mapconcat #'identity
  4722. (append re-latex re-entities re-sub)
  4723. "\\|"))))
  4724. (defun org-do-latex-and-related (_limit)
  4725. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4726. Stop at first highlighted object, if any. Return t if some
  4727. highlighting was done, nil otherwise."
  4728. (when (org-string-nw-p org-latex-and-related-regexp)
  4729. (catch 'found
  4730. (while (re-search-forward org-latex-and-related-regexp
  4731. nil t) ;; on purpose, we ignore LIMIT
  4732. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4733. org-special-keyword)))
  4734. (save-excursion
  4735. (goto-char (1+ (match-beginning 0)))
  4736. (face-at-point nil t)))
  4737. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4738. '(?_ ?^))
  4739. 1
  4740. 0))
  4741. (start (+ offset (match-beginning 0)))
  4742. (end (match-end 0)))
  4743. (if (memq 'native org-highlight-latex-and-related)
  4744. (org-src-font-lock-fontify-block "latex" start end)
  4745. (font-lock-prepend-text-property start end
  4746. 'face 'org-latex-and-related))
  4747. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4748. '(font-lock-multiline t)))
  4749. (throw 'found t)))
  4750. nil)))
  4751. (defun org-restart-font-lock ()
  4752. "Restart `font-lock-mode', to force refontification."
  4753. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4754. (font-lock-mode -1)
  4755. (font-lock-mode 1)))
  4756. (defun org-activate-tags (limit)
  4757. (when (re-search-forward org-tag-line-re limit t)
  4758. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4759. (add-text-properties (match-beginning 1) (match-end 1)
  4760. (list 'mouse-face 'highlight
  4761. 'keymap org-mouse-map))
  4762. (org-rear-nonsticky-at (match-end 1))
  4763. t))
  4764. (defun org-outline-level ()
  4765. "Compute the outline level of the heading at point.
  4766. If this is called at a normal headline, the level is the number
  4767. of stars. Use `org-reduced-level' to remove the effect of
  4768. `org-odd-levels'. Unlike to `org-current-level', this function
  4769. takes into consideration inlinetasks."
  4770. (org-with-wide-buffer
  4771. (end-of-line)
  4772. (if (re-search-backward org-outline-regexp-bol nil t)
  4773. (1- (- (match-end 0) (match-beginning 0)))
  4774. 0)))
  4775. (defvar org-font-lock-keywords nil)
  4776. (defsubst org-re-property (property &optional literal allow-null value)
  4777. "Return a regexp matching a PROPERTY line.
  4778. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4779. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4780. non-nil, match properties even without a value.
  4781. Match group 3 is set to the value when it exists. If there is no
  4782. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4783. With optional argument VALUE, match only property lines with
  4784. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4785. unless LITERAL is non-nil."
  4786. (concat
  4787. "^\\(?4:[ \t]*\\)"
  4788. (format "\\(?1::\\(?2:%s\\):\\)"
  4789. (if literal property (regexp-quote property)))
  4790. (cond (value
  4791. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4792. (if literal value (regexp-quote value))))
  4793. (allow-null
  4794. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4795. (t
  4796. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4797. (defconst org-property-re
  4798. (org-re-property "\\S-+" 'literal t)
  4799. "Regular expression matching a property line.
  4800. There are four matching groups:
  4801. 1: :PROPKEY: including the leading and trailing colon,
  4802. 2: PROPKEY without the leading and trailing colon,
  4803. 3: PROPVAL without leading or trailing spaces,
  4804. 4: the indentation of the current line,
  4805. 5: trailing whitespace.")
  4806. (defvar org-font-lock-hook nil
  4807. "Functions to be called for special font lock stuff.")
  4808. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4809. (defvar org-font-lock-set-keywords-hook nil
  4810. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4811. This is called after `org-font-lock-extra-keywords' is defined, but before
  4812. it is installed to be used by font lock. This can be useful if something
  4813. needs to be inserted at a specific position in the font-lock sequence.")
  4814. (defun org-font-lock-hook (limit)
  4815. "Run `org-font-lock-hook' within LIMIT."
  4816. (run-hook-with-args 'org-font-lock-hook limit))
  4817. (defun org-set-font-lock-defaults ()
  4818. "Set font lock defaults for the current buffer."
  4819. (let* ((em org-fontify-emphasized-text)
  4820. (lk org-highlight-links)
  4821. (org-font-lock-extra-keywords
  4822. (list
  4823. ;; Call the hook
  4824. '(org-font-lock-hook)
  4825. ;; Headlines
  4826. `(,(if org-fontify-whole-heading-line
  4827. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4828. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4829. (1 (org-get-level-face 1))
  4830. (2 (org-get-level-face 2))
  4831. (3 (org-get-level-face 3)))
  4832. ;; Table lines
  4833. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4834. (1 'org-table t))
  4835. ;; Table internals
  4836. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4837. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4838. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4839. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4840. ;; Properties
  4841. (list org-property-re
  4842. '(1 'org-special-keyword t)
  4843. '(3 'org-property-value t))
  4844. ;; Drawers
  4845. '(org-fontify-drawers)
  4846. ;; Link related fontification.
  4847. '(org-activate-links)
  4848. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4849. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4850. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4851. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4852. ;; Targets.
  4853. (list org-radio-target-regexp '(0 'org-target t))
  4854. (list org-target-regexp '(0 'org-target t))
  4855. ;; Diary sexps.
  4856. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4857. ;; Macro
  4858. '(org-fontify-macros)
  4859. ;; TODO keyword
  4860. (list (format org-heading-keyword-regexp-format
  4861. org-todo-regexp)
  4862. '(2 (org-get-todo-face 2) t))
  4863. ;; TODO
  4864. (when org-fontify-todo-headline
  4865. (list (format org-heading-keyword-regexp-format
  4866. (concat
  4867. "\\(?:"
  4868. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4869. "\\)"))
  4870. '(2 'org-headline-todo t)))
  4871. ;; DONE
  4872. (when org-fontify-done-headline
  4873. (list (format org-heading-keyword-regexp-format
  4874. (concat
  4875. "\\(?:"
  4876. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4877. "\\)"))
  4878. '(2 'org-headline-done t)))
  4879. ;; Priorities
  4880. '(org-font-lock-add-priority-faces)
  4881. ;; Tags
  4882. '(org-font-lock-add-tag-faces)
  4883. ;; Tags groups
  4884. (when (and org-group-tags org-tag-groups-alist)
  4885. (list (concat org-outline-regexp-bol ".+\\(:"
  4886. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4887. ":\\).*$")
  4888. '(1 'org-tag-group prepend)))
  4889. ;; Special keywords
  4890. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4891. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4892. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4893. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4894. ;; Emphasis
  4895. (when em '(org-do-emphasis-faces))
  4896. ;; Checkboxes
  4897. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4898. 1 'org-checkbox prepend)
  4899. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4900. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4901. (0 (org-get-checkbox-statistics-face) t)))
  4902. ;; Description list items
  4903. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4904. 1 'org-list-dt prepend)
  4905. ;; ARCHIVEd headings
  4906. (list (concat
  4907. org-outline-regexp-bol
  4908. "\\(.*:" org-archive-tag ":.*\\)")
  4909. '(1 'org-archived prepend))
  4910. ;; Specials
  4911. '(org-do-latex-and-related)
  4912. '(org-fontify-entities)
  4913. '(org-raise-scripts)
  4914. ;; Code
  4915. '(org-activate-code (1 'org-code t))
  4916. ;; COMMENT
  4917. (list (format
  4918. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  4919. org-todo-regexp
  4920. org-comment-string)
  4921. '(9 'org-special-keyword t))
  4922. ;; Blocks and meta lines
  4923. '(org-fontify-meta-lines-and-blocks))))
  4924. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  4925. (run-hooks 'org-font-lock-set-keywords-hook)
  4926. ;; Now set the full font-lock-keywords
  4927. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  4928. (setq-local font-lock-defaults
  4929. '(org-font-lock-keywords t nil nil backward-paragraph))
  4930. (setq-local font-lock-extend-after-change-region-function
  4931. #'org-fontify-extend-region)
  4932. (kill-local-variable 'font-lock-keywords)
  4933. nil))
  4934. (defun org-toggle-pretty-entities ()
  4935. "Toggle the composition display of entities as UTF8 characters."
  4936. (interactive)
  4937. (setq-local org-pretty-entities (not org-pretty-entities))
  4938. (org-restart-font-lock)
  4939. (if org-pretty-entities
  4940. (message "Entities are now displayed as UTF8 characters")
  4941. (save-restriction
  4942. (widen)
  4943. (decompose-region (point-min) (point-max))
  4944. (message "Entities are now displayed as plain text"))))
  4945. (defvar-local org-custom-properties-overlays nil
  4946. "List of overlays used for custom properties.")
  4947. (defun org-toggle-custom-properties-visibility ()
  4948. "Display or hide properties in `org-custom-properties'."
  4949. (interactive)
  4950. (if org-custom-properties-overlays
  4951. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  4952. (setq org-custom-properties-overlays nil))
  4953. (when org-custom-properties
  4954. (org-with-wide-buffer
  4955. (goto-char (point-min))
  4956. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  4957. (while (re-search-forward regexp nil t)
  4958. (let ((end (cdr (save-match-data (org-get-property-block)))))
  4959. (when (and end (< (point) end))
  4960. ;; Hide first custom property in current drawer.
  4961. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  4962. (overlay-put o 'invisible t)
  4963. (overlay-put o 'org-custom-property t)
  4964. (push o org-custom-properties-overlays))
  4965. ;; Hide additional custom properties in the same drawer.
  4966. (while (re-search-forward regexp end t)
  4967. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  4968. (overlay-put o 'invisible t)
  4969. (overlay-put o 'org-custom-property t)
  4970. (push o org-custom-properties-overlays)))))
  4971. ;; Each entry is limited to a single property drawer.
  4972. (outline-next-heading)))))))
  4973. (defun org-fontify-entities (limit)
  4974. "Find an entity to fontify."
  4975. (let (ee)
  4976. (when org-pretty-entities
  4977. (catch 'match
  4978. ;; "\_ "-family is left out on purpose. Only the first one,
  4979. ;; i.e., "\_ ", could be fontified anyway, and it would be
  4980. ;; confusing when adding a second white space character.
  4981. (while (re-search-forward
  4982. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  4983. limit t)
  4984. (when (and (not (org-at-comment-p))
  4985. (setq ee (org-entity-get (match-string 1)))
  4986. (= (length (nth 6 ee)) 1))
  4987. (let* ((end (if (equal (match-string 2) "{}")
  4988. (match-end 2)
  4989. (match-end 1))))
  4990. (add-text-properties
  4991. (match-beginning 0) end
  4992. (list 'font-lock-fontified t))
  4993. (compose-region (match-beginning 0) end
  4994. (nth 6 ee) nil)
  4995. (backward-char 1)
  4996. (throw 'match t))))
  4997. nil))))
  4998. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  4999. "Fontify string S like in Org mode."
  5000. (with-temp-buffer
  5001. (insert s)
  5002. (let ((org-odd-levels-only odd-levels))
  5003. (org-mode)
  5004. (org-font-lock-ensure)
  5005. (buffer-string))))
  5006. (defun org-get-level-face (n)
  5007. "Get the right face for match N in font-lock matching of headlines."
  5008. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5009. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5010. (org-f (if org-cycle-level-faces
  5011. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5012. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5013. (cond
  5014. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5015. ((eq n 2) org-f)
  5016. (t (unless org-level-color-stars-only org-f)))))
  5017. (defun org-face-from-face-or-color (context inherit face-or-color)
  5018. "Create a face list that inherits INHERIT, but sets the foreground color.
  5019. When FACE-OR-COLOR is not a string, just return it."
  5020. (if (stringp face-or-color)
  5021. (list :inherit inherit
  5022. (cdr (assoc context org-faces-easy-properties))
  5023. face-or-color)
  5024. face-or-color))
  5025. (defun org-get-todo-face (kwd)
  5026. "Get the right face for a TODO keyword KWD.
  5027. If KWD is a number, get the corresponding match group."
  5028. (when (numberp kwd) (setq kwd (match-string kwd)))
  5029. (or (org-face-from-face-or-color
  5030. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5031. (and (member kwd org-done-keywords) 'org-done)
  5032. 'org-todo))
  5033. (defun org-get-priority-face (priority)
  5034. "Get the right face for PRIORITY.
  5035. PRIORITY is a character."
  5036. (or (org-face-from-face-or-color
  5037. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5038. 'org-priority))
  5039. (defun org-get-tag-face (tag)
  5040. "Get the right face for TAG.
  5041. If TAG is a number, get the corresponding match group."
  5042. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5043. (or (org-face-from-face-or-color
  5044. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5045. 'org-tag)))
  5046. (defvar org-priority-regexp) ; defined later in the file
  5047. (defun org-font-lock-add-priority-faces (limit)
  5048. "Add the special priority faces."
  5049. (while (re-search-forward org-priority-regexp limit t)
  5050. (add-text-properties
  5051. (match-beginning 1) (match-end 1)
  5052. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5053. 'font-lock-fontified t))))
  5054. (defun org-font-lock-add-tag-faces (limit)
  5055. "Add the special tag faces."
  5056. (when (and org-tag-faces org-tags-special-faces-re)
  5057. (while (re-search-forward org-tags-special-faces-re limit t)
  5058. (add-text-properties (match-beginning 1) (match-end 1)
  5059. (list 'face (org-get-tag-face 1)
  5060. 'font-lock-fontified t))
  5061. (backward-char 1))))
  5062. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5063. "Remove fontification and activation overlays from links."
  5064. (font-lock-default-unfontify-region beg end)
  5065. (let* ((buffer-undo-list t)
  5066. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5067. (inhibit-modification-hooks t)
  5068. deactivate-mark buffer-file-name buffer-file-truename)
  5069. (decompose-region beg end)
  5070. (remove-text-properties beg end
  5071. '(mouse-face t keymap t org-linked-text t
  5072. invisible t intangible t
  5073. org-emphasis t))
  5074. (org-remove-font-lock-display-properties beg end)))
  5075. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5076. ((raise 0.3) (height 0.7))
  5077. ((raise -0.5))
  5078. ((raise 0.5)))
  5079. "Display properties for showing superscripts and subscripts.")
  5080. (defun org-remove-font-lock-display-properties (beg end)
  5081. "Remove specific display properties that have been added by font lock.
  5082. The will remove the raise properties that are used to show superscripts
  5083. and subscripts."
  5084. (let (next prop)
  5085. (while (< beg end)
  5086. (setq next (next-single-property-change beg 'display nil end)
  5087. prop (get-text-property beg 'display))
  5088. (when (member prop org-script-display)
  5089. (put-text-property beg next 'display nil))
  5090. (setq beg next))))
  5091. (defun org-raise-scripts (limit)
  5092. "Add raise properties to sub/superscripts."
  5093. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5094. (re-search-forward
  5095. (if (eq org-use-sub-superscripts t)
  5096. org-match-substring-regexp
  5097. org-match-substring-with-braces-regexp)
  5098. limit t))
  5099. (let* ((pos (point)) table-p comment-p
  5100. (mpos (match-beginning 3))
  5101. (emph-p (get-text-property mpos 'org-emphasis))
  5102. (link-p (get-text-property mpos 'mouse-face))
  5103. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5104. (goto-char (point-at-bol))
  5105. (setq table-p (looking-at-p org-table-dataline-regexp)
  5106. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5107. (goto-char pos)
  5108. ;; Handle a_b^c
  5109. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5110. (unless (or comment-p emph-p link-p keyw-p)
  5111. (put-text-property (match-beginning 3) (match-end 0)
  5112. 'display
  5113. (if (equal (char-after (match-beginning 2)) ?^)
  5114. (nth (if table-p 3 1) org-script-display)
  5115. (nth (if table-p 2 0) org-script-display)))
  5116. (add-text-properties (match-beginning 2) (match-end 2)
  5117. (list 'invisible t))
  5118. (when (and (eq (char-after (match-beginning 3)) ?{)
  5119. (eq (char-before (match-end 3)) ?}))
  5120. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5121. (list 'invisible t))
  5122. (add-text-properties (1- (match-end 3)) (match-end 3)
  5123. (list 'invisible t))))
  5124. t)))
  5125. (defun org-remove-empty-overlays-at (pos)
  5126. "Remove outline overlays that do not contain non-white stuff."
  5127. (dolist (o (overlays-at pos))
  5128. (and (eq 'outline (overlay-get o 'invisible))
  5129. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5130. (overlay-end o))))
  5131. (delete-overlay o))))
  5132. (defun org-show-empty-lines-in-parent ()
  5133. "Move to the parent and re-show empty lines before visible headlines."
  5134. (save-excursion
  5135. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5136. (org-cycle-show-empty-lines context))))
  5137. (defun org-files-list ()
  5138. "Return `org-agenda-files' list, plus all open Org files.
  5139. This is useful for operations that need to scan all of a user's
  5140. open and agenda-wise Org files."
  5141. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5142. (dolist (buf (buffer-list))
  5143. (with-current-buffer buf
  5144. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5145. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5146. :test #'equal))))
  5147. files))
  5148. (defsubst org-entry-beginning-position ()
  5149. "Return the beginning position of the current entry."
  5150. (save-excursion (org-back-to-heading t) (point)))
  5151. (defsubst org-entry-end-position ()
  5152. "Return the end position of the current entry."
  5153. (save-excursion (outline-next-heading) (point)))
  5154. (defun org-subtree-end-visible-p ()
  5155. "Is the end of the current subtree visible?"
  5156. (pos-visible-in-window-p
  5157. (save-excursion (org-end-of-subtree t) (point))))
  5158. (defun org-first-headline-recenter ()
  5159. "Move cursor to the first headline and recenter the headline."
  5160. (let ((window (get-buffer-window)))
  5161. (when window
  5162. (goto-char (point-min))
  5163. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5164. (set-window-start window (line-beginning-position))))))
  5165. ;;; Visibility (headlines, blocks, drawers)
  5166. ;;;; Headlines visibility
  5167. (defun org-show-entry ()
  5168. "Show the body directly following this heading.
  5169. Show the heading too, if it is currently invisible."
  5170. (interactive)
  5171. (save-excursion
  5172. (ignore-errors
  5173. (org-back-to-heading t)
  5174. (org-flag-region
  5175. (line-end-position 0)
  5176. (save-excursion
  5177. (if (re-search-forward
  5178. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5179. (match-beginning 1)
  5180. (point-max)))
  5181. nil
  5182. 'outline))))
  5183. (defun org-show-children (&optional level)
  5184. "Show all direct subheadings of this heading.
  5185. Prefix arg LEVEL is how many levels below the current level
  5186. should be shown. Default is enough to cause the following
  5187. heading to appear."
  5188. (interactive "p")
  5189. (save-excursion
  5190. (org-back-to-heading t)
  5191. (let* ((current-level (funcall outline-level))
  5192. (max-level (org-get-valid-level
  5193. current-level
  5194. (if level (prefix-numeric-value level) 1)))
  5195. (end (save-excursion (org-end-of-subtree t t)))
  5196. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5197. (past-first-child nil)
  5198. ;; Make sure to skip inlinetasks.
  5199. (re (format regexp-fmt
  5200. current-level
  5201. (cond
  5202. ((not (featurep 'org-inlinetask)) "")
  5203. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5204. 3))
  5205. (t (1- org-inlinetask-min-level))))))
  5206. ;; Display parent heading.
  5207. (org-flag-heading nil)
  5208. (forward-line)
  5209. ;; Display children. First child may be deeper than expected
  5210. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5211. ;; MAX-LEVEL accordingly.
  5212. (while (re-search-forward re end t)
  5213. (unless past-first-child
  5214. (setq re (format regexp-fmt
  5215. current-level
  5216. (max (funcall outline-level) max-level)))
  5217. (setq past-first-child t))
  5218. (org-flag-heading nil)))))
  5219. (defun org-show-subtree ()
  5220. "Show everything after this heading at deeper levels."
  5221. (interactive)
  5222. (org-flag-region
  5223. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5224. ;;;; Blocks visibility
  5225. (defun org-hide-block-toggle-maybe ()
  5226. "Toggle visibility of block at point.
  5227. Unlike to `org-hide-block-toggle', this function does not throw
  5228. an error. Return a non-nil value when toggling is successful."
  5229. (interactive)
  5230. (ignore-errors (org-hide-block-toggle)))
  5231. (defun org-hide-block-toggle (&optional force)
  5232. "Toggle the visibility of the current block.
  5233. When optional argument FORCE is `off', make block visible. If it
  5234. is non-nil, hide it unconditionally. Throw an error when not at
  5235. a block. Return a non-nil value when toggling is successful."
  5236. (interactive)
  5237. (let ((element (org-element-at-point)))
  5238. (unless (memq (org-element-type element)
  5239. '(center-block comment-block dynamic-block example-block
  5240. export-block quote-block special-block
  5241. src-block verse-block))
  5242. (user-error "Not at a block"))
  5243. (let* ((post (org-element-property :post-affiliated element))
  5244. (start (save-excursion
  5245. (goto-char post)
  5246. (line-end-position)))
  5247. (end (save-excursion
  5248. (goto-char (org-element-property :end element))
  5249. (skip-chars-backward " \t\n")
  5250. (line-end-position))))
  5251. ;; Do nothing when not before or at the block opening line or at
  5252. ;; the block closing line.
  5253. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5254. (cond ((eq force 'off)
  5255. (org-flag-region start end nil 'org-hide-block))
  5256. (force
  5257. (org-flag-region start end t 'org-hide-block))
  5258. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5259. (org-flag-region start end nil 'org-hide-block))
  5260. (t
  5261. (org-flag-region start end t 'org-hide-block)))
  5262. ;; When the block is hidden away, make sure point is left in
  5263. ;; a visible part of the buffer.
  5264. (when (invisible-p (max (1- (point)) (point-min)))
  5265. (goto-char post))
  5266. ;; Signal success.
  5267. t))))
  5268. (defun org-hide-block-toggle-all ()
  5269. "Toggle the visibility of all blocks in the current buffer."
  5270. (org-block-map 'org-hide-block-toggle))
  5271. (defun org-hide-block-all ()
  5272. "Fold all blocks in the current buffer."
  5273. (interactive)
  5274. (org-show-all '(blocks))
  5275. (org-block-map 'org-hide-block-toggle-maybe))
  5276. ;;;; Drawers visibility
  5277. (defun org-cycle-hide-drawers (state &optional exceptions)
  5278. "Re-hide all drawers after a visibility state change.
  5279. STATE should be one of the symbols listed in the docstring of
  5280. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5281. a list of strings specifying which drawers should not be hidden."
  5282. (when (and (derived-mode-p 'org-mode)
  5283. (not (memq state '(overview folded contents))))
  5284. (save-excursion
  5285. (let* ((globalp (eq state 'all))
  5286. (beg (if globalp (point-min) (point)))
  5287. (end (if globalp (point-max)
  5288. (if (eq state 'children)
  5289. (save-excursion (outline-next-heading) (point))
  5290. (org-end-of-subtree t)))))
  5291. (goto-char beg)
  5292. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5293. (unless (member-ignore-case (match-string 1) exceptions)
  5294. (let ((drawer (org-element-at-point)))
  5295. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5296. (org-flag-drawer t drawer)
  5297. ;; Make sure to skip drawer entirely or we might flag
  5298. ;; it another time when matching its ending line with
  5299. ;; `org-drawer-regexp'.
  5300. (goto-char (org-element-property :end drawer))))))))))
  5301. (defun org-flag-drawer (flag &optional element beg end)
  5302. "When FLAG is non-nil, hide the drawer we are at.
  5303. Otherwise make it visible.
  5304. When optional argument ELEMENT is a parsed drawer, as returned by
  5305. `org-element-at-point', hide or show that drawer instead.
  5306. When buffer positions BEG and END are provided, hide or show that
  5307. region as a drawer without further ado."
  5308. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5309. (let ((drawer (or element
  5310. (and (save-excursion
  5311. (beginning-of-line)
  5312. (looking-at-p org-drawer-regexp))
  5313. (org-element-at-point)))))
  5314. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5315. (let ((post (org-element-property :post-affiliated drawer)))
  5316. (org-flag-region
  5317. (save-excursion (goto-char post) (line-end-position))
  5318. (save-excursion (goto-char (org-element-property :end drawer))
  5319. (skip-chars-backward " \t\n")
  5320. (line-end-position))
  5321. flag 'org-hide-drawer)
  5322. ;; When the drawer is hidden away, make sure point lies in
  5323. ;; a visible part of the buffer.
  5324. (when (invisible-p (max (1- (point)) (point-min)))
  5325. (goto-char post)))))))
  5326. ;;;; Visibility cycling
  5327. (defvar-local org-cycle-global-status nil)
  5328. (put 'org-cycle-global-status 'org-state t)
  5329. (defvar-local org-cycle-subtree-status nil)
  5330. (put 'org-cycle-subtree-status 'org-state t)
  5331. (defun org-show-all (&optional types)
  5332. "Show all contents in the visible part of the buffer.
  5333. By default, the function expands headings, blocks and drawers.
  5334. When optional argument TYPE is a list of symbols among `blocks',
  5335. `drawers' and `headings', to only expand one specific type."
  5336. (interactive)
  5337. (dolist (type (or types '(blocks drawers headings)))
  5338. (org-flag-region (point-min) (point-max) nil
  5339. (pcase type
  5340. (`blocks 'org-hide-block)
  5341. (`drawers 'org-hide-drawer)
  5342. (`headings 'outline)
  5343. (_ (error "Invalid type: %S" type))))))
  5344. ;;;###autoload
  5345. (defun org-cycle (&optional arg)
  5346. "TAB-action and visibility cycling for Org mode.
  5347. This is the command invoked in Org mode by the `TAB' key. Its main
  5348. purpose is outline visibility cycling, but it also invokes other actions
  5349. in special contexts.
  5350. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5351. the entire
  5352. buffer through 3 states (global cycling)
  5353. 1. OVERVIEW: Show only top-level headlines.
  5354. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5355. 3. SHOW ALL: Show everything.
  5356. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5357. switch to the startup visibility,
  5358. determined by the variable `org-startup-folded', and by any VISIBILITY
  5359. properties in the buffer.
  5360. With a `\\[universal-argument] \\[universal-argument] \
  5361. \\[universal-argument]' prefix argument, show the entire buffer, including
  5362. any drawers.
  5363. When inside a table, re-align the table and move to the next field.
  5364. When point is at the beginning of a headline, rotate the subtree started
  5365. by this line through 3 different states (local cycling)
  5366. 1. FOLDED: Only the main headline is shown.
  5367. 2. CHILDREN: The main headline and the direct children are shown.
  5368. From this state, you can move to one of the children
  5369. and zoom in further.
  5370. 3. SUBTREE: Show the entire subtree, including body text.
  5371. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5372. When point is at the beginning of an empty headline and the variable
  5373. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5374. of the headline by demoting and promoting it to likely levels. This
  5375. speeds up creation document structure by pressing `TAB' once or several
  5376. times right after creating a new headline.
  5377. When there is a numeric prefix, go up to a heading with level ARG, do
  5378. a `show-subtree' and return to the previous cursor position. If ARG
  5379. is negative, go up that many levels.
  5380. When point is not at the beginning of a headline, execute the global
  5381. binding for `TAB', which is re-indenting the line. See the option
  5382. `org-cycle-emulate-tab' for details.
  5383. As a special case, if point is at the beginning of the buffer and there is
  5384. no headline in line 1, this function will act as if called with prefix arg
  5385. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5386. prefix arg, but only
  5387. if the variable `org-cycle-global-at-bob' is t."
  5388. (interactive "P")
  5389. (org-load-modules-maybe)
  5390. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5391. (and org-cycle-level-after-item/entry-creation
  5392. (or (org-cycle-level)
  5393. (org-cycle-item-indentation))))
  5394. (let* ((limit-level
  5395. (or org-cycle-max-level
  5396. (and (boundp 'org-inlinetask-min-level)
  5397. org-inlinetask-min-level
  5398. (1- org-inlinetask-min-level))))
  5399. (nstars (and limit-level
  5400. (if org-odd-levels-only
  5401. (and limit-level (1- (* limit-level 2)))
  5402. limit-level)))
  5403. (org-outline-regexp
  5404. (if (not (derived-mode-p 'org-mode))
  5405. outline-regexp
  5406. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5407. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5408. (not (looking-at org-outline-regexp))))
  5409. (org-cycle-hook
  5410. (if bob-special
  5411. (delq 'org-optimize-window-after-visibility-change
  5412. (copy-sequence org-cycle-hook))
  5413. org-cycle-hook))
  5414. (pos (point)))
  5415. (cond
  5416. ((equal arg '(16))
  5417. (setq last-command 'dummy)
  5418. (org-set-startup-visibility)
  5419. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5420. ((equal arg '(64))
  5421. (org-show-all)
  5422. (org-unlogged-message "Entire buffer visible, including drawers"))
  5423. ((equal arg '(4)) (org-cycle-internal-global))
  5424. ;; Try hiding block at point.
  5425. ((org-hide-block-toggle-maybe))
  5426. ;; Try cdlatex TAB completion
  5427. ((org-try-cdlatex-tab))
  5428. ;; Table: enter it or move to the next field.
  5429. ((org-at-table-p 'any)
  5430. (if (org-at-table.el-p)
  5431. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5432. Use `\\[org-edit-special]' to edit table.el tables"))
  5433. (if arg (org-table-edit-field t)
  5434. (org-table-justify-field-maybe)
  5435. (call-interactively 'org-table-next-field))))
  5436. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5437. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5438. (bob-special (org-cycle-internal-global))
  5439. ;; Drawers: delegate to `org-flag-drawer'.
  5440. ((save-excursion
  5441. (beginning-of-line 1)
  5442. (looking-at org-drawer-regexp))
  5443. (org-flag-drawer ; toggle block visibility
  5444. (not (get-char-property (match-end 0) 'invisible))))
  5445. ;; Show-subtree, ARG levels up from here.
  5446. ((integerp arg)
  5447. (save-excursion
  5448. (org-back-to-heading)
  5449. (outline-up-heading (if (< arg 0) (- arg)
  5450. (- (funcall outline-level) arg)))
  5451. (org-show-subtree)))
  5452. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5453. ((and (featurep 'org-inlinetask)
  5454. (org-inlinetask-at-task-p)
  5455. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5456. (org-inlinetask-toggle-visibility))
  5457. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5458. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5459. (save-excursion (move-beginning-of-line 1)
  5460. (looking-at org-outline-regexp)))
  5461. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5462. (org-cycle-internal-local))
  5463. ;; From there: TAB emulation and template completion.
  5464. (buffer-read-only (org-back-to-heading))
  5465. ((run-hook-with-args-until-success
  5466. 'org-tab-after-check-for-cycling-hook))
  5467. ((run-hook-with-args-until-success
  5468. 'org-tab-before-tab-emulation-hook))
  5469. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5470. (or (not (bolp))
  5471. (not (looking-at org-outline-regexp))))
  5472. (call-interactively (global-key-binding "\t")))
  5473. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5474. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5475. (or (and (eq org-cycle-emulate-tab 'white)
  5476. (= (match-end 0) (point-at-eol)))
  5477. (and (eq org-cycle-emulate-tab 'whitestart)
  5478. (>= (match-end 0) pos))))
  5479. t
  5480. (eq org-cycle-emulate-tab t))
  5481. (call-interactively (global-key-binding "\t")))
  5482. (t (save-excursion
  5483. (org-back-to-heading)
  5484. (org-cycle)))))))
  5485. (defun org-cycle-internal-global ()
  5486. "Do the global cycling action."
  5487. ;; Hack to avoid display of messages for .org attachments in Gnus
  5488. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5489. (cond
  5490. ((and (eq last-command this-command)
  5491. (eq org-cycle-global-status 'overview))
  5492. ;; We just created the overview - now do table of contents
  5493. ;; This can be slow in very large buffers, so indicate action
  5494. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5495. (unless ga (org-unlogged-message "CONTENTS..."))
  5496. (org-content)
  5497. (unless ga (org-unlogged-message "CONTENTS...done"))
  5498. (setq org-cycle-global-status 'contents)
  5499. (run-hook-with-args 'org-cycle-hook 'contents))
  5500. ((and (eq last-command this-command)
  5501. (eq org-cycle-global-status 'contents))
  5502. ;; We just showed the table of contents - now show everything
  5503. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5504. (org-show-all '(headings blocks))
  5505. (unless ga (org-unlogged-message "SHOW ALL"))
  5506. (setq org-cycle-global-status 'all)
  5507. (run-hook-with-args 'org-cycle-hook 'all))
  5508. (t
  5509. ;; Default action: go to overview
  5510. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5511. (org-overview)
  5512. (unless ga (org-unlogged-message "OVERVIEW"))
  5513. (setq org-cycle-global-status 'overview)
  5514. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5515. (defvar org-called-with-limited-levels nil
  5516. "Non-nil when `org-with-limited-levels' is currently active.")
  5517. (defun org-cycle-internal-local ()
  5518. "Do the local cycling action."
  5519. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5520. ;; First, determine end of headline (EOH), end of subtree or item
  5521. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5522. (save-excursion
  5523. (if (org-at-item-p)
  5524. (progn
  5525. (beginning-of-line)
  5526. (setq struct (org-list-struct))
  5527. (setq eoh (point-at-eol))
  5528. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5529. (setq has-children (org-list-has-child-p (point) struct)))
  5530. (org-back-to-heading)
  5531. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5532. (setq eos (save-excursion (org-end-of-subtree t t)
  5533. (when (bolp) (backward-char)) (point)))
  5534. (setq has-children
  5535. (or
  5536. (save-excursion
  5537. (let ((level (funcall outline-level)))
  5538. (outline-next-heading)
  5539. (and (org-at-heading-p t)
  5540. (> (funcall outline-level) level))))
  5541. (and (eq org-cycle-include-plain-lists 'integrate)
  5542. (save-excursion
  5543. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5544. ;; Determine end invisible part of buffer (EOL)
  5545. (beginning-of-line 2)
  5546. (while (and (not (eobp)) ;This is like `next-line'.
  5547. (get-char-property (1- (point)) 'invisible))
  5548. (goto-char (next-single-char-property-change (point) 'invisible))
  5549. (and (eolp) (beginning-of-line 2)))
  5550. (setq eol (point)))
  5551. ;; Find out what to do next and set `this-command'
  5552. (cond
  5553. ((= eos eoh)
  5554. ;; Nothing is hidden behind this heading
  5555. (unless (org-before-first-heading-p)
  5556. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5557. (org-unlogged-message "EMPTY ENTRY")
  5558. (setq org-cycle-subtree-status nil)
  5559. (save-excursion
  5560. (goto-char eos)
  5561. (outline-next-heading)
  5562. (when (org-invisible-p) (org-flag-heading nil))))
  5563. ((and (or (>= eol eos)
  5564. (not (string-match "\\S-" (buffer-substring eol eos))))
  5565. (or has-children
  5566. (not (setq children-skipped
  5567. org-cycle-skip-children-state-if-no-children))))
  5568. ;; Entire subtree is hidden in one line: children view
  5569. (unless (org-before-first-heading-p)
  5570. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5571. (if (org-at-item-p)
  5572. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5573. (org-show-entry)
  5574. (org-with-limited-levels (org-show-children))
  5575. (org-show-set-visibility 'canonical)
  5576. ;; Fold every list in subtree to top-level items.
  5577. (when (eq org-cycle-include-plain-lists 'integrate)
  5578. (save-excursion
  5579. (org-back-to-heading)
  5580. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5581. (beginning-of-line 1)
  5582. (let* ((struct (org-list-struct))
  5583. (prevs (org-list-prevs-alist struct))
  5584. (end (org-list-get-bottom-point struct)))
  5585. (dolist (e (org-list-get-all-items (point) struct prevs))
  5586. (org-list-set-item-visibility e struct 'folded))
  5587. (goto-char (if (< end eos) end eos)))))))
  5588. (org-unlogged-message "CHILDREN")
  5589. (save-excursion
  5590. (goto-char eos)
  5591. (outline-next-heading)
  5592. (when (org-invisible-p) (org-flag-heading nil)))
  5593. (setq org-cycle-subtree-status 'children)
  5594. (unless (org-before-first-heading-p)
  5595. (run-hook-with-args 'org-cycle-hook 'children)))
  5596. ((or children-skipped
  5597. (and (eq last-command this-command)
  5598. (eq org-cycle-subtree-status 'children)))
  5599. ;; We just showed the children, or no children are there,
  5600. ;; now show everything.
  5601. (unless (org-before-first-heading-p)
  5602. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5603. (org-flag-region eoh eos nil 'outline)
  5604. (org-unlogged-message
  5605. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5606. (setq org-cycle-subtree-status 'subtree)
  5607. (unless (org-before-first-heading-p)
  5608. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5609. (t
  5610. ;; Default action: hide the subtree.
  5611. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5612. (org-flag-region eoh eos t 'outline)
  5613. (org-unlogged-message "FOLDED")
  5614. (setq org-cycle-subtree-status 'folded)
  5615. (unless (org-before-first-heading-p)
  5616. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5617. ;;;###autoload
  5618. (defun org-global-cycle (&optional arg)
  5619. "Cycle the global visibility. For details see `org-cycle'.
  5620. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5621. With a numeric prefix, show all headlines up to that level."
  5622. (interactive "P")
  5623. (let ((org-cycle-include-plain-lists
  5624. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5625. (cond
  5626. ((integerp arg)
  5627. (org-show-all '(headings blocks))
  5628. (outline-hide-sublevels arg)
  5629. (setq org-cycle-global-status 'contents))
  5630. ((equal arg '(4))
  5631. (org-set-startup-visibility)
  5632. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5633. (t
  5634. (org-cycle '(4))))))
  5635. (defun org-set-startup-visibility ()
  5636. "Set the visibility required by startup options and properties."
  5637. (cond
  5638. ((eq org-startup-folded t)
  5639. (org-overview))
  5640. ((eq org-startup-folded 'content)
  5641. (org-content))
  5642. ((or (eq org-startup-folded 'showeverything)
  5643. (eq org-startup-folded nil))
  5644. (org-show-all)))
  5645. (unless (eq org-startup-folded 'showeverything)
  5646. (when org-hide-block-startup (org-hide-block-all))
  5647. (org-set-visibility-according-to-property)
  5648. (org-cycle-hide-archived-subtrees 'all)
  5649. (org-cycle-hide-drawers 'all)
  5650. (org-cycle-show-empty-lines t)))
  5651. (defun org-set-visibility-according-to-property ()
  5652. "Switch subtree visibility according to VISIBILITY property."
  5653. (interactive)
  5654. (let ((regexp (org-re-property "VISIBILITY")))
  5655. (org-with-point-at 1
  5656. (while (re-search-forward regexp nil t)
  5657. (let ((state (match-string 3)))
  5658. (if (not (org-at-property-p)) (outline-next-heading)
  5659. (save-excursion
  5660. (org-back-to-heading t)
  5661. (org-flag-subtree t)
  5662. (org-reveal)
  5663. (pcase state
  5664. ("folded"
  5665. (org-flag-subtree t))
  5666. ("children"
  5667. (org-show-hidden-entry)
  5668. (org-show-children))
  5669. ("content"
  5670. (save-excursion
  5671. (save-restriction
  5672. (org-narrow-to-subtree)
  5673. (org-content))))
  5674. ((or "all" "showall")
  5675. (outline-show-subtree))
  5676. (_ nil)))
  5677. (org-end-of-subtree)))))))
  5678. (defun org-overview ()
  5679. "Switch to overview mode, showing only top-level headlines.
  5680. This shows all headlines with a level equal or greater than the level
  5681. of the first headline in the buffer. This is important, because if the
  5682. first headline is not level one, then (hide-sublevels 1) gives confusing
  5683. results."
  5684. (interactive)
  5685. (save-excursion
  5686. (let ((level
  5687. (save-excursion
  5688. (goto-char (point-min))
  5689. (when (re-search-forward org-outline-regexp-bol nil t)
  5690. (goto-char (match-beginning 0))
  5691. (funcall outline-level)))))
  5692. (and level (outline-hide-sublevels level)))))
  5693. (defun org-content (&optional arg)
  5694. "Show all headlines in the buffer, like a table of contents.
  5695. With numerical argument N, show content up to level N."
  5696. (interactive "P")
  5697. (org-overview)
  5698. (save-excursion
  5699. ;; Visit all headings and show their offspring
  5700. (and (integerp arg) (org-overview))
  5701. (goto-char (point-max))
  5702. (catch 'exit
  5703. (while (and (progn (condition-case nil
  5704. (outline-previous-visible-heading 1)
  5705. (error (goto-char (point-min))))
  5706. t)
  5707. (looking-at org-outline-regexp))
  5708. (if (integerp arg)
  5709. (org-show-children (1- arg))
  5710. (outline-show-branches))
  5711. (when (bobp) (throw 'exit nil))))))
  5712. (defun org-optimize-window-after-visibility-change (state)
  5713. "Adjust the window after a change in outline visibility.
  5714. This function is the default value of the hook `org-cycle-hook'."
  5715. (when (get-buffer-window (current-buffer))
  5716. (cond
  5717. ((eq state 'content) nil)
  5718. ((eq state 'all) nil)
  5719. ((eq state 'folded) nil)
  5720. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5721. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5722. (defun org-clean-visibility-after-subtree-move ()
  5723. "Fix visibility issues after moving a subtree."
  5724. ;; First, find a reasonable region to look at:
  5725. ;; Start two siblings above, end three below
  5726. (let* ((beg (save-excursion
  5727. (and (org-get-last-sibling)
  5728. (org-get-last-sibling))
  5729. (point)))
  5730. (end (save-excursion
  5731. (and (org-get-next-sibling)
  5732. (org-get-next-sibling)
  5733. (org-get-next-sibling))
  5734. (if (org-at-heading-p)
  5735. (point-at-eol)
  5736. (point))))
  5737. (level (looking-at "\\*+"))
  5738. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5739. (save-excursion
  5740. (save-restriction
  5741. (narrow-to-region beg end)
  5742. (when re
  5743. ;; Properly fold already folded siblings
  5744. (goto-char (point-min))
  5745. (while (re-search-forward re nil t)
  5746. (when (and (not (org-invisible-p))
  5747. (org-invisible-p (line-end-position)))
  5748. (outline-hide-entry))))
  5749. (org-cycle-hide-drawers 'all)
  5750. (org-cycle-show-empty-lines 'overview)))))
  5751. (defun org-cycle-show-empty-lines (state)
  5752. "Show empty lines above all visible headlines.
  5753. The region to be covered depends on STATE when called through
  5754. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5755. entire buffer covered. Note that an empty line is only shown if there
  5756. are at least `org-cycle-separator-lines' empty lines before the headline."
  5757. (when (/= org-cycle-separator-lines 0)
  5758. (save-excursion
  5759. (let* ((n (abs org-cycle-separator-lines))
  5760. (re (cond
  5761. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5762. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5763. (t (let ((ns (number-to-string (- n 2))))
  5764. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5765. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5766. beg end)
  5767. (cond
  5768. ((memq state '(overview contents t))
  5769. (setq beg (point-min) end (point-max)))
  5770. ((memq state '(children folded))
  5771. (setq beg (point)
  5772. end (progn (org-end-of-subtree t t)
  5773. (line-beginning-position 2)))))
  5774. (when beg
  5775. (goto-char beg)
  5776. (while (re-search-forward re end t)
  5777. (unless (get-char-property (match-end 1) 'invisible)
  5778. (let ((e (match-end 1))
  5779. (b (if (>= org-cycle-separator-lines 0)
  5780. (match-beginning 1)
  5781. (save-excursion
  5782. (goto-char (match-beginning 0))
  5783. (skip-chars-backward " \t\n")
  5784. (line-end-position)))))
  5785. (org-flag-region b e nil 'outline))))))))
  5786. ;; Never hide empty lines at the end of the file.
  5787. (save-excursion
  5788. (goto-char (point-max))
  5789. (outline-previous-heading)
  5790. (outline-end-of-heading)
  5791. (when (and (looking-at "[ \t\n]+")
  5792. (= (match-end 0) (point-max)))
  5793. (org-flag-region (point) (match-end 0) nil 'outline))))
  5794. ;;;; Reveal point location
  5795. (defun org-show-context (&optional key)
  5796. "Make sure point and context are visible.
  5797. Optional argument KEY, when non-nil, is a symbol. See
  5798. `org-show-context-detail' for allowed values and how much is to
  5799. be shown."
  5800. (org-show-set-visibility
  5801. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5802. ((cdr (assq key org-show-context-detail)))
  5803. (t (cdr (assq 'default org-show-context-detail))))))
  5804. (defun org-show-set-visibility (detail)
  5805. "Set visibility around point according to DETAIL.
  5806. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5807. `tree', `canonical' or t. See `org-show-context-detail' for more
  5808. information."
  5809. ;; Show current heading and possibly its entry, following headline
  5810. ;; or all children.
  5811. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5812. (org-flag-heading nil)
  5813. (org-show-entry)
  5814. ;; If point is hidden within a drawer or a block, make sure to
  5815. ;; expose it.
  5816. (dolist (o (overlays-at (point)))
  5817. (when (memq (overlay-get o 'invisible)
  5818. '(org-hide-block org-hide-drawer outline))
  5819. (delete-overlay o)))
  5820. (unless (org-before-first-heading-p)
  5821. (org-with-limited-levels
  5822. (cl-case detail
  5823. ((tree canonical t) (org-show-children))
  5824. ((nil minimal ancestors))
  5825. (t (save-excursion
  5826. (outline-next-heading)
  5827. (org-flag-heading nil)))))))
  5828. ;; Show all siblings.
  5829. (when (eq detail 'lineage) (org-show-siblings))
  5830. ;; Show ancestors, possibly with their children.
  5831. (when (memq detail '(ancestors lineage tree canonical t))
  5832. (save-excursion
  5833. (while (org-up-heading-safe)
  5834. (org-flag-heading nil)
  5835. (when (memq detail '(canonical t)) (org-show-entry))
  5836. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5837. (defvar org-reveal-start-hook nil
  5838. "Hook run before revealing a location.")
  5839. (defun org-reveal (&optional siblings)
  5840. "Show current entry, hierarchy above it, and the following headline.
  5841. This can be used to show a consistent set of context around
  5842. locations exposed with `org-show-context'.
  5843. With optional argument SIBLINGS, on each level of the hierarchy all
  5844. siblings are shown. This repairs the tree structure to what it would
  5845. look like when opened with hierarchical calls to `org-cycle'.
  5846. With a \\[universal-argument] \\[universal-argument] prefix, \
  5847. go to the parent and show the entire tree."
  5848. (interactive "P")
  5849. (run-hooks 'org-reveal-start-hook)
  5850. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5851. ((equal siblings '(16))
  5852. (save-excursion
  5853. (when (org-up-heading-safe)
  5854. (org-show-subtree)
  5855. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5856. (t (org-show-set-visibility 'lineage))))
  5857. ;;; Indirect buffer display of subtrees
  5858. (defvar org-indirect-dedicated-frame nil
  5859. "This is the frame being used for indirect tree display.")
  5860. (defvar org-last-indirect-buffer nil)
  5861. (defun org-tree-to-indirect-buffer (&optional arg)
  5862. "Create indirect buffer and narrow it to current subtree.
  5863. With a numerical prefix ARG, go up to this level and then take that tree.
  5864. If ARG is negative, go up that many levels.
  5865. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5866. indirect buffer previously made with this command, to avoid proliferation of
  5867. indirect buffers. However, when you call the command with a \
  5868. `\\[universal-argument]' prefix, or
  5869. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5870. so that you can work with several indirect buffers at the same time. If
  5871. `org-indirect-buffer-display' is `dedicated-frame', the \
  5872. `\\[universal-argument]' prefix also
  5873. requests that a new frame be made for the new buffer, so that the dedicated
  5874. frame is not changed."
  5875. (interactive "P")
  5876. (let ((cbuf (current-buffer))
  5877. (cwin (selected-window))
  5878. (pos (point))
  5879. beg end level heading ibuf)
  5880. (save-excursion
  5881. (org-back-to-heading t)
  5882. (when (numberp arg)
  5883. (setq level (org-outline-level))
  5884. (when (< arg 0) (setq arg (+ level arg)))
  5885. (while (> (setq level (org-outline-level)) arg)
  5886. (org-up-heading-safe)))
  5887. (setq beg (point)
  5888. heading (org-get-heading 'no-tags))
  5889. (org-end-of-subtree t t)
  5890. (when (org-at-heading-p) (backward-char 1))
  5891. (setq end (point)))
  5892. (when (and (buffer-live-p org-last-indirect-buffer)
  5893. (not (eq org-indirect-buffer-display 'new-frame))
  5894. (not arg))
  5895. (kill-buffer org-last-indirect-buffer))
  5896. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5897. org-last-indirect-buffer ibuf)
  5898. (cond
  5899. ((or (eq org-indirect-buffer-display 'new-frame)
  5900. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5901. (select-frame (make-frame))
  5902. (delete-other-windows)
  5903. (pop-to-buffer-same-window ibuf)
  5904. (org-set-frame-title heading))
  5905. ((eq org-indirect-buffer-display 'dedicated-frame)
  5906. (raise-frame
  5907. (select-frame (or (and org-indirect-dedicated-frame
  5908. (frame-live-p org-indirect-dedicated-frame)
  5909. org-indirect-dedicated-frame)
  5910. (setq org-indirect-dedicated-frame (make-frame)))))
  5911. (delete-other-windows)
  5912. (pop-to-buffer-same-window ibuf)
  5913. (org-set-frame-title (concat "Indirect: " heading)))
  5914. ((eq org-indirect-buffer-display 'current-window)
  5915. (pop-to-buffer-same-window ibuf))
  5916. ((eq org-indirect-buffer-display 'other-window)
  5917. (pop-to-buffer ibuf))
  5918. (t (error "Invalid value")))
  5919. (narrow-to-region beg end)
  5920. (org-show-all '(headings blocks))
  5921. (goto-char pos)
  5922. (run-hook-with-args 'org-cycle-hook 'all)
  5923. (and (window-live-p cwin) (select-window cwin))))
  5924. (defun org-get-indirect-buffer (&optional buffer heading)
  5925. (setq buffer (or buffer (current-buffer)))
  5926. (let ((n 1) (base (buffer-name buffer)) bname)
  5927. (while (buffer-live-p
  5928. (get-buffer
  5929. (setq bname
  5930. (concat base "-"
  5931. (if heading (concat heading "-" (number-to-string n))
  5932. (number-to-string n))))))
  5933. (setq n (1+ n)))
  5934. (condition-case nil
  5935. (make-indirect-buffer buffer bname 'clone)
  5936. (error (make-indirect-buffer buffer bname)))))
  5937. (defun org-set-frame-title (title)
  5938. "Set the title of the current frame to the string TITLE."
  5939. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5940. ;;;; Structure editing
  5941. ;;; Inserting headlines
  5942. (defun org--line-empty-p (n)
  5943. "Is the Nth next line empty?
  5944. Counts the current line as N = 1 and the previous line as N = 0;
  5945. see `beginning-of-line'."
  5946. (save-excursion
  5947. (and (not (bobp))
  5948. (or (beginning-of-line n) t)
  5949. (save-match-data
  5950. (looking-at "[ \t]*$")))))
  5951. (defun org-previous-line-empty-p ()
  5952. "Is the previous line a blank line?
  5953. When NEXT is non-nil, check the next line instead."
  5954. (org--line-empty-p 0))
  5955. (defun org-next-line-empty-p ()
  5956. "Is the previous line a blank line?
  5957. When NEXT is non-nil, check the next line instead."
  5958. (org--line-empty-p 2))
  5959. (defun org--blank-before-heading-p (&optional parent)
  5960. "Non-nil when an empty line should precede a new heading here.
  5961. When optional argument PARENT is non-nil, consider parent
  5962. headline instead of current one."
  5963. (pcase (assq 'heading org-blank-before-new-entry)
  5964. (`(heading . auto)
  5965. (save-excursion
  5966. (org-with-limited-levels
  5967. (unless (and (org-before-first-heading-p)
  5968. (not (outline-next-heading)))
  5969. (org-back-to-heading t)
  5970. (when parent (org-up-heading-safe))
  5971. (cond ((not (bobp))
  5972. (org-previous-line-empty-p))
  5973. ((outline-next-heading)
  5974. (org-previous-line-empty-p))
  5975. ;; Ignore trailing spaces on last buffer line.
  5976. ((progn (skip-chars-backward " \t") (bolp))
  5977. (org-previous-line-empty-p))
  5978. (t nil))))))
  5979. (`(heading . ,value) value)
  5980. (_ nil)))
  5981. (defun org-insert-heading (&optional arg invisible-ok top)
  5982. "Insert a new heading or an item with the same depth at point.
  5983. If point is at the beginning of a heading, insert a new heading
  5984. or a new headline above the current one. When at the beginning
  5985. of a regular line of text, turn it into a heading.
  5986. If point is in the middle of a line, split it and create a new
  5987. headline with the text in the current line after point (see
  5988. `org-M-RET-may-split-line' on how to modify this behavior). As
  5989. a special case, on a headline, splitting can only happen on the
  5990. title itself. E.g., this excludes breaking stars or tags.
  5991. With a `\\[universal-argument]' prefix, set \
  5992. `org-insert-heading-respect-content' to
  5993. a non-nil value for the duration of the command. This forces the
  5994. insertion of a heading after the current subtree, independently
  5995. on the location of point.
  5996. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5997. insert the heading at the end of the tree
  5998. above the current heading. For example, if point is within a
  5999. 2nd-level heading, then it will insert a 2nd-level heading at
  6000. the end of the 1st-level parent subtree.
  6001. When INVISIBLE-OK is set, stop at invisible headlines when going
  6002. back. This is important for non-interactive uses of the
  6003. command.
  6004. When optional argument TOP is non-nil, insert a level 1 heading,
  6005. unconditionally."
  6006. (interactive "P")
  6007. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6008. (level (org-current-level))
  6009. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6010. (cond
  6011. ((or org-insert-heading-respect-content
  6012. (member arg '((4) (16)))
  6013. (and (not invisible-ok)
  6014. (invisible-p (max (1- (point)) (point-min)))))
  6015. ;; Position point at the location of insertion. Make sure we
  6016. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6017. (org-with-limited-levels
  6018. (if (not level) (outline-next-heading) ;before first headline
  6019. (org-back-to-heading invisible-ok)
  6020. (when (equal arg '(16)) (org-up-heading-safe))
  6021. (org-end-of-subtree)))
  6022. (unless (bolp) (insert "\n"))
  6023. (unless (and blank? (org-previous-line-empty-p))
  6024. (org-N-empty-lines-before-current (if blank? 1 0)))
  6025. (insert stars " ")
  6026. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6027. ;; is visible.
  6028. (unless invisible-ok
  6029. (pcase (get-char-property-and-overlay (point) 'invisible)
  6030. (`(outline . ,o)
  6031. (move-overlay o (overlay-start o) (line-end-position 0)))
  6032. (_ nil))))
  6033. ;; At a headline...
  6034. ((org-at-heading-p)
  6035. (cond ((bolp)
  6036. (when blank? (save-excursion (insert "\n")))
  6037. (save-excursion (insert stars " \n"))
  6038. (unless (and blank? (org-previous-line-empty-p))
  6039. (org-N-empty-lines-before-current (if blank? 1 0)))
  6040. (end-of-line))
  6041. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6042. (org-match-line org-complex-heading-regexp)
  6043. (org-pos-in-match-range (point) 4))
  6044. ;; Grab the text that should moved to the new headline.
  6045. ;; Preserve tags.
  6046. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6047. (if (looking-at "[ \t]*$") (replace-match "")
  6048. (org-align-tags))
  6049. (end-of-line)
  6050. (when blank? (insert "\n"))
  6051. (insert "\n" stars " ")
  6052. (when (org-string-nw-p split) (insert split))))
  6053. (t
  6054. (end-of-line)
  6055. (when blank? (insert "\n"))
  6056. (insert "\n" stars " "))))
  6057. ;; On regular text, turn line into a headline or split, if
  6058. ;; appropriate.
  6059. ((bolp)
  6060. (insert stars " ")
  6061. (unless (and blank? (org-previous-line-empty-p))
  6062. (org-N-empty-lines-before-current (if blank? 1 0))))
  6063. (t
  6064. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6065. (end-of-line))
  6066. (insert "\n" stars " ")
  6067. (unless (and blank? (org-previous-line-empty-p))
  6068. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6069. (run-hooks 'org-insert-heading-hook))
  6070. (defun org-N-empty-lines-before-current (n)
  6071. "Make the number of empty lines before current exactly N.
  6072. So this will delete or add empty lines."
  6073. (let ((column (current-column)))
  6074. (beginning-of-line)
  6075. (unless (bobp)
  6076. (let ((start (save-excursion
  6077. (skip-chars-backward " \r\t\n")
  6078. (line-end-position))))
  6079. (delete-region start (line-end-position 0))))
  6080. (insert (make-string n ?\n))
  6081. (move-to-column column)))
  6082. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6083. "Return the heading of the current entry, without the stars.
  6084. When NO-TAGS is non-nil, don't include tags.
  6085. When NO-TODO is non-nil, don't include TODO keywords.
  6086. When NO-PRIORITY is non-nil, don't include priority cookie.
  6087. When NO-COMMENT is non-nil, don't include COMMENT string.
  6088. Return nil before first heading."
  6089. (unless (org-before-first-heading-p)
  6090. (save-excursion
  6091. (org-back-to-heading t)
  6092. (let ((case-fold-search nil))
  6093. (looking-at org-complex-heading-regexp)
  6094. (let ((todo (and (not no-todo) (match-string 2)))
  6095. (priority (and (not no-priority) (match-string 3)))
  6096. (headline (pcase (match-string 4)
  6097. (`nil "")
  6098. ((and (guard no-comment) h)
  6099. (replace-regexp-in-string
  6100. (eval-when-compile
  6101. (format "\\`%s[ \t]+" org-comment-string))
  6102. "" h))
  6103. (h h)))
  6104. (tags (and (not no-tags) (match-string 5))))
  6105. (mapconcat #'identity
  6106. (delq nil (list todo priority headline tags))
  6107. " "))))))
  6108. (defun org-heading-components ()
  6109. "Return the components of the current heading.
  6110. This is a list with the following elements:
  6111. - the level as an integer
  6112. - the reduced level, different if `org-odd-levels-only' is set.
  6113. - the TODO keyword, or nil
  6114. - the priority character, like ?A, or nil if no priority is given
  6115. - the headline text itself, or the tags string if no headline text
  6116. - the tags string, or nil."
  6117. (save-excursion
  6118. (org-back-to-heading t)
  6119. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6120. (list (length (match-string 1))
  6121. (org-reduced-level (length (match-string 1)))
  6122. (match-string-no-properties 2)
  6123. (and (match-end 3) (aref (match-string 3) 2))
  6124. (match-string-no-properties 4)
  6125. (match-string-no-properties 5)))))
  6126. (defun org-get-entry ()
  6127. "Get the entry text, after heading, entire subtree."
  6128. (save-excursion
  6129. (org-back-to-heading t)
  6130. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6131. (defun org-edit-headline (&optional heading)
  6132. "Edit the current headline.
  6133. Set it to HEADING when provided."
  6134. (interactive)
  6135. (org-with-wide-buffer
  6136. (org-back-to-heading t)
  6137. (let ((case-fold-search nil))
  6138. (when (looking-at org-complex-heading-regexp)
  6139. (let* ((old (match-string-no-properties 4))
  6140. (new (save-match-data
  6141. (org-trim (or heading (read-string "Edit: " old))))))
  6142. (unless (equal old new)
  6143. (if old (replace-match new t t nil 4)
  6144. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6145. (insert " " new))
  6146. (org-align-tags)
  6147. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6148. (defun org-insert-heading-after-current ()
  6149. "Insert a new heading with same level as current, after current subtree."
  6150. (interactive)
  6151. (org-back-to-heading)
  6152. (org-insert-heading)
  6153. (org-move-subtree-down)
  6154. (end-of-line 1))
  6155. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6156. "Insert heading with `org-insert-heading-respect-content' set to t."
  6157. (interactive)
  6158. (org-insert-heading '(4) invisible-ok))
  6159. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6160. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6161. (interactive)
  6162. (org-insert-todo-heading force-state '(4)))
  6163. (defun org-insert-todo-heading (arg &optional force-heading)
  6164. "Insert a new heading with the same level and TODO state as current heading.
  6165. If the heading has no TODO state, or if the state is DONE, use
  6166. the first state (TODO by default). Also with one prefix arg,
  6167. force first state. With two prefix args, force inserting at the
  6168. end of the parent subtree.
  6169. When called at a plain list item, insert a new item with an
  6170. unchecked check box."
  6171. (interactive "P")
  6172. (when (or force-heading (not (org-insert-item 'checkbox)))
  6173. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6174. force-heading))
  6175. (save-excursion
  6176. (org-forward-heading-same-level -1)
  6177. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6178. (let* ((new-mark-x
  6179. (if (or (equal arg '(4))
  6180. (not (match-beginning 2))
  6181. (member (match-string 2) org-done-keywords))
  6182. (car org-todo-keywords-1)
  6183. (match-string 2)))
  6184. (new-mark
  6185. (or
  6186. (run-hook-with-args-until-success
  6187. 'org-todo-get-default-hook new-mark-x nil)
  6188. new-mark-x)))
  6189. (beginning-of-line 1)
  6190. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6191. (if org-treat-insert-todo-heading-as-state-change
  6192. (org-todo new-mark)
  6193. (insert new-mark " "))))
  6194. (when org-provide-todo-statistics
  6195. (org-update-parent-todo-statistics))))
  6196. (defun org-insert-subheading (arg)
  6197. "Insert a new subheading and demote it.
  6198. Works for outline headings and for plain lists alike."
  6199. (interactive "P")
  6200. (org-insert-heading arg)
  6201. (cond
  6202. ((org-at-heading-p) (org-do-demote))
  6203. ((org-at-item-p) (org-indent-item))))
  6204. (defun org-insert-todo-subheading (arg)
  6205. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6206. Works for outline headings and for plain lists alike."
  6207. (interactive "P")
  6208. (org-insert-todo-heading arg)
  6209. (cond
  6210. ((org-at-heading-p) (org-do-demote))
  6211. ((org-at-item-p) (org-indent-item))))
  6212. ;;; Promotion and Demotion
  6213. (defvar org-after-demote-entry-hook nil
  6214. "Hook run after an entry has been demoted.
  6215. The cursor will be at the beginning of the entry.
  6216. When a subtree is being demoted, the hook will be called for each node.")
  6217. (defvar org-after-promote-entry-hook nil
  6218. "Hook run after an entry has been promoted.
  6219. The cursor will be at the beginning of the entry.
  6220. When a subtree is being promoted, the hook will be called for each node.")
  6221. (defun org-promote-subtree ()
  6222. "Promote the entire subtree.
  6223. See also `org-promote'."
  6224. (interactive)
  6225. (save-excursion
  6226. (org-with-limited-levels (org-map-tree 'org-promote)))
  6227. (org-fix-position-after-promote))
  6228. (defun org-demote-subtree ()
  6229. "Demote the entire subtree.
  6230. See `org-demote' and `org-promote'."
  6231. (interactive)
  6232. (save-excursion
  6233. (org-with-limited-levels (org-map-tree 'org-demote)))
  6234. (org-fix-position-after-promote))
  6235. (defun org-do-promote ()
  6236. "Promote the current heading higher up the tree.
  6237. If the region is active in `transient-mark-mode', promote all
  6238. headings in the region."
  6239. (interactive)
  6240. (save-excursion
  6241. (if (org-region-active-p)
  6242. (org-map-region 'org-promote (region-beginning) (region-end))
  6243. (org-promote)))
  6244. (org-fix-position-after-promote))
  6245. (defun org-do-demote ()
  6246. "Demote the current heading lower down the tree.
  6247. If the region is active in `transient-mark-mode', demote all
  6248. headings in the region."
  6249. (interactive)
  6250. (save-excursion
  6251. (if (org-region-active-p)
  6252. (org-map-region 'org-demote (region-beginning) (region-end))
  6253. (org-demote)))
  6254. (org-fix-position-after-promote))
  6255. (defun org-fix-position-after-promote ()
  6256. "Fix cursor position and indentation after demoting/promoting."
  6257. (let ((pos (point)))
  6258. (when (save-excursion
  6259. (beginning-of-line)
  6260. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6261. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6262. (cond ((eobp) (insert " "))
  6263. ((eolp) (insert " "))
  6264. ((equal (char-after) ?\s) (forward-char 1))))))
  6265. (defun org-current-level ()
  6266. "Return the level of the current entry, or nil if before the first headline.
  6267. The level is the number of stars at the beginning of the
  6268. headline. Use `org-reduced-level' to remove the effect of
  6269. `org-odd-levels'. Unlike to `org-outline-level', this function
  6270. ignores inlinetasks."
  6271. (let ((level (org-with-limited-levels (org-outline-level))))
  6272. (and (> level 0) level)))
  6273. (defun org-get-previous-line-level ()
  6274. "Return the outline depth of the last headline before the current line.
  6275. Returns 0 for the first headline in the buffer, and nil if before the
  6276. first headline."
  6277. (and (org-current-level)
  6278. (or (and (/= (line-beginning-position) (point-min))
  6279. (save-excursion (beginning-of-line 0) (org-current-level)))
  6280. 0)))
  6281. (defun org-reduced-level (l)
  6282. "Compute the effective level of a heading.
  6283. This takes into account the setting of `org-odd-levels-only'."
  6284. (cond
  6285. ((zerop l) 0)
  6286. (org-odd-levels-only (1+ (floor (/ l 2))))
  6287. (t l)))
  6288. (defun org-level-increment ()
  6289. "Return the number of stars that will be added or removed at a
  6290. time to headlines when structure editing, based on the value of
  6291. `org-odd-levels-only'."
  6292. (if org-odd-levels-only 2 1))
  6293. (defun org-get-valid-level (level &optional change)
  6294. "Rectify a level change under the influence of `org-odd-levels-only'.
  6295. LEVEL is a current level, CHANGE is by how much the level should
  6296. be modified. Even if CHANGE is nil, LEVEL may be returned
  6297. modified because even level numbers will become the next higher
  6298. odd number. Returns values greater than 0."
  6299. (if org-odd-levels-only
  6300. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6301. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6302. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6303. (max 1 (+ level (or change 0)))))
  6304. (defun org-promote ()
  6305. "Promote the current heading higher up the tree."
  6306. (org-with-wide-buffer
  6307. (org-back-to-heading t)
  6308. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6309. after-change-functions))
  6310. (level (save-match-data (funcall outline-level)))
  6311. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6312. (diff (abs (- level (length up-head) -1))))
  6313. (cond
  6314. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6315. (replace-match "# " nil t))
  6316. ((= level 1)
  6317. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6318. (t (replace-match up-head nil t)))
  6319. (unless (= level 1)
  6320. (when org-auto-align-tags (org-align-tags))
  6321. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6322. (run-hooks 'org-after-promote-entry-hook))))
  6323. (defun org-demote ()
  6324. "Demote the current heading lower down the tree."
  6325. (org-with-wide-buffer
  6326. (org-back-to-heading t)
  6327. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6328. after-change-functions))
  6329. (level (save-match-data (funcall outline-level)))
  6330. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6331. (diff (abs (- level (length down-head) -1))))
  6332. (replace-match down-head nil t)
  6333. (when org-auto-align-tags (org-align-tags))
  6334. (when org-adapt-indentation (org-fixup-indentation diff))
  6335. (run-hooks 'org-after-demote-entry-hook))))
  6336. (defun org-cycle-level ()
  6337. "Cycle the level of an empty headline through possible states.
  6338. This goes first to child, then to parent, level, then up the hierarchy.
  6339. After top level, it switches back to sibling level."
  6340. (interactive)
  6341. (let ((org-adapt-indentation nil))
  6342. (when (org-point-at-end-of-empty-headline)
  6343. (setq this-command 'org-cycle-level) ; Only needed for caching
  6344. (let ((cur-level (org-current-level))
  6345. (prev-level (org-get-previous-line-level)))
  6346. (cond
  6347. ;; If first headline in file, promote to top-level.
  6348. ((= prev-level 0)
  6349. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6350. do (org-do-promote)))
  6351. ;; If same level as prev, demote one.
  6352. ((= prev-level cur-level)
  6353. (org-do-demote))
  6354. ;; If parent is top-level, promote to top level if not already.
  6355. ((= prev-level 1)
  6356. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6357. do (org-do-promote)))
  6358. ;; If top-level, return to prev-level.
  6359. ((= cur-level 1)
  6360. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6361. do (org-do-demote)))
  6362. ;; If less than prev-level, promote one.
  6363. ((< cur-level prev-level)
  6364. (org-do-promote))
  6365. ;; If deeper than prev-level, promote until higher than
  6366. ;; prev-level.
  6367. ((> cur-level prev-level)
  6368. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6369. do (org-do-promote))))
  6370. t))))
  6371. (defun org-map-tree (fun)
  6372. "Call FUN for every heading underneath the current one."
  6373. (org-back-to-heading t)
  6374. (let ((level (funcall outline-level)))
  6375. (save-excursion
  6376. (funcall fun)
  6377. (while (and (progn
  6378. (outline-next-heading)
  6379. (> (funcall outline-level) level))
  6380. (not (eobp)))
  6381. (funcall fun)))))
  6382. (defun org-map-region (fun beg end)
  6383. "Call FUN for every heading between BEG and END."
  6384. (let ((org-ignore-region t))
  6385. (save-excursion
  6386. (setq end (copy-marker end))
  6387. (goto-char beg)
  6388. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6389. (< (point) end))
  6390. (funcall fun))
  6391. (while (and (progn
  6392. (outline-next-heading)
  6393. (< (point) end))
  6394. (not (eobp)))
  6395. (funcall fun)))))
  6396. (defun org-fixup-indentation (diff)
  6397. "Change the indentation in the current entry by DIFF.
  6398. DIFF is an integer. Indentation is done according to the
  6399. following rules:
  6400. - Planning information and property drawers are always indented
  6401. according to the new level of the headline;
  6402. - Footnote definitions and their contents are ignored;
  6403. - Inlinetasks' boundaries are not shifted;
  6404. - Empty lines are ignored;
  6405. - Other lines' indentation are shifted by DIFF columns, unless
  6406. it would introduce a structural change in the document, in
  6407. which case no shifting is done at all.
  6408. Assume point is at a heading or an inlinetask beginning."
  6409. (org-with-wide-buffer
  6410. (narrow-to-region (line-beginning-position)
  6411. (save-excursion
  6412. (if (org-with-limited-levels (org-at-heading-p))
  6413. (org-with-limited-levels (outline-next-heading))
  6414. (org-inlinetask-goto-end))
  6415. (point)))
  6416. (forward-line)
  6417. ;; Indent properly planning info and property drawer.
  6418. (when (looking-at-p org-planning-line-re)
  6419. (org-indent-line)
  6420. (forward-line))
  6421. (when (looking-at org-property-drawer-re)
  6422. (goto-char (match-end 0))
  6423. (forward-line)
  6424. (org-indent-region (match-beginning 0) (match-end 0)))
  6425. (when (looking-at org-logbook-drawer-re)
  6426. (goto-char (match-end 0))
  6427. (forward-line)
  6428. (org-indent-region (match-beginning 0) (match-end 0)))
  6429. (catch 'no-shift
  6430. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6431. (throw 'no-shift nil))
  6432. ;; If DIFF is negative, first check if a shift is possible at all
  6433. ;; (e.g., it doesn't break structure). This can only happen if
  6434. ;; some contents are not properly indented.
  6435. (let ((case-fold-search t))
  6436. (when (< diff 0)
  6437. (let ((diff (- diff))
  6438. (forbidden-re (concat org-outline-regexp
  6439. "\\|"
  6440. (substring org-footnote-definition-re 1))))
  6441. (save-excursion
  6442. (while (not (eobp))
  6443. (cond
  6444. ((looking-at-p "[ \t]*$") (forward-line))
  6445. ((and (looking-at-p org-footnote-definition-re)
  6446. (let ((e (org-element-at-point)))
  6447. (and (eq (org-element-type e) 'footnote-definition)
  6448. (goto-char (org-element-property :end e))))))
  6449. ((looking-at-p org-outline-regexp) (forward-line))
  6450. ;; Give up if shifting would move before column 0 or
  6451. ;; if it would introduce a headline or a footnote
  6452. ;; definition.
  6453. (t
  6454. (skip-chars-forward " \t")
  6455. (let ((ind (current-column)))
  6456. (when (or (< ind diff)
  6457. (and (= ind diff) (looking-at-p forbidden-re)))
  6458. (throw 'no-shift nil)))
  6459. ;; Ignore contents of example blocks and source
  6460. ;; blocks if their indentation is meant to be
  6461. ;; preserved. Jump to block's closing line.
  6462. (beginning-of-line)
  6463. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6464. (let ((e (org-element-at-point)))
  6465. (and (memq (org-element-type e)
  6466. '(example-block src-block))
  6467. (or org-src-preserve-indentation
  6468. (org-element-property :preserve-indent e))
  6469. (goto-char (org-element-property :end e))
  6470. (progn (skip-chars-backward " \r\t\n")
  6471. (beginning-of-line)
  6472. t))))
  6473. (forward-line))))))))
  6474. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6475. ;; by DIFF. Also skip contents of source or example blocks
  6476. ;; when indentation is meant to be preserved.
  6477. (while (not (eobp))
  6478. (cond
  6479. ((and (looking-at-p org-footnote-definition-re)
  6480. (let ((e (org-element-at-point)))
  6481. (and (eq (org-element-type e) 'footnote-definition)
  6482. (goto-char (org-element-property :end e))))))
  6483. ((looking-at-p org-outline-regexp) (forward-line))
  6484. ((looking-at-p "[ \t]*$") (forward-line))
  6485. (t
  6486. (indent-line-to (+ (current-indentation) diff))
  6487. (beginning-of-line)
  6488. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6489. (let ((e (org-element-at-point)))
  6490. (and (memq (org-element-type e)
  6491. '(example-block src-block))
  6492. (or org-src-preserve-indentation
  6493. (org-element-property :preserve-indent e))
  6494. (goto-char (org-element-property :end e))
  6495. (progn (skip-chars-backward " \r\t\n")
  6496. (beginning-of-line)
  6497. t))))
  6498. (forward-line)))))))))
  6499. (defun org-convert-to-odd-levels ()
  6500. "Convert an Org file with all levels allowed to one with odd levels.
  6501. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6502. level 5 etc."
  6503. (interactive)
  6504. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6505. (let ((outline-level 'org-outline-level)
  6506. (org-odd-levels-only nil) n)
  6507. (save-excursion
  6508. (goto-char (point-min))
  6509. (while (re-search-forward "^\\*\\*+ " nil t)
  6510. (setq n (- (length (match-string 0)) 2))
  6511. (while (>= (setq n (1- n)) 0)
  6512. (org-demote))
  6513. (end-of-line 1))))))
  6514. (defun org-convert-to-oddeven-levels ()
  6515. "Convert an Org file with only odd levels to one with odd/even levels.
  6516. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6517. file contains a section with an even level, conversion would
  6518. destroy the structure of the file. An error is signaled in this
  6519. case."
  6520. (interactive)
  6521. (goto-char (point-min))
  6522. ;; First check if there are no even levels
  6523. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6524. (org-show-set-visibility 'canonical)
  6525. (error "Not all levels are odd in this file. Conversion not possible"))
  6526. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6527. (let ((outline-regexp org-outline-regexp)
  6528. (outline-level 'org-outline-level)
  6529. (org-odd-levels-only nil) n)
  6530. (save-excursion
  6531. (goto-char (point-min))
  6532. (while (re-search-forward "^\\*\\*+ " nil t)
  6533. (setq n (/ (1- (length (match-string 0))) 2))
  6534. (while (>= (setq n (1- n)) 0)
  6535. (org-promote))
  6536. (end-of-line 1))))))
  6537. (defun org-tr-level (n)
  6538. "Make N odd if required."
  6539. (if org-odd-levels-only (1+ (/ n 2)) n))
  6540. ;;; Vertical tree motion, cutting and pasting of subtrees
  6541. (defun org-move-subtree-up (&optional arg)
  6542. "Move the current subtree up past ARG headlines of the same level."
  6543. (interactive "p")
  6544. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6545. (defun org-move-subtree-down (&optional arg)
  6546. "Move the current subtree down past ARG headlines of the same level."
  6547. (interactive "p")
  6548. (setq arg (prefix-numeric-value arg))
  6549. (org-preserve-local-variables
  6550. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6551. 'org-get-last-sibling))
  6552. (ins-point (make-marker))
  6553. (cnt (abs arg))
  6554. (col (current-column))
  6555. beg end txt folded)
  6556. ;; Select the tree
  6557. (org-back-to-heading)
  6558. (setq beg (point))
  6559. (save-match-data
  6560. (save-excursion (outline-end-of-heading)
  6561. (setq folded (org-invisible-p)))
  6562. (progn (org-end-of-subtree nil t)
  6563. (unless (eobp) (backward-char))))
  6564. (outline-next-heading)
  6565. (setq end (point))
  6566. (goto-char beg)
  6567. ;; Find insertion point, with error handling
  6568. (while (> cnt 0)
  6569. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6570. (goto-char beg)
  6571. (user-error "Cannot move past superior level or buffer limit"))
  6572. (setq cnt (1- cnt)))
  6573. (when (> arg 0)
  6574. ;; Moving forward - still need to move over subtree
  6575. (org-end-of-subtree t t)
  6576. (save-excursion
  6577. (org-back-over-empty-lines)
  6578. (or (bolp) (newline))))
  6579. (move-marker ins-point (point))
  6580. (setq txt (buffer-substring beg end))
  6581. (org-save-markers-in-region beg end)
  6582. (delete-region beg end)
  6583. (org-remove-empty-overlays-at beg)
  6584. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6585. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6586. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6587. (let ((bbb (point)))
  6588. (insert-before-markers txt)
  6589. (org-reinstall-markers-in-region bbb)
  6590. (move-marker ins-point bbb))
  6591. (or (bolp) (insert "\n"))
  6592. (goto-char ins-point)
  6593. (org-skip-whitespace)
  6594. (move-marker ins-point nil)
  6595. (if folded
  6596. (org-flag-subtree t)
  6597. (org-show-entry)
  6598. (org-show-children))
  6599. (org-clean-visibility-after-subtree-move)
  6600. ;; move back to the initial column we were at
  6601. (move-to-column col))))
  6602. (defvar org-subtree-clip ""
  6603. "Clipboard for cut and paste of subtrees.
  6604. This is actually only a copy of the kill, because we use the normal kill
  6605. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6606. (defvar org-subtree-clip-folded nil
  6607. "Was the last copied subtree folded?
  6608. This is used to fold the tree back after pasting.")
  6609. (defun org-cut-subtree (&optional n)
  6610. "Cut the current subtree into the clipboard.
  6611. With prefix arg N, cut this many sequential subtrees.
  6612. This is a short-hand for marking the subtree and then cutting it."
  6613. (interactive "p")
  6614. (org-copy-subtree n 'cut))
  6615. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6616. "Copy the current subtree into the clipboard.
  6617. With prefix arg N, copy this many sequential subtrees.
  6618. This is a short-hand for marking the subtree and then copying it.
  6619. If CUT is non-nil, actually cut the subtree.
  6620. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6621. of some markers in the region, even if CUT is non-nil. This is
  6622. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6623. (interactive "p")
  6624. (org-preserve-local-variables
  6625. (let (beg end folded (beg0 (point)))
  6626. (if (called-interactively-p 'any)
  6627. (org-back-to-heading nil) ; take what looks like a subtree
  6628. (org-back-to-heading t)) ; take what is really there
  6629. (setq beg (point))
  6630. (skip-chars-forward " \t\r\n")
  6631. (save-match-data
  6632. (if nosubtrees
  6633. (outline-next-heading)
  6634. (save-excursion (outline-end-of-heading)
  6635. (setq folded (org-invisible-p)))
  6636. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6637. (org-end-of-subtree t t)))
  6638. ;; Include the end of an inlinetask
  6639. (when (and (featurep 'org-inlinetask)
  6640. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6641. "END[ \t]*$")))
  6642. (end-of-line))
  6643. (setq end (point))
  6644. (goto-char beg0)
  6645. (when (> end beg)
  6646. (setq org-subtree-clip-folded folded)
  6647. (when (or cut force-store-markers)
  6648. (org-save-markers-in-region beg end))
  6649. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6650. (setq org-subtree-clip (current-kill 0))
  6651. (message "%s: Subtree(s) with %d characters"
  6652. (if cut "Cut" "Copied")
  6653. (length org-subtree-clip))))))
  6654. (defun org-paste-subtree (&optional level tree for-yank remove)
  6655. "Paste the clipboard as a subtree, with modification of headline level.
  6656. The entire subtree is promoted or demoted in order to match a new headline
  6657. level.
  6658. If the cursor is at the beginning of a headline, the same level as
  6659. that headline is used to paste the tree.
  6660. If not, the new level is derived from the *visible* headings
  6661. before and after the insertion point, and taken to be the inferior headline
  6662. level of the two. So if the previous visible heading is level 3 and the
  6663. next is level 4 (or vice versa), level 4 will be used for insertion.
  6664. This makes sure that the subtree remains an independent subtree and does
  6665. not swallow low level entries.
  6666. You can also force a different level, either by using a numeric prefix
  6667. argument, or by inserting the heading marker by hand. For example, if the
  6668. cursor is after \"*****\", then the tree will be shifted to level 5.
  6669. If optional TREE is given, use this text instead of the kill ring.
  6670. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6671. move back over whitespace before inserting, and move point to the end of
  6672. the inserted text when done.
  6673. When REMOVE is non-nil, remove the subtree from the clipboard."
  6674. (interactive "P")
  6675. (setq tree (or tree (and kill-ring (current-kill 0))))
  6676. (unless (org-kill-is-subtree-p tree)
  6677. (user-error
  6678. (substitute-command-keys
  6679. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6680. (org-with-limited-levels
  6681. (let* ((visp (not (org-invisible-p)))
  6682. (txt tree)
  6683. (old-level (if (string-match org-outline-regexp-bol txt)
  6684. (- (match-end 0) (match-beginning 0) 1)
  6685. -1))
  6686. (force-level
  6687. (cond
  6688. (level (prefix-numeric-value level))
  6689. ;; When point is after the stars in an otherwise empty
  6690. ;; headline, use the number of stars as the forced level.
  6691. ((and (org-match-line "^\\*+[ \t]*$")
  6692. (not (eq ?* (char-after))))
  6693. (org-outline-level))
  6694. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6695. (previous-level
  6696. (save-excursion
  6697. (org-previous-visible-heading 1)
  6698. (if (org-at-heading-p) (org-outline-level) 1)))
  6699. (next-level
  6700. (save-excursion
  6701. (if (org-at-heading-p) (org-outline-level)
  6702. (org-next-visible-heading 1)
  6703. (if (org-at-heading-p) (org-outline-level) 1))))
  6704. (new-level (or force-level (max previous-level next-level)))
  6705. (shift (if (or (= old-level -1)
  6706. (= new-level -1)
  6707. (= old-level new-level))
  6708. 0
  6709. (- new-level old-level)))
  6710. (delta (if (> shift 0) -1 1))
  6711. (func (if (> shift 0) #'org-demote #'org-promote))
  6712. (org-odd-levels-only nil)
  6713. beg end newend)
  6714. ;; Remove the forced level indicator.
  6715. (when (and force-level (not level))
  6716. (delete-region (line-beginning-position) (point)))
  6717. ;; Paste before the next visible heading or at end of buffer,
  6718. ;; unless point is at the beginning of a headline.
  6719. (unless (and (bolp) (org-at-heading-p))
  6720. (org-next-visible-heading 1)
  6721. (unless (bolp) (insert "\n")))
  6722. (setq beg (point))
  6723. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6724. (insert-before-markers txt)
  6725. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6726. (setq newend (point))
  6727. (org-reinstall-markers-in-region beg)
  6728. (setq end (point))
  6729. (goto-char beg)
  6730. (skip-chars-forward " \t\n\r")
  6731. (setq beg (point))
  6732. (when (and (org-invisible-p) visp)
  6733. (save-excursion (outline-show-heading)))
  6734. ;; Shift if necessary.
  6735. (unless (= shift 0)
  6736. (save-restriction
  6737. (narrow-to-region beg end)
  6738. (while (not (= shift 0))
  6739. (org-map-region func (point-min) (point-max))
  6740. (setq shift (+ delta shift)))
  6741. (goto-char (point-min))
  6742. (setq newend (point-max))))
  6743. (when (or for-yank (called-interactively-p 'interactive))
  6744. (message "Clipboard pasted as level %d subtree" new-level))
  6745. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6746. kill-ring
  6747. (equal org-subtree-clip (current-kill 0))
  6748. org-subtree-clip-folded)
  6749. ;; The tree was folded before it was killed/copied
  6750. (org-flag-subtree t))
  6751. (when for-yank (goto-char newend))
  6752. (when remove (pop kill-ring)))))
  6753. (defun org-kill-is-subtree-p (&optional txt)
  6754. "Check if the current kill is an outline subtree, or a set of trees.
  6755. Returns nil if kill does not start with a headline, or if the first
  6756. headline level is not the largest headline level in the tree.
  6757. So this will actually accept several entries of equal levels as well,
  6758. which is OK for `org-paste-subtree'.
  6759. If optional TXT is given, check this string instead of the current kill."
  6760. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6761. (re (org-get-limited-outline-regexp))
  6762. (^re (concat "^" re))
  6763. (start-level (and kill
  6764. (string-match
  6765. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6766. kill)
  6767. (- (match-end 2) (match-beginning 2) 1)))
  6768. (start (1+ (or (match-beginning 2) -1))))
  6769. (if (not start-level)
  6770. (progn
  6771. nil) ;; does not even start with a heading
  6772. (catch 'exit
  6773. (while (setq start (string-match ^re kill (1+ start)))
  6774. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6775. (throw 'exit nil)))
  6776. t))))
  6777. (defvar org-markers-to-move nil
  6778. "Markers that should be moved with a cut-and-paste operation.
  6779. Those markers are stored together with their positions relative to
  6780. the start of the region.")
  6781. (defun org-save-markers-in-region (beg end)
  6782. "Check markers in region.
  6783. If these markers are between BEG and END, record their position relative
  6784. to BEG, so that after moving the block of text, we can put the markers back
  6785. into place.
  6786. This function gets called just before an entry or tree gets cut from the
  6787. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6788. called immediately, to move the markers with the entries."
  6789. (setq org-markers-to-move nil)
  6790. (when (featurep 'org-clock)
  6791. (org-clock-save-markers-for-cut-and-paste beg end))
  6792. (when (featurep 'org-agenda)
  6793. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6794. (defun org-check-and-save-marker (marker beg end)
  6795. "Check if MARKER is between BEG and END.
  6796. If yes, remember the marker and the distance to BEG."
  6797. (when (and (marker-buffer marker)
  6798. (equal (marker-buffer marker) (current-buffer))
  6799. (>= marker beg) (< marker end))
  6800. (push (cons marker (- marker beg)) org-markers-to-move)))
  6801. (defun org-reinstall-markers-in-region (beg)
  6802. "Move all remembered markers to their position relative to BEG."
  6803. (dolist (x org-markers-to-move)
  6804. (move-marker (car x) (+ beg (cdr x))))
  6805. (setq org-markers-to-move nil))
  6806. (defun org-narrow-to-subtree ()
  6807. "Narrow buffer to the current subtree."
  6808. (interactive)
  6809. (save-excursion
  6810. (save-match-data
  6811. (org-with-limited-levels
  6812. (narrow-to-region
  6813. (progn (org-back-to-heading t) (point))
  6814. (progn (org-end-of-subtree t t)
  6815. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6816. (point)))))))
  6817. (defun org-toggle-narrow-to-subtree ()
  6818. "Narrow to the subtree at point or widen a narrowed buffer."
  6819. (interactive)
  6820. (if (buffer-narrowed-p)
  6821. (progn (widen) (message "Buffer widen"))
  6822. (org-narrow-to-subtree)
  6823. (message "Buffer narrowed to current subtree")))
  6824. (defun org-narrow-to-block ()
  6825. "Narrow buffer to the current block."
  6826. (interactive)
  6827. (let* ((case-fold-search t)
  6828. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6829. "^[ \t]*#\\+end_.*")))
  6830. (if blockp
  6831. (narrow-to-region (car blockp) (cdr blockp))
  6832. (user-error "Not in a block"))))
  6833. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6834. "Clone the task (subtree) at point N times.
  6835. The clones will be inserted as siblings.
  6836. In interactive use, the user will be prompted for the number of
  6837. clones to be produced. If the entry has a timestamp, the user
  6838. will also be prompted for a time shift, which may be a repeater
  6839. as used in time stamps, for example `+3d'. To disable this,
  6840. you can call the function with a universal prefix argument.
  6841. When a valid repeater is given and the entry contains any time
  6842. stamps, the clones will become a sequence in time, with time
  6843. stamps in the subtree shifted for each clone produced. If SHIFT
  6844. is nil or the empty string, time stamps will be left alone. The
  6845. ID property of the original subtree is removed.
  6846. In each clone, all the CLOCK entries will be removed. This
  6847. prevents Org from considering that the clocked times overlap.
  6848. If the original subtree did contain time stamps with a repeater,
  6849. the following will happen:
  6850. - the repeater will be removed in each clone
  6851. - an additional clone will be produced, with the current, unshifted
  6852. date(s) in the entry.
  6853. - the original entry will be placed *after* all the clones, with
  6854. repeater intact.
  6855. - the start days in the repeater in the original entry will be shifted
  6856. to past the last clone.
  6857. In this way you can spell out a number of instances of a repeating task,
  6858. and still retain the repeater to cover future instances of the task.
  6859. As described above, N+1 clones are produced when the original
  6860. subtree has a repeater. Setting N to 0, then, can be used to
  6861. remove the repeater from a subtree and create a shifted clone
  6862. with the original repeater."
  6863. (interactive "nNumber of clones to produce: ")
  6864. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6865. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6866. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6867. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6868. (shift
  6869. (or shift
  6870. (if (and (not (equal current-prefix-arg '(4)))
  6871. (save-excursion
  6872. (goto-char beg)
  6873. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6874. (read-from-minibuffer
  6875. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6876. ""))) ;No time shift
  6877. (doshift
  6878. (and (org-string-nw-p shift)
  6879. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6880. shift)
  6881. (user-error "Invalid shift specification %s" shift)))))
  6882. (goto-char end-of-tree)
  6883. (unless (bolp) (insert "\n"))
  6884. (let* ((end (point))
  6885. (template (buffer-substring beg end))
  6886. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6887. (shift-what (pcase (and doshift (match-string 2 shift))
  6888. (`nil nil)
  6889. ("d" 'day)
  6890. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6891. ("m" 'month)
  6892. ("y" 'year)
  6893. (_ (error "Unsupported time unit"))))
  6894. (nmin 1)
  6895. (nmax n)
  6896. (n-no-remove -1)
  6897. (idprop (org-entry-get beg "ID")))
  6898. (when (and doshift
  6899. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6900. template))
  6901. (delete-region beg end)
  6902. (setq end beg)
  6903. (setq nmin 0)
  6904. (setq nmax (1+ nmax))
  6905. (setq n-no-remove nmax))
  6906. (goto-char end)
  6907. (cl-loop for n from nmin to nmax do
  6908. (insert
  6909. ;; Prepare clone.
  6910. (with-temp-buffer
  6911. (insert template)
  6912. (org-mode)
  6913. (goto-char (point-min))
  6914. (org-show-subtree)
  6915. (and idprop (if org-clone-delete-id
  6916. (org-entry-delete nil "ID")
  6917. (org-id-get-create t)))
  6918. (unless (= n 0)
  6919. (while (re-search-forward org-clock-line-re nil t)
  6920. (delete-region (line-beginning-position)
  6921. (line-beginning-position 2)))
  6922. (goto-char (point-min))
  6923. (while (re-search-forward org-drawer-regexp nil t)
  6924. (org-remove-empty-drawer-at (point))))
  6925. (goto-char (point-min))
  6926. (when doshift
  6927. (while (re-search-forward org-ts-regexp-both nil t)
  6928. (org-timestamp-change (* n shift-n) shift-what))
  6929. (unless (= n n-no-remove)
  6930. (goto-char (point-min))
  6931. (while (re-search-forward org-ts-regexp nil t)
  6932. (save-excursion
  6933. (goto-char (match-beginning 0))
  6934. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6935. (delete-region (match-beginning 1) (match-end 1)))))))
  6936. (buffer-string)))))
  6937. (goto-char beg)))
  6938. ;;; Outline Sorting
  6939. (defun org-sort (&optional with-case)
  6940. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6941. Optional argument WITH-CASE means sort case-sensitively."
  6942. (interactive "P")
  6943. (org-call-with-arg
  6944. (cond ((org-at-table-p) #'org-table-sort-lines)
  6945. ((org-at-item-p) #'org-sort-list)
  6946. (t #'org-sort-entries))
  6947. with-case))
  6948. (defun org-sort-remove-invisible (s)
  6949. "Remove invisible part of links and emphasis markers from string S."
  6950. (remove-text-properties 0 (length s) org-rm-props s)
  6951. (replace-regexp-in-string
  6952. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  6953. (replace-regexp-in-string
  6954. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  6955. (org-link-display-format s)
  6956. t t) t t))
  6957. (defvar org-after-sorting-entries-or-items-hook nil
  6958. "Hook that is run after a bunch of entries or items have been sorted.
  6959. When children are sorted, the cursor is in the parent line when this
  6960. hook gets called. When a region or a plain list is sorted, the cursor
  6961. will be in the first entry of the sorted region/list.")
  6962. (defun org-sort-entries
  6963. (&optional with-case sorting-type getkey-func compare-func property
  6964. interactive?)
  6965. "Sort entries on a certain level of an outline tree.
  6966. If there is an active region, the entries in the region are sorted.
  6967. Else, if the cursor is before the first entry, sort the top-level items.
  6968. Else, the children of the entry at point are sorted.
  6969. Sorting can be alphabetically, numerically, by date/time as given by
  6970. a time stamp, by a property, by priority order, or by a custom function.
  6971. The command prompts for the sorting type unless it has been given to the
  6972. function through the SORTING-TYPE argument, which needs to be a character,
  6973. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6974. the precise meaning of each character:
  6975. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6976. c By creation time, which is assumed to be the first inactive time stamp
  6977. at the beginning of a line.
  6978. d By deadline date/time.
  6979. k By clocking time.
  6980. n Numerically, by converting the beginning of the entry/item to a number.
  6981. o By order of TODO keywords.
  6982. p By priority according to the cookie.
  6983. r By the value of a property.
  6984. s By scheduled date/time.
  6985. t By date/time, either the first active time stamp in the entry, or, if
  6986. none exist, by the first inactive one.
  6987. Capital letters will reverse the sort order.
  6988. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6989. called with point at the beginning of the record. It must return a
  6990. value that is compatible with COMPARE-FUNC, the function used to
  6991. compare entries.
  6992. Comparing entries ignores case by default. However, with an optional argument
  6993. WITH-CASE, the sorting considers case as well.
  6994. Sorting is done against the visible part of the headlines, it ignores hidden
  6995. links.
  6996. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6997. A non-nil value for INTERACTIVE? is used to signal that this
  6998. function is being called interactively."
  6999. (interactive (list current-prefix-arg nil nil nil nil t))
  7000. (let ((case-func (if with-case 'identity 'downcase))
  7001. start beg end stars re re2
  7002. txt what tmp)
  7003. ;; Find beginning and end of region to sort
  7004. (cond
  7005. ((org-region-active-p)
  7006. ;; we will sort the region
  7007. (setq end (region-end)
  7008. what "region")
  7009. (goto-char (region-beginning))
  7010. (unless (org-at-heading-p) (outline-next-heading))
  7011. (setq start (point)))
  7012. ((or (org-at-heading-p)
  7013. (ignore-errors (progn (org-back-to-heading) t)))
  7014. ;; we will sort the children of the current headline
  7015. (org-back-to-heading)
  7016. (setq start (point)
  7017. end (progn (org-end-of-subtree t t)
  7018. (or (bolp) (insert "\n"))
  7019. (when (>= (org-back-over-empty-lines) 1)
  7020. (forward-line 1))
  7021. (point))
  7022. what "children")
  7023. (goto-char start)
  7024. (outline-show-subtree)
  7025. (outline-next-heading))
  7026. (t
  7027. ;; we will sort the top-level entries in this file
  7028. (goto-char (point-min))
  7029. (or (org-at-heading-p) (outline-next-heading))
  7030. (setq start (point))
  7031. (goto-char (point-max))
  7032. (beginning-of-line 1)
  7033. (when (looking-at ".*?\\S-")
  7034. ;; File ends in a non-white line
  7035. (end-of-line 1)
  7036. (insert "\n"))
  7037. (setq end (point-max))
  7038. (setq what "top-level")
  7039. (goto-char start)
  7040. (org-show-all '(headings blocks))))
  7041. (setq beg (point))
  7042. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7043. (looking-at "\\(\\*+\\)")
  7044. (setq stars (match-string 1)
  7045. re (concat "^" (regexp-quote stars) " +")
  7046. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7047. txt (buffer-substring beg end))
  7048. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7049. (when (and (not (equal stars "*")) (string-match re2 txt))
  7050. (user-error "Region to sort contains a level above the first entry"))
  7051. (unless sorting-type
  7052. (message
  7053. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7054. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7055. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7056. what)
  7057. (setq sorting-type (read-char-exclusive)))
  7058. (unless getkey-func
  7059. (and (= (downcase sorting-type) ?f)
  7060. (setq getkey-func
  7061. (or (and interactive?
  7062. (org-read-function
  7063. "Function for extracting keys: "))
  7064. (error "Missing key extractor")))))
  7065. (and (= (downcase sorting-type) ?r)
  7066. (not property)
  7067. (setq property
  7068. (completing-read "Property: "
  7069. (mapcar #'list (org-buffer-property-keys t))
  7070. nil t)))
  7071. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7072. (message "Sorting entries...")
  7073. (save-restriction
  7074. (narrow-to-region start end)
  7075. (let ((restore-clock?
  7076. ;; The clock marker is lost when using `sort-subr'; mark
  7077. ;; the clock with temporary `:org-clock-marker-backup'
  7078. ;; text property.
  7079. (when (and (eq (org-clock-is-active) (current-buffer))
  7080. (<= start (marker-position org-clock-marker))
  7081. (>= end (marker-position org-clock-marker)))
  7082. (with-silent-modifications
  7083. (put-text-property (1- org-clock-marker) org-clock-marker
  7084. :org-clock-marker-backup t))
  7085. t))
  7086. (dcst (downcase sorting-type))
  7087. (case-fold-search nil)
  7088. (now (current-time)))
  7089. (org-preserve-local-variables
  7090. (sort-subr
  7091. (/= dcst sorting-type)
  7092. ;; This function moves to the beginning character of the
  7093. ;; "record" to be sorted.
  7094. (lambda nil
  7095. (if (re-search-forward re nil t)
  7096. (goto-char (match-beginning 0))
  7097. (goto-char (point-max))))
  7098. ;; This function moves to the last character of the "record" being
  7099. ;; sorted.
  7100. (lambda nil
  7101. (save-match-data
  7102. (condition-case nil
  7103. (outline-forward-same-level 1)
  7104. (error
  7105. (goto-char (point-max))))))
  7106. ;; This function returns the value that gets sorted against.
  7107. (lambda ()
  7108. (cond
  7109. ((= dcst ?n)
  7110. (string-to-number
  7111. (org-sort-remove-invisible (org-get-heading t t t t))))
  7112. ((= dcst ?a)
  7113. (funcall case-func
  7114. (org-sort-remove-invisible (org-get-heading t t t t))))
  7115. ((= dcst ?k)
  7116. (or (get-text-property (point) :org-clock-minutes) 0))
  7117. ((= dcst ?t)
  7118. (let ((end (save-excursion (outline-next-heading) (point))))
  7119. (if (or (re-search-forward org-ts-regexp end t)
  7120. (re-search-forward org-ts-regexp-both end t))
  7121. (org-time-string-to-seconds (match-string 0))
  7122. (float-time now))))
  7123. ((= dcst ?c)
  7124. (let ((end (save-excursion (outline-next-heading) (point))))
  7125. (if (re-search-forward
  7126. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7127. end t)
  7128. (org-time-string-to-seconds (match-string 0))
  7129. (float-time now))))
  7130. ((= dcst ?s)
  7131. (let ((end (save-excursion (outline-next-heading) (point))))
  7132. (if (re-search-forward org-scheduled-time-regexp end t)
  7133. (org-time-string-to-seconds (match-string 1))
  7134. (float-time now))))
  7135. ((= dcst ?d)
  7136. (let ((end (save-excursion (outline-next-heading) (point))))
  7137. (if (re-search-forward org-deadline-time-regexp end t)
  7138. (org-time-string-to-seconds (match-string 1))
  7139. (float-time now))))
  7140. ((= dcst ?p)
  7141. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7142. (string-to-char (match-string 2))
  7143. org-priority-default))
  7144. ((= dcst ?r)
  7145. (or (org-entry-get nil property) ""))
  7146. ((= dcst ?o)
  7147. (when (looking-at org-complex-heading-regexp)
  7148. (let* ((m (match-string 2))
  7149. (s (if (member m org-done-keywords) '- '+)))
  7150. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7151. ((= dcst ?f)
  7152. (if getkey-func
  7153. (progn
  7154. (setq tmp (funcall getkey-func))
  7155. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7156. tmp)
  7157. (error "Invalid key function `%s'" getkey-func)))
  7158. (t (error "Invalid sorting type `%c'" sorting-type))))
  7159. nil
  7160. (cond
  7161. ((= dcst ?a) 'org-string-collate-lessp)
  7162. ((= dcst ?f)
  7163. (or compare-func
  7164. (and interactive?
  7165. (org-read-function
  7166. (concat "Function for comparing keys "
  7167. "(empty for default `sort-subr' predicate): ")
  7168. 'allow-empty))))
  7169. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7170. (org-cycle-hide-drawers 'all)
  7171. (when restore-clock?
  7172. (move-marker org-clock-marker
  7173. (1+ (next-single-property-change
  7174. start :org-clock-marker-backup)))
  7175. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7176. '(:org-clock-marker-backup t)))))
  7177. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7178. (message "Sorting entries...done")))
  7179. (defun org-contextualize-keys (alist contexts)
  7180. "Return valid elements in ALIST depending on CONTEXTS.
  7181. `org-agenda-custom-commands' or `org-capture-templates' are the
  7182. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7183. or `org-capture-templates-contexts' are the associated contexts
  7184. definitions."
  7185. (let ((contexts
  7186. ;; normalize contexts
  7187. (mapcar
  7188. (lambda(c) (cond ((listp (cadr c))
  7189. (list (car c) (car c) (nth 1 c)))
  7190. ((string= "" (cadr c))
  7191. (list (car c) (car c) (nth 2 c)))
  7192. (t c)))
  7193. contexts))
  7194. (a alist) r s)
  7195. ;; loop over all commands or templates
  7196. (dolist (c a)
  7197. (let (vrules repl)
  7198. (cond
  7199. ((not (assoc (car c) contexts))
  7200. (push c r))
  7201. ((and (assoc (car c) contexts)
  7202. (setq vrules (org-contextualize-validate-key
  7203. (car c) contexts)))
  7204. (mapc (lambda (vr)
  7205. (unless (equal (car vr) (cadr vr))
  7206. (setq repl vr)))
  7207. vrules)
  7208. (if (not repl) (push c r)
  7209. (push (cadr repl) s)
  7210. (push
  7211. (cons (car c)
  7212. (cdr (or (assoc (cadr repl) alist)
  7213. (error "Undefined key `%s' as contextual replacement for `%s'"
  7214. (cadr repl) (car c)))))
  7215. r))))))
  7216. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7217. (delq
  7218. nil
  7219. (delete-dups
  7220. (mapcar (lambda (x)
  7221. (let ((tpl (car x)))
  7222. (unless (delq
  7223. nil
  7224. (mapcar (lambda (y)
  7225. (equal y tpl))
  7226. s))
  7227. x)))
  7228. (reverse r))))))
  7229. (defun org-contextualize-validate-key (key contexts)
  7230. "Check CONTEXTS for agenda or capture KEY."
  7231. (let (res)
  7232. (dolist (r contexts)
  7233. (dolist (rr (car (last r)))
  7234. (when
  7235. (and (equal key (car r))
  7236. (if (functionp rr) (funcall rr)
  7237. (or (and (eq (car rr) 'in-file)
  7238. (buffer-file-name)
  7239. (string-match (cdr rr) (buffer-file-name)))
  7240. (and (eq (car rr) 'in-mode)
  7241. (string-match (cdr rr) (symbol-name major-mode)))
  7242. (and (eq (car rr) 'in-buffer)
  7243. (string-match (cdr rr) (buffer-name)))
  7244. (when (and (eq (car rr) 'not-in-file)
  7245. (buffer-file-name))
  7246. (not (string-match (cdr rr) (buffer-file-name))))
  7247. (when (eq (car rr) 'not-in-mode)
  7248. (not (string-match (cdr rr) (symbol-name major-mode))))
  7249. (when (eq (car rr) 'not-in-buffer)
  7250. (not (string-match (cdr rr) (buffer-name)))))))
  7251. (push r res))))
  7252. (delete-dups (delq nil res))))
  7253. ;; Defined to provide a value for defcustom, since there is no
  7254. ;; string-collate-greaterp in Emacs.
  7255. (defun org-string-collate-greaterp (s1 s2)
  7256. "Return non-nil if S1 is greater than S2 in collation order."
  7257. (not (org-string-collate-lessp s1 s2)))
  7258. ;;;###autoload
  7259. (defun org-run-like-in-org-mode (cmd)
  7260. "Run a command, pretending that the current buffer is in Org mode.
  7261. This will temporarily bind local variables that are typically bound in
  7262. Org mode to the values they have in Org mode, and then interactively
  7263. call CMD."
  7264. (org-load-modules-maybe)
  7265. (let (binds)
  7266. (dolist (var (org-get-local-variables))
  7267. (when (or (not (boundp (car var)))
  7268. (eq (symbol-value (car var))
  7269. (default-value (car var))))
  7270. (push (list (car var) `(quote ,(cadr var))) binds)))
  7271. (eval `(let ,binds
  7272. (call-interactively (quote ,cmd))))))
  7273. (defun org-get-category (&optional pos force-refresh)
  7274. "Get the category applying to position POS."
  7275. (save-match-data
  7276. (when force-refresh (org-refresh-category-properties))
  7277. (let ((pos (or pos (point))))
  7278. (or (get-text-property pos 'org-category)
  7279. (progn (org-refresh-category-properties)
  7280. (get-text-property pos 'org-category))))))
  7281. ;;; Refresh properties
  7282. (defun org-refresh-properties (dprop tprop)
  7283. "Refresh buffer text properties.
  7284. DPROP is the drawer property and TPROP is either the
  7285. corresponding text property to set, or an alist with each element
  7286. being a text property (as a symbol) and a function to apply to
  7287. the value of the drawer property."
  7288. (let* ((case-fold-search t)
  7289. (inhibit-read-only t)
  7290. (inherit? (org-property-inherit-p dprop))
  7291. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7292. (global-or-keyword (and inherit?
  7293. (org--property-global-or-keyword-value dprop nil))))
  7294. (with-silent-modifications
  7295. (org-with-point-at 1
  7296. ;; Set global and keyword based values to the whole buffer.
  7297. (when global-or-keyword
  7298. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7299. ;; Set values based on property-drawers throughout the document.
  7300. (while (re-search-forward property-re nil t)
  7301. (when (org-at-property-p)
  7302. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7303. (outline-next-heading))))))
  7304. (defun org-refresh-property (tprop p &optional inherit)
  7305. "Refresh the buffer text property TPROP from the drawer property P.
  7306. The refresh happens only for the current entry, or the whole
  7307. sub-tree if optional argument INHERIT is non-nil.
  7308. If point is before first headline, the function applies to the
  7309. part before the first headline. In that particular case, when
  7310. optional argument INHERIT is non-nil, it refreshes properties for
  7311. the whole buffer."
  7312. (save-excursion
  7313. (org-back-to-heading-or-point-min t)
  7314. (let ((start (point))
  7315. (end (save-excursion
  7316. (cond ((and inherit (org-before-first-heading-p))
  7317. (point-max))
  7318. (inherit
  7319. (org-end-of-subtree t t))
  7320. ((outline-next-heading))
  7321. ((point-max))))))
  7322. (if (symbolp tprop)
  7323. ;; TPROP is a text property symbol.
  7324. (put-text-property start end tprop p)
  7325. ;; TPROP is an alist with (property . function) elements.
  7326. (pcase-dolist (`(,prop . ,f) tprop)
  7327. (put-text-property start end prop (funcall f p)))))))
  7328. (defun org-refresh-category-properties ()
  7329. "Refresh category text properties in the buffer."
  7330. (let ((case-fold-search t)
  7331. (inhibit-read-only t)
  7332. (default-category
  7333. (cond ((null org-category)
  7334. (if buffer-file-name
  7335. (file-name-sans-extension
  7336. (file-name-nondirectory buffer-file-name))
  7337. "???"))
  7338. ((symbolp org-category) (symbol-name org-category))
  7339. (t org-category))))
  7340. (with-silent-modifications
  7341. (org-with-wide-buffer
  7342. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7343. ;; keyword. If none is found, fall-back to `org-category' or
  7344. ;; buffer file name, or set it by the document property drawer.
  7345. (put-text-property
  7346. (point-min) (point-max)
  7347. 'org-category
  7348. (catch 'buffer-category
  7349. (goto-char (point-max))
  7350. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7351. (let ((element (org-element-at-point)))
  7352. (when (eq (org-element-type element) 'keyword)
  7353. (throw 'buffer-category
  7354. (org-element-property :value element)))))
  7355. default-category))
  7356. ;; Set categories from the document property drawer or
  7357. ;; property drawers in the outline. If category is found in
  7358. ;; the property drawer for the whole buffer that value
  7359. ;; overrides the keyword-based value set above.
  7360. (goto-char (point-min))
  7361. (let ((regexp (org-re-property "CATEGORY")))
  7362. (while (re-search-forward regexp nil t)
  7363. (let ((value (match-string-no-properties 3)))
  7364. (when (org-at-property-p)
  7365. (put-text-property
  7366. (save-excursion (org-back-to-heading-or-point-min t))
  7367. (save-excursion (if (org-before-first-heading-p)
  7368. (point-max)
  7369. (org-end-of-subtree t t)))
  7370. 'org-category
  7371. value)))))))))
  7372. (defun org-refresh-stats-properties ()
  7373. "Refresh stats text properties in the buffer."
  7374. (with-silent-modifications
  7375. (org-with-point-at 1
  7376. (let ((regexp (concat org-outline-regexp-bol
  7377. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7378. (while (re-search-forward regexp nil t)
  7379. (let* ((numerator (string-to-number (match-string 1)))
  7380. (denominator (and (match-end 2)
  7381. (string-to-number (match-string 2))))
  7382. (stats (cond ((not denominator) numerator) ;percent
  7383. ((= denominator 0) 0)
  7384. (t (/ (* numerator 100) denominator)))))
  7385. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7386. 'org-stats stats)))))))
  7387. (defun org-refresh-effort-properties ()
  7388. "Refresh effort properties."
  7389. (org-refresh-properties
  7390. org-effort-property
  7391. '((effort . identity)
  7392. (effort-minutes . org-duration-to-minutes))))
  7393. (defun org-find-file-at-mouse (ev)
  7394. "Open file link or URL at mouse."
  7395. (interactive "e")
  7396. (mouse-set-point ev)
  7397. (org-open-at-point 'in-emacs))
  7398. (defun org-open-at-mouse (ev)
  7399. "Open file link or URL at mouse.
  7400. See the docstring of `org-open-file' for details."
  7401. (interactive "e")
  7402. (mouse-set-point ev)
  7403. (when (eq major-mode 'org-agenda-mode)
  7404. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7405. (org-open-at-point))
  7406. (defvar org-window-config-before-follow-link nil
  7407. "The window configuration before following a link.
  7408. This is saved in case the need arises to restore it.")
  7409. (defun org--file-default-apps ()
  7410. "Return the default applications for this operating system."
  7411. (pcase system-type
  7412. (`darwin org-file-apps-macos)
  7413. (`windows-nt org-file-apps-windowsnt)
  7414. (_ org-file-apps-gnu)))
  7415. (defun org--file-apps-entry-dlink-p (entry)
  7416. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7417. It assumes that is the case when the entry uses a regular
  7418. expression which has at least one grouping construct and the
  7419. action is either a Lisp form or a command string containing
  7420. \"%1\", i.e., using at least one subexpression match as
  7421. a parameter."
  7422. (pcase entry
  7423. (`(,selector . ,action)
  7424. (and (stringp selector)
  7425. (> (regexp-opt-depth selector) 0)
  7426. (or (and (stringp action)
  7427. (string-match "%[0-9]" action))
  7428. (consp action))))
  7429. (_ nil)))
  7430. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7431. "Convert extensions to regular expressions in the cars of LIST.
  7432. Also, weed out any non-string entries, because the return value
  7433. is used only for regexp matching.
  7434. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7435. point to the symbol `emacs', indicating that the file should be
  7436. opened in Emacs."
  7437. (append
  7438. (delq nil
  7439. (mapcar (lambda (x)
  7440. (unless (not (stringp (car x)))
  7441. (if (string-match "\\W" (car x))
  7442. x
  7443. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7444. list))
  7445. (when add-auto-mode
  7446. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7447. ;;;###autoload
  7448. (defun org-open-file (path &optional in-emacs line search)
  7449. "Open the file at PATH.
  7450. First, this expands any special file name abbreviations. Then the
  7451. configuration variable `org-file-apps' is checked if it contains an
  7452. entry for this file type, and if yes, the corresponding command is launched.
  7453. If no application is found, Emacs simply visits the file.
  7454. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7455. With a double \\[universal-argument] \\[universal-argument] \
  7456. prefix arg, Org tries to avoid opening in Emacs
  7457. and to use an external application to visit the file.
  7458. Optional LINE specifies a line to go to, optional SEARCH a string
  7459. to search for. If LINE or SEARCH is given, the file will be
  7460. opened in Emacs, unless an entry from `org-file-apps' that makes
  7461. use of groups in a regexp matches.
  7462. If you want to change the way frames are used when following a
  7463. link, please customize `org-link-frame-setup'.
  7464. If the file does not exist, throw an error."
  7465. (let* ((file (if (equal path "") buffer-file-name
  7466. (substitute-in-file-name (expand-file-name path))))
  7467. (file-apps (append org-file-apps (org--file-default-apps)))
  7468. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7469. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7470. file-apps))
  7471. (remp (and (assq 'remote apps) (file-remote-p file)))
  7472. (dirp (unless remp (file-directory-p file)))
  7473. (file (if (and dirp org-open-directory-means-index-dot-org)
  7474. (concat (file-name-as-directory file) "index.org")
  7475. file))
  7476. (a-m-a-p (assq 'auto-mode apps))
  7477. (dfile (downcase file))
  7478. ;; Reconstruct the original link from the PATH, LINE and
  7479. ;; SEARCH args.
  7480. (link (cond (line (concat file "::" (number-to-string line)))
  7481. (search (concat file "::" search))
  7482. (t file)))
  7483. (dlink (downcase link))
  7484. (ext
  7485. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7486. (match-string 1 dfile)))
  7487. (save-position-maybe
  7488. (let ((old-buffer (current-buffer))
  7489. (old-pos (point))
  7490. (old-mode major-mode))
  7491. (lambda ()
  7492. (and (derived-mode-p 'org-mode)
  7493. (eq old-mode 'org-mode)
  7494. (or (not (eq old-buffer (current-buffer)))
  7495. (not (eq old-pos (point))))
  7496. (org-mark-ring-push old-pos old-buffer)))))
  7497. cmd link-match-data)
  7498. (cond
  7499. ((member in-emacs '((16) system))
  7500. (setq cmd (cdr (assq 'system apps))))
  7501. (in-emacs (setq cmd 'emacs))
  7502. (t
  7503. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7504. (and dirp (cdr (assq 'directory apps)))
  7505. ;; First, try matching against apps-dlink if we
  7506. ;; get a match here, store the match data for
  7507. ;; later.
  7508. (let ((match (assoc-default dlink apps-dlink
  7509. 'string-match)))
  7510. (if match
  7511. (progn (setq link-match-data (match-data))
  7512. match)
  7513. (progn (setq in-emacs (or in-emacs line search))
  7514. nil))) ; if we have no match in apps-dlink,
  7515. ; always open the file in emacs if line or search
  7516. ; is given (for backwards compatibility)
  7517. (assoc-default dfile
  7518. (org--file-apps-regexp-alist apps a-m-a-p)
  7519. 'string-match)
  7520. (cdr (assoc ext apps))
  7521. (cdr (assq t apps))))))
  7522. (when (eq cmd 'system)
  7523. (setq cmd (cdr (assq 'system apps))))
  7524. (when (eq cmd 'default)
  7525. (setq cmd (cdr (assoc t apps))))
  7526. (when (eq cmd 'mailcap)
  7527. (require 'mailcap)
  7528. (mailcap-parse-mailcaps)
  7529. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7530. (command (mailcap-mime-info mime-type)))
  7531. (if (stringp command)
  7532. (setq cmd command)
  7533. (setq cmd 'emacs))))
  7534. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7535. (not (file-exists-p file))
  7536. (not org-open-non-existing-files))
  7537. (user-error "No such file: %s" file))
  7538. (cond
  7539. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7540. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7541. (while (string-match "['\"]%s['\"]" cmd)
  7542. (setq cmd (replace-match "%s" t t cmd)))
  7543. (setq cmd (replace-regexp-in-string
  7544. "%s"
  7545. (shell-quote-argument (convert-standard-filename file))
  7546. cmd
  7547. nil t))
  7548. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7549. (save-match-data
  7550. (let ((match-index 1)
  7551. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7552. (set-match-data link-match-data)
  7553. (while (<= match-index number-of-groups)
  7554. (let ((regex (concat "%" (number-to-string match-index)))
  7555. (replace-with (match-string match-index dlink)))
  7556. (while (string-match regex cmd)
  7557. (setq cmd (replace-match replace-with t t cmd))))
  7558. (setq match-index (+ match-index 1)))))
  7559. (save-window-excursion
  7560. (message "Running %s...done" cmd)
  7561. (start-process-shell-command cmd nil cmd)
  7562. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7563. ((or (stringp cmd)
  7564. (eq cmd 'emacs))
  7565. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7566. (widen)
  7567. (cond (line (org-goto-line line)
  7568. (when (derived-mode-p 'org-mode) (org-reveal)))
  7569. (search (condition-case err
  7570. (org-link-search search)
  7571. ;; Save position before error-ing out so user
  7572. ;; can easily move back to the original buffer.
  7573. (error (funcall save-position-maybe)
  7574. (error (nth 1 err)))))))
  7575. ((functionp cmd)
  7576. (save-match-data
  7577. (set-match-data link-match-data)
  7578. (condition-case nil
  7579. (funcall cmd file link)
  7580. ;; FIXME: Remove this check when most default installations
  7581. ;; of Emacs have at least Org 9.0.
  7582. ((debug wrong-number-of-arguments wrong-type-argument
  7583. invalid-function)
  7584. (user-error "Please see Org News for version 9.0 about \
  7585. `org-file-apps'--Lisp error: %S" cmd)))))
  7586. ((consp cmd)
  7587. ;; FIXME: Remove this check when most default installations of
  7588. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7589. ;; fall back to `org-link-frame-setup' for an old usage of
  7590. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7591. (user-error "Please see Org News for version 9.0 about \
  7592. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7593. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7594. (funcall save-position-maybe)))
  7595. ;;;###autoload
  7596. (defun org-open-at-point-global ()
  7597. "Follow a link or a time-stamp like Org mode does.
  7598. Also follow links and emails as seen by `thing-at-point'.
  7599. This command can be called in any mode to follow an external
  7600. link or a time-stamp that has Org mode syntax. Its behavior
  7601. is undefined when called on internal links like fuzzy links.
  7602. Raise a user error when there is nothing to follow."
  7603. (interactive)
  7604. (let ((tap-url (thing-at-point 'url))
  7605. (tap-email (thing-at-point 'email)))
  7606. (cond ((org-in-regexp org-link-any-re)
  7607. (org-link-open-from-string (match-string-no-properties 0)))
  7608. ((or (org-in-regexp org-ts-regexp-both nil t)
  7609. (org-in-regexp org-tsr-regexp-both nil t))
  7610. (org-follow-timestamp-link))
  7611. (tap-url (org-link-open-from-string tap-url))
  7612. (tap-email (org-link-open-from-string
  7613. (concat "mailto:" tap-email)))
  7614. (t (user-error "No link found")))))
  7615. (defvar org-open-at-point-functions nil
  7616. "Hook that is run when following a link at point.
  7617. Functions in this hook must return t if they identify and follow
  7618. a link at point. If they don't find anything interesting at point,
  7619. they must return nil.")
  7620. (defun org-open-at-point (&optional arg)
  7621. "Open link, timestamp, footnote or tags at point.
  7622. When point is on a link, follow it. Normally, files will be
  7623. opened by an appropriate application. If the optional prefix
  7624. argument ARG is non-nil, Emacs will visit the file. With
  7625. a double prefix argument, try to open outside of Emacs, in the
  7626. application the system uses for this file type.
  7627. When point is on a timestamp, open the agenda at the day
  7628. specified.
  7629. When point is a footnote definition, move to the first reference
  7630. found. If it is on a reference, move to the associated
  7631. definition.
  7632. When point is on a headline, display a list of every link in the
  7633. entry, so it is possible to pick one, or all, of them. If point
  7634. is on a tag, call `org-tags-view' instead.
  7635. On top of syntactically correct links, this function also tries
  7636. to open links and time-stamps in comments, node properties, and
  7637. keywords if point is on something looking like a timestamp or
  7638. a link."
  7639. (interactive "P")
  7640. (org-load-modules-maybe)
  7641. (setq org-window-config-before-follow-link (current-window-configuration))
  7642. (org-remove-occur-highlights nil nil t)
  7643. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7644. (let* ((context
  7645. ;; Only consider supported types, even if they are not the
  7646. ;; closest one.
  7647. (org-element-lineage
  7648. (org-element-context)
  7649. '(clock comment comment-block footnote-definition
  7650. footnote-reference headline inline-src-block inlinetask
  7651. keyword link node-property planning src-block timestamp)
  7652. t))
  7653. (type (org-element-type context))
  7654. (value (org-element-property :value context)))
  7655. (cond
  7656. ((not type) (user-error "No link found"))
  7657. ;; No valid link at point. For convenience, look if something
  7658. ;; looks like a link under point in some specific places.
  7659. ((memq type '(comment comment-block node-property keyword))
  7660. (call-interactively #'org-open-at-point-global))
  7661. ;; On a headline or an inlinetask, but not on a timestamp,
  7662. ;; a link, a footnote reference.
  7663. ((memq type '(headline inlinetask))
  7664. (org-match-line org-complex-heading-regexp)
  7665. (let ((tags-beg (match-beginning 5))
  7666. (tags-end (match-end 5)))
  7667. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7668. ;; On tags.
  7669. (org-tags-view
  7670. arg
  7671. (save-excursion
  7672. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7673. (end-tag (search-forward ":" tags-end nil 2)))
  7674. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7675. ;; Not on tags.
  7676. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7677. (`(nil . ,_)
  7678. (require 'org-attach)
  7679. (when (org-attach-dir)
  7680. (message "Opening attachment")
  7681. (if (equal arg '(4))
  7682. (org-attach-reveal-in-emacs)
  7683. (org-attach-reveal))))
  7684. (`(,links . ,links-end)
  7685. (dolist (link (if (stringp links) (list links) links))
  7686. (search-forward link nil links-end)
  7687. (goto-char (match-beginning 0))
  7688. (org-open-at-point arg)))))))
  7689. ;; On a footnote reference or at definition's label.
  7690. ((or (eq type 'footnote-reference)
  7691. (and (eq type 'footnote-definition)
  7692. (save-excursion
  7693. ;; Do not validate action when point is on the
  7694. ;; spaces right after the footnote label, in order
  7695. ;; to be on par with behavior on links.
  7696. (skip-chars-forward " \t")
  7697. (let ((begin
  7698. (org-element-property :contents-begin context)))
  7699. (if begin (< (point) begin)
  7700. (= (org-element-property :post-affiliated context)
  7701. (line-beginning-position)))))))
  7702. (org-footnote-action))
  7703. ;; On a planning line. Check if we are really on a timestamp.
  7704. ((and (eq type 'planning)
  7705. (org-in-regexp org-ts-regexp-both nil t))
  7706. (org-follow-timestamp-link))
  7707. ;; On a clock line, make sure point is on the timestamp
  7708. ;; before opening it.
  7709. ((and (eq type 'clock)
  7710. value
  7711. (>= (point) (org-element-property :begin value))
  7712. (<= (point) (org-element-property :end value)))
  7713. (org-follow-timestamp-link))
  7714. ((eq type 'src-block) (org-babel-open-src-block-result))
  7715. ;; Do nothing on white spaces after an object.
  7716. ((>= (point)
  7717. (save-excursion
  7718. (goto-char (org-element-property :end context))
  7719. (skip-chars-backward " \t")
  7720. (point)))
  7721. (user-error "No link found"))
  7722. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7723. ((eq type 'timestamp) (org-follow-timestamp-link))
  7724. ((eq type 'link) (org-link-open context arg))
  7725. (t (user-error "No link found")))))
  7726. (run-hook-with-args 'org-follow-link-hook))
  7727. ;;;###autoload
  7728. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7729. "Offer links in the current entry and return the selected link.
  7730. If there is only one link, return it.
  7731. If NTH is an integer, return the NTH link found.
  7732. If ZERO is a string, check also this string for a link, and if
  7733. there is one, return it."
  7734. (with-current-buffer buffer
  7735. (org-with-wide-buffer
  7736. (goto-char marker)
  7737. (let ((cnt ?0)
  7738. have-zero end links link c)
  7739. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7740. (push (match-string 0 zero) links)
  7741. (setq cnt (1- cnt) have-zero t))
  7742. (save-excursion
  7743. (org-back-to-heading t)
  7744. (setq end (save-excursion (outline-next-heading) (point)))
  7745. (while (re-search-forward org-link-any-re end t)
  7746. (push (match-string 0) links))
  7747. (setq links (org-uniquify (reverse links))))
  7748. (cond
  7749. ((null links)
  7750. (message "No links"))
  7751. ((equal (length links) 1)
  7752. (setq link (car links)))
  7753. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7754. (setq link (nth (if have-zero nth (1- nth)) links)))
  7755. (t ; we have to select a link
  7756. (save-excursion
  7757. (save-window-excursion
  7758. (delete-other-windows)
  7759. (with-output-to-temp-buffer "*Select Link*"
  7760. (dolist (l links)
  7761. (cond
  7762. ((not (string-match org-link-bracket-re l))
  7763. (princ (format "[%c] %s\n" (cl-incf cnt)
  7764. (org-unbracket-string "<" ">" l))))
  7765. ((match-end 2)
  7766. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7767. (match-string 2 l) (match-string 1 l))))
  7768. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7769. (match-string 1 l)))))))
  7770. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7771. (message "Select link to open, RET to open all:")
  7772. (setq c (read-char-exclusive))
  7773. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7774. (when (equal c ?q) (user-error "Abort"))
  7775. (if (equal c ?\C-m)
  7776. (setq link links)
  7777. (setq nth (- c ?0))
  7778. (when have-zero (setq nth (1+ nth)))
  7779. (unless (and (integerp nth) (>= (length links) nth))
  7780. (user-error "Invalid link selection"))
  7781. (setq link (nth (1- nth) links)))))
  7782. (cons link end)))))
  7783. ;;; File search
  7784. (defun org-do-occur (regexp &optional cleanup)
  7785. "Call the Emacs command `occur'.
  7786. If CLEANUP is non-nil, remove the printout of the regular expression
  7787. in the *Occur* buffer. This is useful if the regex is long and not useful
  7788. to read."
  7789. (occur regexp)
  7790. (when cleanup
  7791. (let ((cwin (selected-window)) win beg end)
  7792. (when (setq win (get-buffer-window "*Occur*"))
  7793. (select-window win))
  7794. (goto-char (point-min))
  7795. (when (re-search-forward "match[a-z]+" nil t)
  7796. (setq beg (match-end 0))
  7797. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7798. (setq end (1- (match-beginning 0)))))
  7799. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7800. (goto-char (point-min))
  7801. (select-window cwin))))
  7802. ;;; The Mark Ring
  7803. (defvar org-mark-ring nil
  7804. "Mark ring for positions before jumps in Org mode.")
  7805. (defvar org-mark-ring-last-goto nil
  7806. "Last position in the mark ring used to go back.")
  7807. ;; Fill and close the ring
  7808. (setq org-mark-ring nil)
  7809. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7810. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7811. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7812. org-mark-ring)
  7813. (defun org-mark-ring-push (&optional pos buffer)
  7814. "Put the current position into the mark ring and rotate it.
  7815. Also push position into the Emacs mark ring. If optional
  7816. argument POS and BUFFER are not nil, mark this location instead."
  7817. (interactive)
  7818. (let ((pos (or pos (point)))
  7819. (buffer (or buffer (current-buffer))))
  7820. (with-current-buffer buffer
  7821. (org-with-point-at pos (push-mark nil t)))
  7822. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7823. (move-marker (car org-mark-ring) pos buffer))
  7824. (message
  7825. (substitute-command-keys
  7826. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7827. (defun org-mark-ring-goto (&optional n)
  7828. "Jump to the previous position in the mark ring.
  7829. With prefix arg N, jump back that many stored positions. When
  7830. called several times in succession, walk through the entire ring.
  7831. Org mode commands jumping to a different position in the current file,
  7832. or to another Org file, automatically push the old position onto the ring."
  7833. (interactive "p")
  7834. (let (p m)
  7835. (if (eq last-command this-command)
  7836. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7837. (setq p org-mark-ring))
  7838. (setq org-mark-ring-last-goto p)
  7839. (setq m (car p))
  7840. (pop-to-buffer-same-window (marker-buffer m))
  7841. (goto-char m)
  7842. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7843. ;;; Following specific links
  7844. (defvar org-agenda-buffer-tmp-name)
  7845. (defvar org-agenda-start-on-weekday)
  7846. (defun org-follow-timestamp-link ()
  7847. "Open an agenda view for the time-stamp date/range at point."
  7848. (cond
  7849. ((org-at-date-range-p t)
  7850. (let ((org-agenda-start-on-weekday)
  7851. (t1 (match-string 1))
  7852. (t2 (match-string 2)) tt1 tt2)
  7853. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7854. tt2 (time-to-days (org-time-string-to-time t2)))
  7855. (let ((org-agenda-buffer-tmp-name
  7856. (format "*Org Agenda(a:%s)"
  7857. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7858. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7859. ((org-at-timestamp-p 'lax)
  7860. (let ((org-agenda-buffer-tmp-name
  7861. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7862. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7863. (substring (match-string 1) 0 10)))
  7864. 1)))
  7865. (t (error "This should not happen"))))
  7866. ;;; Following file links
  7867. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7868. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7869. (declare-function mailcap-mime-info
  7870. "mailcap" (string &optional request no-decode))
  7871. (defvar org-wait nil)
  7872. ;;;; Refiling
  7873. (defun org-get-org-file ()
  7874. "Read a filename, with default directory `org-directory'."
  7875. (let ((default (or org-default-notes-file remember-data-file)))
  7876. (read-file-name (format "File name [%s]: " default)
  7877. (file-name-as-directory org-directory)
  7878. default)))
  7879. (defun org-notes-order-reversed-p ()
  7880. "Check if the current file should receive notes in reversed order."
  7881. (cond
  7882. ((not org-reverse-note-order) nil)
  7883. ((eq t org-reverse-note-order) t)
  7884. ((not (listp org-reverse-note-order)) nil)
  7885. (t (catch 'exit
  7886. (dolist (entry org-reverse-note-order)
  7887. (when (string-match (car entry) buffer-file-name)
  7888. (throw 'exit (cdr entry))))))))
  7889. (defvar org-agenda-new-buffers nil
  7890. "Buffers created to visit agenda files.")
  7891. (declare-function org-string-nw-p "org-macs" (s))
  7892. ;;;; Dynamic blocks
  7893. (defun org-find-dblock (name)
  7894. "Find the first dynamic block with name NAME in the buffer.
  7895. If not found, stay at current position and return nil."
  7896. (let ((case-fold-search t) pos)
  7897. (save-excursion
  7898. (goto-char (point-min))
  7899. (setq pos (and (re-search-forward
  7900. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7901. (match-beginning 0))))
  7902. (when pos (goto-char pos))
  7903. pos))
  7904. (defun org-create-dblock (plist)
  7905. "Create a dynamic block section, with parameters taken from PLIST.
  7906. PLIST must contain a :name entry which is used as the name of the block."
  7907. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7908. (end-of-line 1)
  7909. (newline))
  7910. (let ((col (current-column))
  7911. (name (plist-get plist :name)))
  7912. (insert "#+BEGIN: " name)
  7913. (while plist
  7914. (if (eq (car plist) :name)
  7915. (setq plist (cddr plist))
  7916. (insert " " (prin1-to-string (pop plist)))))
  7917. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7918. (beginning-of-line -2)))
  7919. (defun org-prepare-dblock ()
  7920. "Prepare dynamic block for refresh.
  7921. This empties the block, puts the cursor at the insert position and returns
  7922. the property list including an extra property :name with the block name."
  7923. (unless (looking-at org-dblock-start-re)
  7924. (user-error "Not at a dynamic block"))
  7925. (let* ((begdel (1+ (match-end 0)))
  7926. (name (org-no-properties (match-string 1)))
  7927. (params (append (list :name name)
  7928. (read (concat "(" (match-string 3) ")")))))
  7929. (save-excursion
  7930. (beginning-of-line 1)
  7931. (skip-chars-forward " \t")
  7932. (setq params (plist-put params :indentation-column (current-column))))
  7933. (unless (re-search-forward org-dblock-end-re nil t)
  7934. (error "Dynamic block not terminated"))
  7935. (setq params
  7936. (append params
  7937. (list :content (buffer-substring
  7938. begdel (match-beginning 0)))))
  7939. (delete-region begdel (match-beginning 0))
  7940. (goto-char begdel)
  7941. (open-line 1)
  7942. params))
  7943. (defun org-map-dblocks (&optional command)
  7944. "Apply COMMAND to all dynamic blocks in the current buffer.
  7945. If COMMAND is not given, use `org-update-dblock'."
  7946. (let ((cmd (or command 'org-update-dblock)))
  7947. (save-excursion
  7948. (goto-char (point-min))
  7949. (while (re-search-forward org-dblock-start-re nil t)
  7950. (goto-char (match-beginning 0))
  7951. (save-excursion
  7952. (condition-case nil
  7953. (funcall cmd)
  7954. (error (message "Error during update of dynamic block"))))
  7955. (unless (re-search-forward org-dblock-end-re nil t)
  7956. (error "Dynamic block not terminated"))))))
  7957. (defvar org-dynamic-block-alist nil
  7958. "Alist defining all the Org dynamic blocks.
  7959. The key is the dynamic block type name, as a string. The value
  7960. is the function used to insert the dynamic block.
  7961. Use `org-dynamic-block-define' to populate it.")
  7962. (defun org-dynamic-block-function (type)
  7963. "Return function associated to a given dynamic block type.
  7964. TYPE is the dynamic block type, as a string."
  7965. (cdr (assoc type org-dynamic-block-alist)))
  7966. (defun org-dynamic-block-types ()
  7967. "List all defined dynamic block types."
  7968. (mapcar #'car org-dynamic-block-alist))
  7969. (defun org-dynamic-block-define (type func)
  7970. "Define dynamic block TYPE with FUNC.
  7971. TYPE is a string. FUNC is the function creating the dynamic
  7972. block of such type."
  7973. (pcase (assoc type org-dynamic-block-alist)
  7974. (`nil (push (cons type func) org-dynamic-block-alist))
  7975. (def (setcdr def func))))
  7976. (defun org-dynamic-block-insert-dblock (type)
  7977. "Insert a dynamic block of type TYPE.
  7978. When used interactively, select the dynamic block types among
  7979. defined types, per `org-dynamic-block-define'."
  7980. (interactive (list (completing-read "Dynamic block: "
  7981. (org-dynamic-block-types))))
  7982. (pcase (org-dynamic-block-function type)
  7983. (`nil (error "No such dynamic block: %S" type))
  7984. ((and f (pred functionp)) (funcall f))
  7985. (_ (error "Invalid function for dynamic block %S" type))))
  7986. (defun org-dblock-update (&optional arg)
  7987. "User command for updating dynamic blocks.
  7988. Update the dynamic block at point. With prefix ARG, update all dynamic
  7989. blocks in the buffer."
  7990. (interactive "P")
  7991. (if arg
  7992. (org-update-all-dblocks)
  7993. (or (looking-at org-dblock-start-re)
  7994. (org-beginning-of-dblock))
  7995. (org-update-dblock)))
  7996. (defun org-update-dblock ()
  7997. "Update the dynamic block at point.
  7998. This means to empty the block, parse for parameters and then call
  7999. the correct writing function."
  8000. (interactive)
  8001. (save-excursion
  8002. (let* ((win (selected-window))
  8003. (pos (point))
  8004. (line (org-current-line))
  8005. (params (org-prepare-dblock))
  8006. (name (plist-get params :name))
  8007. (indent (plist-get params :indentation-column))
  8008. (cmd (intern (concat "org-dblock-write:" name))))
  8009. (message "Updating dynamic block `%s' at line %d..." name line)
  8010. (funcall cmd params)
  8011. (message "Updating dynamic block `%s' at line %d...done" name line)
  8012. (goto-char pos)
  8013. (when (and indent (> indent 0))
  8014. (setq indent (make-string indent ?\ ))
  8015. (save-excursion
  8016. (select-window win)
  8017. (org-beginning-of-dblock)
  8018. (forward-line 1)
  8019. (while (not (looking-at org-dblock-end-re))
  8020. (insert indent)
  8021. (beginning-of-line 2))
  8022. (when (looking-at org-dblock-end-re)
  8023. (and (looking-at "[ \t]+")
  8024. (replace-match ""))
  8025. (insert indent)))))))
  8026. (defun org-beginning-of-dblock ()
  8027. "Find the beginning of the dynamic block at point.
  8028. Error if there is no such block at point."
  8029. (let ((pos (point))
  8030. beg)
  8031. (end-of-line 1)
  8032. (if (and (re-search-backward org-dblock-start-re nil t)
  8033. (setq beg (match-beginning 0))
  8034. (re-search-forward org-dblock-end-re nil t)
  8035. (> (match-end 0) pos))
  8036. (goto-char beg)
  8037. (goto-char pos)
  8038. (error "Not in a dynamic block"))))
  8039. (defun org-update-all-dblocks ()
  8040. "Update all dynamic blocks in the buffer.
  8041. This function can be used in a hook."
  8042. (interactive)
  8043. (when (derived-mode-p 'org-mode)
  8044. (org-map-dblocks 'org-update-dblock)))
  8045. ;;;; Completion
  8046. (declare-function org-export-backend-options "ox" (cl-x) t)
  8047. (defun org-get-export-keywords ()
  8048. "Return a list of all currently understood export keywords.
  8049. Export keywords include options, block names, attributes and
  8050. keywords relative to each registered export back-end."
  8051. (let (keywords)
  8052. (dolist (backend
  8053. (bound-and-true-p org-export-registered-backends)
  8054. (delq nil keywords))
  8055. ;; Back-end name (for keywords, like #+LATEX:)
  8056. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8057. (dolist (option-entry (org-export-backend-options backend))
  8058. ;; Back-end options.
  8059. (push (nth 1 option-entry) keywords)))))
  8060. (defconst org-options-keywords
  8061. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8062. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8063. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8064. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8065. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8066. (defcustom org-structure-template-alist
  8067. '(("a" . "export ascii")
  8068. ("c" . "center")
  8069. ("C" . "comment")
  8070. ("e" . "example")
  8071. ("E" . "export")
  8072. ("h" . "export html")
  8073. ("l" . "export latex")
  8074. ("q" . "quote")
  8075. ("s" . "src")
  8076. ("v" . "verse"))
  8077. "An alist of keys and block types.
  8078. `org-insert-structure-template' will display a menu with this
  8079. list of templates to choose from. The block type is inserted,
  8080. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8081. The menu keys are defined by the car of each entry in this alist.
  8082. If two entries have the keys \"a\" and \"aa\" respectively, the
  8083. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8084. latter will be inserted by typing \"aa\". If an entry with the
  8085. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8086. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8087. block can be inserted by pressing TAB after the string \"<KEY\"."
  8088. :group 'org-edit-structure
  8089. :type '(repeat
  8090. (cons (string :tag "Key")
  8091. (string :tag "Template")))
  8092. :package-version '(Org . "9.2"))
  8093. (defun org--check-org-structure-template-alist (&optional checklist)
  8094. "Check whether `org-structure-template-alist' is set up correctly.
  8095. In particular, check if the Org 9.2 format is used as opposed to
  8096. previous format.
  8097. "
  8098. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8099. (or (eval checklist)
  8100. org-structure-template-alist))))
  8101. (when elm
  8102. (org-display-warning
  8103. (format "
  8104. Please update the entries of `%s'.
  8105. In Org 9.2 the format was changed from something like
  8106. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8107. to something like
  8108. (\"s\" . \"src\")
  8109. Please refer to the documentation of `org-structure-template-alist'.
  8110. The following entries must be updated:
  8111. %s"
  8112. (or checklist 'org-structure-template-alist)
  8113. (pp-to-string elm))))))
  8114. (defun org--insert-structure-template-mks ()
  8115. "Present `org-structure-template-alist' with `org-mks'.
  8116. Menus are added if keys require more than one keystroke. Tabs
  8117. are added to single key entries when more than one stroke is
  8118. needed. Keys longer than two characters are reduced to two
  8119. characters."
  8120. (org--check-org-structure-template-alist)
  8121. (let* (case-fold-search
  8122. (templates (append org-structure-template-alist
  8123. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8124. (keys (mapcar #'car templates))
  8125. (start-letters
  8126. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8127. ;; Sort each element of `org-structure-template-alist' into
  8128. ;; sublists according to the first letter.
  8129. (superlist
  8130. (mapcar (lambda (letter)
  8131. (list letter
  8132. (cl-remove-if-not
  8133. (apply-partially #'string-match-p (concat "^" letter))
  8134. templates :key #'car)))
  8135. start-letters)))
  8136. (org-mks
  8137. (apply #'append
  8138. ;; Make an `org-mks' table. If only one element is
  8139. ;; present in a sublist, make it part of the top-menu,
  8140. ;; otherwise make a submenu according to the starting
  8141. ;; letter and populate it.
  8142. (mapcar (lambda (sublist)
  8143. (if (eq 1 (length (cadr sublist)))
  8144. (mapcar (lambda (elm)
  8145. (list (substring (car elm) 0 1)
  8146. (cdr elm) ""))
  8147. (cadr sublist))
  8148. ;; Create submenu.
  8149. (let* ((topkey (car sublist))
  8150. (elms (cadr sublist))
  8151. (keys (mapcar #'car elms))
  8152. (long (> (length elms) 3)))
  8153. (append
  8154. (list
  8155. ;; Make a description of the submenu.
  8156. (list topkey
  8157. (concat
  8158. (mapconcat #'cdr
  8159. (cl-subseq elms 0 (if long 3 (length elms)))
  8160. ", ")
  8161. (when long ", ..."))))
  8162. ;; List of entries in submenu.
  8163. (cl-mapcar #'list
  8164. (org--insert-structure-template-unique-keys keys)
  8165. (mapcar #'cdr elms)
  8166. (make-list (length elms) ""))))))
  8167. superlist))
  8168. "Select a key\n============"
  8169. "Key: ")))
  8170. (defun org--insert-structure-template-unique-keys (keys)
  8171. "Make a list of unique, two characters long elements from KEYS.
  8172. Elements of length one have a tab appended. Elements of length
  8173. two are kept as is. Longer elements are truncated to length two.
  8174. If an element cannot be made unique, an error is raised."
  8175. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8176. menu-keys)
  8177. (dolist (key ordered-keys)
  8178. (let ((potential-key
  8179. (cl-case (length key)
  8180. (1 (concat key "\t"))
  8181. (2 key)
  8182. (otherwise
  8183. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8184. (mapcar (apply-partially #'concat (substring key 0 1))
  8185. (split-string (substring key 1) "" t)))))))
  8186. (if (or (not potential-key) (assoc potential-key menu-keys))
  8187. (user-error "Could not make unique key for %s." key)
  8188. (push (cons potential-key key) menu-keys))))
  8189. (mapcar #'car
  8190. (cl-sort menu-keys #'<
  8191. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8192. (defun org-insert-structure-template (type)
  8193. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8194. Select a block from `org-structure-template-alist' then type
  8195. either RET, TAB or SPC to write the block type. With an active
  8196. region, wrap the region in the block. Otherwise, insert an empty
  8197. block."
  8198. (interactive
  8199. (list (pcase (org--insert-structure-template-mks)
  8200. (`("\t" . ,_) (read-string "Structure type: "))
  8201. (`(,_ ,choice . ,_) choice))))
  8202. (let* ((region? (use-region-p))
  8203. (region-start (and region? (region-beginning)))
  8204. (region-end (and region? (copy-marker (region-end))))
  8205. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8206. (verbatim? (string-match-p
  8207. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8208. type)))
  8209. (when region? (goto-char region-start))
  8210. (let ((column (current-indentation)))
  8211. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8212. (beginning-of-line)
  8213. (insert "\n"))
  8214. (save-excursion
  8215. (indent-to column)
  8216. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8217. (when region?
  8218. (when verbatim? (org-escape-code-in-region (point) region-end))
  8219. (goto-char region-end)
  8220. ;; Ignore empty lines at the end of the region.
  8221. (skip-chars-backward " \r\t\n")
  8222. (end-of-line))
  8223. (unless (bolp) (insert "\n"))
  8224. (indent-to column)
  8225. (insert (format "#+end_%s" (car (split-string type))))
  8226. (if (looking-at "[ \t]*$") (replace-match "")
  8227. (insert "\n"))
  8228. (when (and (eobp) (not (bolp))) (insert "\n")))
  8229. (if extended? (end-of-line)
  8230. (forward-line)
  8231. (skip-chars-forward " \t")))))
  8232. ;;;; TODO, DEADLINE, Comments
  8233. (defun org-toggle-comment ()
  8234. "Change the COMMENT state of an entry."
  8235. (interactive)
  8236. (save-excursion
  8237. (org-back-to-heading)
  8238. (let ((case-fold-search nil))
  8239. (looking-at org-complex-heading-regexp))
  8240. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8241. (skip-chars-forward " \t")
  8242. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8243. (if (org-in-commented-heading-p t)
  8244. (delete-region (point)
  8245. (progn (search-forward " " (line-end-position) 'move)
  8246. (skip-chars-forward " \t")
  8247. (point)))
  8248. (insert org-comment-string)
  8249. (unless (eolp) (insert " ")))))
  8250. (defvar org-last-todo-state-is-todo nil
  8251. "This is non-nil when the last TODO state change led to a TODO state.
  8252. If the last change removed the TODO tag or switched to DONE, then
  8253. this is nil.")
  8254. (defvar org-todo-setup-filter-hook nil
  8255. "Hook for functions that pre-filter todo specs.
  8256. Each function takes a todo spec and returns either nil or the spec
  8257. transformed into canonical form." )
  8258. (defvar org-todo-get-default-hook nil
  8259. "Hook for functions that get a default item for todo.
  8260. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8261. nil or a string to be used for the todo mark." )
  8262. (defvar org-agenda-headline-snapshot-before-repeat)
  8263. (defun org-current-effective-time ()
  8264. "Return current time adjusted for `org-extend-today-until' variable."
  8265. (let* ((ct (org-current-time))
  8266. (dct (decode-time ct))
  8267. (ct1
  8268. (cond
  8269. (org-use-last-clock-out-time-as-effective-time
  8270. (or (org-clock-get-last-clock-out-time) ct))
  8271. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8272. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8273. (t ct))))
  8274. ct1))
  8275. (defun org-todo-yesterday (&optional arg)
  8276. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8277. (interactive "P")
  8278. (if (eq major-mode 'org-agenda-mode)
  8279. (apply 'org-agenda-todo-yesterday arg)
  8280. (let* ((org-use-effective-time t)
  8281. (hour (nth 2 (decode-time (org-current-time))))
  8282. (org-extend-today-until (1+ hour)))
  8283. (org-todo arg))))
  8284. (defvar org-block-entry-blocking ""
  8285. "First entry preventing the TODO state change.")
  8286. (defun org-cancel-repeater ()
  8287. "Cancel a repeater by setting its numeric value to zero."
  8288. (interactive)
  8289. (save-excursion
  8290. (org-back-to-heading t)
  8291. (let ((bound1 (point))
  8292. (bound0 (save-excursion (outline-next-heading) (point))))
  8293. (when (and (re-search-forward
  8294. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8295. org-deadline-time-regexp "\\)\\|\\("
  8296. org-ts-regexp "\\)")
  8297. bound0 t)
  8298. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8299. bound1 t))
  8300. (replace-match "0" t nil nil 1)))))
  8301. (defvar org-state)
  8302. (defvar org-blocked-by-checkboxes)
  8303. (defun org-todo (&optional arg)
  8304. "Change the TODO state of an item.
  8305. The state of an item is given by a keyword at the start of the heading,
  8306. like
  8307. *** TODO Write paper
  8308. *** DONE Call mom
  8309. The different keywords are specified in the variable `org-todo-keywords'.
  8310. By default the available states are \"TODO\" and \"DONE\". So, for this
  8311. example: when the item starts with TODO, it is changed to DONE.
  8312. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8313. DONE are present, add TODO at the beginning of the heading.
  8314. You can set up single-character keys to fast-select the new state. See the
  8315. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8316. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8317. and take a
  8318. logging note.
  8319. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8320. next set of TODO \
  8321. keywords (nextset).
  8322. Another way to achieve this is `S-C-<right>'.
  8323. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8324. prefix, circumvent any state blocking.
  8325. With numeric prefix arg, switch to the Nth state.
  8326. With a numeric prefix arg of 0, inhibit note taking for the change.
  8327. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8328. When called through ELisp, arg is also interpreted in the following way:
  8329. `none' -> empty state
  8330. \"\" -> switch to empty state
  8331. `done' -> switch to DONE
  8332. `nextset' -> switch to the next set of keywords
  8333. `previousset' -> switch to the previous set of keywords
  8334. \"WAITING\" -> switch to the specified keyword, but only if it
  8335. really is a member of `org-todo-keywords'."
  8336. (interactive "P")
  8337. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8338. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8339. 'region-start-level 'region))
  8340. org-loop-over-headlines-in-active-region)
  8341. (org-map-entries
  8342. `(org-todo ,arg)
  8343. org-loop-over-headlines-in-active-region
  8344. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8345. (when (equal arg '(16)) (setq arg 'nextset))
  8346. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8347. (let ((org-blocker-hook org-blocker-hook)
  8348. commentp
  8349. case-fold-search)
  8350. (when (equal arg '(64))
  8351. (setq arg nil org-blocker-hook nil))
  8352. (when (and org-blocker-hook
  8353. (or org-inhibit-blocking
  8354. (org-entry-get nil "NOBLOCKING")))
  8355. (setq org-blocker-hook nil))
  8356. (save-excursion
  8357. (catch 'exit
  8358. (org-back-to-heading t)
  8359. (when (org-in-commented-heading-p t)
  8360. (org-toggle-comment)
  8361. (setq commentp t))
  8362. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8363. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8364. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8365. (let* ((match-data (match-data))
  8366. (startpos (copy-marker (line-beginning-position)))
  8367. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8368. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8369. (org-log-done org-log-done)
  8370. (org-log-repeat org-log-repeat)
  8371. (org-todo-log-states org-todo-log-states)
  8372. (org-inhibit-logging
  8373. (if (equal arg 0)
  8374. (progn (setq arg nil) 'note) org-inhibit-logging))
  8375. (this (match-string 1))
  8376. (hl-pos (match-beginning 0))
  8377. (head (org-get-todo-sequence-head this))
  8378. (ass (assoc head org-todo-kwd-alist))
  8379. (interpret (nth 1 ass))
  8380. (done-word (nth 3 ass))
  8381. (final-done-word (nth 4 ass))
  8382. (org-last-state (or this ""))
  8383. (completion-ignore-case t)
  8384. (member (member this org-todo-keywords-1))
  8385. (tail (cdr member))
  8386. (org-state (cond
  8387. ((eq arg 'right)
  8388. ;; Next state
  8389. (if this
  8390. (if tail (car tail) nil)
  8391. (car org-todo-keywords-1)))
  8392. ((eq arg 'left)
  8393. ;; Previous state
  8394. (unless (equal member org-todo-keywords-1)
  8395. (if this
  8396. (nth (- (length org-todo-keywords-1)
  8397. (length tail) 2)
  8398. org-todo-keywords-1)
  8399. (org-last org-todo-keywords-1))))
  8400. (arg
  8401. ;; User or caller requests a specific state.
  8402. (cond
  8403. ((equal arg "") nil)
  8404. ((eq arg 'none) nil)
  8405. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8406. ((eq arg 'nextset)
  8407. (or (car (cdr (member head org-todo-heads)))
  8408. (car org-todo-heads)))
  8409. ((eq arg 'previousset)
  8410. (let ((org-todo-heads (reverse org-todo-heads)))
  8411. (or (car (cdr (member head org-todo-heads)))
  8412. (car org-todo-heads))))
  8413. ((car (member arg org-todo-keywords-1)))
  8414. ((stringp arg)
  8415. (user-error "State `%s' not valid in this file" arg))
  8416. ((nth (1- (prefix-numeric-value arg))
  8417. org-todo-keywords-1))))
  8418. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8419. ;; Use fast selection.
  8420. (org-fast-todo-selection this))
  8421. ((null member) (or head (car org-todo-keywords-1)))
  8422. ((equal this final-done-word) nil) ;-> make empty
  8423. ((null tail) nil) ;-> first entry
  8424. ((memq interpret '(type priority))
  8425. (if (eq this-command last-command)
  8426. (car tail)
  8427. (if (> (length tail) 0)
  8428. (or done-word (car org-done-keywords))
  8429. nil)))
  8430. (t
  8431. (car tail))))
  8432. (org-state (or
  8433. (run-hook-with-args-until-success
  8434. 'org-todo-get-default-hook org-state org-last-state)
  8435. org-state))
  8436. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8437. (change-plist (list :type 'todo-state-change :from this :to org-state
  8438. :position startpos))
  8439. dolog now-done-p)
  8440. (when org-blocker-hook
  8441. (let (org-blocked-by-checkboxes block-reason)
  8442. (setq org-last-todo-state-is-todo
  8443. (not (member this org-done-keywords)))
  8444. (unless (save-excursion
  8445. (save-match-data
  8446. (org-with-wide-buffer
  8447. (run-hook-with-args-until-failure
  8448. 'org-blocker-hook change-plist))))
  8449. (setq block-reason (if org-blocked-by-checkboxes
  8450. "contained checkboxes"
  8451. (format "\"%s\"" org-block-entry-blocking)))
  8452. (if (called-interactively-p 'interactive)
  8453. (user-error "TODO state change from %s to %s blocked (by %s)"
  8454. this org-state block-reason)
  8455. ;; Fail silently.
  8456. (message "TODO state change from %s to %s blocked (by %s)"
  8457. this org-state block-reason)
  8458. (throw 'exit nil)))))
  8459. (store-match-data match-data)
  8460. (replace-match next t t)
  8461. (cond ((and org-state (equal this org-state))
  8462. (message "TODO state was already %s" (org-trim next)))
  8463. ((not (pos-visible-in-window-p hl-pos))
  8464. (message "TODO state changed to %s" (org-trim next))))
  8465. (unless head
  8466. (setq head (org-get-todo-sequence-head org-state)
  8467. ass (assoc head org-todo-kwd-alist)
  8468. interpret (nth 1 ass)
  8469. done-word (nth 3 ass)
  8470. final-done-word (nth 4 ass)))
  8471. (when (memq arg '(nextset previousset))
  8472. (message "Keyword-Set %d/%d: %s"
  8473. (- (length org-todo-sets) -1
  8474. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8475. (length org-todo-sets)
  8476. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8477. (setq org-last-todo-state-is-todo
  8478. (not (member org-state org-done-keywords)))
  8479. (setq now-done-p (and (member org-state org-done-keywords)
  8480. (not (member this org-done-keywords))))
  8481. (and logging (org-local-logging logging))
  8482. (when (or (and (or org-todo-log-states org-log-done)
  8483. (not (eq org-inhibit-logging t))
  8484. (not (memq arg '(nextset previousset))))
  8485. force-log)
  8486. ;; We need to look at recording a time and note.
  8487. (setq dolog (or (if force-log 'note)
  8488. (nth 1 (assoc org-state org-todo-log-states))
  8489. (nth 2 (assoc this org-todo-log-states))))
  8490. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8491. (setq dolog 'time))
  8492. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8493. (and org-state
  8494. (member org-state org-not-done-keywords)
  8495. (not (member this org-not-done-keywords))))
  8496. ;; This is now a todo state and was not one before
  8497. ;; If there was a CLOSED time stamp, get rid of it.
  8498. (org-add-planning-info nil nil 'closed))
  8499. (when (and now-done-p org-log-done)
  8500. ;; It is now done, and it was not done before.
  8501. (org-add-planning-info 'closed (org-current-effective-time))
  8502. (when (and (not dolog) (eq 'note org-log-done))
  8503. (org-add-log-setup 'done org-state this 'note)))
  8504. (when (and org-state dolog)
  8505. ;; This is a non-nil state, and we need to log it.
  8506. (org-add-log-setup 'state org-state this dolog)))
  8507. ;; Fixup tag positioning.
  8508. (org-todo-trigger-tag-changes org-state)
  8509. (when org-auto-align-tags (org-align-tags))
  8510. (when org-provide-todo-statistics
  8511. (org-update-parent-todo-statistics))
  8512. (when (bound-and-true-p org-clock-out-when-done)
  8513. (org-clock-out-if-current))
  8514. (run-hooks 'org-after-todo-state-change-hook)
  8515. (when (and arg (not (member org-state org-done-keywords)))
  8516. (setq head (org-get-todo-sequence-head org-state)))
  8517. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8518. ;; Do we need to trigger a repeat?
  8519. (when now-done-p
  8520. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8521. ;; This is for the agenda, take a snapshot of the headline.
  8522. (save-match-data
  8523. (setq org-agenda-headline-snapshot-before-repeat
  8524. (org-get-heading))))
  8525. (org-auto-repeat-maybe org-state))
  8526. ;; Fixup cursor location if close to the keyword.
  8527. (when (and (outline-on-heading-p)
  8528. (not (bolp))
  8529. (save-excursion (beginning-of-line 1)
  8530. (looking-at org-todo-line-regexp))
  8531. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8532. (goto-char (or (match-end 2) (match-end 1)))
  8533. (and (looking-at " ")
  8534. (not (looking-at " *:"))
  8535. (just-one-space)))
  8536. (when org-trigger-hook
  8537. (save-excursion
  8538. (run-hook-with-args 'org-trigger-hook change-plist)))
  8539. (when commentp (org-toggle-comment))))))))
  8540. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8541. "Block turning an entry into a TODO, using the hierarchy.
  8542. This checks whether the current task should be blocked from state
  8543. changes. Such blocking occurs when:
  8544. 1. The task has children which are not all in a completed state.
  8545. 2. A task has a parent with the property :ORDERED:, and there
  8546. are siblings prior to the current task with incomplete
  8547. status.
  8548. 3. The parent of the task is blocked because it has siblings that should
  8549. be done first, or is child of a block grandparent TODO entry."
  8550. (if (not org-enforce-todo-dependencies)
  8551. t ; if locally turned off don't block
  8552. (catch 'dont-block
  8553. ;; If this is not a todo state change, or if this entry is already DONE,
  8554. ;; do not block
  8555. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8556. (member (plist-get change-plist :from)
  8557. (cons 'done org-done-keywords))
  8558. (member (plist-get change-plist :to)
  8559. (cons 'todo org-not-done-keywords))
  8560. (not (plist-get change-plist :to)))
  8561. (throw 'dont-block t))
  8562. ;; If this task has children, and any are undone, it's blocked
  8563. (save-excursion
  8564. (org-back-to-heading t)
  8565. (let ((this-level (funcall outline-level)))
  8566. (outline-next-heading)
  8567. (let ((child-level (funcall outline-level)))
  8568. (while (and (not (eobp))
  8569. (> child-level this-level))
  8570. ;; this todo has children, check whether they are all
  8571. ;; completed
  8572. (when (and (not (org-entry-is-done-p))
  8573. (org-entry-is-todo-p))
  8574. (setq org-block-entry-blocking (org-get-heading))
  8575. (throw 'dont-block nil))
  8576. (outline-next-heading)
  8577. (setq child-level (funcall outline-level))))))
  8578. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8579. ;; any previous siblings are undone, it's blocked
  8580. (save-excursion
  8581. (org-back-to-heading t)
  8582. (let* ((pos (point))
  8583. (parent-pos (and (org-up-heading-safe) (point)))
  8584. (case-fold-search nil))
  8585. (unless parent-pos (throw 'dont-block t)) ; no parent
  8586. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8587. (forward-line 1)
  8588. (re-search-forward org-not-done-heading-regexp pos t))
  8589. (setq org-block-entry-blocking (match-string 0))
  8590. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8591. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8592. (while t
  8593. (goto-char parent-pos)
  8594. (unless (looking-at org-not-done-heading-regexp)
  8595. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8596. (setq pos (point))
  8597. (setq parent-pos (and (org-up-heading-safe) (point)))
  8598. (unless parent-pos (throw 'dont-block t)) ; no parent
  8599. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8600. (forward-line 1)
  8601. (re-search-forward org-not-done-heading-regexp pos t)
  8602. (setq org-block-entry-blocking (org-get-heading)))
  8603. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8604. (defcustom org-track-ordered-property-with-tag nil
  8605. "Should the ORDERED property also be shown as a tag?
  8606. The ORDERED property decides if an entry should require subtasks to be
  8607. completed in sequence. Since a property is not very visible, setting
  8608. this option means that toggling the ORDERED property with the command
  8609. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8610. not relevant for the behavior, but it makes things more visible.
  8611. Note that toggling the tag with tags commands will not change the property
  8612. and therefore not influence behavior!
  8613. This can be t, meaning the tag ORDERED should be used. It can also be a
  8614. string to select a different tag for this task."
  8615. :group 'org-todo
  8616. :type '(choice
  8617. (const :tag "No tracking" nil)
  8618. (const :tag "Track with ORDERED tag" t)
  8619. (string :tag "Use other tag")))
  8620. (defun org-toggle-ordered-property ()
  8621. "Toggle the ORDERED property of the current entry.
  8622. For better visibility, you can track the value of this property with a tag.
  8623. See variable `org-track-ordered-property-with-tag'."
  8624. (interactive)
  8625. (let* ((t1 org-track-ordered-property-with-tag)
  8626. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8627. (save-excursion
  8628. (org-back-to-heading)
  8629. (if (org-entry-get nil "ORDERED")
  8630. (progn
  8631. (org-delete-property "ORDERED")
  8632. (and tag (org-toggle-tag tag 'off))
  8633. (message "Subtasks can be completed in arbitrary order"))
  8634. (org-entry-put nil "ORDERED" "t")
  8635. (and tag (org-toggle-tag tag 'on))
  8636. (message "Subtasks must be completed in sequence")))))
  8637. (defun org-block-todo-from-checkboxes (change-plist)
  8638. "Block turning an entry into a TODO, using checkboxes.
  8639. This checks whether the current task should be blocked from state
  8640. changes because there are unchecked boxes in this entry."
  8641. (if (not org-enforce-todo-checkbox-dependencies)
  8642. t ; if locally turned off don't block
  8643. (catch 'dont-block
  8644. ;; If this is not a todo state change, or if this entry is already DONE,
  8645. ;; do not block
  8646. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8647. (member (plist-get change-plist :from)
  8648. (cons 'done org-done-keywords))
  8649. (member (plist-get change-plist :to)
  8650. (cons 'todo org-not-done-keywords))
  8651. (not (plist-get change-plist :to)))
  8652. (throw 'dont-block t))
  8653. ;; If this task has checkboxes that are not checked, it's blocked
  8654. (save-excursion
  8655. (org-back-to-heading t)
  8656. (let ((beg (point)) end)
  8657. (outline-next-heading)
  8658. (setq end (point))
  8659. (goto-char beg)
  8660. (when (org-list-search-forward
  8661. (concat (org-item-beginning-re)
  8662. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8663. "\\[[- ]\\]")
  8664. end t)
  8665. (when (boundp 'org-blocked-by-checkboxes)
  8666. (setq org-blocked-by-checkboxes t))
  8667. (throw 'dont-block nil))))
  8668. t))) ; do not block
  8669. (defun org-entry-blocked-p ()
  8670. "Non-nil if entry at point is blocked."
  8671. (and (not (org-entry-get nil "NOBLOCKING"))
  8672. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8673. (not (run-hook-with-args-until-failure
  8674. 'org-blocker-hook
  8675. (list :type 'todo-state-change
  8676. :position (point)
  8677. :from 'todo
  8678. :to 'done)))))
  8679. (defun org-update-statistics-cookies (all)
  8680. "Update the statistics cookie, either from TODO or from checkboxes.
  8681. This should be called with the cursor in a line with a statistics
  8682. cookie. When called with a \\[universal-argument] prefix, update
  8683. all statistics cookies in the buffer."
  8684. (interactive "P")
  8685. (if all
  8686. (progn
  8687. (org-update-checkbox-count 'all)
  8688. (org-map-entries 'org-update-parent-todo-statistics))
  8689. (if (not (org-at-heading-p))
  8690. (org-update-checkbox-count)
  8691. (let ((pos (point-marker))
  8692. end l1 l2)
  8693. (ignore-errors (org-back-to-heading t))
  8694. (if (not (org-at-heading-p))
  8695. (org-update-checkbox-count)
  8696. (setq l1 (org-outline-level))
  8697. (setq end (save-excursion
  8698. (outline-next-heading)
  8699. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8700. (point)))
  8701. (if (and (save-excursion
  8702. (re-search-forward
  8703. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8704. (not (save-excursion (re-search-forward
  8705. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8706. (org-update-checkbox-count)
  8707. (if (and l2 (> l2 l1))
  8708. (progn
  8709. (goto-char end)
  8710. (org-update-parent-todo-statistics))
  8711. (goto-char pos)
  8712. (beginning-of-line 1)
  8713. (while (re-search-forward
  8714. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8715. (point-at-eol) t)
  8716. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8717. (goto-char pos)
  8718. (move-marker pos nil)))))
  8719. (defvar org-entry-property-inherited-from) ;; defined below
  8720. (defun org-update-parent-todo-statistics ()
  8721. "Update any statistics cookie in the parent of the current headline.
  8722. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8723. the entire subtree and this will travel up the hierarchy and update
  8724. statistics everywhere."
  8725. (let* ((prop (save-excursion (org-up-heading-safe)
  8726. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8727. (recursive (or (not org-hierarchical-todo-statistics)
  8728. (and prop (string-match "\\<recursive\\>" prop))))
  8729. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8730. 0))
  8731. (first t)
  8732. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8733. level ltoggle l1 new ndel
  8734. (cnt-all 0) (cnt-done 0) is-percent kwd
  8735. checkbox-beg cookie-present)
  8736. (catch 'exit
  8737. (save-excursion
  8738. (beginning-of-line 1)
  8739. (setq ltoggle (funcall outline-level))
  8740. ;; Three situations are to consider:
  8741. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8742. ;; to the top-level ancestor on the headline;
  8743. ;; 2. If parent has "recursive" property, repeat up to the
  8744. ;; headline setting that property, taking inheritance into
  8745. ;; account;
  8746. ;; 3. Else, move up to direct parent and proceed only once.
  8747. (while (and (setq level (org-up-heading-safe))
  8748. (or recursive first)
  8749. (>= (point) lim))
  8750. (setq first nil cookie-present nil)
  8751. (unless (and level
  8752. (not (string-match
  8753. "\\<checkbox\\>"
  8754. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8755. "")))))
  8756. (throw 'exit nil))
  8757. (while (re-search-forward box-re (point-at-eol) t)
  8758. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8759. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8760. (save-match-data
  8761. (unless (outline-next-heading) (throw 'exit nil))
  8762. (while (and (looking-at org-complex-heading-regexp)
  8763. (> (setq l1 (length (match-string 1))) level))
  8764. (setq kwd (and (or recursive (= l1 ltoggle))
  8765. (match-string 2)))
  8766. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8767. (and (eq org-provide-todo-statistics t)
  8768. (or (member kwd org-done-keywords)))
  8769. (and (listp org-provide-todo-statistics)
  8770. (stringp (car org-provide-todo-statistics))
  8771. (or (member kwd org-provide-todo-statistics)
  8772. (member kwd org-done-keywords)))
  8773. (and (listp org-provide-todo-statistics)
  8774. (listp (car org-provide-todo-statistics))
  8775. (or (member kwd (car org-provide-todo-statistics))
  8776. (and (member kwd org-done-keywords)
  8777. (member kwd (cadr org-provide-todo-statistics))))))
  8778. (setq cnt-all (1+ cnt-all))
  8779. (and (eq org-provide-todo-statistics t)
  8780. kwd
  8781. (setq cnt-all (1+ cnt-all))))
  8782. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8783. (member kwd org-done-keywords))
  8784. (and (listp org-provide-todo-statistics)
  8785. (listp (car org-provide-todo-statistics))
  8786. (member kwd org-done-keywords)
  8787. (member kwd (cadr org-provide-todo-statistics)))
  8788. (and (listp org-provide-todo-statistics)
  8789. (stringp (car org-provide-todo-statistics))
  8790. (member kwd org-done-keywords)))
  8791. (setq cnt-done (1+ cnt-done)))
  8792. (outline-next-heading)))
  8793. (setq new
  8794. (if is-percent
  8795. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8796. (max 1 cnt-all)))
  8797. (format "[%d/%d]" cnt-done cnt-all))
  8798. ndel (- (match-end 0) checkbox-beg))
  8799. (goto-char checkbox-beg)
  8800. (insert new)
  8801. (delete-region (point) (+ (point) ndel))
  8802. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8803. (when cookie-present
  8804. (run-hook-with-args 'org-after-todo-statistics-hook
  8805. cnt-done (- cnt-all cnt-done))))))
  8806. (run-hooks 'org-todo-statistics-hook)))
  8807. (defvar org-after-todo-statistics-hook nil
  8808. "Hook that is called after a TODO statistics cookie has been updated.
  8809. Each function is called with two arguments: the number of not-done entries
  8810. and the number of done entries.
  8811. For example, the following function, when added to this hook, will switch
  8812. an entry to DONE when all children are done, and back to TODO when new
  8813. entries are set to a TODO status. Note that this hook is only called
  8814. when there is a statistics cookie in the headline!
  8815. (defun org-summary-todo (n-done n-not-done)
  8816. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8817. (let (org-log-done org-log-states) ; turn off logging
  8818. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  8819. ")
  8820. (defvar org-todo-statistics-hook nil
  8821. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8822. This hook runs even if there is no statistics cookie present, in which case
  8823. `org-after-todo-statistics-hook' would not run.")
  8824. (defun org-todo-trigger-tag-changes (state)
  8825. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8826. (let ((l org-todo-state-tags-triggers)
  8827. changes)
  8828. (when (or (not state) (equal state ""))
  8829. (setq changes (append changes (cdr (assoc "" l)))))
  8830. (when (and (stringp state) (> (length state) 0))
  8831. (setq changes (append changes (cdr (assoc state l)))))
  8832. (when (member state org-not-done-keywords)
  8833. (setq changes (append changes (cdr (assq 'todo l)))))
  8834. (when (member state org-done-keywords)
  8835. (setq changes (append changes (cdr (assq 'done l)))))
  8836. (dolist (c changes)
  8837. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8838. (defun org-local-logging (value)
  8839. "Get logging settings from a property VALUE."
  8840. ;; Directly set the variables, they are already local.
  8841. (setq org-log-done nil
  8842. org-log-repeat nil
  8843. org-todo-log-states nil)
  8844. (dolist (w (split-string value))
  8845. (let (a)
  8846. (cond
  8847. ((setq a (assoc w org-startup-options))
  8848. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8849. (set (nth 1 a) (nth 2 a))))
  8850. ((setq a (org-extract-log-state-settings w))
  8851. (and (member (car a) org-todo-keywords-1)
  8852. (push a org-todo-log-states)))))))
  8853. (defun org-get-todo-sequence-head (kwd)
  8854. "Return the head of the TODO sequence to which KWD belongs.
  8855. If KWD is not set, check if there is a text property remembering the
  8856. right sequence."
  8857. (let (p)
  8858. (cond
  8859. ((not kwd)
  8860. (or (get-text-property (point-at-bol) 'org-todo-head)
  8861. (progn
  8862. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8863. nil (point-at-eol)))
  8864. (get-text-property p 'org-todo-head))))
  8865. ((not (member kwd org-todo-keywords-1))
  8866. (car org-todo-keywords-1))
  8867. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8868. (defun org-fast-todo-selection (&optional current-state)
  8869. "Fast TODO keyword selection with single keys.
  8870. Returns the new TODO keyword, or nil if no state change should occur.
  8871. When CURRENT-STATE is given and selection letters are not unique globally,
  8872. prefer a state in the current sequence over on in another sequence."
  8873. (let* ((fulltable org-todo-key-alist)
  8874. (head (org-get-todo-sequence-head current-state))
  8875. (done-keywords org-done-keywords) ;; needed for the faces.
  8876. (maxlen (apply 'max (mapcar
  8877. (lambda (x)
  8878. (if (stringp (car x)) (string-width (car x)) 0))
  8879. fulltable)))
  8880. (expert (equal org-use-fast-todo-selection 'expert))
  8881. (prompt "")
  8882. (fwidth (+ maxlen 3 1 3))
  8883. (ncol (/ (- (window-width) 4) fwidth))
  8884. tg cnt e c tbl subtable
  8885. groups ingroup in-current-sequence)
  8886. (save-excursion
  8887. (save-window-excursion
  8888. (if expert
  8889. (set-buffer (get-buffer-create " *Org todo*"))
  8890. (delete-other-windows)
  8891. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8892. (org-switch-to-buffer-other-window " *Org todo*"))
  8893. (erase-buffer)
  8894. (setq-local org-done-keywords done-keywords)
  8895. (setq tbl fulltable cnt 0)
  8896. (while (setq e (pop tbl))
  8897. (cond
  8898. ((equal e '(:startgroup))
  8899. (push '() groups) (setq ingroup t)
  8900. (unless (= cnt 0)
  8901. (setq cnt 0)
  8902. (insert "\n"))
  8903. (setq prompt (concat prompt "{"))
  8904. (insert "{ "))
  8905. ((equal e '(:endgroup))
  8906. (setq ingroup nil cnt 0 in-current-sequence nil)
  8907. (setq prompt (concat prompt "}"))
  8908. (insert "}\n"))
  8909. ((equal e '(:newline))
  8910. (unless (= cnt 0)
  8911. (setq cnt 0)
  8912. (insert "\n")
  8913. (setq e (car tbl))
  8914. (while (equal (car tbl) '(:newline))
  8915. (insert "\n")
  8916. (setq tbl (cdr tbl)))))
  8917. (t
  8918. (setq tg (car e) c (cdr e))
  8919. (if (equal tg head) (setq in-current-sequence t))
  8920. (when ingroup (push tg (car groups)))
  8921. (when in-current-sequence (push e subtable))
  8922. (setq tg (org-add-props tg nil 'face
  8923. (org-get-todo-face tg)))
  8924. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8925. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8926. (insert "[" c "] " tg (make-string
  8927. (- fwidth 4 (length tg)) ?\ ))
  8928. (when (and (= (setq cnt (1+ cnt)) ncol)
  8929. ;; Avoid lines with just a closing delimiter.
  8930. (not (equal (car tbl) '(:endgroup))))
  8931. (insert "\n")
  8932. (when ingroup (insert " "))
  8933. (setq cnt 0)))))
  8934. (insert "\n")
  8935. (goto-char (point-min))
  8936. (unless expert (org-fit-window-to-buffer))
  8937. (message (concat "[a-z..]:Set [SPC]:clear"
  8938. (if expert (concat "\n" prompt) "")))
  8939. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8940. (setq subtable (nreverse subtable))
  8941. (cond
  8942. ((or (= c ?\C-g)
  8943. (and (= c ?q) (not (rassoc c fulltable))))
  8944. (setq quit-flag t))
  8945. ((= c ?\ ) nil)
  8946. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8947. tg (car e))
  8948. tg)
  8949. (t (setq quit-flag t)))))))
  8950. (defun org-entry-is-todo-p ()
  8951. (member (org-get-todo-state) org-not-done-keywords))
  8952. (defun org-entry-is-done-p ()
  8953. (member (org-get-todo-state) org-done-keywords))
  8954. (defun org-get-todo-state ()
  8955. "Return the TODO keyword of the current subtree."
  8956. (save-excursion
  8957. (org-back-to-heading t)
  8958. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  8959. (match-end 2)
  8960. (match-string 2))))
  8961. (defun org-at-date-range-p (&optional inactive-ok)
  8962. "Non-nil if point is inside a date range.
  8963. When optional argument INACTIVE-OK is non-nil, also consider
  8964. inactive time ranges.
  8965. When this function returns a non-nil value, match data is set
  8966. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8967. on INACTIVE-OK."
  8968. (interactive)
  8969. (save-excursion
  8970. (catch 'exit
  8971. (let ((pos (point)))
  8972. (skip-chars-backward "^[<\r\n")
  8973. (skip-chars-backward "<[")
  8974. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8975. (>= (match-end 0) pos)
  8976. (throw 'exit t))
  8977. (skip-chars-backward "^<[\r\n")
  8978. (skip-chars-backward "<[")
  8979. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8980. (>= (match-end 0) pos)
  8981. (throw 'exit t)))
  8982. nil)))
  8983. (defun org-get-repeat (&optional timestamp)
  8984. "Check if there is a time-stamp with repeater in this entry.
  8985. Return the repeater, as a string, or nil. Also return nil when
  8986. this function is called before first heading.
  8987. When optional argument TIMESTAMP is a string, extract the
  8988. repeater from there instead."
  8989. (save-match-data
  8990. (cond (timestamp
  8991. (and (string-match org-repeat-re timestamp)
  8992. (match-string-no-properties 1 timestamp)))
  8993. ((org-before-first-heading-p) nil)
  8994. (t
  8995. (save-excursion
  8996. (org-back-to-heading t)
  8997. (let ((end (org-entry-end-position)))
  8998. (catch :repeat
  8999. (while (re-search-forward org-repeat-re end t)
  9000. (when (save-match-data (org-at-timestamp-p 'agenda))
  9001. (throw :repeat (match-string-no-properties 1)))))))))))
  9002. (defvar org-last-changed-timestamp)
  9003. (defvar org-last-inserted-timestamp)
  9004. (defvar org-log-post-message)
  9005. (defvar org-log-note-purpose)
  9006. (defvar org-log-note-how nil)
  9007. (defvar org-log-note-extra)
  9008. (defun org-auto-repeat-maybe (done-word)
  9009. "Check if the current headline contains a repeated time-stamp.
  9010. If yes, set TODO state back to what it was and change the base date
  9011. of repeating deadline/scheduled time stamps to new date.
  9012. This function is run automatically after each state change to a DONE state."
  9013. (let* ((repeat (org-get-repeat))
  9014. (aa (assoc org-last-state org-todo-kwd-alist))
  9015. (interpret (nth 1 aa))
  9016. (head (nth 2 aa))
  9017. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9018. (msg "Entry repeats: ")
  9019. (org-log-done nil)
  9020. (org-todo-log-states nil)
  9021. (end (copy-marker (org-entry-end-position))))
  9022. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9023. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9024. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9025. (and (stringp org-todo-repeat-to-state)
  9026. org-todo-repeat-to-state)
  9027. (and org-todo-repeat-to-state org-last-state))))
  9028. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9029. to-state)
  9030. ((eq interpret 'type) org-last-state)
  9031. (head)
  9032. (t 'none))))
  9033. (org-back-to-heading t)
  9034. (org-add-planning-info nil nil 'closed)
  9035. ;; When `org-log-repeat' is non-nil or entry contains
  9036. ;; a clock, set LAST_REPEAT property.
  9037. (when (or org-log-repeat
  9038. (catch :clock
  9039. (save-excursion
  9040. (while (re-search-forward org-clock-line-re end t)
  9041. (when (org-at-clock-log-p) (throw :clock t))))))
  9042. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9043. (org-time-stamp-format t t))))
  9044. (when org-log-repeat
  9045. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9046. (memq 'org-add-log-note post-command-hook))
  9047. ;; We are already setup for some record.
  9048. (when (eq org-log-repeat 'note)
  9049. ;; Make sure we take a note, not only a time stamp.
  9050. (setq org-log-note-how 'note))
  9051. ;; Set up for taking a record.
  9052. (org-add-log-setup 'state
  9053. (or done-word (car org-done-keywords))
  9054. org-last-state
  9055. org-log-repeat)))
  9056. ;; Time-stamps without a repeater are usually skipped. However,
  9057. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9058. ;; longer relevant.
  9059. (save-excursion
  9060. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9061. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9062. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9063. ;; Update every time-stamp with a repeater in the entry.
  9064. (let ((planning-re (regexp-opt
  9065. (list org-scheduled-string org-deadline-string))))
  9066. (while (re-search-forward org-repeat-re end t)
  9067. (let* ((ts (match-string 0))
  9068. (type (if (not (org-at-planning-p)) "Plain:"
  9069. (save-excursion
  9070. (re-search-backward
  9071. planning-re (line-beginning-position) t)
  9072. (match-string 0)))))
  9073. (when (and (org-at-timestamp-p 'agenda)
  9074. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9075. (let ((n (string-to-number (match-string 2 ts)))
  9076. (what (match-string 3 ts)))
  9077. (when (equal what "w") (setq n (* n 7) what "d"))
  9078. (when (and (equal what "h")
  9079. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9080. ts)))
  9081. (user-error
  9082. "Cannot repeat in %d hour(s) because no hour has been set"
  9083. n))
  9084. ;; Preparation, see if we need to modify the start
  9085. ;; date for the change.
  9086. (when (match-end 1)
  9087. (let ((time (save-match-data (org-time-string-to-time ts)))
  9088. (repeater-type (match-string 1 ts)))
  9089. (cond
  9090. ((equal "." repeater-type)
  9091. ;; Shift starting date to today.
  9092. (org-timestamp-change (- (org-today) (time-to-days time))
  9093. 'day))
  9094. ((equal "+" repeater-type)
  9095. (let ((nshiftmax 10)
  9096. (nshift 0))
  9097. (while (or (= nshift 0)
  9098. (not (org-time-less-p nil time)))
  9099. (when (= nshiftmax (cl-incf nshift))
  9100. (or (y-or-n-p
  9101. (format "%d repeater intervals were not \
  9102. enough to shift date past today. Continue? "
  9103. nshift))
  9104. (user-error "Abort")))
  9105. (org-timestamp-change n (cdr (assoc what whata)))
  9106. (org-in-regexp org-ts-regexp3)
  9107. (setq ts (match-string 1))
  9108. (setq time
  9109. (save-match-data
  9110. (org-time-string-to-time ts)))))
  9111. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9112. ;; Rematch, so that we have everything in place
  9113. ;; for the real shift.
  9114. (org-in-regexp org-ts-regexp3)
  9115. (setq ts (match-string 1))
  9116. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9117. ts)))))
  9118. (save-excursion
  9119. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9120. (setq msg
  9121. (concat msg type " " org-last-changed-timestamp " ")))))))
  9122. (run-hooks 'org-todo-repeat-hook)
  9123. (setq org-log-post-message msg)
  9124. (message msg))))
  9125. (defun org-show-todo-tree (arg)
  9126. "Make a compact tree which shows all headlines marked with TODO.
  9127. The tree will show the lines where the regexp matches, and all higher
  9128. headlines above the match.
  9129. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9130. With a numeric prefix N, construct a sparse tree for the Nth element
  9131. of `org-todo-keywords-1'."
  9132. (interactive "P")
  9133. (let ((case-fold-search nil)
  9134. (kwd-re
  9135. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9136. ((equal arg '(4))
  9137. (let ((kwd
  9138. (completing-read "Keyword (or KWD1|KWD2|...): "
  9139. (mapcar #'list org-todo-keywords-1))))
  9140. (concat "\\("
  9141. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9142. "\\)\\>")))
  9143. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9144. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9145. org-todo-keywords-1)))
  9146. (t (user-error "Invalid prefix argument: %s" arg)))))
  9147. (message "%d TODO entries found"
  9148. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9149. (defun org--deadline-or-schedule (arg type time)
  9150. "Insert DEADLINE or SCHEDULE information in current entry.
  9151. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9152. `org-schedule' for information about ARG and TIME arguments."
  9153. (let* ((deadline? (eq type 'deadline))
  9154. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9155. (log (if deadline? org-log-redeadline org-log-reschedule))
  9156. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9157. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9158. ;; Save repeater cookie from either TIME or current scheduled
  9159. ;; time stamp. We are going to insert it back at the end of
  9160. ;; the process.
  9161. (repeater (or (and (org-string-nw-p time)
  9162. ;; We use `org-repeat-re' because we need
  9163. ;; to tell the difference between a real
  9164. ;; repeater and a time delta, e.g. "+2d".
  9165. (string-match org-repeat-re time)
  9166. (match-string 1 time))
  9167. (and (org-string-nw-p old-date)
  9168. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9169. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9170. old-date)
  9171. (match-string 1 old-date)))))
  9172. (pcase arg
  9173. (`(4)
  9174. (if (not old-date)
  9175. (message (if deadline? "Entry had no deadline to remove"
  9176. "Entry was not scheduled"))
  9177. (when (and old-date log)
  9178. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9179. nil old-date log))
  9180. (org-remove-timestamp-with-keyword keyword)
  9181. (message (if deadline? "Entry no longer has a deadline."
  9182. "Entry is no longer scheduled."))))
  9183. (`(16)
  9184. (save-excursion
  9185. (org-back-to-heading t)
  9186. (let ((regexp (if deadline? org-deadline-time-regexp
  9187. org-scheduled-time-regexp)))
  9188. (if (not (re-search-forward regexp (line-end-position 2) t))
  9189. (user-error (if deadline? "No deadline information to update"
  9190. "No scheduled information to update"))
  9191. (let* ((rpl0 (match-string 1))
  9192. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9193. (msg (if deadline? "Warn starting from" "Delay until")))
  9194. (replace-match
  9195. (concat keyword
  9196. " <" rpl
  9197. (format " -%dd"
  9198. (abs (- (time-to-days
  9199. (save-match-data
  9200. (org-read-date
  9201. nil t nil msg old-date-time)))
  9202. (time-to-days old-date-time))))
  9203. ">") t t))))))
  9204. (_
  9205. (org-add-planning-info type time 'closed)
  9206. (when (and old-date
  9207. log
  9208. (not (equal old-date org-last-inserted-timestamp)))
  9209. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9210. org-last-inserted-timestamp
  9211. old-date
  9212. log))
  9213. (when repeater
  9214. (save-excursion
  9215. (org-back-to-heading t)
  9216. (when (re-search-forward
  9217. (concat keyword " " org-last-inserted-timestamp)
  9218. (line-end-position 2)
  9219. t)
  9220. (goto-char (1- (match-end 0)))
  9221. (insert " " repeater)
  9222. (setq org-last-inserted-timestamp
  9223. (concat (substring org-last-inserted-timestamp 0 -1)
  9224. " " repeater
  9225. (substring org-last-inserted-timestamp -1))))))
  9226. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9227. org-last-inserted-timestamp)))))
  9228. (defun org-deadline (arg &optional time)
  9229. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9230. With one universal prefix argument, remove any deadline from the item.
  9231. With two universal prefix arguments, prompt for a warning delay.
  9232. With argument TIME, set the deadline at the corresponding date. TIME
  9233. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9234. (interactive "P")
  9235. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9236. (org-map-entries
  9237. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9238. nil
  9239. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9240. 'region-start-level
  9241. 'region)
  9242. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9243. (org--deadline-or-schedule arg 'deadline time)))
  9244. (defun org-schedule (arg &optional time)
  9245. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9246. With one universal prefix argument, remove any scheduling date from the item.
  9247. With two universal prefix arguments, prompt for a delay cookie.
  9248. With argument TIME, scheduled at the corresponding date. TIME can
  9249. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9250. (interactive "P")
  9251. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9252. (org-map-entries
  9253. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9254. nil
  9255. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9256. 'region-start-level
  9257. 'region)
  9258. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9259. (org--deadline-or-schedule arg 'scheduled time)))
  9260. (defun org-get-scheduled-time (pom &optional inherit)
  9261. "Get the scheduled time as a time tuple, of a format suitable
  9262. for calling org-schedule with, or if there is no scheduling,
  9263. returns nil."
  9264. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9265. (when time
  9266. (org-time-string-to-time time))))
  9267. (defun org-get-deadline-time (pom &optional inherit)
  9268. "Get the deadline as a time tuple, of a format suitable for
  9269. calling org-deadline with, or if there is no scheduling, returns
  9270. nil."
  9271. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9272. (when time
  9273. (org-time-string-to-time time))))
  9274. (defun org-remove-timestamp-with-keyword (keyword)
  9275. "Remove all time stamps with KEYWORD in the current entry."
  9276. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9277. beg)
  9278. (save-excursion
  9279. (org-back-to-heading t)
  9280. (setq beg (point))
  9281. (outline-next-heading)
  9282. (while (re-search-backward re beg t)
  9283. (replace-match "")
  9284. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9285. (equal (char-before) ?\ ))
  9286. (backward-delete-char 1)
  9287. (when (string-match "^[ \t]*$" (buffer-substring
  9288. (point-at-bol) (point-at-eol)))
  9289. (delete-region (point-at-bol)
  9290. (min (point-max) (1+ (point-at-eol))))))))))
  9291. (defvar org-time-was-given) ; dynamically scoped parameter
  9292. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9293. (defun org-at-planning-p ()
  9294. "Non-nil when point is on a planning info line."
  9295. ;; This is as accurate and faster than `org-element-at-point' since
  9296. ;; planning info location is fixed in the section.
  9297. (org-with-wide-buffer
  9298. (beginning-of-line)
  9299. (and (looking-at-p org-planning-line-re)
  9300. (eq (point)
  9301. (ignore-errors
  9302. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9303. (org-back-to-heading t)
  9304. (org-with-limited-levels (org-back-to-heading t)))
  9305. (line-beginning-position 2))))))
  9306. (defun org-add-planning-info (what &optional time &rest remove)
  9307. "Insert new timestamp with keyword in the planning line.
  9308. WHAT indicates what kind of time stamp to add. It is a symbol
  9309. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9310. the time to use. If none is given, the user is prompted for
  9311. a date. REMOVE indicates what kind of entries to remove. An old
  9312. WHAT entry will also be removed."
  9313. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9314. (catch 'exit
  9315. (when (and (memq what '(scheduled deadline))
  9316. (or (not time)
  9317. (and (stringp time)
  9318. (string-match "^[-+]+[0-9]" time))))
  9319. ;; Try to get a default date/time from existing timestamp
  9320. (save-excursion
  9321. (org-back-to-heading t)
  9322. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9323. (when (re-search-forward (if (eq what 'scheduled)
  9324. org-scheduled-time-regexp
  9325. org-deadline-time-regexp)
  9326. end t)
  9327. (setq ts (match-string 1)
  9328. default-time (org-time-string-to-time ts)
  9329. default-input (and ts (org-get-compact-tod ts)))))))
  9330. (when what
  9331. (setq time
  9332. (if (stringp time)
  9333. ;; This is a string (relative or absolute), set
  9334. ;; proper date.
  9335. (apply #'encode-time
  9336. (org-read-date-analyze
  9337. time default-time (decode-time default-time)))
  9338. ;; If necessary, get the time from the user
  9339. (or time (org-read-date nil 'to-time nil
  9340. (cl-case what
  9341. (deadline "DEADLINE")
  9342. (scheduled "SCHEDULED")
  9343. (otherwise nil))
  9344. default-time default-input)))))
  9345. (org-with-wide-buffer
  9346. (org-back-to-heading t)
  9347. (forward-line)
  9348. (unless (bolp) (insert "\n"))
  9349. (cond ((looking-at-p org-planning-line-re)
  9350. ;; Move to current indentation.
  9351. (skip-chars-forward " \t")
  9352. ;; Check if we have to remove something.
  9353. (dolist (type (if what (cons what remove) remove))
  9354. (save-excursion
  9355. (when (re-search-forward
  9356. (cl-case type
  9357. (closed org-closed-time-regexp)
  9358. (deadline org-deadline-time-regexp)
  9359. (scheduled org-scheduled-time-regexp)
  9360. (otherwise
  9361. (error "Invalid planning type: %s" type)))
  9362. (line-end-position) t)
  9363. ;; Delete until next keyword or end of line.
  9364. (delete-region
  9365. (match-beginning 0)
  9366. (if (re-search-forward org-keyword-time-not-clock-regexp
  9367. (line-end-position)
  9368. t)
  9369. (match-beginning 0)
  9370. (line-end-position))))))
  9371. ;; If there is nothing more to add and no more keyword
  9372. ;; is left, remove the line completely.
  9373. (if (and (looking-at-p "[ \t]*$") (not what))
  9374. (delete-region (line-beginning-position)
  9375. (line-beginning-position 2))
  9376. ;; If we removed last keyword, do not leave trailing
  9377. ;; white space at the end of line.
  9378. (let ((p (point)))
  9379. (save-excursion
  9380. (end-of-line)
  9381. (unless (= (skip-chars-backward " \t" p) 0)
  9382. (delete-region (point) (line-end-position)))))))
  9383. ((not what) (throw 'exit nil)) ; Nothing to do.
  9384. (t (insert-before-markers "\n")
  9385. (backward-char 1)
  9386. (when org-adapt-indentation
  9387. (indent-to-column (1+ (org-outline-level))))))
  9388. (when what
  9389. ;; Insert planning keyword.
  9390. (insert (cl-case what
  9391. (closed org-closed-string)
  9392. (deadline org-deadline-string)
  9393. (scheduled org-scheduled-string)
  9394. (otherwise (error "Invalid planning type: %s" what)))
  9395. " ")
  9396. ;; Insert associated timestamp.
  9397. (let ((ts (org-insert-time-stamp
  9398. time
  9399. (or org-time-was-given
  9400. (and (eq what 'closed) org-log-done-with-time))
  9401. (eq what 'closed)
  9402. nil nil (list org-end-time-was-given))))
  9403. (unless (eolp) (insert " "))
  9404. ts))))))
  9405. (defvar org-log-note-marker (make-marker)
  9406. "Marker pointing at the entry where the note is to be inserted.")
  9407. (defvar org-log-note-purpose nil)
  9408. (defvar org-log-note-state nil)
  9409. (defvar org-log-note-previous-state nil)
  9410. (defvar org-log-note-extra nil)
  9411. (defvar org-log-note-window-configuration nil)
  9412. (defvar org-log-note-return-to (make-marker))
  9413. (defvar org-log-note-effective-time nil
  9414. "Remembered current time so that dynamically scoped
  9415. `org-extend-today-until' affects timestamps in state change log")
  9416. (defvar org-log-post-message nil
  9417. "Message to be displayed after a log note has been stored.
  9418. The auto-repeater uses this.")
  9419. (defun org-add-note ()
  9420. "Add a note to the current entry.
  9421. This is done in the same way as adding a state change note."
  9422. (interactive)
  9423. (org-add-log-setup 'note))
  9424. (defun org-log-beginning (&optional create)
  9425. "Return expected start of log notes in current entry.
  9426. When optional argument CREATE is non-nil, the function creates
  9427. a drawer to store notes, if necessary. Returned position ignores
  9428. narrowing."
  9429. (org-with-wide-buffer
  9430. (let ((drawer (org-log-into-drawer)))
  9431. (cond
  9432. (drawer
  9433. (org-end-of-meta-data)
  9434. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9435. (end (if (org-at-heading-p) (point)
  9436. (save-excursion (outline-next-heading) (point))))
  9437. (case-fold-search t))
  9438. (catch 'exit
  9439. ;; Try to find existing drawer.
  9440. (while (re-search-forward regexp end t)
  9441. (let ((element (org-element-at-point)))
  9442. (when (eq (org-element-type element) 'drawer)
  9443. (let ((cend (org-element-property :contents-end element)))
  9444. (when (and (not org-log-states-order-reversed) cend)
  9445. (goto-char cend)))
  9446. (throw 'exit nil))))
  9447. ;; No drawer found. Create one, if permitted.
  9448. (when create
  9449. (unless (bolp) (insert "\n"))
  9450. (let ((beg (point)))
  9451. (insert ":" drawer ":\n:END:\n")
  9452. (org-indent-region beg (point))
  9453. (org-flag-region
  9454. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  9455. (end-of-line -1)))))
  9456. (t
  9457. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9458. (skip-chars-forward " \t\n")
  9459. (beginning-of-line)
  9460. (unless org-log-states-order-reversed
  9461. (org-skip-over-state-notes)
  9462. (skip-chars-backward " \t\n")
  9463. (forward-line)))))
  9464. (if (bolp) (point) (line-beginning-position 2))))
  9465. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9466. "Set up the post command hook to take a note.
  9467. If this is about to TODO state change, the new state is expected in STATE.
  9468. HOW is an indicator what kind of note should be created.
  9469. EXTRA is additional text that will be inserted into the notes buffer."
  9470. (move-marker org-log-note-marker (point))
  9471. (setq org-log-note-purpose purpose
  9472. org-log-note-state state
  9473. org-log-note-previous-state prev-state
  9474. org-log-note-how how
  9475. org-log-note-extra extra
  9476. org-log-note-effective-time (org-current-effective-time))
  9477. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9478. (defun org-skip-over-state-notes ()
  9479. "Skip past the list of State notes in an entry."
  9480. (when (ignore-errors (goto-char (org-in-item-p)))
  9481. (let* ((struct (org-list-struct))
  9482. (prevs (org-list-prevs-alist struct))
  9483. (regexp
  9484. (concat "[ \t]*- +"
  9485. (replace-regexp-in-string
  9486. " +" " +"
  9487. (org-replace-escapes
  9488. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9489. `(("%d" . ,org-ts-regexp-inactive)
  9490. ("%D" . ,org-ts-regexp)
  9491. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9492. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9493. ("%t" . ,org-ts-regexp-inactive)
  9494. ("%T" . ,org-ts-regexp)
  9495. ("%u" . ".*?")
  9496. ("%U" . ".*?")))))))
  9497. (while (looking-at-p regexp)
  9498. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9499. (org-list-get-item-end (point) struct)))))))
  9500. (defun org-add-log-note (&optional _purpose)
  9501. "Pop up a window for taking a note, and add this note later."
  9502. (remove-hook 'post-command-hook 'org-add-log-note)
  9503. (setq org-log-note-window-configuration (current-window-configuration))
  9504. (delete-other-windows)
  9505. (move-marker org-log-note-return-to (point))
  9506. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9507. (goto-char org-log-note-marker)
  9508. (org-switch-to-buffer-other-window "*Org Note*")
  9509. (erase-buffer)
  9510. (if (memq org-log-note-how '(time state))
  9511. (org-store-log-note)
  9512. (let ((org-inhibit-startup t)) (org-mode))
  9513. (insert (format "# Insert note for %s.
  9514. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9515. (cl-case org-log-note-purpose
  9516. (clock-out "stopped clock")
  9517. (done "closed todo item")
  9518. (reschedule "rescheduling")
  9519. (delschedule "no longer scheduled")
  9520. (redeadline "changing deadline")
  9521. (deldeadline "removing deadline")
  9522. (refile "refiling")
  9523. (note "this entry")
  9524. (state
  9525. (format "state change from \"%s\" to \"%s\""
  9526. (or org-log-note-previous-state "")
  9527. (or org-log-note-state "")))
  9528. (t (error "This should not happen")))))
  9529. (when org-log-note-extra (insert org-log-note-extra))
  9530. (setq-local org-finish-function 'org-store-log-note)
  9531. (run-hooks 'org-log-buffer-setup-hook)))
  9532. (defvar org-note-abort nil) ; dynamically scoped
  9533. (defun org-store-log-note ()
  9534. "Finish taking a log note, and insert it to where it belongs."
  9535. (let ((txt (prog1 (buffer-string)
  9536. (kill-buffer)))
  9537. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9538. lines)
  9539. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9540. (setq txt (replace-match "" t t txt)))
  9541. (when (string-match "\\s-+\\'" txt)
  9542. (setq txt (replace-match "" t t txt)))
  9543. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9544. (when (org-string-nw-p note)
  9545. (setq note
  9546. (org-replace-escapes
  9547. note
  9548. (list (cons "%u" (user-login-name))
  9549. (cons "%U" user-full-name)
  9550. (cons "%t" (format-time-string
  9551. (org-time-stamp-format 'long 'inactive)
  9552. org-log-note-effective-time))
  9553. (cons "%T" (format-time-string
  9554. (org-time-stamp-format 'long nil)
  9555. org-log-note-effective-time))
  9556. (cons "%d" (format-time-string
  9557. (org-time-stamp-format nil 'inactive)
  9558. org-log-note-effective-time))
  9559. (cons "%D" (format-time-string
  9560. (org-time-stamp-format nil nil)
  9561. org-log-note-effective-time))
  9562. (cons "%s" (cond
  9563. ((not org-log-note-state) "")
  9564. ((string-match-p org-ts-regexp
  9565. org-log-note-state)
  9566. (format "\"[%s]\""
  9567. (substring org-log-note-state 1 -1)))
  9568. (t (format "\"%s\"" org-log-note-state))))
  9569. (cons "%S"
  9570. (cond
  9571. ((not org-log-note-previous-state) "")
  9572. ((string-match-p org-ts-regexp
  9573. org-log-note-previous-state)
  9574. (format "\"[%s]\""
  9575. (substring
  9576. org-log-note-previous-state 1 -1)))
  9577. (t (format "\"%s\""
  9578. org-log-note-previous-state)))))))
  9579. (when lines (setq note (concat note " \\\\")))
  9580. (push note lines))
  9581. (when (and lines (not org-note-abort))
  9582. (with-current-buffer (marker-buffer org-log-note-marker)
  9583. (org-with-wide-buffer
  9584. ;; Find location for the new note.
  9585. (goto-char org-log-note-marker)
  9586. (set-marker org-log-note-marker nil)
  9587. ;; Note associated to a clock is to be located right after
  9588. ;; the clock. Do not move point.
  9589. (unless (eq org-log-note-purpose 'clock-out)
  9590. (goto-char (org-log-beginning t)))
  9591. ;; Make sure point is at the beginning of an empty line.
  9592. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9593. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9594. ;; In an existing list, add a new item at the top level.
  9595. ;; Otherwise, indent line like a regular one.
  9596. (let ((itemp (org-in-item-p)))
  9597. (if itemp
  9598. (indent-line-to
  9599. (let ((struct (save-excursion
  9600. (goto-char itemp) (org-list-struct))))
  9601. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9602. (org-indent-line)))
  9603. (insert (org-list-bullet-string "-") (pop lines))
  9604. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9605. (dolist (line lines)
  9606. (insert "\n")
  9607. (indent-line-to ind)
  9608. (insert line)))
  9609. (message "Note stored")
  9610. (org-back-to-heading t))
  9611. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9612. ;; from within `org-add-log-note' because `buffer-undo-list'
  9613. ;; is then modified outside of `org-with-remote-undo'.
  9614. (when (eq this-command 'org-agenda-todo)
  9615. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9616. ;; Don't add undo information when called from `org-agenda-todo'.
  9617. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9618. (set-window-configuration org-log-note-window-configuration)
  9619. (with-current-buffer (marker-buffer org-log-note-return-to)
  9620. (goto-char org-log-note-return-to))
  9621. (move-marker org-log-note-return-to nil)
  9622. (when org-log-post-message (message "%s" org-log-post-message))))
  9623. (defun org-remove-empty-drawer-at (pos)
  9624. "Remove an empty drawer at position POS.
  9625. POS may also be a marker."
  9626. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9627. (org-with-wide-buffer
  9628. (goto-char pos)
  9629. (let ((drawer (org-element-at-point)))
  9630. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9631. (not (org-element-property :contents-begin drawer)))
  9632. (delete-region (org-element-property :begin drawer)
  9633. (progn (goto-char (org-element-property :end drawer))
  9634. (skip-chars-backward " \r\t\n")
  9635. (forward-line)
  9636. (point))))))))
  9637. (defvar org-ts-type nil)
  9638. (defun org-sparse-tree (&optional arg type)
  9639. "Create a sparse tree, prompt for the details.
  9640. This command can create sparse trees. You first need to select the type
  9641. of match used to create the tree:
  9642. t Show all TODO entries.
  9643. T Show entries with a specific TODO keyword.
  9644. m Show entries selected by a tags/property match.
  9645. p Enter a property name and its value (both with completion on existing
  9646. names/values) and show entries with that property.
  9647. r Show entries matching a regular expression (`/' can be used as well).
  9648. b Show deadlines and scheduled items before a date.
  9649. a Show deadlines and scheduled items after a date.
  9650. d Show deadlines due within `org-deadline-warning-days'.
  9651. D Show deadlines and scheduled items between a date range."
  9652. (interactive "P")
  9653. (setq type (or type org-sparse-tree-default-date-type))
  9654. (setq org-ts-type type)
  9655. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9656. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  9657. \[c]ycle through date types: %s"
  9658. (cl-case type
  9659. (all "all timestamps")
  9660. (scheduled "only scheduled")
  9661. (deadline "only deadline")
  9662. (active "only active timestamps")
  9663. (inactive "only inactive timestamps")
  9664. (closed "with a closed time-stamp")
  9665. (otherwise "scheduled/deadline")))
  9666. (let ((answer (read-char-exclusive)))
  9667. (cl-case answer
  9668. (?c
  9669. (org-sparse-tree
  9670. arg
  9671. (cadr
  9672. (memq type '(nil all scheduled deadline active inactive closed)))))
  9673. (?d (call-interactively 'org-check-deadlines))
  9674. (?b (call-interactively 'org-check-before-date))
  9675. (?a (call-interactively 'org-check-after-date))
  9676. (?D (call-interactively 'org-check-dates-range))
  9677. (?t (call-interactively 'org-show-todo-tree))
  9678. (?T (org-show-todo-tree '(4)))
  9679. (?m (call-interactively 'org-match-sparse-tree))
  9680. ((?p ?P)
  9681. (let* ((kwd (completing-read
  9682. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9683. (value (completing-read
  9684. "Value: " (mapcar #'list (org-property-values kwd)))))
  9685. (unless (string-match "\\`{.*}\\'" value)
  9686. (setq value (concat "\"" value "\"")))
  9687. (org-match-sparse-tree arg (concat kwd "=" value))))
  9688. ((?r ?R ?/) (call-interactively 'org-occur))
  9689. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9690. (defvar-local org-occur-highlights nil
  9691. "List of overlays used for occur matches.")
  9692. (defvar-local org-occur-parameters nil
  9693. "Parameters of the active org-occur calls.
  9694. This is a list, each call to org-occur pushes as cons cell,
  9695. containing the regular expression and the callback, onto the list.
  9696. The list can contain several entries if `org-occur' has been called
  9697. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9698. will only contain one set of parameters. When the highlights are
  9699. removed (for example with `C-c C-c', or with the next edit (depending
  9700. on `org-remove-highlights-with-change'), this variable is emptied
  9701. as well.")
  9702. (defun org-occur (regexp &optional keep-previous callback)
  9703. "Make a compact tree which shows all matches of REGEXP.
  9704. The tree will show the lines where the regexp matches, and any other context
  9705. defined in `org-show-context-detail', which see.
  9706. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9707. done by a previous call to `org-occur' will be kept, to allow stacking of
  9708. calls to this command.
  9709. Optional argument CALLBACK can be a function of no argument. In this case,
  9710. it is called with point at the end of the match, match data being set
  9711. accordingly. Current match is shown only if the return value is non-nil.
  9712. The function must neither move point nor alter narrowing."
  9713. (interactive "sRegexp: \nP")
  9714. (when (equal regexp "")
  9715. (user-error "Regexp cannot be empty"))
  9716. (unless keep-previous
  9717. (org-remove-occur-highlights nil nil t))
  9718. (push (cons regexp callback) org-occur-parameters)
  9719. (let ((cnt 0))
  9720. (save-excursion
  9721. (goto-char (point-min))
  9722. (when (or (not keep-previous) ; do not want to keep
  9723. (not org-occur-highlights)) ; no previous matches
  9724. ;; hide everything
  9725. (org-overview))
  9726. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9727. (isearch-no-upper-case-p regexp t)
  9728. org-occur-case-fold-search)))
  9729. (while (re-search-forward regexp nil t)
  9730. (when (or (not callback)
  9731. (save-match-data (funcall callback)))
  9732. (setq cnt (1+ cnt))
  9733. (when org-highlight-sparse-tree-matches
  9734. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9735. (org-show-context 'occur-tree)))))
  9736. (when org-remove-highlights-with-change
  9737. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9738. nil 'local))
  9739. (unless org-sparse-tree-open-archived-trees
  9740. (org-hide-archived-subtrees (point-min) (point-max)))
  9741. (run-hooks 'org-occur-hook)
  9742. (when (called-interactively-p 'interactive)
  9743. (message "%d match(es) for regexp %s" cnt regexp))
  9744. cnt))
  9745. (defun org-occur-next-match (&optional n _reset)
  9746. "Function for `next-error-function' to find sparse tree matches.
  9747. N is the number of matches to move, when negative move backwards.
  9748. This function always goes back to the starting point when no
  9749. match is found."
  9750. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9751. (search-func (if (< n 0)
  9752. 'previous-single-char-property-change
  9753. 'next-single-char-property-change))
  9754. (n (abs n))
  9755. (pos (point))
  9756. p1)
  9757. (catch 'exit
  9758. (while (setq p1 (funcall search-func (point) 'org-type))
  9759. (when (equal p1 limit)
  9760. (goto-char pos)
  9761. (user-error "No more matches"))
  9762. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9763. (setq n (1- n))
  9764. (when (= n 0)
  9765. (goto-char p1)
  9766. (throw 'exit (point))))
  9767. (goto-char p1))
  9768. (goto-char p1)
  9769. (user-error "No more matches"))))
  9770. (defun org-highlight-new-match (beg end)
  9771. "Highlight from BEG to END and mark the highlight is an occur headline."
  9772. (let ((ov (make-overlay beg end)))
  9773. (overlay-put ov 'face 'secondary-selection)
  9774. (overlay-put ov 'org-type 'org-occur)
  9775. (push ov org-occur-highlights)))
  9776. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9777. "Remove the occur highlights from the buffer.
  9778. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9779. from the `before-change-functions' in the current buffer."
  9780. (interactive)
  9781. (unless org-inhibit-highlight-removal
  9782. (mapc #'delete-overlay org-occur-highlights)
  9783. (setq org-occur-highlights nil)
  9784. (setq org-occur-parameters nil)
  9785. (unless noremove
  9786. (remove-hook 'before-change-functions
  9787. 'org-remove-occur-highlights 'local))))
  9788. ;;;; Priorities
  9789. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9790. "Regular expression matching the priority indicator.
  9791. A priority indicator can be e.g. [#A] or [#1].
  9792. This regular expression matches these groups:
  9793. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9794. 1 : the priority cookie, e.g. \"[#A]\"
  9795. 2 : the value of the priority cookie, e.g. \"A\".")
  9796. (defun org-priority-up ()
  9797. "Increase the priority of the current item."
  9798. (interactive)
  9799. (org-priority 'up))
  9800. (defun org-priority-down ()
  9801. "Decrease the priority of the current item."
  9802. (interactive)
  9803. (org-priority 'down))
  9804. (defun org-priority (&optional action show)
  9805. "Change the priority of an item.
  9806. When called interactively with a `\\[universal-argument]' prefix,
  9807. show the priority in the minibuffer instead of changing it.
  9808. When called programmatically, ACTION can be `set', `up', `down',
  9809. or a character."
  9810. (interactive "P")
  9811. (when show
  9812. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9813. ;; passed the SHOW argument should be removed.
  9814. (warn "`org-priority' called with deprecated SHOW argument"))
  9815. (if (equal action '(4))
  9816. (org-priority-show)
  9817. (unless org-priority-enable-commands
  9818. (user-error "Priority commands are disabled"))
  9819. (setq action (or action 'set))
  9820. (let ((nump (< org-priority-lowest 65))
  9821. current new news have remove)
  9822. (save-excursion
  9823. (org-back-to-heading t)
  9824. (when (looking-at org-priority-regexp)
  9825. (let ((ms (match-string 2)))
  9826. (setq current (org-priority-to-value ms)
  9827. have t)))
  9828. (cond
  9829. ((eq action 'remove)
  9830. (setq remove t new ?\ ))
  9831. ((or (eq action 'set)
  9832. (integerp action))
  9833. (if (not (eq action 'set))
  9834. (setq new action)
  9835. (setq
  9836. new
  9837. (if nump
  9838. (string-to-number
  9839. (read-string (format "Priority %s-%s, SPC to remove: "
  9840. (number-to-string org-priority-highest)
  9841. (number-to-string org-priority-lowest))))
  9842. (progn (message "Priority %c-%c, SPC to remove: "
  9843. org-priority-highest org-priority-lowest)
  9844. (save-match-data
  9845. (setq new (read-char-exclusive)))))))
  9846. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9847. (= (upcase org-priority-lowest) org-priority-lowest))
  9848. (setq new (upcase new)))
  9849. (cond ((equal new ?\s) (setq remove t))
  9850. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9851. (user-error
  9852. (if nump
  9853. "Priority must be between `%s' and `%s'"
  9854. "Priority must be between `%c' and `%c'")
  9855. org-priority-highest org-priority-lowest))))
  9856. ((eq action 'up)
  9857. (setq new (if have
  9858. (1- current) ; normal cycling
  9859. ;; last priority was empty
  9860. (if (eq last-command this-command)
  9861. org-priority-lowest ; wrap around empty to lowest
  9862. ;; default
  9863. (if org-priority-start-cycle-with-default
  9864. org-priority-default
  9865. (1- org-priority-default))))))
  9866. ((eq action 'down)
  9867. (setq new (if have
  9868. (1+ current) ; normal cycling
  9869. ;; last priority was empty
  9870. (if (eq last-command this-command)
  9871. org-priority-highest ; wrap around empty to highest
  9872. ;; default
  9873. (if org-priority-start-cycle-with-default
  9874. org-priority-default
  9875. (1+ org-priority-default))))))
  9876. (t (user-error "Invalid action")))
  9877. (when (or (< (upcase new) org-priority-highest)
  9878. (> (upcase new) org-priority-lowest))
  9879. (if (and (memq action '(up down))
  9880. (not have) (not (eq last-command this-command)))
  9881. ;; `new' is from default priority
  9882. (error
  9883. "The default can not be set, see `org-priority-default' why")
  9884. ;; normal cycling: `new' is beyond highest/lowest priority
  9885. ;; and is wrapped around to the empty priority
  9886. (setq remove t)))
  9887. ;; Numerical priorities are limited to 64, beyond that number,
  9888. ;; assume the priority cookie is a character.
  9889. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9890. (if have
  9891. (if remove
  9892. (replace-match "" t t nil 1)
  9893. (replace-match news t t nil 2))
  9894. (if remove
  9895. (user-error "No priority cookie found in line")
  9896. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9897. (if (match-end 2)
  9898. (progn
  9899. (goto-char (match-end 2))
  9900. (insert " [#" news "]"))
  9901. (goto-char (match-beginning 3))
  9902. (insert "[#" news "] "))))
  9903. (org-align-tags))
  9904. (if remove
  9905. (message "Priority removed")
  9906. (message "Priority of current item set to %s" news)))))
  9907. (defalias 'org-show-priority 'org-priority-show)
  9908. (defun org-priority-show ()
  9909. "Show the priority of the current item.
  9910. This priority is composed of the main priority given with the [#A] cookies,
  9911. and by additional input from the age of a schedules or deadline entry."
  9912. (interactive)
  9913. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9914. (org-get-at-bol 'priority)
  9915. (save-excursion
  9916. (save-match-data
  9917. (beginning-of-line)
  9918. (and (looking-at org-heading-regexp)
  9919. (org-get-priority (match-string 0))))))))
  9920. (message "Priority is %d" (if pri pri -1000))))
  9921. (defun org-get-priority (s)
  9922. "Find priority cookie and return priority.
  9923. S is a string against which you can match `org-priority-regexp'.
  9924. If `org-priority-get-priority-function' is set to a custom
  9925. function, use it. Otherwise process S and output the priority
  9926. value, an integer."
  9927. (save-match-data
  9928. (if (functionp org-priority-get-priority-function)
  9929. (funcall org-priority-get-priority-function s)
  9930. (if (not (string-match org-priority-regexp s))
  9931. (* 1000 (- org-priority-lowest org-priority-default))
  9932. (* 1000 (- org-priority-lowest
  9933. (org-priority-to-value (match-string 2 s))))))))
  9934. ;;;; Tags
  9935. (defvar org-agenda-archives-mode)
  9936. (defvar org-map-continue-from nil
  9937. "Position from where mapping should continue.
  9938. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9939. (defvar org-scanner-tags nil
  9940. "The current tag list while the tags scanner is running.")
  9941. (defvar org-trust-scanner-tags nil
  9942. "Should `org-get-tags' use the tags for the scanner.
  9943. This is for internal dynamical scoping only.
  9944. When this is non-nil, the function `org-get-tags' will return the value
  9945. of `org-scanner-tags' instead of building the list by itself. This
  9946. can lead to large speed-ups when the tags scanner is used in a file with
  9947. many entries, and when the list of tags is retrieved, for example to
  9948. obtain a list of properties. Building the tags list for each entry in such
  9949. a file becomes an N^2 operation - but with this variable set, it scales
  9950. as N.")
  9951. (defvar org--matcher-tags-todo-only nil)
  9952. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9953. "Scan headline tags with inheritance and produce output ACTION.
  9954. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9955. or `agenda' to produce an entry list for an agenda view. It can also be
  9956. a Lisp form or a function that should be called at each matched headline, in
  9957. this case the return value is a list of all return values from these calls.
  9958. MATCHER is a function accepting three arguments, returning
  9959. a non-nil value whenever a given set of tags qualifies a headline
  9960. for inclusion. See `org-make-tags-matcher' for more information.
  9961. As a special case, it can also be set to t (respectively nil) in
  9962. order to match all (respectively none) headline.
  9963. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9964. included in the output.
  9965. START-LEVEL can be a string with asterisks, reducing the scope to
  9966. headlines matching this string."
  9967. (require 'org-agenda)
  9968. (let* ((re (concat "^"
  9969. (if start-level
  9970. ;; Get the correct level to match
  9971. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9972. org-outline-regexp)
  9973. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9974. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9975. (props (list 'face 'default
  9976. 'done-face 'org-agenda-done
  9977. 'undone-face 'default
  9978. 'mouse-face 'highlight
  9979. 'org-not-done-regexp org-not-done-regexp
  9980. 'org-todo-regexp org-todo-regexp
  9981. 'org-complex-heading-regexp org-complex-heading-regexp
  9982. 'help-echo
  9983. (format "mouse-2 or RET jump to Org file %S"
  9984. (abbreviate-file-name
  9985. (or (buffer-file-name (buffer-base-buffer))
  9986. (buffer-name (buffer-base-buffer)))))))
  9987. (org-map-continue-from nil)
  9988. lspos tags tags-list
  9989. (tags-alist (list (cons 0 org-file-tags)))
  9990. (llast 0) rtn rtn1 level category i txt
  9991. todo marker entry priority
  9992. ts-date ts-date-type ts-date-pair)
  9993. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9994. (setq action (list 'lambda nil action)))
  9995. (save-excursion
  9996. (goto-char (point-min))
  9997. (when (eq action 'sparse-tree)
  9998. (org-overview)
  9999. (org-remove-occur-highlights))
  10000. (while (let (case-fold-search)
  10001. (re-search-forward re nil t))
  10002. (setq org-map-continue-from nil)
  10003. (catch :skip
  10004. ;; Ignore closing parts of inline tasks.
  10005. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10006. (throw :skip t))
  10007. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10008. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10009. (goto-char (setq lspos (match-beginning 0)))
  10010. (setq level (org-reduced-level (org-outline-level))
  10011. category (org-get-category))
  10012. (when (eq action 'agenda)
  10013. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10014. ts-date (car ts-date-pair)
  10015. ts-date-type (cdr ts-date-pair)))
  10016. (setq i llast llast level)
  10017. ;; remove tag lists from same and sublevels
  10018. (while (>= i level)
  10019. (when (setq entry (assoc i tags-alist))
  10020. (setq tags-alist (delete entry tags-alist)))
  10021. (setq i (1- i)))
  10022. ;; add the next tags
  10023. (when tags
  10024. (setq tags (org-split-string tags ":")
  10025. tags-alist
  10026. (cons (cons level tags) tags-alist)))
  10027. ;; compile tags for current headline
  10028. (setq tags-list
  10029. (if org-use-tag-inheritance
  10030. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10031. tags)
  10032. org-scanner-tags tags-list)
  10033. (when org-use-tag-inheritance
  10034. (setcdr (car tags-alist)
  10035. (mapcar (lambda (x)
  10036. (setq x (copy-sequence x))
  10037. (org-add-prop-inherited x))
  10038. (cdar tags-alist))))
  10039. (when (and tags org-use-tag-inheritance
  10040. (or (not (eq t org-use-tag-inheritance))
  10041. org-tags-exclude-from-inheritance))
  10042. ;; Selective inheritance, remove uninherited ones.
  10043. (setcdr (car tags-alist)
  10044. (org-remove-uninherited-tags (cdar tags-alist))))
  10045. (when (and
  10046. ;; eval matcher only when the todo condition is OK
  10047. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10048. (if (functionp matcher)
  10049. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10050. (funcall matcher todo tags-list level))
  10051. matcher))
  10052. ;; Call the skipper, but return t if it does not
  10053. ;; skip, so that the `and' form continues evaluating.
  10054. (progn
  10055. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10056. t)
  10057. ;; Check if timestamps are deselecting this entry
  10058. (or (not todo-only)
  10059. (and (member todo org-todo-keywords-1)
  10060. (or (not org-agenda-tags-todo-honor-ignore-options)
  10061. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10062. ;; select this headline
  10063. (cond
  10064. ((eq action 'sparse-tree)
  10065. (and org-highlight-sparse-tree-matches
  10066. (org-get-heading) (match-end 0)
  10067. (org-highlight-new-match
  10068. (match-beginning 1) (match-end 1)))
  10069. (org-show-context 'tags-tree))
  10070. ((eq action 'agenda)
  10071. (setq txt (org-agenda-format-item
  10072. ""
  10073. (concat
  10074. (if (eq org-tags-match-list-sublevels 'indented)
  10075. (make-string (1- level) ?.) "")
  10076. (org-get-heading))
  10077. (make-string level ?\s)
  10078. category
  10079. tags-list)
  10080. priority (org-get-priority txt))
  10081. (goto-char lspos)
  10082. (setq marker (org-agenda-new-marker))
  10083. (org-add-props txt props
  10084. 'org-marker marker 'org-hd-marker marker 'org-category category
  10085. 'todo-state todo
  10086. 'ts-date ts-date
  10087. 'priority priority
  10088. 'type (concat "tagsmatch" ts-date-type))
  10089. (push txt rtn))
  10090. ((functionp action)
  10091. (setq org-map-continue-from nil)
  10092. (save-excursion
  10093. (setq rtn1 (funcall action))
  10094. (push rtn1 rtn)))
  10095. (t (user-error "Invalid action")))
  10096. ;; if we are to skip sublevels, jump to end of subtree
  10097. (unless org-tags-match-list-sublevels
  10098. (org-end-of-subtree t)
  10099. (backward-char 1))))
  10100. ;; Get the correct position from where to continue
  10101. (if org-map-continue-from
  10102. (goto-char org-map-continue-from)
  10103. (and (= (point) lspos) (end-of-line 1)))))
  10104. (when (and (eq action 'sparse-tree)
  10105. (not org-sparse-tree-open-archived-trees))
  10106. (org-hide-archived-subtrees (point-min) (point-max)))
  10107. (nreverse rtn)))
  10108. (defun org-remove-uninherited-tags (tags)
  10109. "Remove all tags that are not inherited from the list TAGS."
  10110. (cond
  10111. ((eq org-use-tag-inheritance t)
  10112. (if org-tags-exclude-from-inheritance
  10113. (org-delete-all org-tags-exclude-from-inheritance tags)
  10114. tags))
  10115. ((not org-use-tag-inheritance) nil)
  10116. ((stringp org-use-tag-inheritance)
  10117. (delq nil (mapcar
  10118. (lambda (x)
  10119. (if (and (string-match org-use-tag-inheritance x)
  10120. (not (member x org-tags-exclude-from-inheritance)))
  10121. x nil))
  10122. tags)))
  10123. ((listp org-use-tag-inheritance)
  10124. (delq nil (mapcar
  10125. (lambda (x)
  10126. (if (member x org-use-tag-inheritance) x nil))
  10127. tags)))))
  10128. (defun org-match-sparse-tree (&optional todo-only match)
  10129. "Create a sparse tree according to tags string MATCH.
  10130. MATCH is a string with match syntax. It can contain a selection
  10131. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10132. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10133. those. See the manual for details.
  10134. If optional argument TODO-ONLY is non-nil, only select lines that
  10135. are also TODO tasks."
  10136. (interactive "P")
  10137. (org-agenda-prepare-buffers (list (current-buffer)))
  10138. (let ((org--matcher-tags-todo-only todo-only))
  10139. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10140. org--matcher-tags-todo-only)))
  10141. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10142. (defvar org-cached-props nil)
  10143. (defun org-cached-entry-get (pom property)
  10144. (if (or (eq t org-use-property-inheritance)
  10145. (and (stringp org-use-property-inheritance)
  10146. (let ((case-fold-search t))
  10147. (string-match-p org-use-property-inheritance property)))
  10148. (and (listp org-use-property-inheritance)
  10149. (member-ignore-case property org-use-property-inheritance)))
  10150. ;; Caching is not possible, check it directly.
  10151. (org-entry-get pom property 'inherit)
  10152. ;; Get all properties, so we can do complicated checks easily.
  10153. (cdr (assoc-string property
  10154. (or org-cached-props
  10155. (setq org-cached-props (org-entry-properties pom)))
  10156. t))))
  10157. (defun org-global-tags-completion-table (&optional files)
  10158. "Return the list of all tags in all agenda buffer/files.
  10159. Optional FILES argument is a list of files which can be used
  10160. instead of the agenda files."
  10161. (save-excursion
  10162. (org-uniquify
  10163. (delq nil
  10164. (apply #'append
  10165. (mapcar
  10166. (lambda (file)
  10167. (set-buffer (find-file-noselect file))
  10168. (org--tag-add-to-alist
  10169. (org-get-buffer-tags)
  10170. (mapcar (lambda (x)
  10171. (and (stringp (car-safe x))
  10172. (list (car-safe x))))
  10173. org-current-tag-alist)))
  10174. (if (car-safe files) files
  10175. (org-agenda-files))))))))
  10176. (defun org-make-tags-matcher (match)
  10177. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10178. Returns a cons of the selection string MATCH and a function
  10179. implementing the matcher.
  10180. The matcher is to be called at an Org entry, with point on the
  10181. headline, and returns non-nil if the entry matches the selection
  10182. string MATCH. It must be called with three arguments: the TODO
  10183. keyword at the entry (or nil if none), the list of all tags at
  10184. the entry including inherited ones and the reduced level of the
  10185. headline. Additionally, the category of the entry, if any, must
  10186. be specified as the text property `org-category' on the headline.
  10187. This function sets the variable `org--matcher-tags-todo-only' to
  10188. a non-nil value if the matcher restricts matching to TODO
  10189. entries, otherwise it is not touched.
  10190. See also `org-scan-tags'."
  10191. (unless match
  10192. ;; Get a new match request, with completion against the global
  10193. ;; tags table and the local tags in current buffer.
  10194. (let ((org-last-tags-completion-table
  10195. (org--tag-add-to-alist
  10196. (org-get-buffer-tags)
  10197. (org-global-tags-completion-table))))
  10198. (setq match
  10199. (completing-read
  10200. "Match: "
  10201. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10202. (let ((match0 match)
  10203. (re (concat
  10204. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10205. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10206. "\\([<>=]\\{1,2\\}\\)"
  10207. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10208. "\\|" org-tag-re "\\)"))
  10209. (start 0)
  10210. tagsmatch todomatch tagsmatcher todomatcher)
  10211. ;; Expand group tags.
  10212. (setq match (org-tags-expand match))
  10213. ;; Check if there is a TODO part of this match, which would be the
  10214. ;; part after a "/". To make sure that this slash is not part of
  10215. ;; a property value to be matched against, we also check that
  10216. ;; there is no / after that slash. First, find the last slash.
  10217. (let ((s 0))
  10218. (while (string-match "/+" match s)
  10219. (setq start (match-beginning 0))
  10220. (setq s (match-end 0))))
  10221. (if (and (string-match "/+" match start)
  10222. (not (string-match-p "\"" match start)))
  10223. ;; Match contains also a TODO-matching request.
  10224. (progn
  10225. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10226. (setq todomatch (substring match (match-end 0)))
  10227. (when (string-prefix-p "!" todomatch)
  10228. (setq org--matcher-tags-todo-only t)
  10229. (setq todomatch (substring todomatch 1)))
  10230. (when (string-match "\\`\\s-*\\'" todomatch)
  10231. (setq todomatch nil)))
  10232. ;; Only matching tags.
  10233. (setq tagsmatch match)
  10234. (setq todomatch nil))
  10235. ;; Make the tags matcher.
  10236. (when (org-string-nw-p tagsmatch)
  10237. (let ((orlist nil)
  10238. (orterms (org-split-string tagsmatch "|"))
  10239. term)
  10240. (while (setq term (pop orterms))
  10241. (while (and (equal (substring term -1) "\\") orterms)
  10242. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10243. (while (string-match re term)
  10244. (let* ((rest (substring term (match-end 0)))
  10245. (minus (and (match-end 1)
  10246. (equal (match-string 1 term) "-")))
  10247. (tag (save-match-data
  10248. (replace-regexp-in-string
  10249. "\\\\-" "-" (match-string 2 term))))
  10250. (regexp (eq (string-to-char tag) ?{))
  10251. (levelp (match-end 4))
  10252. (propp (match-end 5))
  10253. (mm
  10254. (cond
  10255. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10256. (levelp
  10257. `(,(org-op-to-function (match-string 3 term))
  10258. level
  10259. ,(string-to-number (match-string 4 term))))
  10260. (propp
  10261. (let* ((gv (pcase (upcase (match-string 5 term))
  10262. ("CATEGORY"
  10263. '(get-text-property (point) 'org-category))
  10264. ("TODO" 'todo)
  10265. (p `(org-cached-entry-get nil ,p))))
  10266. (pv (match-string 7 term))
  10267. (regexp (eq (string-to-char pv) ?{))
  10268. (strp (eq (string-to-char pv) ?\"))
  10269. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10270. (po (org-op-to-function (match-string 6 term)
  10271. (if timep 'time strp))))
  10272. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10273. (when timep (setq pv (org-matcher-time pv)))
  10274. (cond ((and regexp (eq po '/=))
  10275. `(not (string-match ,pv (or ,gv ""))))
  10276. (regexp `(string-match ,pv (or ,gv "")))
  10277. (strp `(,po (or ,gv "") ,pv))
  10278. (t
  10279. `(,po
  10280. (string-to-number (or ,gv ""))
  10281. ,(string-to-number pv))))))
  10282. (t `(member ,tag tags-list)))))
  10283. (push (if minus `(not ,mm) mm) tagsmatcher)
  10284. (setq term rest)))
  10285. (push `(and ,@tagsmatcher) orlist)
  10286. (setq tagsmatcher nil))
  10287. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10288. ;; Make the TODO matcher.
  10289. (when (org-string-nw-p todomatch)
  10290. (let ((orlist nil))
  10291. (dolist (term (org-split-string todomatch "|"))
  10292. (while (string-match re term)
  10293. (let* ((minus (and (match-end 1)
  10294. (equal (match-string 1 term) "-")))
  10295. (kwd (match-string 2 term))
  10296. (regexp (eq (string-to-char kwd) ?{))
  10297. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10298. `(equal todo ,kwd))))
  10299. (push (if minus `(not ,mm) mm) todomatcher))
  10300. (setq term (substring term (match-end 0))))
  10301. (push (if (> (length todomatcher) 1)
  10302. (cons 'and todomatcher)
  10303. (car todomatcher))
  10304. orlist)
  10305. (setq todomatcher nil))
  10306. (setq todomatcher (cons 'or orlist))))
  10307. ;; Return the string and function of the matcher. If no
  10308. ;; tags-specific or todo-specific matcher exists, match
  10309. ;; everything.
  10310. (let ((matcher (if (and tagsmatcher todomatcher)
  10311. `(and ,tagsmatcher ,todomatcher)
  10312. (or tagsmatcher todomatcher t))))
  10313. (when org--matcher-tags-todo-only
  10314. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10315. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10316. (defun org--tags-expand-group (group tag-groups expanded)
  10317. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10318. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10319. an accumulator used in recursive calls."
  10320. (dolist (tag group)
  10321. (unless (member tag expanded)
  10322. (let ((group (assoc tag tag-groups)))
  10323. (push tag expanded)
  10324. (when group
  10325. (setq expanded
  10326. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10327. expanded)
  10328. (defun org-tags-expand (match &optional single-as-list downcased)
  10329. "Expand group tags in MATCH.
  10330. This replaces every group tag in MATCH with a regexp tag search.
  10331. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10332. will be replaced like this:
  10333. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10334. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10335. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10336. Replacing by a regexp preserves the structure of the match.
  10337. E.g., this expansion
  10338. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10339. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10340. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10341. A group tag in MATCH can contain regular expressions of its own.
  10342. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10343. will be replaced like this:
  10344. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10345. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10346. assumed to be a single group tag, and the function will return
  10347. the list of tags in this group.
  10348. When DOWNCASED is non-nil, expand downcased TAGS."
  10349. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10350. (let ((tag-groups
  10351. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10352. (if (not downcased) g
  10353. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10354. (cond
  10355. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10356. (org-group-tags
  10357. (let* ((case-fold-search t)
  10358. (tag-syntax org-mode-syntax-table)
  10359. (group-keys (mapcar #'car tag-groups))
  10360. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10361. (return-match (if downcased (downcase match) match)))
  10362. ;; Mark regexp-expressions in the match-expression so that we
  10363. ;; do not replace them later on.
  10364. (let ((s 0))
  10365. (while (string-match "{.+?}" return-match s)
  10366. (setq s (match-end 0))
  10367. (add-text-properties
  10368. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10369. ;; @ and _ are allowed as word-components in tags.
  10370. (modify-syntax-entry ?@ "w" tag-syntax)
  10371. (modify-syntax-entry ?_ "w" tag-syntax)
  10372. ;; For each tag token found in MATCH, compute a regexp and it
  10373. (with-syntax-table tag-syntax
  10374. (replace-regexp-in-string
  10375. key-regexp
  10376. (lambda (m)
  10377. (if (get-text-property (match-beginning 2) 'regexp m)
  10378. m ;regexp tag: ignore
  10379. (let* ((operator (match-string 1 m))
  10380. (tag-token (let ((tag (match-string 2 m)))
  10381. (list (if downcased (downcase tag) tag))))
  10382. regexp-tags regular-tags)
  10383. ;; Partition tags between regexp and regular tags.
  10384. ;; Remove curly bracket syntax from regexp tags.
  10385. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10386. (save-match-data
  10387. (if (string-match "{\\(.+?\\)}" tag)
  10388. (push (match-string 1 tag) regexp-tags)
  10389. (push tag regular-tags))))
  10390. ;; Replace tag token by the appropriate regexp.
  10391. ;; Regular tags need to be regexp-quoted, whereas
  10392. ;; regexp-tags are inserted as-is.
  10393. (let ((regular (regexp-opt regular-tags))
  10394. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10395. (concat operator
  10396. (cond
  10397. ((null regular-tags) (format "{%s}" regexp))
  10398. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10399. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10400. return-match
  10401. t t))))
  10402. (t match))))
  10403. (defun org-op-to-function (op &optional stringp)
  10404. "Turn an operator into the appropriate function."
  10405. (setq op
  10406. (cond
  10407. ((equal op "<" ) '(< org-string< org-time<))
  10408. ((equal op ">" ) '(> org-string> org-time>))
  10409. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10410. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10411. ((member op '("=" "==")) '(= string= org-time=))
  10412. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10413. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10414. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10415. (defvar org-tags-overlay (make-overlay 1 1))
  10416. (delete-overlay org-tags-overlay)
  10417. (defun org-add-prop-inherited (s)
  10418. (add-text-properties 0 (length s) '(inherited t) s)
  10419. s)
  10420. (defun org-toggle-tag (tag &optional onoff)
  10421. "Toggle the tag TAG for the current line.
  10422. If ONOFF is `on' or `off', don't toggle but set to this state."
  10423. (save-excursion
  10424. (org-back-to-heading t)
  10425. (let ((current
  10426. ;; Reverse the tags list so any new tag is appended to the
  10427. ;; current list of tags.
  10428. (nreverse (org-get-tags nil t)))
  10429. res)
  10430. (pcase onoff
  10431. (`off (setq current (delete tag current)))
  10432. ((or `on (guard (not (member tag current))))
  10433. (setq res t)
  10434. (cl-pushnew tag current :test #'equal))
  10435. (_ (setq current (delete tag current))))
  10436. (org-set-tags (nreverse current))
  10437. res)))
  10438. (defun org--align-tags-here (to-col)
  10439. "Align tags on the current headline to TO-COL.
  10440. Assume point is on a headline. Preserve point when aligning
  10441. tags."
  10442. (when (org-match-line org-tag-line-re)
  10443. (let* ((tags-start (match-beginning 1))
  10444. (blank-start (save-excursion
  10445. (goto-char tags-start)
  10446. (skip-chars-backward " \t")
  10447. (point)))
  10448. (new (max (if (>= to-col 0) to-col
  10449. (- (abs to-col) (string-width (match-string 1))))
  10450. ;; Introduce at least one space after the heading
  10451. ;; or the stars.
  10452. (save-excursion
  10453. (goto-char blank-start)
  10454. (1+ (current-column)))))
  10455. (current
  10456. (save-excursion (goto-char tags-start) (current-column)))
  10457. (origin (point-marker))
  10458. (column (current-column))
  10459. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10460. (when (/= new current)
  10461. (delete-region blank-start tags-start)
  10462. (goto-char blank-start)
  10463. (let ((indent-tabs-mode nil)) (indent-to new))
  10464. ;; Try to move back to original position. If point was in the
  10465. ;; blanks before the tags, ORIGIN marker is of no use because
  10466. ;; it now points to BLANK-START. Use COLUMN instead.
  10467. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10468. (defun org-set-tags-command (&optional arg)
  10469. "Set the tags for the current visible entry.
  10470. When called with `\\[universal-argument]' prefix argument ARG, \
  10471. realign all tags
  10472. in the current buffer.
  10473. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10474. unconditionally do not
  10475. offer the fast tag selection interface.
  10476. If a region is active, set tags in the region according to the
  10477. setting of `org-loop-over-headlines-in-active-region'.
  10478. This function is for interactive use only;
  10479. in Lisp code use `org-set-tags' instead."
  10480. (interactive "P")
  10481. (let ((org-use-fast-tag-selection
  10482. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10483. (cond
  10484. ((equal '(4) arg) (org-align-tags t))
  10485. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10486. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10487. (org-map-entries
  10488. #'org-set-tags-command
  10489. nil
  10490. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10491. 'region-start-level
  10492. 'region)
  10493. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10494. (t
  10495. (save-excursion
  10496. (org-back-to-heading)
  10497. (let* ((all-tags (org-get-tags))
  10498. (table (setq org-last-tags-completion-table
  10499. (org--tag-add-to-alist
  10500. (and org-complete-tags-always-offer-all-agenda-tags
  10501. (org-global-tags-completion-table
  10502. (org-agenda-files)))
  10503. (or org-current-tag-alist (org-get-buffer-tags)))))
  10504. (current-tags
  10505. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10506. all-tags))
  10507. (inherited-tags
  10508. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10509. all-tags))
  10510. (tags
  10511. (replace-regexp-in-string
  10512. ;; Ignore all forbidden characters in tags.
  10513. "[^[:alnum:]_@#%]+" ":"
  10514. (if (or (eq t org-use-fast-tag-selection)
  10515. (and org-use-fast-tag-selection
  10516. (delq nil (mapcar #'cdr table))))
  10517. (org-fast-tag-selection
  10518. current-tags
  10519. inherited-tags
  10520. table
  10521. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10522. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10523. (org-trim (completing-read
  10524. "Tags: "
  10525. #'org-tags-completion-function
  10526. nil nil (org-make-tag-string current-tags)
  10527. 'org-tags-history)))))))
  10528. (org-set-tags tags)))))))
  10529. (defun org-align-tags (&optional all)
  10530. "Align tags in current entry.
  10531. When optional argument ALL is non-nil, align all tags in the
  10532. visible part of the buffer."
  10533. (let ((get-indent-column
  10534. (lambda ()
  10535. (let ((offset (if (bound-and-true-p org-indent-mode)
  10536. (* (1- org-indent-indentation-per-level)
  10537. (1- (org-current-level)))
  10538. 0)))
  10539. (+ org-tags-column
  10540. (if (> org-tags-column 0) (- offset) offset))))))
  10541. (if (and (not all) (org-at-heading-p))
  10542. (org--align-tags-here (funcall get-indent-column))
  10543. (save-excursion
  10544. (if all
  10545. (progn
  10546. (goto-char (point-min))
  10547. (while (re-search-forward org-tag-line-re nil t)
  10548. (org--align-tags-here (funcall get-indent-column))))
  10549. (org-back-to-heading t)
  10550. (org--align-tags-here (funcall get-indent-column)))))))
  10551. (defun org-set-tags (tags)
  10552. "Set the tags of the current entry to TAGS, replacing current tags.
  10553. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10554. If TAGS is nil or the empty string, all tags are removed.
  10555. This function assumes point is on a headline."
  10556. (org-with-wide-buffer
  10557. (let ((tags (pcase tags
  10558. ((pred listp) tags)
  10559. ((pred stringp) (split-string (org-trim tags) ":" t))
  10560. (_ (error "Invalid tag specification: %S" tags))))
  10561. (old-tags (org-get-tags nil t))
  10562. (tags-change? nil))
  10563. (when (functionp org-tags-sort-function)
  10564. (setq tags (sort tags org-tags-sort-function)))
  10565. (setq tags-change? (not (equal tags old-tags)))
  10566. (when tags-change?
  10567. ;; Delete previous tags and any trailing white space.
  10568. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10569. (line-end-position)))
  10570. (skip-chars-backward " \t")
  10571. (delete-region (point) (line-end-position))
  10572. ;; Deleting white spaces may break an otherwise empty headline.
  10573. ;; Re-introduce one space in this case.
  10574. (unless (org-at-heading-p) (insert " "))
  10575. (when tags
  10576. (save-excursion (insert " " (org-make-tag-string tags)))
  10577. ;; When text is being inserted on an invisible region
  10578. ;; boundary, it can be inadvertently sucked into
  10579. ;; invisibility.
  10580. (unless (org-invisible-p (line-beginning-position))
  10581. (org-flag-region (point) (line-end-position) nil 'outline))))
  10582. ;; Align tags, if any.
  10583. (when tags (org-align-tags))
  10584. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10585. (defun org-change-tag-in-region (beg end tag off)
  10586. "Add or remove TAG for each entry in the region.
  10587. This works in the agenda, and also in an Org buffer."
  10588. (interactive
  10589. (list (region-beginning) (region-end)
  10590. (let ((org-last-tags-completion-table
  10591. (if (derived-mode-p 'org-mode)
  10592. (org--tag-add-to-alist
  10593. (org-get-buffer-tags)
  10594. (org-global-tags-completion-table))
  10595. (org-global-tags-completion-table))))
  10596. (completing-read
  10597. "Tag: " 'org-tags-completion-function nil nil nil
  10598. 'org-tags-history))
  10599. (progn
  10600. (message "[s]et or [r]emove? ")
  10601. (equal (read-char-exclusive) ?r))))
  10602. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10603. (let ((agendap (equal major-mode 'org-agenda-mode))
  10604. l1 l2 m buf pos newhead (cnt 0))
  10605. (goto-char end)
  10606. (setq l2 (1- (org-current-line)))
  10607. (goto-char beg)
  10608. (setq l1 (org-current-line))
  10609. (cl-loop for l from l1 to l2 do
  10610. (org-goto-line l)
  10611. (setq m (get-text-property (point) 'org-hd-marker))
  10612. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10613. (and agendap m))
  10614. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10615. pos (if agendap m (point)))
  10616. (with-current-buffer buf
  10617. (save-excursion
  10618. (save-restriction
  10619. (goto-char pos)
  10620. (setq cnt (1+ cnt))
  10621. (org-toggle-tag tag (if off 'off 'on))
  10622. (setq newhead (org-get-heading)))))
  10623. (and agendap (org-agenda-change-all-lines newhead m))))
  10624. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10625. (defun org-tags-completion-function (string _predicate &optional flag)
  10626. "Complete tag STRING.
  10627. FLAG specifies the type of completion operation to perform. This
  10628. function is passed as a collection function to `completing-read',
  10629. which see."
  10630. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10631. (confirm (lambda (x) (stringp (car x))))
  10632. (prefix ""))
  10633. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10634. (setq prefix (match-string 1 string))
  10635. (setq string (match-string 2 string)))
  10636. (pcase flag
  10637. (`t (all-completions string org-last-tags-completion-table confirm))
  10638. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10639. (`nil
  10640. (pcase (try-completion string org-last-tags-completion-table confirm)
  10641. ((and completion (pred stringp))
  10642. (concat prefix
  10643. completion
  10644. (if (and org-add-colon-after-tag-completion
  10645. (assoc completion org-last-tags-completion-table))
  10646. ":"
  10647. "")))
  10648. (completion completion)))
  10649. (_ nil))))
  10650. (defun org-fast-tag-insert (kwd tags face &optional end)
  10651. "Insert KWD, and the TAGS, the latter with face FACE.
  10652. Also insert END."
  10653. (insert (format "%-12s" (concat kwd ":"))
  10654. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10655. (or end "")))
  10656. (defun org-fast-tag-show-exit (flag)
  10657. (save-excursion
  10658. (org-goto-line 3)
  10659. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10660. (replace-match ""))
  10661. (when flag
  10662. (end-of-line 1)
  10663. (org-move-to-column (- (window-width) 19) t)
  10664. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10665. (defun org-set-current-tags-overlay (current prefix)
  10666. "Add an overlay to CURRENT tag with PREFIX."
  10667. (let ((s (org-make-tag-string current)))
  10668. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10669. (org-overlay-display org-tags-overlay (concat prefix s))))
  10670. (defvar org-last-tag-selection-key nil)
  10671. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10672. "Fast tag selection with single keys.
  10673. CURRENT is the current list of tags in the headline, INHERITED is the
  10674. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10675. possibly with grouping information. TODO-TABLE is a similar table with
  10676. TODO keywords, should these have keys assigned to them.
  10677. If the keys are nil, a-z are automatically assigned.
  10678. Returns the new tags string, or nil to not change the current settings."
  10679. (let* ((fulltable (append table todo-table))
  10680. (maxlen (if (null fulltable) 0
  10681. (apply #'max
  10682. (mapcar (lambda (x)
  10683. (if (stringp (car x)) (string-width (car x))
  10684. 0))
  10685. fulltable))))
  10686. (buf (current-buffer))
  10687. (expert (eq org-fast-tag-selection-single-key 'expert))
  10688. (buffer-tags nil)
  10689. (fwidth (+ maxlen 3 1 3))
  10690. (ncol (/ (- (window-width) 4) fwidth))
  10691. (i-face 'org-done)
  10692. (c-face 'org-todo)
  10693. tg cnt e c char c1 c2 ntable tbl rtn
  10694. ov-start ov-end ov-prefix
  10695. (exit-after-next org-fast-tag-selection-single-key)
  10696. (done-keywords org-done-keywords)
  10697. groups ingroup intaggroup)
  10698. (save-excursion
  10699. (beginning-of-line)
  10700. (if (looking-at org-tag-line-re)
  10701. (setq ov-start (match-beginning 1)
  10702. ov-end (match-end 1)
  10703. ov-prefix "")
  10704. (setq ov-start (1- (point-at-eol))
  10705. ov-end (1+ ov-start))
  10706. (skip-chars-forward "^\n\r")
  10707. (setq ov-prefix
  10708. (concat
  10709. (buffer-substring (1- (point)) (point))
  10710. (if (> (current-column) org-tags-column)
  10711. " "
  10712. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10713. (move-overlay org-tags-overlay ov-start ov-end)
  10714. (save-excursion
  10715. (save-window-excursion
  10716. (if expert
  10717. (set-buffer (get-buffer-create " *Org tags*"))
  10718. (delete-other-windows)
  10719. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10720. (org-switch-to-buffer-other-window " *Org tags*"))
  10721. (erase-buffer)
  10722. (setq-local org-done-keywords done-keywords)
  10723. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10724. (org-fast-tag-insert "Current" current c-face "\n\n")
  10725. (org-fast-tag-show-exit exit-after-next)
  10726. (org-set-current-tags-overlay current ov-prefix)
  10727. (setq tbl fulltable char ?a cnt 0)
  10728. (while (setq e (pop tbl))
  10729. (cond
  10730. ((eq (car e) :startgroup)
  10731. (push '() groups) (setq ingroup t)
  10732. (unless (zerop cnt)
  10733. (setq cnt 0)
  10734. (insert "\n"))
  10735. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10736. ((eq (car e) :endgroup)
  10737. (setq ingroup nil cnt 0)
  10738. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10739. ((eq (car e) :startgrouptag)
  10740. (setq intaggroup t)
  10741. (unless (zerop cnt)
  10742. (setq cnt 0)
  10743. (insert "\n"))
  10744. (insert "[ "))
  10745. ((eq (car e) :endgrouptag)
  10746. (setq intaggroup nil cnt 0)
  10747. (insert "]\n"))
  10748. ((equal e '(:newline))
  10749. (unless (zerop cnt)
  10750. (setq cnt 0)
  10751. (insert "\n")
  10752. (setq e (car tbl))
  10753. (while (equal (car tbl) '(:newline))
  10754. (insert "\n")
  10755. (setq tbl (cdr tbl)))))
  10756. ((equal e '(:grouptags)) (insert " : "))
  10757. (t
  10758. (setq tg (copy-sequence (car e)) c2 nil)
  10759. (if (cdr e)
  10760. (setq c (cdr e))
  10761. ;; automatically assign a character.
  10762. (setq c1 (string-to-char
  10763. (downcase (substring
  10764. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10765. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10766. (while (or (rassoc char ntable) (rassoc char table))
  10767. (setq char (1+ char)))
  10768. (setq c2 c1))
  10769. (setq c (or c2 char)))
  10770. (when ingroup (push tg (car groups)))
  10771. (setq tg (org-add-props tg nil 'face
  10772. (cond
  10773. ((not (assoc tg table))
  10774. (org-get-todo-face tg))
  10775. ((member tg current) c-face)
  10776. ((member tg inherited) i-face))))
  10777. (when (equal (caar tbl) :grouptags)
  10778. (org-add-props tg nil 'face 'org-tag-group))
  10779. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10780. (insert "[" c "] " tg (make-string
  10781. (- fwidth 4 (length tg)) ?\ ))
  10782. (push (cons tg c) ntable)
  10783. (when (= (cl-incf cnt) ncol)
  10784. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10785. (insert "\n")
  10786. (when (or ingroup intaggroup) (insert " ")))
  10787. (setq cnt 0)))))
  10788. (setq ntable (nreverse ntable))
  10789. (insert "\n")
  10790. (goto-char (point-min))
  10791. (unless expert (org-fit-window-to-buffer))
  10792. (setq rtn
  10793. (catch 'exit
  10794. (while t
  10795. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10796. (if (not groups) "no " "")
  10797. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10798. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10799. (setq org-last-tag-selection-key c)
  10800. (cond
  10801. ((= c ?\r) (throw 'exit t))
  10802. ((= c ?!)
  10803. (setq groups (not groups))
  10804. (goto-char (point-min))
  10805. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10806. ((= c ?\C-c)
  10807. (if (not expert)
  10808. (org-fast-tag-show-exit
  10809. (setq exit-after-next (not exit-after-next)))
  10810. (setq expert nil)
  10811. (delete-other-windows)
  10812. (set-window-buffer (split-window-vertically) " *Org tags*")
  10813. (org-switch-to-buffer-other-window " *Org tags*")
  10814. (org-fit-window-to-buffer)))
  10815. ((or (= c ?\C-g)
  10816. (and (= c ?q) (not (rassoc c ntable))))
  10817. (delete-overlay org-tags-overlay)
  10818. (setq quit-flag t))
  10819. ((= c ?\ )
  10820. (setq current nil)
  10821. (when exit-after-next (setq exit-after-next 'now)))
  10822. ((= c ?\t)
  10823. (condition-case nil
  10824. (setq tg (completing-read
  10825. "Tag: "
  10826. (or buffer-tags
  10827. (with-current-buffer buf
  10828. (setq buffer-tags
  10829. (org-get-buffer-tags))))))
  10830. (quit (setq tg "")))
  10831. (when (string-match "\\S-" tg)
  10832. (cl-pushnew (list tg) buffer-tags :test #'equal)
  10833. (if (member tg current)
  10834. (setq current (delete tg current))
  10835. (push tg current)))
  10836. (when exit-after-next (setq exit-after-next 'now)))
  10837. ((setq e (rassoc c todo-table) tg (car e))
  10838. (with-current-buffer buf
  10839. (save-excursion (org-todo tg)))
  10840. (when exit-after-next (setq exit-after-next 'now)))
  10841. ((setq e (rassoc c ntable) tg (car e))
  10842. (if (member tg current)
  10843. (setq current (delete tg current))
  10844. (cl-loop for g in groups do
  10845. (when (member tg g)
  10846. (dolist (x g) (setq current (delete x current)))))
  10847. (push tg current))
  10848. (when exit-after-next (setq exit-after-next 'now))))
  10849. ;; Create a sorted list
  10850. (setq current
  10851. (sort current
  10852. (lambda (a b)
  10853. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10854. (when (eq exit-after-next 'now) (throw 'exit t))
  10855. (goto-char (point-min))
  10856. (beginning-of-line 2)
  10857. (delete-region (point) (point-at-eol))
  10858. (org-fast-tag-insert "Current" current c-face)
  10859. (org-set-current-tags-overlay current ov-prefix)
  10860. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10861. (while (re-search-forward tag-re nil t)
  10862. (let ((tag (match-string 1)))
  10863. (add-text-properties
  10864. (match-beginning 1) (match-end 1)
  10865. (list 'face
  10866. (cond
  10867. ((member tag current) c-face)
  10868. ((member tag inherited) i-face)
  10869. (t (get-text-property (match-beginning 1) '
  10870. face))))))))
  10871. (goto-char (point-min)))))
  10872. (delete-overlay org-tags-overlay)
  10873. (if rtn
  10874. (mapconcat 'identity current ":")
  10875. nil)))))
  10876. (defun org-make-tag-string (tags)
  10877. "Return string associated to TAGS.
  10878. TAGS is a list of strings."
  10879. (if (null tags) ""
  10880. (format ":%s:" (mapconcat #'identity tags ":"))))
  10881. (defun org--get-local-tags ()
  10882. "Return list of tags for the current headline.
  10883. Assume point is at the beginning of the headline."
  10884. (and (looking-at org-tag-line-re)
  10885. (split-string (match-string-no-properties 2) ":" t)))
  10886. (defun org-get-tags (&optional pos local)
  10887. "Get the list of tags specified in the current headline.
  10888. When argument POS is non-nil, retrieve tags for headline at POS.
  10889. According to `org-use-tag-inheritance', tags may be inherited
  10890. from parent headlines, and from the whole document, through
  10891. `org-file-tags'. In this case, the returned list of tags
  10892. contains tags in this order: file tags, tags inherited from
  10893. parent headlines, local tags.
  10894. However, when optional argument LOCAL is non-nil, only return
  10895. tags specified at the headline.
  10896. Inherited tags have the `inherited' text property."
  10897. (if (and org-trust-scanner-tags
  10898. (or (not pos) (eq pos (point)))
  10899. (not local))
  10900. org-scanner-tags
  10901. (org-with-point-at (or pos (point))
  10902. (unless (org-before-first-heading-p)
  10903. (org-back-to-heading t)
  10904. (let ((ltags (org--get-local-tags)) itags)
  10905. (if (or local (not org-use-tag-inheritance)) ltags
  10906. (while (org-up-heading-safe)
  10907. (setq itags (append (mapcar #'org-add-prop-inherited
  10908. (org--get-local-tags))
  10909. itags)))
  10910. (setq itags (append org-file-tags itags))
  10911. (delete-dups
  10912. (append (org-remove-uninherited-tags itags) ltags))))))))
  10913. (defun org-get-buffer-tags ()
  10914. "Get a table of all tags used in the buffer, for completion."
  10915. (org-with-point-at 1
  10916. (let (tags)
  10917. (while (re-search-forward org-tag-line-re nil t)
  10918. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10919. tags)))
  10920. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  10921. ;;;; The mapping API
  10922. (defvar org-agenda-skip-comment-trees)
  10923. (defvar org-agenda-skip-function)
  10924. (defun org-map-entries (func &optional match scope &rest skip)
  10925. "Call FUNC at each headline selected by MATCH in SCOPE.
  10926. FUNC is a function or a lisp form. The function will be called without
  10927. arguments, with the cursor positioned at the beginning of the headline.
  10928. The return values of all calls to the function will be collected and
  10929. returned as a list.
  10930. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  10931. does not need to preserve point. After evaluation, the cursor will be
  10932. moved to the end of the line (presumably of the headline of the
  10933. processed entry) and search continues from there. Under some
  10934. circumstances, this may not produce the wanted results. For example,
  10935. if you have removed (e.g. archived) the current (sub)tree it could
  10936. mean that the next entry will be skipped entirely. In such cases, you
  10937. can specify the position from where search should continue by making
  10938. FUNC set the variable `org-map-continue-from' to the desired buffer
  10939. position.
  10940. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10941. Only headlines that are matched by this query will be considered during
  10942. the iteration. When MATCH is nil or t, all headlines will be
  10943. visited by the iteration.
  10944. SCOPE determines the scope of this command. It can be any of:
  10945. nil The current buffer, respecting the restriction if any
  10946. tree The subtree started with the entry at point
  10947. region The entries within the active region, if any
  10948. region-start-level
  10949. The entries within the active region, but only those at
  10950. the same level than the first one.
  10951. file The current buffer, without restriction
  10952. file-with-archives
  10953. The current buffer, and any archives associated with it
  10954. agenda All agenda files
  10955. agenda-with-archives
  10956. All agenda files with any archive files associated with them
  10957. \(file1 file2 ...)
  10958. If this is a list, all files in the list will be scanned
  10959. The remaining args are treated as settings for the skipping facilities of
  10960. the scanner. The following items can be given here:
  10961. archive skip trees with the archive tag
  10962. comment skip trees with the COMMENT keyword
  10963. function or Emacs Lisp form:
  10964. will be used as value for `org-agenda-skip-function', so
  10965. whenever the function returns a position, FUNC will not be
  10966. called for that entry and search will continue from the
  10967. position returned
  10968. If your function needs to retrieve the tags including inherited tags
  10969. at the *current* entry, you can use the value of the variable
  10970. `org-scanner-tags' which will be much faster than getting the value
  10971. with `org-get-tags'. If your function gets properties with
  10972. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10973. to t around the call to `org-entry-properties' to get the same speedup.
  10974. Note that if your function moves around to retrieve tags and properties at
  10975. a *different* entry, you cannot use these techniques."
  10976. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10977. (not (org-region-active-p)))
  10978. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10979. (org-agenda-skip-archived-trees (memq 'archive skip))
  10980. (org-agenda-skip-comment-trees (memq 'comment skip))
  10981. (org-agenda-skip-function
  10982. (car (org-delete-all '(comment archive) skip)))
  10983. (org-tags-match-list-sublevels t)
  10984. (start-level (eq scope 'region-start-level))
  10985. matcher res
  10986. org-todo-keywords-for-agenda
  10987. org-done-keywords-for-agenda
  10988. org-todo-keyword-alist-for-agenda
  10989. org-tag-alist-for-agenda
  10990. org--matcher-tags-todo-only)
  10991. (cond
  10992. ((eq match t) (setq matcher t))
  10993. ((eq match nil) (setq matcher t))
  10994. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10995. (save-excursion
  10996. (save-restriction
  10997. (cond ((eq scope 'tree)
  10998. (org-back-to-heading t)
  10999. (org-narrow-to-subtree)
  11000. (setq scope nil))
  11001. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11002. (org-region-active-p))
  11003. ;; If needed, set start-level to a string like "2"
  11004. (when start-level
  11005. (save-excursion
  11006. (goto-char (region-beginning))
  11007. (unless (org-at-heading-p) (outline-next-heading))
  11008. (setq start-level (org-current-level))))
  11009. (narrow-to-region (region-beginning)
  11010. (save-excursion
  11011. (goto-char (region-end))
  11012. (unless (and (bolp) (org-at-heading-p))
  11013. (outline-next-heading))
  11014. (point)))
  11015. (setq scope nil)))
  11016. (if (not scope)
  11017. (progn
  11018. (org-agenda-prepare-buffers
  11019. (and buffer-file-name (list buffer-file-name)))
  11020. (setq res
  11021. (org-scan-tags
  11022. func matcher org--matcher-tags-todo-only start-level)))
  11023. ;; Get the right scope
  11024. (cond
  11025. ((and scope (listp scope) (symbolp (car scope)))
  11026. (setq scope (eval scope)))
  11027. ((eq scope 'agenda)
  11028. (setq scope (org-agenda-files t)))
  11029. ((eq scope 'agenda-with-archives)
  11030. (setq scope (org-agenda-files t))
  11031. (setq scope (org-add-archive-files scope)))
  11032. ((eq scope 'file)
  11033. (setq scope (and buffer-file-name (list buffer-file-name))))
  11034. ((eq scope 'file-with-archives)
  11035. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11036. (org-agenda-prepare-buffers scope)
  11037. (dolist (file scope)
  11038. (with-current-buffer (org-find-base-buffer-visiting file)
  11039. (org-with-wide-buffer
  11040. (goto-char (point-min))
  11041. (setq res
  11042. (append
  11043. res
  11044. (org-scan-tags
  11045. func matcher org--matcher-tags-todo-only)))))))))
  11046. res)))
  11047. ;;; Properties API
  11048. (defconst org-special-properties
  11049. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11050. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11051. "The special properties valid in Org mode.
  11052. These are properties that are not defined in the property drawer,
  11053. but in some other way.")
  11054. (defconst org-default-properties
  11055. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11056. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11057. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11058. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11059. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11060. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11061. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11062. "Some properties that are used by Org mode for various purposes.
  11063. Being in this list makes sure that they are offered for completion.")
  11064. (defun org--valid-property-p (property)
  11065. "Non-nil when string PROPERTY is a valid property name."
  11066. (not
  11067. (or (equal property "")
  11068. (string-match-p "\\s-" property))))
  11069. (defun org--update-property-plist (key val props)
  11070. "Associate KEY to VAL in alist PROPS.
  11071. Modifications are made by side-effect. Return new alist."
  11072. (let* ((appending (string= (substring key -1) "+"))
  11073. (key (if appending (substring key 0 -1) key))
  11074. (old (assoc-string key props t)))
  11075. (if (not old) (cons (cons key val) props)
  11076. (setcdr old (if appending (concat (cdr old) " " val) val))
  11077. props)))
  11078. (defun org-get-property-block (&optional beg force)
  11079. "Return the (beg . end) range of the body of the property drawer.
  11080. BEG is the beginning of the current subtree or the beginning of
  11081. the document if before the first headline. If it is not given,
  11082. it will be found. If the drawer does not exist, create it if
  11083. FORCE is non-nil, or return nil."
  11084. (org-with-wide-buffer
  11085. (let ((beg (cond (beg (goto-char beg))
  11086. ((or (not (featurep 'org-inlinetask))
  11087. (org-inlinetask-in-task-p))
  11088. (org-back-to-heading-or-point-min t) (point))
  11089. (t (org-with-limited-levels
  11090. (org-back-to-heading-or-point-min t))
  11091. (point)))))
  11092. ;; Move point to its position according to its positional rules.
  11093. (cond ((org-before-first-heading-p)
  11094. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11095. (t (forward-line)
  11096. (when (looking-at-p org-planning-line-re) (forward-line))))
  11097. (cond ((looking-at org-property-drawer-re)
  11098. (forward-line)
  11099. (cons (point) (progn (goto-char (match-end 0))
  11100. (line-beginning-position))))
  11101. (force
  11102. (goto-char beg)
  11103. (org-insert-property-drawer)
  11104. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11105. (line-beginning-position))))
  11106. (cons pos pos)))))))
  11107. (defun org-at-property-block-p ()
  11108. "Return t when point is at the first line of a property drawer.
  11109. The property drawer is validated according to its positional
  11110. rules using `org-get-property-block'."
  11111. (save-excursion
  11112. (beginning-of-line)
  11113. (and (looking-at org-property-start-re)
  11114. (forward-line)
  11115. (let ((property-drawer (org-get-property-block)))
  11116. (and property-drawer
  11117. (= (point) (car property-drawer)))))))
  11118. (defun org-at-property-p ()
  11119. "Non-nil when point is inside a property drawer.
  11120. See `org-property-re' for match data, if applicable."
  11121. (save-excursion
  11122. (beginning-of-line)
  11123. (and (looking-at org-property-re)
  11124. (let ((property-drawer (save-match-data (org-get-property-block))))
  11125. (and property-drawer
  11126. (>= (point) (car property-drawer))
  11127. (< (point) (cdr property-drawer)))))))
  11128. (defun org-property-action ()
  11129. "Do an action on properties."
  11130. (interactive)
  11131. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11132. (let ((c (read-char-exclusive)))
  11133. (cl-case c
  11134. (?s (call-interactively #'org-set-property))
  11135. (?d (call-interactively #'org-delete-property))
  11136. (?D (call-interactively #'org-delete-property-globally))
  11137. (?c (call-interactively #'org-compute-property-at-point))
  11138. (otherwise (user-error "No such property action %c" c)))))
  11139. (defun org-inc-effort ()
  11140. "Increment the value of the effort property in the current entry."
  11141. (interactive)
  11142. (org-set-effort t))
  11143. (defvar org-clock-effort) ; Defined in org-clock.el.
  11144. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11145. (defun org-set-effort (&optional increment value)
  11146. "Set the effort property of the current entry.
  11147. If INCREMENT is non-nil, set the property to the next allowed
  11148. value. Otherwise, if optional argument VALUE is provided, use
  11149. it. Eventually, prompt for the new value if none of the previous
  11150. variables is set."
  11151. (interactive "P")
  11152. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11153. (current (org-entry-get nil org-effort-property))
  11154. (value
  11155. (cond
  11156. (increment
  11157. (unless allowed (user-error "Allowed effort values are not set"))
  11158. (or (cl-caadr (member (list current) allowed))
  11159. (user-error "Unknown value %S among allowed values" current)))
  11160. (value
  11161. (if (stringp value) value
  11162. (error "Invalid effort value: %S" value)))
  11163. (t
  11164. (let ((must-match
  11165. (and allowed
  11166. (not (get-text-property 0 'org-unrestricted
  11167. (caar allowed))))))
  11168. (completing-read "Effort: " allowed nil must-match))))))
  11169. ;; Test whether the value can be interpreted as a duration before
  11170. ;; inserting it in the buffer:
  11171. (org-duration-to-minutes value)
  11172. ;; Maybe update the effort value:
  11173. (unless (equal current value)
  11174. (org-entry-put nil org-effort-property value))
  11175. (org-refresh-property '((effort . identity)
  11176. (effort-minutes . org-duration-to-minutes))
  11177. value)
  11178. (when (equal (org-get-heading t t t t)
  11179. (bound-and-true-p org-clock-current-task))
  11180. (setq org-clock-effort value)
  11181. (org-clock-update-mode-line))
  11182. (message "%s is now %s" org-effort-property value)))
  11183. (defun org-entry-properties (&optional pom which)
  11184. "Get all properties of the current entry.
  11185. When POM is a buffer position, get all properties from the entry
  11186. there instead.
  11187. This includes the TODO keyword, the tags, time strings for
  11188. deadline, scheduled, and clocking, and any additional properties
  11189. defined in the entry.
  11190. If WHICH is nil or `all', get all properties. If WHICH is
  11191. `special' or `standard', only get that subclass. If WHICH is
  11192. a string, only get that property.
  11193. Return value is an alist. Keys are properties, as upcased
  11194. strings."
  11195. (org-with-point-at pom
  11196. (when (and (derived-mode-p 'org-mode)
  11197. (org-back-to-heading-or-point-min t))
  11198. (catch 'exit
  11199. (let* ((beg (point))
  11200. (specific (and (stringp which) (upcase which)))
  11201. (which (cond ((not specific) which)
  11202. ((member specific org-special-properties) 'special)
  11203. (t 'standard)))
  11204. props)
  11205. ;; Get the special properties, like TODO and TAGS.
  11206. (when (memq which '(nil all special))
  11207. (when (or (not specific) (string= specific "CLOCKSUM"))
  11208. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11209. (when clocksum
  11210. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11211. props)))
  11212. (when specific (throw 'exit props)))
  11213. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11214. (let ((clocksumt (get-text-property (point)
  11215. :org-clock-minutes-today)))
  11216. (when clocksumt
  11217. (push (cons "CLOCKSUM_T"
  11218. (org-duration-from-minutes clocksumt))
  11219. props)))
  11220. (when specific (throw 'exit props)))
  11221. (when (or (not specific) (string= specific "ITEM"))
  11222. (let ((case-fold-search nil))
  11223. (when (looking-at org-complex-heading-regexp)
  11224. (push (cons "ITEM"
  11225. (let ((title (match-string-no-properties 4)))
  11226. (if (org-string-nw-p title)
  11227. (org-remove-tabs title)
  11228. "")))
  11229. props)))
  11230. (when specific (throw 'exit props)))
  11231. (when (or (not specific) (string= specific "TODO"))
  11232. (let ((case-fold-search nil))
  11233. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11234. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11235. (when specific (throw 'exit props)))
  11236. (when (or (not specific) (string= specific "PRIORITY"))
  11237. (push (cons "PRIORITY"
  11238. (if (looking-at org-priority-regexp)
  11239. (match-string-no-properties 2)
  11240. (char-to-string org-priority-default)))
  11241. props)
  11242. (when specific (throw 'exit props)))
  11243. (when (or (not specific) (string= specific "FILE"))
  11244. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11245. props)
  11246. (when specific (throw 'exit props)))
  11247. (when (or (not specific) (string= specific "TAGS"))
  11248. (let ((tags (org-get-tags nil t)))
  11249. (when tags
  11250. (push (cons "TAGS" (org-make-tag-string tags))
  11251. props)))
  11252. (when specific (throw 'exit props)))
  11253. (when (or (not specific) (string= specific "ALLTAGS"))
  11254. (let ((tags (org-get-tags)))
  11255. (when tags
  11256. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11257. props)))
  11258. (when specific (throw 'exit props)))
  11259. (when (or (not specific) (string= specific "BLOCKED"))
  11260. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11261. (when specific (throw 'exit props)))
  11262. (when (or (not specific)
  11263. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11264. (forward-line)
  11265. (when (looking-at-p org-planning-line-re)
  11266. (end-of-line)
  11267. (let ((bol (line-beginning-position))
  11268. ;; Backward compatibility: time keywords used to
  11269. ;; be configurable (before 8.3). Make sure we
  11270. ;; get the correct keyword.
  11271. (key-assoc `(("CLOSED" . ,org-closed-string)
  11272. ("DEADLINE" . ,org-deadline-string)
  11273. ("SCHEDULED" . ,org-scheduled-string))))
  11274. (dolist (pair (if specific (list (assoc specific key-assoc))
  11275. key-assoc))
  11276. (save-excursion
  11277. (when (search-backward (cdr pair) bol t)
  11278. (goto-char (match-end 0))
  11279. (skip-chars-forward " \t")
  11280. (and (looking-at org-ts-regexp-both)
  11281. (push (cons (car pair)
  11282. (match-string-no-properties 0))
  11283. props)))))))
  11284. (when specific (throw 'exit props)))
  11285. (when (or (not specific)
  11286. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11287. (let ((find-ts
  11288. (lambda (end ts)
  11289. ;; Fix next time-stamp before END. TS is the
  11290. ;; list of time-stamps found so far.
  11291. (let ((ts ts)
  11292. (regexp (cond
  11293. ((string= specific "TIMESTAMP")
  11294. org-ts-regexp)
  11295. ((string= specific "TIMESTAMP_IA")
  11296. org-ts-regexp-inactive)
  11297. ((assoc "TIMESTAMP_IA" ts)
  11298. org-ts-regexp)
  11299. ((assoc "TIMESTAMP" ts)
  11300. org-ts-regexp-inactive)
  11301. (t org-ts-regexp-both))))
  11302. (catch 'next
  11303. (while (re-search-forward regexp end t)
  11304. (backward-char)
  11305. (let ((object (org-element-context)))
  11306. ;; Accept to match timestamps in node
  11307. ;; properties, too.
  11308. (when (memq (org-element-type object)
  11309. '(node-property timestamp))
  11310. (let ((type
  11311. (org-element-property :type object)))
  11312. (cond
  11313. ((and (memq type '(active active-range))
  11314. (not (equal specific "TIMESTAMP_IA")))
  11315. (unless (assoc "TIMESTAMP" ts)
  11316. (push (cons "TIMESTAMP"
  11317. (org-element-property
  11318. :raw-value object))
  11319. ts)
  11320. (when specific (throw 'exit ts))))
  11321. ((and (memq type '(inactive inactive-range))
  11322. (not (string= specific "TIMESTAMP")))
  11323. (unless (assoc "TIMESTAMP_IA" ts)
  11324. (push (cons "TIMESTAMP_IA"
  11325. (org-element-property
  11326. :raw-value object))
  11327. ts)
  11328. (when specific (throw 'exit ts))))))
  11329. ;; Both timestamp types are found,
  11330. ;; move to next part.
  11331. (when (= (length ts) 2) (throw 'next ts)))))
  11332. ts)))))
  11333. (goto-char beg)
  11334. ;; First look for timestamps within headline.
  11335. (let ((ts (funcall find-ts (line-end-position) nil)))
  11336. (if (= (length ts) 2) (setq props (nconc ts props))
  11337. ;; Then find timestamps in the section, skipping
  11338. ;; planning line.
  11339. (let ((end (save-excursion (outline-next-heading))))
  11340. (forward-line)
  11341. (when (looking-at-p org-planning-line-re) (forward-line))
  11342. (setq props (nconc (funcall find-ts end ts) props))))))))
  11343. ;; Get the standard properties, like :PROP:.
  11344. (when (memq which '(nil all standard))
  11345. ;; If we are looking after a specific property, delegate
  11346. ;; to `org-entry-get', which is faster. However, make an
  11347. ;; exception for "CATEGORY", since it can be also set
  11348. ;; through keywords (i.e. #+CATEGORY).
  11349. (if (and specific (not (equal specific "CATEGORY")))
  11350. (let ((value (org-entry-get beg specific nil t)))
  11351. (throw 'exit (and value (list (cons specific value)))))
  11352. (let ((range (org-get-property-block beg)))
  11353. (when range
  11354. (let ((end (cdr range)) seen-base)
  11355. (goto-char (car range))
  11356. ;; Unlike to `org--update-property-plist', we
  11357. ;; handle the case where base values is found
  11358. ;; after its extension. We also forbid standard
  11359. ;; properties to be named as special properties.
  11360. (while (re-search-forward org-property-re end t)
  11361. (let* ((key (upcase (match-string-no-properties 2)))
  11362. (extendp (string-match-p "\\+\\'" key))
  11363. (key-base (if extendp (substring key 0 -1) key))
  11364. (value (match-string-no-properties 3)))
  11365. (cond
  11366. ((member-ignore-case key-base org-special-properties))
  11367. (extendp
  11368. (setq props
  11369. (org--update-property-plist key value props)))
  11370. ((member key seen-base))
  11371. (t (push key seen-base)
  11372. (let ((p (assoc-string key props t)))
  11373. (if p (setcdr p (concat value " " (cdr p)))
  11374. (push (cons key value) props))))))))))))
  11375. (unless (assoc "CATEGORY" props)
  11376. (push (cons "CATEGORY" (org-get-category beg)) props)
  11377. (when (string= specific "CATEGORY") (throw 'exit props)))
  11378. ;; Return value.
  11379. props)))))
  11380. (defun org--property-local-values (property literal-nil)
  11381. "Return value for PROPERTY in current entry.
  11382. Value is a list whose car is the base value for PROPERTY and cdr
  11383. a list of accumulated values. Return nil if neither is found in
  11384. the entry. Also return nil when PROPERTY is set to \"nil\",
  11385. unless LITERAL-NIL is non-nil."
  11386. (let ((range (org-get-property-block)))
  11387. (when range
  11388. (goto-char (car range))
  11389. (let* ((case-fold-search t)
  11390. (end (cdr range))
  11391. (value
  11392. ;; Base value.
  11393. (save-excursion
  11394. (let ((v (and (re-search-forward
  11395. (org-re-property property nil t) end t)
  11396. (match-string-no-properties 3))))
  11397. (list (if literal-nil v (org-not-nil v)))))))
  11398. ;; Find additional values.
  11399. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11400. (while (re-search-forward property+ end t)
  11401. (push (match-string-no-properties 3) value)))
  11402. ;; Return final values.
  11403. (and (not (equal value '(nil))) (nreverse value))))))
  11404. (defun org--property-global-or-keyword-value (property literal-nil)
  11405. "Return value for PROPERTY as defined by global properties or by keyword.
  11406. Return value is a string. Return nil if property is not set
  11407. globally or by keyword. Also return nil when PROPERTY is set to
  11408. \"nil\", unless LITERAL-NIL is non-nil."
  11409. (let ((global
  11410. (cdr (or (assoc-string property org-keyword-properties t)
  11411. (assoc-string property org-global-properties t)
  11412. (assoc-string property org-global-properties-fixed t)))))
  11413. (if literal-nil global (org-not-nil global))))
  11414. (defun org-entry-get (pom property &optional inherit literal-nil)
  11415. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11416. If INHERIT is non-nil and the entry does not have the property,
  11417. then also check higher levels of the hierarchy. If INHERIT is
  11418. the symbol `selective', use inheritance only if the setting in
  11419. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11420. If the property is present but empty, the return value is the
  11421. empty string. If the property is not present at all, nil is
  11422. returned. In any other case, return the value as a string.
  11423. Search is case-insensitive.
  11424. If LITERAL-NIL is set, return the string value \"nil\" as
  11425. a string, do not interpret it as the list atom nil. This is used
  11426. for inheritance when a \"nil\" value can supersede a non-nil
  11427. value higher up the hierarchy."
  11428. (org-with-point-at pom
  11429. (cond
  11430. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11431. ;; We need a special property. Use `org-entry-properties' to
  11432. ;; retrieve it, but specify the wanted property.
  11433. (cdr (assoc-string property (org-entry-properties nil property))))
  11434. ((and inherit
  11435. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11436. (org-entry-get-with-inheritance property literal-nil))
  11437. (t
  11438. (let* ((local (org--property-local-values property literal-nil))
  11439. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11440. (if literal-nil value (org-not-nil value)))))))
  11441. (defun org-property-or-variable-value (var &optional inherit)
  11442. "Check if there is a property fixing the value of VAR.
  11443. If yes, return this value. If not, return the current value of the variable."
  11444. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11445. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11446. (read prop)
  11447. (symbol-value var))))
  11448. (defun org-entry-delete (pom property)
  11449. "Delete PROPERTY from entry at point-or-marker POM.
  11450. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11451. non-nil when a property was removed."
  11452. (org-with-point-at pom
  11453. (pcase (org-get-property-block)
  11454. (`(,begin . ,origin)
  11455. (let* ((end (copy-marker origin))
  11456. (re (org-re-property
  11457. (concat (regexp-quote property) "\\+?") t t)))
  11458. (goto-char begin)
  11459. (while (re-search-forward re end t)
  11460. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11461. ;; If drawer is empty, remove it altogether.
  11462. (when (= begin end)
  11463. (delete-region (line-beginning-position 0)
  11464. (line-beginning-position 2)))
  11465. ;; Return non-nil if some property was removed.
  11466. (prog1 (/= end origin) (set-marker end nil))))
  11467. (_ nil))))
  11468. ;; Multi-values properties are properties that contain multiple values
  11469. ;; These values are assumed to be single words, separated by whitespace.
  11470. (defun org-entry-add-to-multivalued-property (pom property value)
  11471. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11472. (let* ((old (org-entry-get pom property))
  11473. (values (and old (split-string old))))
  11474. (setq value (org-entry-protect-space value))
  11475. (unless (member value values)
  11476. (setq values (append values (list value)))
  11477. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11478. (defun org-entry-remove-from-multivalued-property (pom property value)
  11479. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11480. (let* ((old (org-entry-get pom property))
  11481. (values (and old (split-string old))))
  11482. (setq value (org-entry-protect-space value))
  11483. (when (member value values)
  11484. (setq values (delete value values))
  11485. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11486. (defun org-entry-member-in-multivalued-property (pom property value)
  11487. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11488. (let* ((old (org-entry-get pom property))
  11489. (values (and old (split-string old))))
  11490. (setq value (org-entry-protect-space value))
  11491. (member value values)))
  11492. (defun org-entry-get-multivalued-property (pom property)
  11493. "Return a list of values in a multivalued property."
  11494. (let* ((value (org-entry-get pom property))
  11495. (values (and value (split-string value))))
  11496. (mapcar #'org-entry-restore-space values)))
  11497. (defun org-entry-put-multivalued-property (pom property &rest values)
  11498. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11499. VALUES should be a list of strings. Spaces will be protected."
  11500. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11501. (let* ((value (org-entry-get pom property))
  11502. (values (and value (split-string value))))
  11503. (mapcar #'org-entry-restore-space values)))
  11504. (defun org-entry-protect-space (s)
  11505. "Protect spaces and newline in string S."
  11506. (while (string-match " " s)
  11507. (setq s (replace-match "%20" t t s)))
  11508. (while (string-match "\n" s)
  11509. (setq s (replace-match "%0A" t t s)))
  11510. s)
  11511. (defun org-entry-restore-space (s)
  11512. "Restore spaces and newline in string S."
  11513. (while (string-match "%20" s)
  11514. (setq s (replace-match " " t t s)))
  11515. (while (string-match "%0A" s)
  11516. (setq s (replace-match "\n" t t s)))
  11517. s)
  11518. (defvar org-entry-property-inherited-from (make-marker)
  11519. "Marker pointing to the entry from where a property was inherited.
  11520. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11521. location of the entry where the inheritance search matched. If there was
  11522. no match, the marker will point nowhere.
  11523. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11524. is set.")
  11525. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11526. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11527. The search will stop at the first ancestor which has the property defined.
  11528. If the value found is \"nil\", return nil to show that the property
  11529. should be considered as undefined (this is the meaning of nil here).
  11530. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11531. (move-marker org-entry-property-inherited-from nil)
  11532. (org-with-wide-buffer
  11533. (let (value)
  11534. (catch 'exit
  11535. (while t
  11536. (let ((v (org--property-local-values property literal-nil)))
  11537. (when v
  11538. (setq value
  11539. (concat (mapconcat #'identity (delq nil v) " ")
  11540. (and value " ")
  11541. value)))
  11542. (cond
  11543. ((car v)
  11544. (org-back-to-heading-or-point-min t)
  11545. (move-marker org-entry-property-inherited-from (point))
  11546. (throw 'exit nil))
  11547. ((org-up-heading-or-point-min))
  11548. (t
  11549. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11550. (cond ((not global))
  11551. (value (setq value (concat global " " value)))
  11552. (t (setq value global))))
  11553. (throw 'exit nil))))))
  11554. (if literal-nil value (org-not-nil value)))))
  11555. (defvar org-property-changed-functions nil
  11556. "Hook called when the value of a property has changed.
  11557. Each hook function should accept two arguments, the name of the property
  11558. and the new value.")
  11559. (defun org-entry-put (pom property value)
  11560. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11561. If the value is nil, it is converted to the empty string. If it
  11562. is not a string, an error is raised. Also raise an error on
  11563. invalid property names.
  11564. PROPERTY can be any regular property (see
  11565. `org-special-properties'). It can also be \"TODO\",
  11566. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11567. For the last two properties, VALUE may have any of the special
  11568. values \"earlier\" and \"later\". The function then increases or
  11569. decreases scheduled or deadline date by one day."
  11570. (cond ((null value) (setq value ""))
  11571. ((not (stringp value)) (error "Properties values should be strings"))
  11572. ((not (org--valid-property-p property))
  11573. (user-error "Invalid property name: \"%s\"" property)))
  11574. (org-with-point-at pom
  11575. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11576. (org-back-to-heading-or-point-min t)
  11577. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11578. (let ((beg (point)))
  11579. (cond
  11580. ((equal property "TODO")
  11581. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11582. ((not (member value org-todo-keywords-1))
  11583. (user-error "\"%s\" is not a valid TODO state" value)))
  11584. (org-todo value)
  11585. (org-align-tags))
  11586. ((equal property "PRIORITY")
  11587. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11588. (org-align-tags))
  11589. ((equal property "SCHEDULED")
  11590. (forward-line)
  11591. (if (and (looking-at-p org-planning-line-re)
  11592. (re-search-forward
  11593. org-scheduled-time-regexp (line-end-position) t))
  11594. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11595. ((string= value "later") (org-timestamp-change 1 'day))
  11596. ((string= value "") (org-schedule '(4)))
  11597. (t (org-schedule nil value)))
  11598. (if (member value '("earlier" "later" ""))
  11599. (call-interactively #'org-schedule)
  11600. (org-schedule nil value))))
  11601. ((equal property "DEADLINE")
  11602. (forward-line)
  11603. (if (and (looking-at-p org-planning-line-re)
  11604. (re-search-forward
  11605. org-deadline-time-regexp (line-end-position) t))
  11606. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11607. ((string= value "later") (org-timestamp-change 1 'day))
  11608. ((string= value "") (org-deadline '(4)))
  11609. (t (org-deadline nil value)))
  11610. (if (member value '("earlier" "later" ""))
  11611. (call-interactively #'org-deadline)
  11612. (org-deadline nil value))))
  11613. ((member property org-special-properties)
  11614. (error "The %s property cannot be set with `org-entry-put'" property))
  11615. (t
  11616. (let* ((range (org-get-property-block beg 'force))
  11617. (end (cdr range))
  11618. (case-fold-search t))
  11619. (goto-char (car range))
  11620. (if (re-search-forward (org-re-property property nil t) end t)
  11621. (progn (delete-region (match-beginning 0) (match-end 0))
  11622. (goto-char (match-beginning 0)))
  11623. (goto-char end)
  11624. (insert "\n")
  11625. (backward-char))
  11626. (insert ":" property ":")
  11627. (when value (insert " " value))
  11628. (org-indent-line)))))
  11629. (run-hook-with-args 'org-property-changed-functions property value)))
  11630. (defun org-buffer-property-keys (&optional specials defaults columns)
  11631. "Get all property keys in the current buffer.
  11632. When SPECIALS is non-nil, also list the special properties that
  11633. reflect things like tags and TODO state.
  11634. When DEFAULTS is non-nil, also include properties that has
  11635. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11636. DESCRIPTION, LOCATION, and LOGGING and others.
  11637. When COLUMNS in non-nil, also include property names given in
  11638. COLUMN formats in the current buffer."
  11639. (let ((case-fold-search t)
  11640. (props (append
  11641. (and specials org-special-properties)
  11642. (and defaults (cons org-effort-property org-default-properties))
  11643. nil)))
  11644. (org-with-wide-buffer
  11645. (goto-char (point-min))
  11646. (while (re-search-forward org-property-start-re nil t)
  11647. (catch :skip
  11648. (let ((range (org-get-property-block)))
  11649. (unless range (throw :skip nil))
  11650. (goto-char (car range))
  11651. (let ((begin (car range))
  11652. (end (cdr range)))
  11653. ;; Make sure that found property block is not located
  11654. ;; before current point, as it would generate an infloop.
  11655. ;; It can happen, for example, in the following
  11656. ;; situation:
  11657. ;;
  11658. ;; * Headline
  11659. ;; :PROPERTIES:
  11660. ;; ...
  11661. ;; :END:
  11662. ;; *************** Inlinetask
  11663. ;; #+BEGIN_EXAMPLE
  11664. ;; :PROPERTIES:
  11665. ;; #+END_EXAMPLE
  11666. ;;
  11667. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11668. (while (< (point) end)
  11669. (let ((p (progn (looking-at org-property-re)
  11670. (match-string-no-properties 2))))
  11671. ;; Only add true property name, not extension symbol.
  11672. (push (if (not (string-match-p "\\+\\'" p)) p
  11673. (substring p 0 -1))
  11674. props))
  11675. (forward-line))))
  11676. (outline-next-heading)))
  11677. (when columns
  11678. (goto-char (point-min))
  11679. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11680. (let ((element (org-element-at-point)))
  11681. (when (memq (org-element-type element) '(keyword node-property))
  11682. (let ((value (org-element-property :value element))
  11683. (start 0))
  11684. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11685. \\(?:{[^}]+}\\)?"
  11686. value start)
  11687. (setq start (match-end 0))
  11688. (let ((p (match-string-no-properties 1 value)))
  11689. (unless (member-ignore-case p org-special-properties)
  11690. (push p props))))))))))
  11691. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  11692. (defun org-property-values (key)
  11693. "List all non-nil values of property KEY in current buffer."
  11694. (org-with-wide-buffer
  11695. (goto-char (point-min))
  11696. (let ((case-fold-search t)
  11697. (re (org-re-property key))
  11698. values)
  11699. (while (re-search-forward re nil t)
  11700. (push (org-entry-get (point) key) values))
  11701. (delete-dups values))))
  11702. (defun org-insert-property-drawer ()
  11703. "Insert a property drawer into the current entry.
  11704. Do nothing if the drawer already exists. The newly created
  11705. drawer is immediately hidden."
  11706. (org-with-wide-buffer
  11707. ;; Set point to the position where the drawer should be inserted.
  11708. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11709. (org-back-to-heading-or-point-min t)
  11710. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11711. (if (org-before-first-heading-p)
  11712. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11713. (progn
  11714. (forward-line)
  11715. (when (looking-at-p org-planning-line-re) (forward-line))))
  11716. (unless (looking-at-p org-property-drawer-re)
  11717. ;; Make sure we start editing a line from current entry, not from
  11718. ;; next one. It prevents extending text properties or overlays
  11719. ;; belonging to the latter.
  11720. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11721. (let ((begin (if (bobp) (point) (1+ (point))))
  11722. (inhibit-read-only t))
  11723. (unless (bobp) (insert "\n"))
  11724. (insert ":PROPERTIES:\n:END:")
  11725. (org-flag-drawer t nil (line-end-position 0) (point))
  11726. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11727. (org-indent-region begin (point))))))
  11728. (defun org-insert-drawer (&optional arg drawer)
  11729. "Insert a drawer at point.
  11730. When optional argument ARG is non-nil, insert a property drawer.
  11731. Optional argument DRAWER, when non-nil, is a string representing
  11732. drawer's name. Otherwise, the user is prompted for a name.
  11733. If a region is active, insert the drawer around that region
  11734. instead.
  11735. Point is left between drawer's boundaries."
  11736. (interactive "P")
  11737. (let* ((drawer (if arg "PROPERTIES"
  11738. (or drawer (read-from-minibuffer "Drawer: ")))))
  11739. (cond
  11740. ;; With C-u, fall back on `org-insert-property-drawer'
  11741. (arg (org-insert-property-drawer))
  11742. ;; Check validity of suggested drawer's name.
  11743. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11744. (user-error "Invalid drawer name"))
  11745. ;; With an active region, insert a drawer at point.
  11746. ((not (org-region-active-p))
  11747. (progn
  11748. (unless (bolp) (insert "\n"))
  11749. (insert (format ":%s:\n\n:END:\n" drawer))
  11750. (forward-line -2)))
  11751. ;; Otherwise, insert the drawer at point
  11752. (t
  11753. (let ((rbeg (region-beginning))
  11754. (rend (copy-marker (region-end))))
  11755. (unwind-protect
  11756. (progn
  11757. (goto-char rbeg)
  11758. (beginning-of-line)
  11759. (when (save-excursion
  11760. (re-search-forward org-outline-regexp-bol rend t))
  11761. (user-error "Drawers cannot contain headlines"))
  11762. ;; Position point at the beginning of the first
  11763. ;; non-blank line in region. Insert drawer's opening
  11764. ;; there, then indent it.
  11765. (org-skip-whitespace)
  11766. (beginning-of-line)
  11767. (insert ":" drawer ":\n")
  11768. (forward-line -1)
  11769. (indent-for-tab-command)
  11770. ;; Move point to the beginning of the first blank line
  11771. ;; after the last non-blank line in region. Insert
  11772. ;; drawer's closing, then indent it.
  11773. (goto-char rend)
  11774. (skip-chars-backward " \r\t\n")
  11775. (insert "\n:END:")
  11776. (deactivate-mark t)
  11777. (indent-for-tab-command)
  11778. (unless (eolp) (insert "\n")))
  11779. ;; Clear marker, whatever the outcome of insertion is.
  11780. (set-marker rend nil)))))))
  11781. (defvar org-property-set-functions-alist nil
  11782. "Property set function alist.
  11783. Each entry should have the following format:
  11784. (PROPERTY . READ-FUNCTION)
  11785. The read function will be called with the same argument as
  11786. `org-completing-read'.")
  11787. (defun org-set-property-function (property)
  11788. "Get the function that should be used to set PROPERTY.
  11789. This is computed according to `org-property-set-functions-alist'."
  11790. (or (cdr (assoc property org-property-set-functions-alist))
  11791. 'org-completing-read))
  11792. (defun org-read-property-value (property &optional pom)
  11793. "Read value for PROPERTY, as a string.
  11794. When optional argument POM is non-nil, completion uses additional
  11795. information, i.e., allowed or existing values at point or marker
  11796. POM."
  11797. (let* ((completion-ignore-case t)
  11798. (allowed
  11799. (or (org-property-get-allowed-values nil property 'table)
  11800. (and pom (org-property-get-allowed-values pom property 'table))))
  11801. (current (org-entry-get nil property))
  11802. (prompt (format "%s value%s: "
  11803. property
  11804. (if (org-string-nw-p current)
  11805. (format " [%s]" current)
  11806. "")))
  11807. (set-function (org-set-property-function property)))
  11808. (org-trim
  11809. (if allowed
  11810. (funcall set-function
  11811. prompt allowed nil
  11812. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  11813. (let ((all (mapcar #'list
  11814. (append (org-property-values property)
  11815. (and pom
  11816. (org-with-point-at pom
  11817. (org-property-values property)))))))
  11818. (funcall set-function prompt all nil nil "" nil current))))))
  11819. (defvar org-last-set-property nil)
  11820. (defvar org-last-set-property-value nil)
  11821. (defun org-read-property-name ()
  11822. "Read a property name."
  11823. (let ((completion-ignore-case t)
  11824. (default-prop (or (and (org-at-property-p)
  11825. (match-string-no-properties 2))
  11826. org-last-set-property)))
  11827. (org-completing-read
  11828. (concat "Property"
  11829. (if default-prop (concat " [" default-prop "]") "")
  11830. ": ")
  11831. (mapcar #'list (org-buffer-property-keys nil t t))
  11832. nil nil nil nil default-prop)))
  11833. (defun org-set-property-and-value (use-last)
  11834. "Allow to set [PROPERTY]: [value] direction from prompt.
  11835. When use-default, don't even ask, just use the last
  11836. \"[PROPERTY]: [value]\" string from the history."
  11837. (interactive "P")
  11838. (let* ((completion-ignore-case t)
  11839. (pv (or (and use-last org-last-set-property-value)
  11840. (org-completing-read
  11841. "Enter a \"[Property]: [value]\" pair: "
  11842. nil nil nil nil nil
  11843. org-last-set-property-value)))
  11844. prop val)
  11845. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11846. (setq prop (match-string 1 pv)
  11847. val (match-string 2 pv))
  11848. (org-set-property prop val))))
  11849. (defun org-set-property (property value)
  11850. "In the current entry, set PROPERTY to VALUE.
  11851. When called interactively, this will prompt for a property name, offering
  11852. completion on existing and default properties. And then it will prompt
  11853. for a value, offering completion either on allowed values (via an inherited
  11854. xxx_ALL property) or on existing values in other instances of this property
  11855. in the current file.
  11856. Throw an error when trying to set a property with an invalid name."
  11857. (interactive (list nil nil))
  11858. (let ((property (or property (org-read-property-name))))
  11859. ;; `org-entry-put' also makes the following check, but this one
  11860. ;; avoids polluting `org-last-set-property' and
  11861. ;; `org-last-set-property-value' needlessly.
  11862. (unless (org--valid-property-p property)
  11863. (user-error "Invalid property name: \"%s\"" property))
  11864. (let ((value (or value (org-read-property-value property)))
  11865. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11866. (setq org-last-set-property property)
  11867. (setq org-last-set-property-value (concat property ": " value))
  11868. ;; Possibly postprocess the inserted value:
  11869. (when fn (setq value (funcall fn value)))
  11870. (unless (equal (org-entry-get nil property) value)
  11871. (org-entry-put nil property value)))))
  11872. (defun org-find-property (property &optional value)
  11873. "Find first entry in buffer that sets PROPERTY.
  11874. When optional argument VALUE is non-nil, only consider an entry
  11875. if it contains PROPERTY set to this value. If PROPERTY should be
  11876. explicitly set to nil, use string \"nil\" for VALUE.
  11877. Return position where the entry begins, or nil if there is no
  11878. such entry. If narrowing is in effect, only search the visible
  11879. part of the buffer."
  11880. (save-excursion
  11881. (goto-char (point-min))
  11882. (let ((case-fold-search t)
  11883. (re (org-re-property property nil (not value) value)))
  11884. (catch 'exit
  11885. (while (re-search-forward re nil t)
  11886. (when (if value (org-at-property-p)
  11887. (org-entry-get (point) property nil t))
  11888. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  11889. (defun org-delete-property (property)
  11890. "In the current entry, delete PROPERTY."
  11891. (interactive
  11892. (let* ((completion-ignore-case t)
  11893. (cat (org-entry-get (point) "CATEGORY"))
  11894. (props0 (org-entry-properties nil 'standard))
  11895. (props (if cat props0
  11896. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11897. (prop (if (< 1 (length props))
  11898. (completing-read "Property: " props nil t)
  11899. (caar props))))
  11900. (list prop)))
  11901. (if (not property)
  11902. (message "No property to delete in this entry")
  11903. (org-entry-delete nil property)
  11904. (message "Property \"%s\" deleted" property)))
  11905. (defun org-delete-property-globally (property)
  11906. "Remove PROPERTY globally, from all entries.
  11907. This function ignores narrowing, if any."
  11908. (interactive
  11909. (let* ((completion-ignore-case t)
  11910. (prop (completing-read
  11911. "Globally remove property: "
  11912. (mapcar #'list (org-buffer-property-keys)))))
  11913. (list prop)))
  11914. (org-with-wide-buffer
  11915. (goto-char (point-min))
  11916. (let ((count 0)
  11917. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11918. (while (re-search-forward re nil t)
  11919. (when (org-entry-delete (point) property) (cl-incf count)))
  11920. (message "Property \"%s\" removed from %d entries" property count))))
  11921. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11922. (defun org-compute-property-at-point ()
  11923. "Compute the property at point.
  11924. This looks for an enclosing column format, extracts the operator and
  11925. then applies it to the property in the column format's scope."
  11926. (interactive)
  11927. (unless (org-at-property-p)
  11928. (user-error "Not at a property"))
  11929. (let ((prop (match-string-no-properties 2)))
  11930. (org-columns-get-format-and-top-level)
  11931. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11932. (user-error "No operator defined for property %s" prop))
  11933. (org-columns-compute prop)))
  11934. (defvar org-property-allowed-value-functions nil
  11935. "Hook for functions supplying allowed values for a specific property.
  11936. The functions must take a single argument, the name of the property, and
  11937. return a flat list of allowed values. If \":ETC\" is one of
  11938. the values, this means that these values are intended as defaults for
  11939. completion, but that other values should be allowed too.
  11940. The functions must return nil if they are not responsible for this
  11941. property.")
  11942. (defun org-property-get-allowed-values (pom property &optional table)
  11943. "Get allowed values for the property PROPERTY.
  11944. When TABLE is non-nil, return an alist that can directly be used for
  11945. completion."
  11946. (let (vals)
  11947. (cond
  11948. ((equal property "TODO")
  11949. (setq vals (org-with-point-at pom
  11950. (append org-todo-keywords-1 '("")))))
  11951. ((equal property "PRIORITY")
  11952. (let ((n org-priority-lowest))
  11953. (while (>= n org-priority-highest)
  11954. (push (char-to-string n) vals)
  11955. (setq n (1- n)))))
  11956. ((equal property "CATEGORY"))
  11957. ((member property org-special-properties))
  11958. ((setq vals (run-hook-with-args-until-success
  11959. 'org-property-allowed-value-functions property)))
  11960. (t
  11961. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11962. (when (and vals (string-match "\\S-" vals))
  11963. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11964. (setq vals (mapcar (lambda (x)
  11965. (cond ((stringp x) x)
  11966. ((numberp x) (number-to-string x))
  11967. ((symbolp x) (symbol-name x))
  11968. (t "???")))
  11969. vals)))))
  11970. (when (member ":ETC" vals)
  11971. (setq vals (remove ":ETC" vals))
  11972. (org-add-props (car vals) '(org-unrestricted t)))
  11973. (if table (mapcar 'list vals) vals)))
  11974. (defun org-property-previous-allowed-value (&optional _previous)
  11975. "Switch to the next allowed value for this property."
  11976. (interactive)
  11977. (org-property-next-allowed-value t))
  11978. (defun org-property-next-allowed-value (&optional previous)
  11979. "Switch to the next allowed value for this property."
  11980. (interactive)
  11981. (unless (org-at-property-p)
  11982. (user-error "Not at a property"))
  11983. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11984. (key (match-string 2))
  11985. (value (match-string 3))
  11986. (allowed (or (org-property-get-allowed-values (point) key)
  11987. (and (member value '("[ ]" "[-]" "[X]"))
  11988. '("[ ]" "[X]"))))
  11989. (heading (save-match-data (nth 4 (org-heading-components))))
  11990. nval)
  11991. (unless allowed
  11992. (user-error "Allowed values for this property have not been defined"))
  11993. (when previous (setq allowed (reverse allowed)))
  11994. (when (member value allowed)
  11995. (setq nval (car (cdr (member value allowed)))))
  11996. (setq nval (or nval (car allowed)))
  11997. (when (equal nval value)
  11998. (user-error "Only one allowed value for this property"))
  11999. (org-at-property-p)
  12000. (replace-match (concat " :" key ": " nval) t t)
  12001. (org-indent-line)
  12002. (beginning-of-line 1)
  12003. (skip-chars-forward " \t")
  12004. (when (equal prop org-effort-property)
  12005. (org-refresh-property
  12006. '((effort . identity)
  12007. (effort-minutes . org-duration-to-minutes))
  12008. nval)
  12009. (when (string= org-clock-current-task heading)
  12010. (setq org-clock-effort nval)
  12011. (org-clock-update-mode-line)))
  12012. (run-hook-with-args 'org-property-changed-functions key nval)))
  12013. (defun org-find-olp (path &optional this-buffer)
  12014. "Return a marker pointing to the entry at outline path OLP.
  12015. If anything goes wrong, throw an error.
  12016. You can wrap this call to catch the error like this:
  12017. (condition-case msg
  12018. (org-mobile-locate-entry (match-string 4))
  12019. (error (nth 1 msg)))
  12020. The return value will then be either a string with the error message,
  12021. or a marker if everything is OK.
  12022. If THIS-BUFFER is set, the outline path does not contain a file,
  12023. only headings."
  12024. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12025. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12026. (level 1)
  12027. (lmin 1)
  12028. (lmax 1)
  12029. end found flevel)
  12030. (unless buffer (error "File not found :%s" file))
  12031. (with-current-buffer buffer
  12032. (unless (derived-mode-p 'org-mode)
  12033. (error "Buffer %s needs to be in Org mode" buffer))
  12034. (org-with-wide-buffer
  12035. (goto-char (point-min))
  12036. (dolist (heading path)
  12037. (let ((re (format org-complex-heading-regexp-format
  12038. (regexp-quote heading)))
  12039. (cnt 0))
  12040. (while (re-search-forward re end t)
  12041. (setq level (- (match-end 1) (match-beginning 1)))
  12042. (when (and (>= level lmin) (<= level lmax))
  12043. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12044. (when (= cnt 0)
  12045. (error "Heading not found on level %d: %s" lmax heading))
  12046. (when (> cnt 1)
  12047. (error "Heading not unique on level %d: %s" lmax heading))
  12048. (goto-char found)
  12049. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12050. (setq end (save-excursion (org-end-of-subtree t t)))))
  12051. (when (org-at-heading-p)
  12052. (point-marker))))))
  12053. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12054. "Find node HEADING in BUFFER.
  12055. Return a marker to the heading if it was found, or nil if not.
  12056. If POS-ONLY is set, return just the position instead of a marker.
  12057. The heading text must match exact, but it may have a TODO keyword,
  12058. a priority cookie and tags in the standard locations."
  12059. (with-current-buffer (or buffer (current-buffer))
  12060. (org-with-wide-buffer
  12061. (goto-char (point-min))
  12062. (let (case-fold-search)
  12063. (when (re-search-forward
  12064. (format org-complex-heading-regexp-format
  12065. (regexp-quote heading)) nil t)
  12066. (if pos-only
  12067. (match-beginning 0)
  12068. (move-marker (make-marker) (match-beginning 0))))))))
  12069. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12070. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12071. When the target headline is found, return a marker to this location."
  12072. (let ((files (directory-files (or dir default-directory)
  12073. t "\\`[^.#].*\\.org\\'"))
  12074. visiting m buffer)
  12075. (catch 'found
  12076. (dolist (file files)
  12077. (message "trying %s" file)
  12078. (setq visiting (org-find-base-buffer-visiting file))
  12079. (setq buffer (or visiting (find-file-noselect file)))
  12080. (setq m (org-find-exact-headline-in-buffer
  12081. heading buffer))
  12082. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12083. (and m (throw 'found m))))))
  12084. (defun org-find-entry-with-id (ident)
  12085. "Locate the entry that contains the ID property with exact value IDENT.
  12086. IDENT can be a string, a symbol or a number, this function will search for
  12087. the string representation of it.
  12088. Return the position where this entry starts, or nil if there is no such entry."
  12089. (interactive "sID: ")
  12090. (let ((id (cond
  12091. ((stringp ident) ident)
  12092. ((symbolp ident) (symbol-name ident))
  12093. ((numberp ident) (number-to-string ident))
  12094. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12095. (org-with-wide-buffer (org-find-property "ID" id))))
  12096. ;;;; Timestamps
  12097. (defvar org-last-changed-timestamp nil)
  12098. (defvar org-last-inserted-timestamp nil
  12099. "The last time stamp inserted with `org-insert-time-stamp'.")
  12100. (defun org-time-stamp (arg &optional inactive)
  12101. "Prompt for a date/time and insert a time stamp.
  12102. If the user specifies a time like HH:MM or if this command is
  12103. called with at least one prefix argument, the time stamp contains
  12104. the date and the time. Otherwise, only the date is included.
  12105. All parts of a date not specified by the user are filled in from
  12106. the timestamp at point, if any, or the current date/time
  12107. otherwise.
  12108. If there is already a timestamp at the cursor, it is replaced.
  12109. With two universal prefix arguments, insert an active timestamp
  12110. with the current time without prompting the user.
  12111. When called from lisp, the timestamp is inactive if INACTIVE is
  12112. non-nil."
  12113. (interactive "P")
  12114. (let* ((ts (cond
  12115. ((org-at-date-range-p t)
  12116. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12117. ((org-at-timestamp-p 'lax) (match-string 0))))
  12118. ;; Default time is either the timestamp at point or today.
  12119. ;; When entering a range, only the range start is considered.
  12120. (default-time (and ts (org-time-string-to-time ts)))
  12121. (default-input (and ts (org-get-compact-tod ts)))
  12122. (repeater (and ts
  12123. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12124. (match-string 0 ts)))
  12125. org-time-was-given
  12126. org-end-time-was-given
  12127. (time
  12128. (if (equal arg '(16)) (current-time)
  12129. ;; Preserve `this-command' and `last-command'.
  12130. (let ((this-command this-command)
  12131. (last-command last-command))
  12132. (org-read-date
  12133. arg 'totime nil nil default-time default-input
  12134. inactive)))))
  12135. (cond
  12136. ((and ts
  12137. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12138. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12139. (insert "--")
  12140. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12141. (ts
  12142. ;; Make sure we're on a timestamp. When in the middle of a date
  12143. ;; range, move arbitrarily to range end.
  12144. (unless (org-at-timestamp-p 'lax)
  12145. (skip-chars-forward "-")
  12146. (org-at-timestamp-p 'lax))
  12147. (replace-match "")
  12148. (setq org-last-changed-timestamp
  12149. (org-insert-time-stamp
  12150. time (or org-time-was-given arg)
  12151. inactive nil nil (list org-end-time-was-given)))
  12152. (when repeater
  12153. (backward-char)
  12154. (insert " " repeater)
  12155. (setq org-last-changed-timestamp
  12156. (concat (substring org-last-inserted-timestamp 0 -1)
  12157. " " repeater ">")))
  12158. (message "Timestamp updated"))
  12159. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12160. (t (org-insert-time-stamp
  12161. time (or org-time-was-given arg) inactive nil nil
  12162. (list org-end-time-was-given))))))
  12163. ;; FIXME: can we use this for something else, like computing time differences?
  12164. (defun org-get-compact-tod (s)
  12165. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12166. (let* ((t1 (match-string 1 s))
  12167. (h1 (string-to-number (match-string 2 s)))
  12168. (m1 (string-to-number (match-string 3 s)))
  12169. (t2 (and (match-end 4) (match-string 5 s)))
  12170. (h2 (and t2 (string-to-number (match-string 6 s))))
  12171. (m2 (and t2 (string-to-number (match-string 7 s))))
  12172. dh dm)
  12173. (if (not t2)
  12174. t1
  12175. (setq dh (- h2 h1) dm (- m2 m1))
  12176. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12177. (concat t1 "+" (number-to-string dh)
  12178. (and (/= 0 dm) (format ":%02d" dm)))))))
  12179. (defun org-time-stamp-inactive (&optional arg)
  12180. "Insert an inactive time stamp.
  12181. An inactive time stamp is enclosed in square brackets instead of angle
  12182. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12183. does not link to the calendar and cannot be changed with the S-cursor keys.
  12184. So these are more for recording a certain time/date.
  12185. If the user specifies a time like HH:MM or if this command is called with
  12186. at least one prefix argument, the time stamp contains the date and the time.
  12187. Otherwise, only the date is included.
  12188. When called with two universal prefix arguments, insert an active time stamp
  12189. with the current time without prompting the user."
  12190. (interactive "P")
  12191. (org-time-stamp arg 'inactive))
  12192. (defvar org-date-ovl (make-overlay 1 1))
  12193. (overlay-put org-date-ovl 'face 'org-date-selected)
  12194. (delete-overlay org-date-ovl)
  12195. (defvar org-ans1) ; dynamically scoped parameter
  12196. (defvar org-ans2) ; dynamically scoped parameter
  12197. (defvar org-plain-time-of-day-regexp) ; defined below
  12198. (defvar org-overriding-default-time nil) ; dynamically scoped
  12199. (defvar org-read-date-overlay nil)
  12200. (defvar org-read-date-history nil)
  12201. (defvar org-read-date-final-answer nil)
  12202. (defvar org-read-date-analyze-futurep nil)
  12203. (defvar org-read-date-analyze-forced-year nil)
  12204. (defvar org-read-date-inactive)
  12205. (defvar org-def)
  12206. (defvar org-defdecode)
  12207. (defvar org-with-time)
  12208. (defvar calendar-setup) ; Dynamically scoped.
  12209. (defun org-read-date (&optional with-time to-time from-string prompt
  12210. default-time default-input inactive)
  12211. "Read a date, possibly a time, and make things smooth for the user.
  12212. The prompt will suggest to enter an ISO date, but you can also enter anything
  12213. which will at least partially be understood by `parse-time-string'.
  12214. Unrecognized parts of the date will default to the current day, month, year,
  12215. hour and minute. If this command is called to replace a timestamp at point,
  12216. or to enter the second timestamp of a range, the default time is taken
  12217. from the existing stamp. Furthermore, the command prefers the future,
  12218. so if you are giving a date where the year is not given, and the day-month
  12219. combination is already past in the current year, it will assume you
  12220. mean next year. For details, see the manual. A few examples:
  12221. 3-2-5 --> 2003-02-05
  12222. feb 15 --> currentyear-02-15
  12223. 2/15 --> currentyear-02-15
  12224. sep 12 9 --> 2009-09-12
  12225. 12:45 --> today 12:45
  12226. 22 sept 0:34 --> currentyear-09-22 0:34
  12227. 12 --> currentyear-currentmonth-12
  12228. Fri --> nearest Friday after today
  12229. -Tue --> last Tuesday
  12230. etc.
  12231. Furthermore you can specify a relative date by giving, as the *first* thing
  12232. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12233. change in days weeks, months, years.
  12234. With a single plus or minus, the date is relative to today. With a double
  12235. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12236. +4d --> four days from today
  12237. +4 --> same as above
  12238. +2w --> two weeks from today
  12239. ++5 --> five days from default date
  12240. The function understands only English month and weekday abbreviations.
  12241. While prompting, a calendar is popped up - you can also select the
  12242. date with the mouse (button 1). The calendar shows a period of three
  12243. months. To scroll it to other months, use the keys `>' and `<'.
  12244. If you don't like the calendar, turn it off with
  12245. (setq org-read-date-popup-calendar nil)
  12246. With optional argument TO-TIME, the date will immediately be converted
  12247. to an internal time.
  12248. With an optional argument WITH-TIME, the prompt will suggest to
  12249. also insert a time. Note that when WITH-TIME is not set, you can
  12250. still enter a time, and this function will inform the calling routine
  12251. about this change. The calling routine may then choose to change the
  12252. format used to insert the time stamp into the buffer to include the time.
  12253. With optional argument FROM-STRING, read from this string instead from
  12254. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12255. the time/date that is used for everything that is not specified by the
  12256. user."
  12257. (require 'parse-time)
  12258. (let* ((org-with-time with-time)
  12259. (org-time-stamp-rounding-minutes
  12260. (if (equal org-with-time '(16))
  12261. '(0 0)
  12262. org-time-stamp-rounding-minutes))
  12263. (ct (org-current-time))
  12264. (org-def (or org-overriding-default-time default-time ct))
  12265. (org-defdecode (decode-time org-def))
  12266. (cur-frame (selected-frame))
  12267. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12268. (calendar-setup
  12269. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12270. (calendar-move-hook nil)
  12271. (calendar-view-diary-initially-flag nil)
  12272. (calendar-view-holidays-initially-flag nil)
  12273. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12274. ;; Rationalize `org-def' and `org-defdecode', if required.
  12275. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12276. (setf (nth 2 org-defdecode) -1)
  12277. (setf (nth 1 org-defdecode) 59)
  12278. (setq org-def (apply #'encode-time org-defdecode))
  12279. (setq org-defdecode (decode-time org-def)))
  12280. (let* ((timestr (format-time-string
  12281. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12282. org-def))
  12283. (prompt (concat (if prompt (concat prompt " ") "")
  12284. (format "Date+time [%s]: " timestr))))
  12285. (cond
  12286. (from-string (setq ans from-string))
  12287. (org-read-date-popup-calendar
  12288. (save-excursion
  12289. (save-window-excursion
  12290. (calendar)
  12291. (when (eq calendar-setup 'calendar-only)
  12292. (setq cal-frame
  12293. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12294. (select-frame cal-frame))
  12295. (org-eval-in-calendar '(setq cursor-type nil) t)
  12296. (unwind-protect
  12297. (progn
  12298. (calendar-forward-day (- (time-to-days org-def)
  12299. (calendar-absolute-from-gregorian
  12300. (calendar-current-date))))
  12301. (org-eval-in-calendar nil t)
  12302. (let* ((old-map (current-local-map))
  12303. (map (copy-keymap calendar-mode-map))
  12304. (minibuffer-local-map
  12305. (copy-keymap org-read-date-minibuffer-local-map)))
  12306. (org-defkey map (kbd "RET") 'org-calendar-select)
  12307. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12308. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12309. (unwind-protect
  12310. (progn
  12311. (use-local-map map)
  12312. (setq org-read-date-inactive inactive)
  12313. (add-hook 'post-command-hook 'org-read-date-display)
  12314. (setq org-ans0
  12315. (read-string prompt
  12316. default-input
  12317. 'org-read-date-history
  12318. nil))
  12319. ;; org-ans0: from prompt
  12320. ;; org-ans1: from mouse click
  12321. ;; org-ans2: from calendar motion
  12322. (setq ans
  12323. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12324. (remove-hook 'post-command-hook 'org-read-date-display)
  12325. (use-local-map old-map)
  12326. (when org-read-date-overlay
  12327. (delete-overlay org-read-date-overlay)
  12328. (setq org-read-date-overlay nil)))))
  12329. (bury-buffer "*Calendar*")
  12330. (when cal-frame
  12331. (delete-frame cal-frame)
  12332. (select-frame-set-input-focus cur-frame))))))
  12333. (t ; Naked prompt only
  12334. (unwind-protect
  12335. (setq ans (read-string prompt default-input
  12336. 'org-read-date-history timestr))
  12337. (when org-read-date-overlay
  12338. (delete-overlay org-read-date-overlay)
  12339. (setq org-read-date-overlay nil))))))
  12340. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12341. (when org-read-date-analyze-forced-year
  12342. (message "Year was forced into %s"
  12343. (if org-read-date-force-compatible-dates
  12344. "compatible range (1970-2037)"
  12345. "range representable on this machine"))
  12346. (ding))
  12347. (setq final (apply #'encode-time final))
  12348. (setq org-read-date-final-answer ans)
  12349. (if to-time
  12350. final
  12351. ;; This round-trip gets rid of 34th of August and stuff like that....
  12352. (setq final (decode-time final))
  12353. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12354. (format "%04d-%02d-%02d %02d:%02d"
  12355. (nth 5 final) (nth 4 final) (nth 3 final)
  12356. (nth 2 final) (nth 1 final))
  12357. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12358. (defun org-read-date-display ()
  12359. "Display the current date prompt interpretation in the minibuffer."
  12360. (when org-read-date-display-live
  12361. (when org-read-date-overlay
  12362. (delete-overlay org-read-date-overlay))
  12363. (when (minibufferp (current-buffer))
  12364. (save-excursion
  12365. (end-of-line 1)
  12366. (while (not (equal (buffer-substring
  12367. (max (point-min) (- (point) 4)) (point))
  12368. " "))
  12369. (insert " ")))
  12370. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12371. " " (or org-ans1 org-ans2)))
  12372. (org-end-time-was-given nil)
  12373. (f (org-read-date-analyze ans org-def org-defdecode))
  12374. (fmts (if org-display-custom-times
  12375. org-time-stamp-custom-formats
  12376. org-time-stamp-formats))
  12377. (fmt (if (or org-with-time
  12378. (and (boundp 'org-time-was-given) org-time-was-given))
  12379. (cdr fmts)
  12380. (car fmts)))
  12381. (txt (format-time-string fmt (apply #'encode-time f)))
  12382. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12383. (txt (concat "=> " txt)))
  12384. (when (and org-end-time-was-given
  12385. (string-match org-plain-time-of-day-regexp txt))
  12386. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12387. org-end-time-was-given
  12388. (substring txt (match-end 0)))))
  12389. (when org-read-date-analyze-futurep
  12390. (setq txt (concat txt " (=>F)")))
  12391. (setq org-read-date-overlay
  12392. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12393. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12394. (defun org-read-date-analyze (ans def defdecode)
  12395. "Analyze the combined answer of the date prompt."
  12396. ;; FIXME: cleanup and comment
  12397. (let ((org-def def)
  12398. (org-defdecode defdecode)
  12399. (nowdecode (decode-time))
  12400. delta deltan deltaw deltadef year month day
  12401. hour minute second wday pm h2 m2 tl wday1
  12402. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12403. (setq org-read-date-analyze-futurep nil
  12404. org-read-date-analyze-forced-year nil)
  12405. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12406. (setq ans "+0"))
  12407. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12408. (setq ans (replace-match "" t t ans)
  12409. deltan (car delta)
  12410. deltaw (nth 1 delta)
  12411. deltadef (nth 2 delta)))
  12412. ;; Check if there is an iso week date in there. If yes, store the
  12413. ;; info and postpone interpreting it until the rest of the parsing
  12414. ;; is done.
  12415. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12416. (setq iso-year (when (match-end 1)
  12417. (org-small-year-to-year
  12418. (string-to-number (match-string 1 ans))))
  12419. iso-weekday (when (match-end 3)
  12420. (string-to-number (match-string 3 ans)))
  12421. iso-week (string-to-number (match-string 2 ans)))
  12422. (setq ans (replace-match "" t t ans)))
  12423. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12424. (when (string-match
  12425. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12426. (setq year (if (match-end 2)
  12427. (string-to-number (match-string 2 ans))
  12428. (progn (setq kill-year t)
  12429. (string-to-number (format-time-string "%Y"))))
  12430. month (string-to-number (match-string 3 ans))
  12431. day (string-to-number (match-string 4 ans)))
  12432. (setq year (org-small-year-to-year year))
  12433. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12434. t nil ans)))
  12435. ;; Help matching dotted european dates
  12436. (when (string-match
  12437. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12438. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12439. (setq kill-year t)
  12440. (string-to-number (format-time-string "%Y")))
  12441. day (string-to-number (match-string 1 ans))
  12442. month (string-to-number (match-string 2 ans))
  12443. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12444. t nil ans)))
  12445. ;; Help matching american dates, like 5/30 or 5/30/7
  12446. (when (string-match
  12447. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12448. (setq year (if (match-end 4)
  12449. (string-to-number (match-string 4 ans))
  12450. (progn (setq kill-year t)
  12451. (string-to-number (format-time-string "%Y"))))
  12452. month (string-to-number (match-string 1 ans))
  12453. day (string-to-number (match-string 2 ans)))
  12454. (setq year (org-small-year-to-year year))
  12455. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12456. t nil ans)))
  12457. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12458. ;; If there is a time with am/pm, and *no* time without it, we convert
  12459. ;; so that matching will be successful.
  12460. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12461. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12462. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12463. (setq hour (string-to-number (match-string 1 ans))
  12464. minute (if (match-end 3)
  12465. (string-to-number (match-string 3 ans))
  12466. 0)
  12467. pm (equal ?p
  12468. (string-to-char (downcase (match-string 4 ans)))))
  12469. (if (and (= hour 12) (not pm))
  12470. (setq hour 0)
  12471. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12472. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12473. t t ans))))
  12474. ;; Check if a time range is given as a duration
  12475. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12476. (setq hour (string-to-number (match-string 1 ans))
  12477. h2 (+ hour (string-to-number (match-string 3 ans)))
  12478. minute (string-to-number (match-string 2 ans))
  12479. m2 (+ minute (if (match-end 5) (string-to-number
  12480. (match-string 5 ans))0)))
  12481. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12482. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12483. t t ans)))
  12484. ;; Check if there is a time range
  12485. (when (boundp 'org-end-time-was-given)
  12486. (setq org-time-was-given nil)
  12487. (when (and (string-match org-plain-time-of-day-regexp ans)
  12488. (match-end 8))
  12489. (setq org-end-time-was-given (match-string 8 ans))
  12490. (setq ans (concat (substring ans 0 (match-beginning 7))
  12491. (substring ans (match-end 7))))))
  12492. (setq tl (parse-time-string ans)
  12493. day (or (nth 3 tl) (nth 3 org-defdecode))
  12494. month
  12495. (cond ((nth 4 tl))
  12496. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12497. ;; Day was specified. Make sure DAY+MONTH
  12498. ;; combination happens in the future.
  12499. ((nth 3 tl)
  12500. (setq futurep t)
  12501. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12502. (nth 4 nowdecode)))
  12503. (t (nth 4 org-defdecode)))
  12504. year
  12505. (cond ((and (not kill-year) (nth 5 tl)))
  12506. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12507. ;; Month was guessed in the future and is at least
  12508. ;; equal to NOWDECODE's. Fix year accordingly.
  12509. (futurep
  12510. (if (or (> month (nth 4 nowdecode))
  12511. (>= day (nth 3 nowdecode)))
  12512. (nth 5 nowdecode)
  12513. (1+ (nth 5 nowdecode))))
  12514. ;; Month was specified. Make sure MONTH+YEAR
  12515. ;; combination happens in the future.
  12516. ((nth 4 tl)
  12517. (setq futurep t)
  12518. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12519. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12520. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12521. (t (nth 5 nowdecode))))
  12522. (t (nth 5 org-defdecode)))
  12523. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12524. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12525. second (or (nth 0 tl) 0)
  12526. wday (nth 6 tl))
  12527. (when (and (eq org-read-date-prefer-future 'time)
  12528. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12529. (equal day (nth 3 nowdecode))
  12530. (equal month (nth 4 nowdecode))
  12531. (equal year (nth 5 nowdecode))
  12532. (nth 2 tl)
  12533. (or (< (nth 2 tl) (nth 2 nowdecode))
  12534. (and (= (nth 2 tl) (nth 2 nowdecode))
  12535. (nth 1 tl)
  12536. (< (nth 1 tl) (nth 1 nowdecode)))))
  12537. (setq day (1+ day)
  12538. futurep t))
  12539. ;; Special date definitions below
  12540. (cond
  12541. (iso-week
  12542. ;; There was an iso week
  12543. (require 'cal-iso)
  12544. (setq futurep nil)
  12545. (setq year (or iso-year year)
  12546. day (or iso-weekday wday 1)
  12547. wday nil ; to make sure that the trigger below does not match
  12548. iso-date (calendar-gregorian-from-absolute
  12549. (calendar-iso-to-absolute
  12550. (list iso-week day year))))
  12551. ; FIXME: Should we also push ISO weeks into the future?
  12552. ; (when (and org-read-date-prefer-future
  12553. ; (not iso-year)
  12554. ; (< (calendar-absolute-from-gregorian iso-date)
  12555. ; (time-to-days nil)))
  12556. ; (setq year (1+ year)
  12557. ; iso-date (calendar-gregorian-from-absolute
  12558. ; (calendar-iso-to-absolute
  12559. ; (list iso-week day year)))))
  12560. (setq month (car iso-date)
  12561. year (nth 2 iso-date)
  12562. day (nth 1 iso-date)))
  12563. (deltan
  12564. (setq futurep nil)
  12565. (unless deltadef
  12566. (let ((now (decode-time)))
  12567. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12568. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12569. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12570. ((equal deltaw "m") (setq month (+ month deltan)))
  12571. ((equal deltaw "y") (setq year (+ year deltan)))))
  12572. ((and wday (not (nth 3 tl)))
  12573. ;; Weekday was given, but no day, so pick that day in the week
  12574. ;; on or after the derived date.
  12575. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12576. (unless (equal wday wday1)
  12577. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12578. (when (and (boundp 'org-time-was-given)
  12579. (nth 2 tl))
  12580. (setq org-time-was-given t))
  12581. (when (< year 100) (setq year (+ 2000 year)))
  12582. ;; Check of the date is representable
  12583. (if org-read-date-force-compatible-dates
  12584. (progn
  12585. (when (< year 1970)
  12586. (setq year 1970 org-read-date-analyze-forced-year t))
  12587. (when (> year 2037)
  12588. (setq year 2037 org-read-date-analyze-forced-year t)))
  12589. (condition-case nil
  12590. (ignore (encode-time second minute hour day month year))
  12591. (error
  12592. (setq year (nth 5 org-defdecode))
  12593. (setq org-read-date-analyze-forced-year t))))
  12594. (setq org-read-date-analyze-futurep futurep)
  12595. (list second minute hour day month year)))
  12596. (defvar parse-time-weekdays)
  12597. (defun org-read-date-get-relative (s today default)
  12598. "Check string S for special relative date string.
  12599. TODAY and DEFAULT are internal times, for today and for a default.
  12600. Return shift list (N what def-flag)
  12601. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12602. N is the number of WHATs to shift.
  12603. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12604. the DEFAULT date rather than TODAY."
  12605. (require 'parse-time)
  12606. (when (and
  12607. (string-match
  12608. (concat
  12609. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12610. "\\([0-9]+\\)?"
  12611. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12612. "\\([ \t]\\|$\\)") s)
  12613. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12614. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12615. (string-to-char (substring (match-string 1 s) -1))
  12616. ?+))
  12617. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12618. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12619. (what (if (match-end 3) (match-string 3 s) "d"))
  12620. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12621. (date (if rel default today))
  12622. (wday (nth 6 (decode-time date)))
  12623. delta)
  12624. (if wday1
  12625. (progn
  12626. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12627. (when (= delta 0) (setq delta 7))
  12628. (when (= dir ?-)
  12629. (setq delta (- delta 7))
  12630. (when (= delta 0) (setq delta -7)))
  12631. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12632. (list delta "d" rel))
  12633. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12634. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12635. "Turn a user-specified date into the internal representation.
  12636. The internal representation needed by the calendar is (month day year).
  12637. This is a wrapper to handle the brain-dead convention in calendar that
  12638. user function argument order change dependent on argument order."
  12639. (pcase calendar-date-style
  12640. (`american (list arg1 arg2 arg3))
  12641. (`european (list arg2 arg1 arg3))
  12642. (`iso (list arg2 arg3 arg1))))
  12643. (defun org-eval-in-calendar (form &optional keepdate)
  12644. "Eval FORM in the calendar window and return to current window.
  12645. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12646. (let ((sf (selected-frame))
  12647. (sw (selected-window)))
  12648. (select-window (get-buffer-window "*Calendar*" t))
  12649. (eval form)
  12650. (when (and (not keepdate) (calendar-cursor-to-date))
  12651. (let* ((date (calendar-cursor-to-date))
  12652. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12653. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12654. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12655. (select-window sw)
  12656. (select-frame-set-input-focus sf)))
  12657. (defun org-calendar-select ()
  12658. "Return to `org-read-date' with the date currently selected.
  12659. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12660. (interactive)
  12661. (when (calendar-cursor-to-date)
  12662. (let* ((date (calendar-cursor-to-date))
  12663. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12664. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12665. (when (active-minibuffer-window) (exit-minibuffer))))
  12666. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12667. "Insert a date stamp for the date given by the internal TIME.
  12668. See `format-time-string' for the format of TIME.
  12669. WITH-HM means use the stamp format that includes the time of the day.
  12670. INACTIVE means use square brackets instead of angular ones, so that the
  12671. stamp will not contribute to the agenda.
  12672. PRE and POST are optional strings to be inserted before and after the
  12673. stamp.
  12674. The command returns the inserted time stamp."
  12675. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12676. stamp)
  12677. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12678. (insert-before-markers (or pre ""))
  12679. (when (listp extra)
  12680. (setq extra (car extra))
  12681. (if (and (stringp extra)
  12682. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12683. (setq extra (format "-%02d:%02d"
  12684. (string-to-number (match-string 1 extra))
  12685. (string-to-number (match-string 2 extra))))
  12686. (setq extra nil)))
  12687. (when extra
  12688. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12689. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12690. (insert-before-markers (or post ""))
  12691. (setq org-last-inserted-timestamp stamp)))
  12692. (defun org-toggle-time-stamp-overlays ()
  12693. "Toggle the use of custom time stamp formats."
  12694. (interactive)
  12695. (setq org-display-custom-times (not org-display-custom-times))
  12696. (unless org-display-custom-times
  12697. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12698. (while (setq p (next-single-property-change p 'display))
  12699. (when (and (get-text-property p 'display)
  12700. (eq (get-text-property p 'face) 'org-date))
  12701. (remove-text-properties
  12702. p (setq p (next-single-property-change p 'display))
  12703. '(display t))))
  12704. (set-buffer-modified-p bmp)))
  12705. (org-restart-font-lock)
  12706. (setq org-table-may-need-update t)
  12707. (if org-display-custom-times
  12708. (message "Time stamps are overlaid with custom format")
  12709. (message "Time stamp overlays removed")))
  12710. (defun org-display-custom-time (beg end)
  12711. "Overlay modified time stamp format over timestamp between BEG and END."
  12712. (let* ((ts (buffer-substring beg end))
  12713. t1 with-hm tf time str (off 0))
  12714. (save-match-data
  12715. (setq t1 (org-parse-time-string ts t))
  12716. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12717. (setq off (- (match-end 0) (match-beginning 0)))))
  12718. (setq end (- end off))
  12719. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12720. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12721. time (org-fix-decoded-time t1)
  12722. str (org-add-props
  12723. (format-time-string
  12724. (substring tf 1 -1) (apply 'encode-time time))
  12725. nil 'mouse-face 'highlight))
  12726. (put-text-property beg end 'display str)))
  12727. (defun org-fix-decoded-time (time)
  12728. "Set 0 instead of nil for the first 6 elements of time.
  12729. Don't touch the rest."
  12730. (let ((n 0))
  12731. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12732. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12733. "Difference between TIMESTAMP-STRING and now in days.
  12734. If SECONDS is non-nil, return the difference in seconds."
  12735. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12736. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12737. (funcall fdiff nil))))
  12738. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12739. "Is the time in TIMESTAMP-STRING close to the current date?"
  12740. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12741. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12742. (not (org-entry-is-done-p))))
  12743. (defun org-get-wdays (ts &optional delay zero-delay)
  12744. "Get the deadline lead time appropriate for timestring TS.
  12745. When DELAY is non-nil, get the delay time for scheduled items
  12746. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12747. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12748. don't try to find the delay cookie in the scheduled timestamp."
  12749. (let ((tv (if delay org-scheduled-delay-days
  12750. org-deadline-warning-days)))
  12751. (cond
  12752. ((or (and delay (< tv 0))
  12753. (and delay zero-delay (<= tv 0))
  12754. (and (not delay) (<= tv 0)))
  12755. ;; Enforce this value no matter what
  12756. (- tv))
  12757. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12758. ;; lead time is specified.
  12759. (floor (* (string-to-number (match-string 1 ts))
  12760. (cdr (assoc (match-string 2 ts)
  12761. '(("d" . 1) ("w" . 7)
  12762. ("m" . 30.4) ("y" . 365.25)
  12763. ("h" . 0.041667)))))))
  12764. ;; go for the default.
  12765. (t tv))))
  12766. (defun org-calendar-select-mouse (ev)
  12767. "Return to `org-read-date' with the date currently selected.
  12768. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12769. (interactive "e")
  12770. (mouse-set-point ev)
  12771. (when (calendar-cursor-to-date)
  12772. (let* ((date (calendar-cursor-to-date))
  12773. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12774. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12775. (when (active-minibuffer-window) (exit-minibuffer))))
  12776. (defun org-check-deadlines (ndays)
  12777. "Check if there are any deadlines due or past due.
  12778. A deadline is considered due if it happens within `org-deadline-warning-days'
  12779. days from today's date. If the deadline appears in an entry marked DONE,
  12780. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12781. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12782. are shown."
  12783. (interactive "P")
  12784. (let* ((org-warn-days
  12785. (cond
  12786. ((equal ndays '(4)) 100000)
  12787. (ndays (prefix-numeric-value ndays))
  12788. (t (abs org-deadline-warning-days))))
  12789. (case-fold-search nil)
  12790. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12791. (callback
  12792. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12793. (message "%d deadlines past-due or due within %d days"
  12794. (org-occur regexp nil callback)
  12795. org-warn-days)))
  12796. (defsubst org-re-timestamp (type)
  12797. "Return a regexp for timestamp TYPE.
  12798. Allowed values for TYPE are:
  12799. all: all timestamps
  12800. active: only active timestamps (<...>)
  12801. inactive: only inactive timestamps ([...])
  12802. scheduled: only scheduled timestamps
  12803. deadline: only deadline timestamps
  12804. closed: only closed time-stamps
  12805. When TYPE is nil, fall back on returning a regexp that matches
  12806. both scheduled and deadline timestamps."
  12807. (cl-case type
  12808. (all org-ts-regexp-both)
  12809. (active org-ts-regexp)
  12810. (inactive org-ts-regexp-inactive)
  12811. (scheduled org-scheduled-time-regexp)
  12812. (deadline org-deadline-time-regexp)
  12813. (closed org-closed-time-regexp)
  12814. (otherwise
  12815. (concat "\\<"
  12816. (regexp-opt (list org-deadline-string org-scheduled-string))
  12817. " *<\\([^>]+\\)>"))))
  12818. (defun org-check-before-date (d)
  12819. "Check if there are deadlines or scheduled entries before date D."
  12820. (interactive (list (org-read-date)))
  12821. (let* ((case-fold-search nil)
  12822. (regexp (org-re-timestamp org-ts-type))
  12823. (ts-type org-ts-type)
  12824. (callback
  12825. (lambda ()
  12826. (let ((match (match-string 1)))
  12827. (and (if (memq ts-type '(active inactive all))
  12828. (eq (org-element-type (save-excursion
  12829. (backward-char)
  12830. (org-element-context)))
  12831. 'timestamp)
  12832. (org-at-planning-p))
  12833. (time-less-p
  12834. (org-time-string-to-time match)
  12835. (org-time-string-to-time d)))))))
  12836. (message "%d entries before %s"
  12837. (org-occur regexp nil callback)
  12838. d)))
  12839. (defun org-check-after-date (d)
  12840. "Check if there are deadlines or scheduled entries after date D."
  12841. (interactive (list (org-read-date)))
  12842. (let* ((case-fold-search nil)
  12843. (regexp (org-re-timestamp org-ts-type))
  12844. (ts-type org-ts-type)
  12845. (callback
  12846. (lambda ()
  12847. (let ((match (match-string 1)))
  12848. (and (if (memq ts-type '(active inactive all))
  12849. (eq (org-element-type (save-excursion
  12850. (backward-char)
  12851. (org-element-context)))
  12852. 'timestamp)
  12853. (org-at-planning-p))
  12854. (not (time-less-p
  12855. (org-time-string-to-time match)
  12856. (org-time-string-to-time d))))))))
  12857. (message "%d entries after %s"
  12858. (org-occur regexp nil callback)
  12859. d)))
  12860. (defun org-check-dates-range (start-date end-date)
  12861. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12862. (interactive (list (org-read-date nil nil nil "Range starts")
  12863. (org-read-date nil nil nil "Range end")))
  12864. (let ((case-fold-search nil)
  12865. (regexp (org-re-timestamp org-ts-type))
  12866. (callback
  12867. (let ((type org-ts-type))
  12868. (lambda ()
  12869. (let ((match (match-string 1)))
  12870. (and
  12871. (if (memq type '(active inactive all))
  12872. (eq (org-element-type (save-excursion
  12873. (backward-char)
  12874. (org-element-context)))
  12875. 'timestamp)
  12876. (org-at-planning-p))
  12877. (not (time-less-p
  12878. (org-time-string-to-time match)
  12879. (org-time-string-to-time start-date)))
  12880. (time-less-p
  12881. (org-time-string-to-time match)
  12882. (org-time-string-to-time end-date))))))))
  12883. (message "%d entries between %s and %s"
  12884. (org-occur regexp nil callback) start-date end-date)))
  12885. (defun org-evaluate-time-range (&optional to-buffer)
  12886. "Evaluate a time range by computing the difference between start and end.
  12887. Normally the result is just printed in the echo area, but with prefix arg
  12888. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12889. If the time range is actually in a table, the result is inserted into the
  12890. next column.
  12891. For time difference computation, a year is assumed to be exactly 365
  12892. days in order to avoid rounding problems."
  12893. (interactive "P")
  12894. (or
  12895. (org-clock-update-time-maybe)
  12896. (save-excursion
  12897. (unless (org-at-date-range-p t)
  12898. (goto-char (point-at-bol))
  12899. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12900. (unless (org-at-date-range-p t)
  12901. (user-error "Not at a time-stamp range, and none found in current line")))
  12902. (let* ((ts1 (match-string 1))
  12903. (ts2 (match-string 2))
  12904. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12905. (match-end (match-end 0))
  12906. (time1 (org-time-string-to-time ts1))
  12907. (time2 (org-time-string-to-time ts2))
  12908. (diff (abs (float-time (time-subtract time2 time1))))
  12909. (negative (time-less-p time2 time1))
  12910. ;; (ys (floor (* 365 24 60 60)))
  12911. (ds (* 24 60 60))
  12912. (hs (* 60 60))
  12913. (fy "%dy %dd %02d:%02d")
  12914. (fy1 "%dy %dd")
  12915. (fd "%dd %02d:%02d")
  12916. (fd1 "%dd")
  12917. (fh "%02d:%02d")
  12918. y d h m align)
  12919. (if havetime
  12920. (setq ; y (floor diff ys) diff (mod diff ys)
  12921. y 0
  12922. d (floor diff ds) diff (mod diff ds)
  12923. h (floor diff hs) diff (mod diff hs)
  12924. m (floor diff 60))
  12925. (setq ; y (floor diff ys) diff (mod diff ys)
  12926. y 0
  12927. d (round diff ds)
  12928. h 0 m 0))
  12929. (if (not to-buffer)
  12930. (message "%s" (org-make-tdiff-string y d h m))
  12931. (if (org-at-table-p)
  12932. (progn
  12933. (goto-char match-end)
  12934. (setq align t)
  12935. (and (looking-at " *|") (goto-char (match-end 0))))
  12936. (goto-char match-end))
  12937. (when (looking-at
  12938. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12939. (replace-match ""))
  12940. (when negative (insert " -"))
  12941. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12942. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12943. (insert " " (format fh h m))))
  12944. (when align (org-table-align))
  12945. (message "Time difference inserted")))))
  12946. (defun org-make-tdiff-string (y d h m)
  12947. (let ((fmt "")
  12948. (l nil))
  12949. (when (> y 0)
  12950. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12951. (push y l))
  12952. (when (> d 0)
  12953. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12954. (push d l))
  12955. (when (> h 0)
  12956. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12957. (push h l))
  12958. (when (> m 0)
  12959. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12960. (push m l))
  12961. (apply 'format fmt (nreverse l))))
  12962. (defun org-time-string-to-time (s)
  12963. "Convert timestamp string S into internal time."
  12964. (apply #'encode-time (org-parse-time-string s)))
  12965. (defun org-time-string-to-seconds (s)
  12966. "Convert a timestamp string S into a number of seconds."
  12967. (float-time (org-time-string-to-time s)))
  12968. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12969. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12970. "Convert time stamp S to an absolute day number.
  12971. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12972. stamp, get the closest date to DAYNR. If PREFER is
  12973. `past' (respectively `future') return a date past (respectively
  12974. after) or equal to DAYNR.
  12975. POS is the location of time stamp S, as a buffer position in
  12976. BUFFER.
  12977. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12978. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12979. signaled."
  12980. (cond
  12981. ((string-match "\\`%%\\((.*)\\)" s)
  12982. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  12983. ;; only able to match individual dates. If it fails, raise an
  12984. ;; error.
  12985. (if (and daynr
  12986. (org-diary-sexp-entry
  12987. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  12988. daynr
  12989. (signal 'org-diary-sexp-no-match (list s))))
  12990. (daynr (org-closest-date s daynr prefer))
  12991. (t (time-to-days
  12992. (condition-case errdata
  12993. (org-time-string-to-time s)
  12994. (error (error "Bad timestamp `%s'%s\nError was: %s"
  12995. s
  12996. (if (not (and buffer pos)) ""
  12997. (format-message " at %d in buffer `%s'" pos buffer))
  12998. (cdr errdata))))))))
  12999. (defun org-days-to-iso-week (days)
  13000. "Return the iso week number."
  13001. (require 'cal-iso)
  13002. (car (calendar-iso-from-absolute days)))
  13003. (defun org-small-year-to-year (year)
  13004. "Convert 2-digit years into 4-digit years.
  13005. YEAR is expanded into one of the 30 next years, if possible, or
  13006. into a past one. Any year larger than 99 is returned unchanged."
  13007. (if (>= year 100) year
  13008. (let* ((current (string-to-number (format-time-string "%Y")))
  13009. (century (/ current 100))
  13010. (offset (- year (% current 100))))
  13011. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13012. ((> offset -70) (+ (* century 100) year))
  13013. (t (+ (* (1+ century) 100) year))))))
  13014. (defun org-time-from-absolute (d)
  13015. "Return the time corresponding to date D.
  13016. D may be an absolute day number, or a calendar-type list (month day year)."
  13017. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13018. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13019. (defvar org-agenda-current-date)
  13020. (defun org-calendar-holiday ()
  13021. "List of holidays, for Diary display in Org mode."
  13022. (require 'holidays)
  13023. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13024. (and hl (mapconcat #'identity hl "; "))))
  13025. (defun org-diary-sexp-entry (sexp entry d)
  13026. "Process a SEXP diary ENTRY for date D."
  13027. (require 'diary-lib)
  13028. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13029. ;; dynamically.
  13030. (let* ((sexp `(let ((entry ,entry)
  13031. (date ',d))
  13032. ,(car (read-from-string sexp))))
  13033. (result (if calendar-debug-sexp (eval sexp)
  13034. (condition-case nil
  13035. (eval sexp)
  13036. (error
  13037. (beep)
  13038. (message "Bad sexp at line %d in %s: %s"
  13039. (org-current-line)
  13040. (buffer-file-name) sexp)
  13041. (sleep-for 2))))))
  13042. (cond ((stringp result) (split-string result "; "))
  13043. ((and (consp result)
  13044. (not (consp (cdr result)))
  13045. (stringp (cdr result))) (cdr result))
  13046. ((and (consp result)
  13047. (stringp (car result))) result)
  13048. (result entry))))
  13049. (defun org-diary-to-ical-string (frombuf)
  13050. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13051. This uses the icalendar.el library."
  13052. (let* ((tmpdir temporary-file-directory)
  13053. (tmpfile (make-temp-name
  13054. (expand-file-name "orgics" tmpdir)))
  13055. buf rtn b e)
  13056. (with-current-buffer frombuf
  13057. (icalendar-export-region (point-min) (point-max) tmpfile)
  13058. (setq buf (find-buffer-visiting tmpfile))
  13059. (set-buffer buf)
  13060. (goto-char (point-min))
  13061. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13062. (setq b (match-beginning 0)))
  13063. (goto-char (point-max))
  13064. (when (re-search-backward "^END:VEVENT" nil t)
  13065. (setq e (match-end 0)))
  13066. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13067. (kill-buffer buf)
  13068. (delete-file tmpfile)
  13069. rtn))
  13070. (defun org-closest-date (start current prefer)
  13071. "Return closest date to CURRENT starting from START.
  13072. CURRENT and START are both time stamps.
  13073. When PREFER is `past', return a date that is either CURRENT or
  13074. past. When PREFER is `future', return a date that is either
  13075. CURRENT or future.
  13076. Only time stamps with a repeater are modified. Any other time
  13077. stamp stay unchanged. In any case, return value is an absolute
  13078. day number."
  13079. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13080. ;; No repeater. Do not shift time stamp.
  13081. (time-to-days (org-time-string-to-time start))
  13082. (let ((value (string-to-number (match-string 1 start)))
  13083. (type (match-string 2 start)))
  13084. (if (= 0 value)
  13085. ;; Repeater with a 0-value is considered as void.
  13086. (time-to-days (org-time-string-to-time start))
  13087. (let* ((base (org-date-to-gregorian start))
  13088. (target (org-date-to-gregorian current))
  13089. (sday (calendar-absolute-from-gregorian base))
  13090. (cday (calendar-absolute-from-gregorian target))
  13091. n1 n2)
  13092. ;; If START is already past CURRENT, just return START.
  13093. (if (<= cday sday) sday
  13094. ;; Compute closest date before (N1) and closest date past
  13095. ;; (N2) CURRENT.
  13096. (pcase type
  13097. ("h"
  13098. (let ((missing-hours
  13099. (mod (+ (- (* 24 (- cday sday))
  13100. (nth 2 (org-parse-time-string start)))
  13101. org-extend-today-until)
  13102. value)))
  13103. (setf n1 (if (= missing-hours 0) cday
  13104. (- cday (1+ (/ missing-hours 24)))))
  13105. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13106. ((or "d" "w")
  13107. (let ((value (if (equal type "w") (* 7 value) value)))
  13108. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13109. (setf n2 (+ n1 value))))
  13110. ("m"
  13111. (let* ((add-months
  13112. (lambda (d n)
  13113. ;; Add N months to gregorian date D, i.e.,
  13114. ;; a list (MONTH DAY YEAR). Return a valid
  13115. ;; gregorian date.
  13116. (let ((m (+ (nth 0 d) n)))
  13117. (list (mod m 12)
  13118. (nth 1 d)
  13119. (+ (/ m 12) (nth 2 d))))))
  13120. (months ; Complete months to TARGET.
  13121. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13122. (- (nth 0 target) (nth 0 base))
  13123. ;; If START's day is greater than
  13124. ;; TARGET's, remove incomplete month.
  13125. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13126. value)
  13127. value))
  13128. (before (funcall add-months base months)))
  13129. (setf n1 (calendar-absolute-from-gregorian before))
  13130. (setf n2
  13131. (calendar-absolute-from-gregorian
  13132. (funcall add-months before value)))))
  13133. (_
  13134. (let* ((d (nth 1 base))
  13135. (m (nth 0 base))
  13136. (y (nth 2 base))
  13137. (years ; Complete years to TARGET.
  13138. (* (/ (- (nth 2 target)
  13139. y
  13140. ;; If START's month and day are
  13141. ;; greater than TARGET's, remove
  13142. ;; incomplete year.
  13143. (if (or (> (nth 0 target) m)
  13144. (and (= (nth 0 target) m)
  13145. (> (nth 1 target) d)))
  13146. 0
  13147. 1))
  13148. value)
  13149. value))
  13150. (before (list m d (+ y years))))
  13151. (setf n1 (calendar-absolute-from-gregorian before))
  13152. (setf n2 (calendar-absolute-from-gregorian
  13153. (list m d (+ (nth 2 before) value)))))))
  13154. ;; Handle PREFER parameter, if any.
  13155. (cond
  13156. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13157. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13158. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13159. (defun org-date-to-gregorian (d)
  13160. "Turn any specification of date D into a Gregorian date for the calendar."
  13161. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13162. ((and (listp d) (= (length d) 3)) d)
  13163. ((stringp d)
  13164. (let ((d (org-parse-time-string d)))
  13165. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13166. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13167. (defun org-timestamp-up (&optional arg)
  13168. "Increase the date item at the cursor by one.
  13169. If the cursor is on the year, change the year. If it is on the month,
  13170. the day or the time, change that. If the cursor is on the enclosing
  13171. bracket, change the timestamp type.
  13172. With prefix ARG, change by that many units."
  13173. (interactive "p")
  13174. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13175. (defun org-timestamp-down (&optional arg)
  13176. "Decrease the date item at the cursor by one.
  13177. If the cursor is on the year, change the year. If it is on the month,
  13178. the day or the time, change that. If the cursor is on the enclosing
  13179. bracket, change the timestamp type.
  13180. With prefix ARG, change by that many units."
  13181. (interactive "p")
  13182. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13183. (defun org-timestamp-up-day (&optional arg)
  13184. "Increase the date in the time stamp by one day.
  13185. With prefix ARG, change that many days."
  13186. (interactive "p")
  13187. (if (and (not (org-at-timestamp-p 'lax))
  13188. (org-at-heading-p))
  13189. (org-todo 'up)
  13190. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13191. (defun org-timestamp-down-day (&optional arg)
  13192. "Decrease the date in the time stamp by one day.
  13193. With prefix ARG, change that many days."
  13194. (interactive "p")
  13195. (if (and (not (org-at-timestamp-p 'lax))
  13196. (org-at-heading-p))
  13197. (org-todo 'down)
  13198. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13199. (defun org-at-timestamp-p (&optional extended)
  13200. "Non-nil if point is inside a timestamp.
  13201. By default, the function only consider syntactically valid active
  13202. timestamps. However, the caller may have a broader definition
  13203. for timestamps. As a consequence, optional argument EXTENDED can
  13204. be set to the following values
  13205. `inactive'
  13206. Include also syntactically valid inactive timestamps.
  13207. `agenda'
  13208. Include timestamps allowed in Agenda, i.e., those in
  13209. properties drawers, planning lines and clock lines.
  13210. `lax'
  13211. Ignore context. The function matches any part of the
  13212. document looking like a timestamp. This includes comments,
  13213. example blocks...
  13214. For backward-compatibility with Org 9.0, every other non-nil
  13215. value is equivalent to `inactive'.
  13216. When at a timestamp, return the position of the point as a symbol
  13217. among `bracket', `after', `year', `month', `hour', `minute',
  13218. `day' or a number of character from the last know part of the
  13219. time stamp.
  13220. When matching, the match groups are the following:
  13221. group 1: year
  13222. group 2: month
  13223. group 3: day number
  13224. group 4: day name
  13225. group 5: hours, if any
  13226. group 6: minutes, if any"
  13227. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13228. (pos (point))
  13229. (match?
  13230. (let ((boundaries (org-in-regexp regexp)))
  13231. (save-match-data
  13232. (cond ((null boundaries) nil)
  13233. ((eq extended 'lax) t)
  13234. (t
  13235. (or (and (eq extended 'agenda)
  13236. (or (org-at-planning-p)
  13237. (org-at-property-p)
  13238. (and (bound-and-true-p
  13239. org-agenda-include-inactive-timestamps)
  13240. (org-at-clock-log-p))))
  13241. (eq 'timestamp
  13242. (save-excursion
  13243. (when (= pos (cdr boundaries)) (forward-char -1))
  13244. (org-element-type (org-element-context)))))))))))
  13245. (cond
  13246. ((not match?) nil)
  13247. ((= pos (match-beginning 0)) 'bracket)
  13248. ;; Distinguish location right before the closing bracket from
  13249. ;; right after it.
  13250. ((= pos (1- (match-end 0))) 'bracket)
  13251. ((= pos (match-end 0)) 'after)
  13252. ((org-pos-in-match-range pos 2) 'year)
  13253. ((org-pos-in-match-range pos 3) 'month)
  13254. ((org-pos-in-match-range pos 7) 'hour)
  13255. ((org-pos-in-match-range pos 8) 'minute)
  13256. ((or (org-pos-in-match-range pos 4)
  13257. (org-pos-in-match-range pos 5)) 'day)
  13258. ((and (> pos (or (match-end 8) (match-end 5)))
  13259. (< pos (match-end 0)))
  13260. (- pos (or (match-end 8) (match-end 5))))
  13261. (t 'day))))
  13262. (defun org-toggle-timestamp-type ()
  13263. "Toggle the type (<active> or [inactive]) of a time stamp."
  13264. (interactive)
  13265. (when (org-at-timestamp-p 'lax)
  13266. (let ((beg (match-beginning 0)) (end (match-end 0))
  13267. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13268. (save-excursion
  13269. (goto-char beg)
  13270. (while (re-search-forward "[][<>]" end t)
  13271. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13272. t t)))
  13273. (message "Timestamp is now %sactive"
  13274. (if (equal (char-after beg) ?<) "" "in")))))
  13275. (defun org-at-clock-log-p ()
  13276. "Non-nil if point is on a clock log line."
  13277. (and (org-match-line org-clock-line-re)
  13278. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13279. (defvar org-clock-history) ; defined in org-clock.el
  13280. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13281. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13282. "Change the date in the time stamp at point.
  13283. The date is changed by N times WHAT. WHAT can be `day', `month',
  13284. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13285. position in the timestamp determines what is changed.
  13286. When optional argument UPDOWN is non-nil, minutes are rounded
  13287. according to `org-time-stamp-rounding-minutes'.
  13288. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13289. \"--2d\"."
  13290. (let ((origin (point))
  13291. (timestamp? (org-at-timestamp-p 'lax))
  13292. origin-cat
  13293. with-hm inactive
  13294. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13295. extra rem
  13296. ts time time0 fixnext clrgx)
  13297. (unless timestamp? (user-error "Not at a timestamp"))
  13298. (if (and (not what) (eq timestamp? 'bracket))
  13299. (org-toggle-timestamp-type)
  13300. ;; Point isn't on brackets. Remember the part of the time-stamp
  13301. ;; the point was in. Indeed, size of time-stamps may change,
  13302. ;; but point must be kept in the same category nonetheless.
  13303. (setq origin-cat timestamp?)
  13304. (when (and (not what) (not (eq timestamp? 'day))
  13305. org-display-custom-times
  13306. (get-text-property (point) 'display)
  13307. (not (get-text-property (1- (point)) 'display)))
  13308. (setq timestamp? 'day))
  13309. (setq timestamp? (or what timestamp?)
  13310. inactive (= (char-after (match-beginning 0)) ?\[)
  13311. ts (match-string 0))
  13312. (replace-match "")
  13313. (when (string-match
  13314. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13315. ts)
  13316. (setq extra (match-string 1 ts))
  13317. (when suppress-tmp-delay
  13318. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13319. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13320. (setq with-hm t))
  13321. (setq time0 (org-parse-time-string ts))
  13322. (when (and updown
  13323. (eq timestamp? 'minute)
  13324. (not current-prefix-arg))
  13325. ;; This looks like s-up and s-down. Change by one rounding step.
  13326. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13327. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13328. (setcar (cdr time0) (+ (nth 1 time0)
  13329. (if (> n 0) (- rem) (- dm rem))))))
  13330. (setq time
  13331. (apply #'encode-time
  13332. (or (car time0) 0)
  13333. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13334. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13335. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13336. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13337. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13338. (nthcdr 6 time0)))
  13339. (when (and (memq timestamp? '(hour minute))
  13340. extra
  13341. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13342. (setq extra (org-modify-ts-extra
  13343. extra
  13344. (if (eq timestamp? 'hour) 2 5)
  13345. n dm)))
  13346. (when (integerp timestamp?)
  13347. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13348. (when (eq what 'calendar)
  13349. (let ((cal-date (org-get-date-from-calendar)))
  13350. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13351. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13352. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13353. (setcar time0 (or (car time0) 0))
  13354. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13355. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13356. (setq time (apply 'encode-time time0))))
  13357. ;; Insert the new time-stamp, and ensure point stays in the same
  13358. ;; category as before (i.e. not after the last position in that
  13359. ;; category).
  13360. (let ((pos (point)))
  13361. ;; Stay before inserted string. `save-excursion' is of no use.
  13362. (setq org-last-changed-timestamp
  13363. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13364. (goto-char pos))
  13365. (save-match-data
  13366. (looking-at org-ts-regexp3)
  13367. (goto-char
  13368. (pcase origin-cat
  13369. ;; `day' category ends before `hour' if any, or at the end
  13370. ;; of the day name.
  13371. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13372. (`hour (min (match-end 7) origin))
  13373. (`minute (min (1- (match-end 8)) origin))
  13374. ((pred integerp) (min (1- (match-end 0)) origin))
  13375. ;; Point was right after the time-stamp. However, the
  13376. ;; time-stamp length might have changed, so refer to
  13377. ;; (match-end 0) instead.
  13378. (`after (match-end 0))
  13379. ;; `year' and `month' have both fixed size: point couldn't
  13380. ;; have moved into another part.
  13381. (_ origin))))
  13382. ;; Update clock if on a CLOCK line.
  13383. (org-clock-update-time-maybe)
  13384. ;; Maybe adjust the closest clock in `org-clock-history'
  13385. (when org-clock-adjust-closest
  13386. (if (not (and (org-at-clock-log-p)
  13387. (< 1 (length (delq nil (mapcar 'marker-position
  13388. org-clock-history))))))
  13389. (message "No clock to adjust")
  13390. (cond ((save-excursion ; fix previous clock?
  13391. (re-search-backward org-ts-regexp0 nil t)
  13392. (looking-back (concat org-clock-string " \\[")
  13393. (line-beginning-position)))
  13394. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13395. ((save-excursion ; fix next clock?
  13396. (re-search-backward org-ts-regexp0 nil t)
  13397. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13398. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13399. (save-window-excursion
  13400. ;; Find closest clock to point, adjust the previous/next one in history
  13401. (let* ((p (save-excursion (org-back-to-heading t)))
  13402. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13403. (clfixnth
  13404. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13405. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13406. (if (not clfixpos)
  13407. (message "No clock to adjust")
  13408. (save-excursion
  13409. (org-goto-marker-or-bmk clfixpos)
  13410. (org-show-subtree)
  13411. (when (re-search-forward clrgx nil t)
  13412. (goto-char (match-beginning 1))
  13413. (let (org-clock-adjust-closest)
  13414. (org-timestamp-change n timestamp? updown))
  13415. (message "Clock adjusted in %s for heading: %s"
  13416. (file-name-nondirectory (buffer-file-name))
  13417. (org-get-heading t t)))))))))
  13418. ;; Try to recenter the calendar window, if any.
  13419. (when (and org-calendar-follow-timestamp-change
  13420. (get-buffer-window "*Calendar*" t)
  13421. (memq timestamp? '(day month year)))
  13422. (org-recenter-calendar (time-to-days time))))))
  13423. (defun org-modify-ts-extra (s pos n dm)
  13424. "Change the different parts of the lead-time and repeat fields in timestamp."
  13425. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13426. ng h m new rem)
  13427. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13428. (cond
  13429. ((or (org-pos-in-match-range pos 2)
  13430. (org-pos-in-match-range pos 3))
  13431. (setq m (string-to-number (match-string 3 s))
  13432. h (string-to-number (match-string 2 s)))
  13433. (if (org-pos-in-match-range pos 2)
  13434. (setq h (+ h n))
  13435. (setq n (* dm (with-no-warnings (cl-signum n))))
  13436. (unless (= 0 (setq rem (% m dm)))
  13437. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13438. (setq m (+ m n)))
  13439. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13440. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13441. (setq h (mod h 24))
  13442. (setq ng 1 new (format "-%02d:%02d" h m)))
  13443. ((org-pos-in-match-range pos 6)
  13444. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13445. ((org-pos-in-match-range pos 5)
  13446. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13447. ((org-pos-in-match-range pos 9)
  13448. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13449. ((org-pos-in-match-range pos 8)
  13450. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13451. (when ng
  13452. (setq s (concat
  13453. (substring s 0 (match-beginning ng))
  13454. new
  13455. (substring s (match-end ng))))))
  13456. s))
  13457. (defun org-recenter-calendar (d)
  13458. "If the calendar is visible, recenter it to date D."
  13459. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13460. (when cwin
  13461. (let ((calendar-move-hook nil))
  13462. (with-selected-window cwin
  13463. (calendar-goto-date
  13464. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13465. (defun org-goto-calendar (&optional arg)
  13466. "Go to the Emacs calendar at the current date.
  13467. If there is a time stamp in the current line, go to that date.
  13468. A prefix ARG can be used to force the current date."
  13469. (interactive "P")
  13470. (let ((calendar-move-hook nil)
  13471. (calendar-view-holidays-initially-flag nil)
  13472. (calendar-view-diary-initially-flag nil)
  13473. diff)
  13474. (when (or (org-at-timestamp-p 'lax)
  13475. (org-match-line (concat ".*" org-ts-regexp)))
  13476. (let ((d1 (time-to-days nil))
  13477. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13478. (setq diff (- d2 d1))))
  13479. (calendar)
  13480. (calendar-goto-today)
  13481. (when (and diff (not arg)) (calendar-forward-day diff))))
  13482. (defun org-get-date-from-calendar ()
  13483. "Return a list (month day year) of date at point in calendar."
  13484. (with-current-buffer "*Calendar*"
  13485. (save-match-data
  13486. (calendar-cursor-to-date))))
  13487. (defun org-date-from-calendar ()
  13488. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13489. If there is already a time stamp at the cursor position, update it."
  13490. (interactive)
  13491. (if (org-at-timestamp-p 'lax)
  13492. (org-timestamp-change 0 'calendar)
  13493. (let ((cal-date (org-get-date-from-calendar)))
  13494. (org-insert-time-stamp
  13495. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13496. (defcustom org-image-actual-width t
  13497. "When non-nil, use the actual width of images when inlining them.
  13498. When set to a number, use imagemagick (when available) to set the
  13499. image's width to this value.
  13500. When set to a number in a list, try to get the width from any
  13501. #+ATTR.* keyword if it matches a width specification like
  13502. #+ATTR_HTML: :width 300px
  13503. and fall back on that number if none is found.
  13504. When set to nil, try to get the width from an #+ATTR.* keyword
  13505. and fall back on the original width if none is found.
  13506. When set to any other non-nil value, always use the image width.
  13507. This requires Emacs >= 24.1, built with imagemagick support."
  13508. :group 'org-appearance
  13509. :version "24.4"
  13510. :package-version '(Org . "8.0")
  13511. :type '(choice
  13512. (const :tag "Use the image width" t)
  13513. (integer :tag "Use a number of pixels")
  13514. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13515. (const :tag "Use #+ATTR* or don't resize" nil)))
  13516. (defcustom org-agenda-inhibit-startup nil
  13517. "Inhibit startup when preparing agenda buffers.
  13518. When this variable is t, the initialization of the Org agenda
  13519. buffers is inhibited: e.g. the visibility state is not set, the
  13520. tables are not re-aligned, etc."
  13521. :type 'boolean
  13522. :version "24.3"
  13523. :group 'org-agenda)
  13524. (defcustom org-agenda-ignore-properties nil
  13525. "Avoid updating text properties when building the agenda.
  13526. Properties are used to prepare buffers for effort estimates,
  13527. appointments, statistics and subtree-local categories.
  13528. If you don't use these in the agenda, you can add them to this
  13529. list and agenda building will be a bit faster.
  13530. The value is a list, with zero or more of the symbols `effort', `appt',
  13531. `stats' or `category'."
  13532. :type '(set :greedy t
  13533. (const effort)
  13534. (const appt)
  13535. (const stats)
  13536. (const category))
  13537. :version "26.1"
  13538. :package-version '(Org . "8.3")
  13539. :group 'org-agenda)
  13540. ;;;; Files
  13541. (defun org-save-all-org-buffers ()
  13542. "Save all Org buffers without user confirmation."
  13543. (interactive)
  13544. (message "Saving all Org buffers...")
  13545. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13546. (when (featurep 'org-id) (org-id-locations-save))
  13547. (message "Saving all Org buffers... done"))
  13548. (defun org-revert-all-org-buffers ()
  13549. "Revert all Org buffers.
  13550. Prompt for confirmation when there are unsaved changes.
  13551. Be sure you know what you are doing before letting this function
  13552. overwrite your changes.
  13553. This function is useful in a setup where one tracks Org files
  13554. with a version control system, to revert on one machine after pulling
  13555. changes from another. I believe the procedure must be like this:
  13556. 1. M-x org-save-all-org-buffers
  13557. 2. Pull changes from the other machine, resolve conflicts
  13558. 3. M-x org-revert-all-org-buffers"
  13559. (interactive)
  13560. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13561. (user-error "Abort"))
  13562. (save-excursion
  13563. (save-window-excursion
  13564. (dolist (b (buffer-list))
  13565. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13566. (with-current-buffer b buffer-file-name))
  13567. (pop-to-buffer-same-window b)
  13568. (revert-buffer t 'no-confirm)))
  13569. (when (and (featurep 'org-id) org-id-track-globally)
  13570. (org-id-locations-load)))))
  13571. ;;;; Agenda files
  13572. ;;;###autoload
  13573. (defun org-switchb (&optional arg)
  13574. "Switch between Org buffers.
  13575. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13576. With `\\[universal-argument] \\[universal-argument]' \
  13577. prefix, restrict available buffers to agenda files."
  13578. (interactive "P")
  13579. (let ((blist (org-buffer-list
  13580. (cond ((equal arg '(4)) 'files)
  13581. ((equal arg '(16)) 'agenda)))))
  13582. (pop-to-buffer-same-window
  13583. (completing-read "Org buffer: "
  13584. (mapcar #'list (mapcar #'buffer-name blist))
  13585. nil t))))
  13586. (defun org-buffer-list (&optional predicate exclude-tmp)
  13587. "Return a list of Org buffers.
  13588. PREDICATE can be `export', `files' or `agenda'.
  13589. export restrict the list to Export buffers.
  13590. files restrict the list to buffers visiting Org files.
  13591. agenda restrict the list to buffers visiting agenda files.
  13592. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13593. (let* ((bfn nil)
  13594. (agenda-files (and (eq predicate 'agenda)
  13595. (mapcar 'file-truename (org-agenda-files t))))
  13596. (filter
  13597. (cond
  13598. ((eq predicate 'files)
  13599. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13600. ((eq predicate 'export)
  13601. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13602. ((eq predicate 'agenda)
  13603. (lambda (b)
  13604. (with-current-buffer b
  13605. (and (derived-mode-p 'org-mode)
  13606. (setq bfn (buffer-file-name b))
  13607. (member (file-truename bfn) agenda-files)))))
  13608. (t (lambda (b) (with-current-buffer b
  13609. (or (derived-mode-p 'org-mode)
  13610. (string-match "\\*Org .*Export"
  13611. (buffer-name b)))))))))
  13612. (delq nil
  13613. (mapcar
  13614. (lambda(b)
  13615. (if (and (funcall filter b)
  13616. (or (not exclude-tmp)
  13617. (not (string-match "tmp" (buffer-name b)))))
  13618. b
  13619. nil))
  13620. (buffer-list)))))
  13621. (defun org-agenda-files (&optional unrestricted archives)
  13622. "Get the list of agenda files.
  13623. Optional UNRESTRICTED means return the full list even if a restriction
  13624. is currently in place.
  13625. When ARCHIVES is t, include all archive files that are really being
  13626. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13627. `org-agenda-archives-mode' is t."
  13628. (let ((files
  13629. (cond
  13630. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13631. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13632. ((listp org-agenda-files) org-agenda-files)
  13633. (t (error "Invalid value of `org-agenda-files'")))))
  13634. (setq files (apply 'append
  13635. (mapcar (lambda (f)
  13636. (if (file-directory-p f)
  13637. (directory-files
  13638. f t org-agenda-file-regexp)
  13639. (list f)))
  13640. files)))
  13641. (when org-agenda-skip-unavailable-files
  13642. (setq files (delq nil
  13643. (mapcar (function
  13644. (lambda (file)
  13645. (and (file-readable-p file) file)))
  13646. files))))
  13647. (when (or (eq archives t)
  13648. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13649. (setq files (org-add-archive-files files)))
  13650. files))
  13651. (defun org-agenda-file-p (&optional file)
  13652. "Return non-nil, if FILE is an agenda file.
  13653. If FILE is omitted, use the file associated with the current
  13654. buffer."
  13655. (let ((fname (or file (buffer-file-name))))
  13656. (and fname
  13657. (member (file-truename fname)
  13658. (mapcar #'file-truename (org-agenda-files t))))))
  13659. (defun org-edit-agenda-file-list ()
  13660. "Edit the list of agenda files.
  13661. Depending on setup, this either uses customize to edit the variable
  13662. `org-agenda-files', or it visits the file that is holding the list. In the
  13663. latter case, the buffer is set up in a way that saving it automatically kills
  13664. the buffer and restores the previous window configuration."
  13665. (interactive)
  13666. (if (stringp org-agenda-files)
  13667. (let ((cw (current-window-configuration)))
  13668. (find-file org-agenda-files)
  13669. (setq-local org-window-configuration cw)
  13670. (add-hook 'after-save-hook
  13671. (lambda ()
  13672. (set-window-configuration
  13673. (prog1 org-window-configuration
  13674. (kill-buffer (current-buffer))))
  13675. (org-install-agenda-files-menu)
  13676. (message "New agenda file list installed"))
  13677. nil 'local)
  13678. (message "%s" (substitute-command-keys
  13679. "Edit list and finish with \\[save-buffer]")))
  13680. (customize-variable 'org-agenda-files)))
  13681. (defun org-store-new-agenda-file-list (list)
  13682. "Set new value for the agenda file list and save it correctly."
  13683. (if (stringp org-agenda-files)
  13684. (let ((fe (org-read-agenda-file-list t)) b u)
  13685. (while (setq b (find-buffer-visiting org-agenda-files))
  13686. (kill-buffer b))
  13687. (with-temp-file org-agenda-files
  13688. (insert
  13689. (mapconcat
  13690. (lambda (f) ;; Keep un-expanded entries.
  13691. (if (setq u (assoc f fe))
  13692. (cdr u)
  13693. f))
  13694. list "\n")
  13695. "\n")))
  13696. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13697. (org-insert-mode-line-in-empty-file nil))
  13698. (setq org-agenda-files list)
  13699. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13700. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13701. "Read the list of agenda files from a file.
  13702. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13703. filenames, used by `org-store-new-agenda-file-list' to write back
  13704. un-expanded file names."
  13705. (when (file-directory-p org-agenda-files)
  13706. (error "`org-agenda-files' cannot be a single directory"))
  13707. (when (stringp org-agenda-files)
  13708. (with-temp-buffer
  13709. (insert-file-contents org-agenda-files)
  13710. (mapcar
  13711. (lambda (f)
  13712. (let ((e (expand-file-name (substitute-in-file-name f)
  13713. org-directory)))
  13714. (if pair-with-expansion
  13715. (cons e f)
  13716. e)))
  13717. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13718. ;;;###autoload
  13719. (defun org-cycle-agenda-files ()
  13720. "Cycle through the files in `org-agenda-files'.
  13721. If the current buffer visits an agenda file, find the next one in the list.
  13722. If the current buffer does not, find the first agenda file."
  13723. (interactive)
  13724. (let* ((fs (or (org-agenda-files t)
  13725. (user-error "No agenda files")))
  13726. (files (copy-sequence fs))
  13727. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13728. file)
  13729. (when tcf
  13730. (while (and (setq file (pop files))
  13731. (not (equal (file-truename file) tcf)))))
  13732. (find-file (car (or files fs)))
  13733. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13734. (defun org-agenda-file-to-front (&optional to-end)
  13735. "Move/add the current file to the top of the agenda file list.
  13736. If the file is not present in the list, it is added to the front. If it is
  13737. present, it is moved there. With optional argument TO-END, add/move to the
  13738. end of the list."
  13739. (interactive "P")
  13740. (let ((org-agenda-skip-unavailable-files nil)
  13741. (file-alist (mapcar (lambda (x)
  13742. (cons (file-truename x) x))
  13743. (org-agenda-files t)))
  13744. (ctf (file-truename
  13745. (or buffer-file-name
  13746. (user-error "Please save the current buffer to a file"))))
  13747. x had)
  13748. (setq x (assoc ctf file-alist) had x)
  13749. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13750. (if to-end
  13751. (setq file-alist (append (delq x file-alist) (list x)))
  13752. (setq file-alist (cons x (delq x file-alist))))
  13753. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13754. (org-install-agenda-files-menu)
  13755. (message "File %s to %s of agenda file list"
  13756. (if had "moved" "added") (if to-end "end" "front"))))
  13757. (defun org-remove-file (&optional file)
  13758. "Remove current file from the list of files in variable `org-agenda-files'.
  13759. These are the files which are being checked for agenda entries.
  13760. Optional argument FILE means use this file instead of the current."
  13761. (interactive)
  13762. (let* ((org-agenda-skip-unavailable-files nil)
  13763. (file (or file buffer-file-name
  13764. (user-error "Current buffer does not visit a file")))
  13765. (true-file (file-truename file))
  13766. (afile (abbreviate-file-name file))
  13767. (files (delq nil (mapcar
  13768. (lambda (x)
  13769. (unless (equal true-file
  13770. (file-truename x))
  13771. x))
  13772. (org-agenda-files t)))))
  13773. (if (not (= (length files) (length (org-agenda-files t))))
  13774. (progn
  13775. (org-store-new-agenda-file-list files)
  13776. (org-install-agenda-files-menu)
  13777. (message "Removed from Org Agenda list: %s" afile))
  13778. (message "File was not in list: %s (not removed)" afile))))
  13779. (defun org-file-menu-entry (file)
  13780. (vector file (list 'find-file file) t))
  13781. (defun org-check-agenda-file (file)
  13782. "Make sure FILE exists. If not, ask user what to do."
  13783. (unless (file-exists-p file)
  13784. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13785. (abbreviate-file-name file))
  13786. (let ((r (downcase (read-char-exclusive))))
  13787. (cond
  13788. ((equal r ?r)
  13789. (org-remove-file file)
  13790. (throw 'nextfile t))
  13791. (t (user-error "Abort"))))))
  13792. (defun org-get-agenda-file-buffer (file)
  13793. "Get an agenda buffer visiting FILE.
  13794. If the buffer needs to be created, add it to the list of buffers
  13795. which might be released later."
  13796. (let ((buf (org-find-base-buffer-visiting file)))
  13797. (if buf
  13798. buf ; just return it
  13799. ;; Make a new buffer and remember it
  13800. (setq buf (find-file-noselect file))
  13801. (when buf (push buf org-agenda-new-buffers))
  13802. buf)))
  13803. (defun org-release-buffers (blist)
  13804. "Release all buffers in list, asking the user for confirmation when needed.
  13805. When a buffer is unmodified, it is just killed. When modified, it is saved
  13806. \(if the user agrees) and then killed."
  13807. (let (file)
  13808. (dolist (buf blist)
  13809. (setq file (buffer-file-name buf))
  13810. (when (and (buffer-modified-p buf)
  13811. file
  13812. (y-or-n-p (format "Save file %s? " file)))
  13813. (with-current-buffer buf (save-buffer)))
  13814. (kill-buffer buf))))
  13815. (defun org-agenda-prepare-buffers (files)
  13816. "Create buffers for all agenda files, protect archived trees and comments."
  13817. (interactive)
  13818. (let ((pa '(:org-archived t))
  13819. (pc '(:org-comment t))
  13820. (pall '(:org-archived t :org-comment t))
  13821. (inhibit-read-only t)
  13822. (org-inhibit-startup org-agenda-inhibit-startup)
  13823. (rea (org-make-tag-string (list org-archive-tag)))
  13824. re pos)
  13825. (setq org-tag-alist-for-agenda nil
  13826. org-tag-groups-alist-for-agenda nil)
  13827. (save-excursion
  13828. (save-restriction
  13829. (dolist (file files)
  13830. (catch 'nextfile
  13831. (if (bufferp file)
  13832. (set-buffer file)
  13833. (org-check-agenda-file file)
  13834. (set-buffer (org-get-agenda-file-buffer file)))
  13835. (widen)
  13836. (org-set-regexps-and-options 'tags-only)
  13837. (setq pos (point))
  13838. (or (memq 'category org-agenda-ignore-properties)
  13839. (org-refresh-category-properties))
  13840. (or (memq 'stats org-agenda-ignore-properties)
  13841. (org-refresh-stats-properties))
  13842. (or (memq 'effort org-agenda-ignore-properties)
  13843. (org-refresh-effort-properties))
  13844. (or (memq 'appt org-agenda-ignore-properties)
  13845. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13846. (setq org-todo-keywords-for-agenda
  13847. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13848. (setq org-done-keywords-for-agenda
  13849. (append org-done-keywords-for-agenda org-done-keywords))
  13850. (setq org-todo-keyword-alist-for-agenda
  13851. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13852. (setq org-tag-alist-for-agenda
  13853. (org--tag-add-to-alist
  13854. org-tag-alist-for-agenda
  13855. org-current-tag-alist))
  13856. ;; Merge current file's tag groups into global
  13857. ;; `org-tag-groups-alist-for-agenda'.
  13858. (when org-group-tags
  13859. (dolist (alist org-tag-groups-alist)
  13860. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13861. (if old
  13862. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13863. (push alist org-tag-groups-alist-for-agenda)))))
  13864. (with-silent-modifications
  13865. (save-excursion
  13866. (remove-text-properties (point-min) (point-max) pall)
  13867. (when org-agenda-skip-archived-trees
  13868. (goto-char (point-min))
  13869. (while (re-search-forward rea nil t)
  13870. (when (org-at-heading-p t)
  13871. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  13872. (goto-char (point-min))
  13873. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  13874. (while (re-search-forward re nil t)
  13875. (when (save-match-data (org-in-commented-heading-p t))
  13876. (add-text-properties
  13877. (match-beginning 0) (org-end-of-subtree t) pc)))))
  13878. (goto-char pos)))))
  13879. (setq org-todo-keywords-for-agenda
  13880. (org-uniquify org-todo-keywords-for-agenda))
  13881. (setq org-todo-keyword-alist-for-agenda
  13882. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13883. ;;;; CDLaTeX minor mode
  13884. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13885. "Keymap for the minor `org-cdlatex-mode'.")
  13886. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13887. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13888. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13889. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13890. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13891. (defvar org-cdlatex-texmathp-advice-is-done nil
  13892. "Flag remembering if we have applied the advice to texmathp already.")
  13893. (define-minor-mode org-cdlatex-mode
  13894. "Toggle the minor `org-cdlatex-mode'.
  13895. This mode supports entering LaTeX environment and math in LaTeX fragments
  13896. in Org mode.
  13897. \\{org-cdlatex-mode-map}"
  13898. nil " OCDL" nil
  13899. (when org-cdlatex-mode
  13900. (require 'cdlatex)
  13901. (run-hooks 'cdlatex-mode-hook)
  13902. (cdlatex-compute-tables))
  13903. (unless org-cdlatex-texmathp-advice-is-done
  13904. (setq org-cdlatex-texmathp-advice-is-done t)
  13905. (defadvice texmathp (around org-math-always-on activate)
  13906. "Always return t in Org buffers.
  13907. This is because we want to insert math symbols without dollars even outside
  13908. the LaTeX math segments. If Org mode thinks that point is actually inside
  13909. an embedded LaTeX fragment, let `texmathp' do its job.
  13910. `\\[org-cdlatex-mode-map]'"
  13911. (interactive)
  13912. (let (p)
  13913. (cond
  13914. ((not (derived-mode-p 'org-mode)) ad-do-it)
  13915. ((eq this-command 'cdlatex-math-symbol)
  13916. (setq ad-return-value t
  13917. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  13918. (t
  13919. (let ((p (org-inside-LaTeX-fragment-p)))
  13920. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  13921. (setq ad-return-value t
  13922. texmathp-why '("Org mode embedded math" . 0))
  13923. (when p ad-do-it)))))))))
  13924. (defun turn-on-org-cdlatex ()
  13925. "Unconditionally turn on `org-cdlatex-mode'."
  13926. (org-cdlatex-mode 1))
  13927. (defun org-try-cdlatex-tab ()
  13928. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13929. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13930. - inside a LaTeX fragment, or
  13931. - after the first word in a line, where an abbreviation expansion could
  13932. insert a LaTeX environment."
  13933. (when org-cdlatex-mode
  13934. (cond
  13935. ;; Before any word on the line: No expansion possible.
  13936. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13937. ;; Just after first word on the line: Expand it. Make sure it
  13938. ;; cannot happen on headlines, though.
  13939. ((save-excursion
  13940. (skip-chars-backward "a-zA-Z0-9*")
  13941. (skip-chars-backward " \t")
  13942. (and (bolp) (not (org-at-heading-p))))
  13943. (cdlatex-tab) t)
  13944. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13945. (defun org-cdlatex-underscore-caret (&optional _arg)
  13946. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13947. Revert to the normal definition outside of these fragments."
  13948. (interactive "P")
  13949. (if (org-inside-LaTeX-fragment-p)
  13950. (call-interactively 'cdlatex-sub-superscript)
  13951. (let (org-cdlatex-mode)
  13952. (call-interactively (key-binding (vector last-input-event))))))
  13953. (defun org-cdlatex-math-modify (&optional _arg)
  13954. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13955. Revert to the normal definition outside of these fragments."
  13956. (interactive "P")
  13957. (if (org-inside-LaTeX-fragment-p)
  13958. (call-interactively 'cdlatex-math-modify)
  13959. (let (org-cdlatex-mode)
  13960. (call-interactively (key-binding (vector last-input-event))))))
  13961. (defun org-cdlatex-environment-indent (&optional environment item)
  13962. "Execute `cdlatex-environment' and indent the inserted environment.
  13963. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13964. The inserted environment is indented to current indentation
  13965. unless point is at the beginning of the line, in which the
  13966. environment remains unintended."
  13967. (interactive)
  13968. ;; cdlatex-environment always return nil. Therefore, capture output
  13969. ;; first and determine if an environment was selected.
  13970. (let* ((beg (point-marker))
  13971. (end (copy-marker (point) t))
  13972. (inserted (progn
  13973. (ignore-errors (cdlatex-environment environment item))
  13974. (< beg end)))
  13975. ;; Figure out how many lines to move forward after the
  13976. ;; environment has been inserted.
  13977. (lines (when inserted
  13978. (save-excursion
  13979. (- (cl-loop while (< beg (point))
  13980. with x = 0
  13981. do (forward-line -1)
  13982. (cl-incf x)
  13983. finally return x)
  13984. (if (progn (goto-char beg)
  13985. (and (progn (skip-chars-forward " \t") (eolp))
  13986. (progn (skip-chars-backward " \t") (bolp))))
  13987. 1 0)))))
  13988. (env (org-trim (delete-and-extract-region beg end))))
  13989. (when inserted
  13990. ;; Get indentation of next line unless at column 0.
  13991. (let ((ind (if (bolp) 0
  13992. (save-excursion
  13993. (org-return-indent)
  13994. (prog1 (current-indentation)
  13995. (when (progn (skip-chars-forward " \t") (eolp))
  13996. (delete-region beg (point)))))))
  13997. (bol (progn (skip-chars-backward " \t") (bolp))))
  13998. ;; Insert a newline before environment unless at column zero
  13999. ;; to "escape" the current line. Insert a newline if
  14000. ;; something is one the same line as \end{ENVIRONMENT}.
  14001. (insert
  14002. (concat (unless bol "\n") env
  14003. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14004. (unless (zerop ind)
  14005. (save-excursion
  14006. (goto-char beg)
  14007. (while (< (point) end)
  14008. (unless (eolp) (indent-line-to ind))
  14009. (forward-line))))
  14010. (goto-char beg)
  14011. (forward-line lines)
  14012. (indent-line-to ind)))
  14013. (set-marker beg nil)
  14014. (set-marker end nil)))
  14015. ;;;; LaTeX fragments
  14016. (defun org-inside-LaTeX-fragment-p ()
  14017. "Test if point is inside a LaTeX fragment.
  14018. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14019. sequence appearing also before point.
  14020. Even though the matchers for math are configurable, this function assumes
  14021. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14022. delimiters are skipped when they have been removed by customization.
  14023. The return value is nil, or a cons cell with the delimiter and the
  14024. position of this delimiter.
  14025. This function does a reasonably good job, but can locally be fooled by
  14026. for example currency specifications. For example it will assume being in
  14027. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14028. fragments that are properly closed, but during editing, we have to live
  14029. with the uncertainty caused by missing closing delimiters. This function
  14030. looks only before point, not after."
  14031. (catch 'exit
  14032. (let ((pos (point))
  14033. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14034. (lim (save-excursion (org-backward-paragraph) (point)))
  14035. dd-on str (start 0) m re)
  14036. (goto-char pos)
  14037. (when dodollar
  14038. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14039. re (nth 1 (assoc "$" org-latex-regexps)))
  14040. (while (string-match re str start)
  14041. (cond
  14042. ((= (match-end 0) (length str))
  14043. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14044. ((= (match-end 0) (- (length str) 5))
  14045. (throw 'exit nil))
  14046. (t (setq start (match-end 0))))))
  14047. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14048. (goto-char pos)
  14049. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14050. (and (match-beginning 2) (throw 'exit nil))
  14051. ;; count $$
  14052. (while (re-search-backward "\\$\\$" lim t)
  14053. (setq dd-on (not dd-on)))
  14054. (goto-char pos)
  14055. (when dd-on (cons "$$" m))))))
  14056. (defun org-inside-latex-macro-p ()
  14057. "Is point inside a LaTeX macro or its arguments?"
  14058. (save-match-data
  14059. (org-in-regexp
  14060. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14061. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14062. "Build an overlay between BEG and END using IMAGE file.
  14063. Argument IMAGETYPE is the extension of the displayed image,
  14064. as a string. It defaults to \"png\"."
  14065. (let ((ov (make-overlay beg end))
  14066. (imagetype (or (intern imagetype) 'png)))
  14067. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14068. (overlay-put ov 'evaporate t)
  14069. (overlay-put ov
  14070. 'modification-hooks
  14071. (list (lambda (o _flag _beg _end &optional _l)
  14072. (delete-overlay o))))
  14073. (overlay-put ov
  14074. 'display
  14075. (list 'image :type imagetype :file image :ascent 'center))))
  14076. (defun org-clear-latex-preview (&optional beg end)
  14077. "Remove all overlays with LaTeX fragment images in current buffer.
  14078. When optional arguments BEG and END are non-nil, remove all
  14079. overlays between them instead. Return a non-nil value when some
  14080. overlays were removed, nil otherwise."
  14081. (let ((overlays
  14082. (cl-remove-if-not
  14083. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14084. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14085. (mapc #'delete-overlay overlays)
  14086. overlays))
  14087. (defun org--latex-preview-region (beg end)
  14088. "Preview LaTeX fragments between BEG and END.
  14089. BEG and END are buffer positions."
  14090. (let ((file (buffer-file-name (buffer-base-buffer))))
  14091. (save-excursion
  14092. (org-format-latex
  14093. (concat org-preview-latex-image-directory "org-ltximg")
  14094. beg end
  14095. ;; Emacs cannot overlay images from remote hosts. Create it in
  14096. ;; `temporary-file-directory' instead.
  14097. (if (or (not file) (file-remote-p file))
  14098. temporary-file-directory
  14099. default-directory)
  14100. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14101. (defun org-latex-preview (&optional arg)
  14102. "Toggle preview of the LaTeX fragment at point.
  14103. If the cursor is on a LaTeX fragment, create the image and
  14104. overlay it over the source code, if there is none. Remove it
  14105. otherwise. If there is no fragment at point, display images for
  14106. all fragments in the current section.
  14107. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14108. for all fragments
  14109. in the current section.
  14110. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14111. argument ARG, display image for all
  14112. fragments in the buffer.
  14113. With a `\\[universal-argument] \\[universal-argument] \
  14114. \\[universal-argument]' prefix argument ARG, clear image for all
  14115. fragments in the buffer."
  14116. (interactive "P")
  14117. (cond
  14118. ((not (display-graphic-p)) nil)
  14119. ;; Clear whole buffer.
  14120. ((equal arg '(64))
  14121. (org-clear-latex-preview (point-min) (point-max))
  14122. (message "LaTeX previews removed from buffer"))
  14123. ;; Preview whole buffer.
  14124. ((equal arg '(16))
  14125. (message "Creating LaTeX previews in buffer...")
  14126. (org--latex-preview-region (point-min) (point-max))
  14127. (message "Creating LaTeX previews in buffer... done."))
  14128. ;; Clear current section.
  14129. ((equal arg '(4))
  14130. (org-clear-latex-preview
  14131. (if (org-before-first-heading-p) (point-min)
  14132. (save-excursion
  14133. (org-with-limited-levels (org-back-to-heading t) (point))))
  14134. (org-with-limited-levels (org-entry-end-position))))
  14135. ;; Toggle preview on LaTeX code at point.
  14136. ((let ((datum (org-element-context)))
  14137. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14138. (let ((beg (org-element-property :begin datum))
  14139. (end (org-element-property :end datum)))
  14140. (if (org-clear-latex-preview beg end)
  14141. (message "LaTeX preview removed")
  14142. (message "Creating LaTeX preview...")
  14143. (org--latex-preview-region beg end)
  14144. (message "Creating LaTeX preview... done."))
  14145. t))))
  14146. ;; Preview current section.
  14147. (t
  14148. (let ((beg (if (org-before-first-heading-p) (point-min)
  14149. (save-excursion
  14150. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14151. (end (org-with-limited-levels (org-entry-end-position))))
  14152. (message "Creating LaTeX previews in section...")
  14153. (org--latex-preview-region beg end)
  14154. (message "Creating LaTeX previews in section... done.")))))
  14155. (defun org-format-latex
  14156. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14157. "Replace LaTeX fragments with links to an image.
  14158. The function takes care of creating the replacement image.
  14159. Only consider fragments between BEG and END when those are
  14160. provided.
  14161. When optional argument OVERLAYS is non-nil, display the image on
  14162. top of the fragment instead of replacing it.
  14163. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14164. Some of the options can be changed using the variable
  14165. `org-format-latex-options', which see."
  14166. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14167. (unless (eq processing-type 'verbatim)
  14168. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14169. (cnt 0)
  14170. checkdir-flag)
  14171. (goto-char (or beg (point-min)))
  14172. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14173. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14174. (overlay-recenter (or end (point-max))))
  14175. (while (re-search-forward math-regexp end t)
  14176. (unless (and overlays
  14177. (eq (get-char-property (point) 'org-overlay-type)
  14178. 'org-latex-overlay))
  14179. (let* ((context (org-element-context))
  14180. (type (org-element-type context)))
  14181. (when (memq type '(latex-environment latex-fragment))
  14182. (let ((block-type (eq type 'latex-environment))
  14183. (value (org-element-property :value context))
  14184. (beg (org-element-property :begin context))
  14185. (end (save-excursion
  14186. (goto-char (org-element-property :end context))
  14187. (skip-chars-backward " \r\t\n")
  14188. (point))))
  14189. (cond
  14190. ((eq processing-type 'mathjax)
  14191. ;; Prepare for MathJax processing.
  14192. (if (not (string-match "\\`\\$\\$?" value))
  14193. (goto-char end)
  14194. (delete-region beg end)
  14195. (if (string= (match-string 0 value) "$$")
  14196. (insert "\\[" (substring value 2 -2) "\\]")
  14197. (insert "\\(" (substring value 1 -1) "\\)"))))
  14198. ((assq processing-type org-preview-latex-process-alist)
  14199. ;; Process to an image.
  14200. (cl-incf cnt)
  14201. (goto-char beg)
  14202. (let* ((processing-info
  14203. (cdr (assq processing-type org-preview-latex-process-alist)))
  14204. (face (face-at-point))
  14205. ;; Get the colors from the face at point.
  14206. (fg
  14207. (let ((color (plist-get org-format-latex-options
  14208. :foreground)))
  14209. (if (and forbuffer (eq color 'auto))
  14210. (face-attribute face :foreground nil 'default)
  14211. color)))
  14212. (bg
  14213. (let ((color (plist-get org-format-latex-options
  14214. :background)))
  14215. (if (and forbuffer (eq color 'auto))
  14216. (face-attribute face :background nil 'default)
  14217. color)))
  14218. (hash (sha1 (prin1-to-string
  14219. (list org-format-latex-header
  14220. org-latex-default-packages-alist
  14221. org-latex-packages-alist
  14222. org-format-latex-options
  14223. forbuffer value fg bg))))
  14224. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14225. (absprefix (expand-file-name prefix dir))
  14226. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14227. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14228. (sep (and block-type "\n\n"))
  14229. (link (concat sep "[[file:" linkfile "]]" sep))
  14230. (options
  14231. (org-combine-plists
  14232. org-format-latex-options
  14233. `(:foreground ,fg :background ,bg))))
  14234. (when msg (message msg cnt))
  14235. (unless checkdir-flag ; Ensure the directory exists.
  14236. (setq checkdir-flag t)
  14237. (let ((todir (file-name-directory absprefix)))
  14238. (unless (file-directory-p todir)
  14239. (make-directory todir t))))
  14240. (unless (file-exists-p movefile)
  14241. (org-create-formula-image
  14242. value movefile options forbuffer processing-type))
  14243. (if overlays
  14244. (progn
  14245. (dolist (o (overlays-in beg end))
  14246. (when (eq (overlay-get o 'org-overlay-type)
  14247. 'org-latex-overlay)
  14248. (delete-overlay o)))
  14249. (org--make-preview-overlay beg end movefile imagetype)
  14250. (goto-char end))
  14251. (delete-region beg end)
  14252. (insert
  14253. (org-add-props link
  14254. (list 'org-latex-src
  14255. (replace-regexp-in-string "\"" "" value)
  14256. 'org-latex-src-embed-type
  14257. (if block-type 'paragraph 'character)))))))
  14258. ((eq processing-type 'mathml)
  14259. ;; Process to MathML.
  14260. (unless (org-format-latex-mathml-available-p)
  14261. (user-error "LaTeX to MathML converter not configured"))
  14262. (cl-incf cnt)
  14263. (when msg (message msg cnt))
  14264. (goto-char beg)
  14265. (delete-region beg end)
  14266. (insert (org-format-latex-as-mathml
  14267. value block-type prefix dir)))
  14268. (t
  14269. (error "Unknown conversion process %s for LaTeX fragments"
  14270. processing-type)))))))))))
  14271. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14272. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14273. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14274. successful, return the portion between \"<math...> </math>\"
  14275. elements otherwise return nil. When MATHML-FILE is specified,
  14276. write the results in to that file. When invoked as an
  14277. interactive command, prompt for LATEX-FRAG, with initial value
  14278. set to the current active region and echo the results for user
  14279. inspection."
  14280. (interactive (list (let ((frag (when (org-region-active-p)
  14281. (buffer-substring-no-properties
  14282. (region-beginning) (region-end)))))
  14283. (read-string "LaTeX Fragment: " frag nil frag))))
  14284. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14285. (let* ((tmp-in-file
  14286. (let ((file (file-relative-name
  14287. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14288. (write-region latex-frag nil file)
  14289. file))
  14290. (tmp-out-file (file-relative-name
  14291. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14292. (cmd (format-spec
  14293. org-latex-to-mathml-convert-command
  14294. `((?j . ,(and org-latex-to-mathml-jar-file
  14295. (shell-quote-argument
  14296. (expand-file-name
  14297. org-latex-to-mathml-jar-file))))
  14298. (?I . ,(shell-quote-argument tmp-in-file))
  14299. (?i . ,latex-frag)
  14300. (?o . ,(shell-quote-argument tmp-out-file)))))
  14301. mathml shell-command-output)
  14302. (when (called-interactively-p 'any)
  14303. (unless (org-format-latex-mathml-available-p)
  14304. (user-error "LaTeX to MathML converter not configured")))
  14305. (message "Running %s" cmd)
  14306. (setq shell-command-output (shell-command-to-string cmd))
  14307. (setq mathml
  14308. (when (file-readable-p tmp-out-file)
  14309. (with-current-buffer (find-file-noselect tmp-out-file t)
  14310. (goto-char (point-min))
  14311. (when (re-search-forward
  14312. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14313. (regexp-quote
  14314. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14315. nil t)
  14316. (prog1 (match-string 0) (kill-buffer))))))
  14317. (cond
  14318. (mathml
  14319. (setq mathml
  14320. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14321. (when mathml-file
  14322. (write-region mathml nil mathml-file))
  14323. (when (called-interactively-p 'any)
  14324. (message mathml)))
  14325. ((message "LaTeX to MathML conversion failed")
  14326. (message shell-command-output)))
  14327. (delete-file tmp-in-file)
  14328. (when (file-exists-p tmp-out-file)
  14329. (delete-file tmp-out-file))
  14330. mathml))
  14331. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14332. prefix &optional dir)
  14333. "Use `org-create-math-formula' but check local cache first."
  14334. (let* ((absprefix (expand-file-name prefix dir))
  14335. (print-length nil) (print-level nil)
  14336. (formula-id (concat
  14337. "formula-"
  14338. (sha1
  14339. (prin1-to-string
  14340. (list latex-frag
  14341. org-latex-to-mathml-convert-command)))))
  14342. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14343. (formula-cache-dir (file-name-directory formula-cache)))
  14344. (unless (file-directory-p formula-cache-dir)
  14345. (make-directory formula-cache-dir t))
  14346. (unless (file-exists-p formula-cache)
  14347. (org-create-math-formula latex-frag formula-cache))
  14348. (if (file-exists-p formula-cache)
  14349. ;; Successful conversion. Return the link to MathML file.
  14350. (org-add-props
  14351. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14352. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14353. 'org-latex-src-embed-type (if latex-frag-type
  14354. 'paragraph 'character)))
  14355. ;; Failed conversion. Return the LaTeX fragment verbatim
  14356. latex-frag)))
  14357. (defun org--get-display-dpi ()
  14358. "Get the DPI of the display.
  14359. The function assumes that the display has the same pixel width in
  14360. the horizontal and vertical directions."
  14361. (if (display-graphic-p)
  14362. (round (/ (display-pixel-height)
  14363. (/ (display-mm-height) 25.4)))
  14364. (error "Attempt to calculate the dpi of a non-graphic display")))
  14365. (defun org-create-formula-image
  14366. (string tofile options buffer &optional processing-type)
  14367. "Create an image from LaTeX source using external processes.
  14368. The LaTeX STRING is saved to a temporary LaTeX file, then
  14369. converted to an image file by process PROCESSING-TYPE defined in
  14370. `org-preview-latex-process-alist'. A nil value defaults to
  14371. `org-preview-latex-default-process'.
  14372. The generated image file is eventually moved to TOFILE.
  14373. The OPTIONS argument controls the size, foreground color and
  14374. background color of the generated image.
  14375. When BUFFER non-nil, this function is used for LaTeX previewing.
  14376. Otherwise, it is used to deal with LaTeX snippets showed in
  14377. a HTML file."
  14378. (let* ((processing-type (or processing-type
  14379. org-preview-latex-default-process))
  14380. (processing-info
  14381. (cdr (assq processing-type org-preview-latex-process-alist)))
  14382. (programs (plist-get processing-info :programs))
  14383. (error-message (or (plist-get processing-info :message) ""))
  14384. (image-input-type (plist-get processing-info :image-input-type))
  14385. (image-output-type (plist-get processing-info :image-output-type))
  14386. (post-clean (or (plist-get processing-info :post-clean)
  14387. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14388. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14389. (latex-header
  14390. (or (plist-get processing-info :latex-header)
  14391. (org-latex-make-preamble
  14392. (org-export-get-environment (org-export-get-backend 'latex))
  14393. org-format-latex-header
  14394. 'snippet)))
  14395. (latex-compiler (plist-get processing-info :latex-compiler))
  14396. (image-converter (plist-get processing-info :image-converter))
  14397. (tmpdir temporary-file-directory)
  14398. (texfilebase (make-temp-name
  14399. (expand-file-name "orgtex" tmpdir)))
  14400. (texfile (concat texfilebase ".tex"))
  14401. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14402. '(1.0 . 1.0)))
  14403. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14404. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14405. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14406. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14407. "Black"))
  14408. (bg (or (plist-get options (if buffer :background :html-background))
  14409. "Transparent"))
  14410. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14411. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14412. (dolist (program programs)
  14413. (org-check-external-command program error-message))
  14414. (if (eq fg 'default)
  14415. (setq fg (org-latex-color :foreground))
  14416. (setq fg (org-latex-color-format fg)))
  14417. (if (eq bg 'default)
  14418. (setq bg (org-latex-color :background))
  14419. (setq bg (org-latex-color-format
  14420. (if (string= bg "Transparent") "white" bg))))
  14421. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14422. (if (string-suffix-p string "\n")
  14423. (aset string (1- (length string)) ?%)
  14424. (setq string (concat string "%")))
  14425. (with-temp-file texfile
  14426. (insert latex-header)
  14427. (insert "\n\\begin{document}\n"
  14428. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14429. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14430. "\n\\pagecolor{bg}%\n"
  14431. "\n{\\color{fg}\n"
  14432. string
  14433. "\n}\n"
  14434. "\n\\end{document}\n"))
  14435. (let* ((err-msg (format "Please adjust `%s' part of \
  14436. `org-preview-latex-process-alist'."
  14437. processing-type))
  14438. (image-input-file
  14439. (org-compile-file
  14440. texfile latex-compiler image-input-type err-msg log-buf))
  14441. (image-output-file
  14442. (org-compile-file
  14443. image-input-file image-converter image-output-type err-msg log-buf
  14444. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14445. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14446. (copy-file image-output-file tofile 'replace)
  14447. (dolist (e post-clean)
  14448. (when (file-exists-p (concat texfilebase e))
  14449. (delete-file (concat texfilebase e))))
  14450. image-output-file)))
  14451. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14452. "Fill a LaTeX header template TPL.
  14453. In the template, the following place holders will be recognized:
  14454. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14455. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14456. [PACKAGES] \\usepackage statements for PKG
  14457. [NO-PACKAGES] do not include PKG
  14458. [EXTRA] the string EXTRA
  14459. [NO-EXTRA] do not include EXTRA
  14460. For backward compatibility, if both the positive and the negative place
  14461. holder is missing, the positive one (without the \"NO-\") will be
  14462. assumed to be present at the end of the template.
  14463. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14464. EXTRA is a string.
  14465. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14466. (let (rpl (end ""))
  14467. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14468. (setq rpl (if (or (match-end 1) (not def-pkg))
  14469. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14470. tpl (replace-match rpl t t tpl))
  14471. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14472. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14473. (setq rpl (if (or (match-end 1) (not pkg))
  14474. "" (org-latex-packages-to-string pkg snippets-p t))
  14475. tpl (replace-match rpl t t tpl))
  14476. (when pkg (setq end
  14477. (concat end "\n"
  14478. (org-latex-packages-to-string pkg snippets-p)))))
  14479. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14480. (setq rpl (if (or (match-end 1) (not extra))
  14481. "" (concat extra "\n"))
  14482. tpl (replace-match rpl t t tpl))
  14483. (when (and extra (string-match "\\S-" extra))
  14484. (setq end (concat end "\n" extra))))
  14485. (if (string-match "\\S-" end)
  14486. (concat tpl "\n" end)
  14487. tpl)))
  14488. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14489. "Turn an alist of packages into a string with the \\usepackage macros."
  14490. (setq pkg (mapconcat (lambda(p)
  14491. (cond
  14492. ((stringp p) p)
  14493. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14494. (format "%% Package %s omitted" (cadr p)))
  14495. ((equal "" (car p))
  14496. (format "\\usepackage{%s}" (cadr p)))
  14497. (t
  14498. (format "\\usepackage[%s]{%s}"
  14499. (car p) (cadr p)))))
  14500. pkg
  14501. "\n"))
  14502. (if newline (concat pkg "\n") pkg))
  14503. (defun org-dvipng-color (attr)
  14504. "Return a RGB color specification for dvipng."
  14505. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14506. (defun org-dvipng-color-format (color-name)
  14507. "Convert COLOR-NAME to a RGB color value for dvipng."
  14508. (apply #'format "rgb %s %s %s"
  14509. (mapcar 'org-normalize-color
  14510. (color-values color-name))))
  14511. (defun org-latex-color (attr)
  14512. "Return a RGB color for the LaTeX color package."
  14513. (org-latex-color-format (face-attribute 'default attr nil)))
  14514. (defun org-latex-color-format (color-name)
  14515. "Convert COLOR-NAME to a RGB color value."
  14516. (apply #'format "%s,%s,%s"
  14517. (mapcar 'org-normalize-color
  14518. (color-values color-name))))
  14519. (defun org-normalize-color (value)
  14520. "Return string to be used as color value for an RGB component."
  14521. (format "%g" (/ value 65535.0)))
  14522. ;; Image display
  14523. (defvar-local org-inline-image-overlays nil)
  14524. (defun org-toggle-inline-images (&optional include-linked)
  14525. "Toggle the display of inline images.
  14526. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14527. (interactive "P")
  14528. (if org-inline-image-overlays
  14529. (progn
  14530. (org-remove-inline-images)
  14531. (when (called-interactively-p 'interactive)
  14532. (message "Inline image display turned off")))
  14533. (org-display-inline-images include-linked)
  14534. (when (called-interactively-p 'interactive)
  14535. (message (if org-inline-image-overlays
  14536. (format "%d images displayed inline"
  14537. (length org-inline-image-overlays))
  14538. "No images to display inline")))))
  14539. (defun org-redisplay-inline-images ()
  14540. "Assure display of inline images and refresh them."
  14541. (interactive)
  14542. (org-toggle-inline-images)
  14543. (unless org-inline-image-overlays
  14544. (org-toggle-inline-images)))
  14545. ;; For without-x builds.
  14546. (declare-function image-refresh "image" (spec &optional frame))
  14547. (defcustom org-display-remote-inline-images 'skip
  14548. "How to display remote inline images.
  14549. Possible values of this option are:
  14550. skip Don't display remote images.
  14551. download Always download and display remote images.
  14552. cache Display remote images, and open them in separate buffers
  14553. for cacheing. Silently update the image buffer when a file
  14554. change is detected."
  14555. :group 'org-appearance
  14556. :package-version '(Org . "9.4")
  14557. :type '(choice
  14558. (const :tag "Ignore remote images" skip)
  14559. (const :tag "Always display remote images" download)
  14560. (const :tag "Display and silently update remote images" cache))
  14561. :safe #'symbolp)
  14562. (defun org--create-inline-image (file width)
  14563. "Create image located at FILE, or return nil.
  14564. WIDTH is the width of the image. The image may not be created
  14565. according to the value of `org-display-remote-inline-images'."
  14566. (let* ((remote? (file-remote-p file))
  14567. (file-or-data
  14568. (pcase org-display-remote-inline-images
  14569. ((guard (not remote?)) file)
  14570. (`download (with-temp-buffer
  14571. (set-buffer-multibyte nil)
  14572. (insert-file-contents-literally file)
  14573. (buffer-string)))
  14574. (`cache (let ((revert-without-query '(".")))
  14575. (with-current-buffer (find-file-noselect file)
  14576. (buffer-string))))
  14577. (`skip nil)
  14578. (other
  14579. (message "Invalid value of `org-display-remote-inline-images': %S"
  14580. other)
  14581. nil))))
  14582. (when file-or-data
  14583. (create-image file-or-data
  14584. (and (image-type-available-p 'imagemagick)
  14585. width
  14586. 'imagemagick)
  14587. remote?
  14588. :width width))))
  14589. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14590. "Display inline images.
  14591. An inline image is a link which follows either of these
  14592. conventions:
  14593. 1. Its path is a file with an extension matching return value
  14594. from `image-file-name-regexp' and it has no contents.
  14595. 2. Its description consists in a single link of the previous
  14596. type. In this case, that link must be a well-formed plain
  14597. or angle link, i.e., it must have an explicit \"file\" type.
  14598. Equip each image with the key-map `image-map'.
  14599. When optional argument INCLUDE-LINKED is non-nil, also links with
  14600. a text description part will be inlined. This can be nice for
  14601. a quick look at those images, but it does not reflect what
  14602. exported files will look like.
  14603. When optional argument REFRESH is non-nil, refresh existing
  14604. images between BEG and END. This will create new image displays
  14605. only if necessary.
  14606. BEG and END define the considered part. They default to the
  14607. buffer boundaries with possible narrowing."
  14608. (interactive "P")
  14609. (when (display-graphic-p)
  14610. (unless refresh
  14611. (org-remove-inline-images)
  14612. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14613. (let ((end (or end (point-max))))
  14614. (org-with-point-at (or beg (point-min))
  14615. (let* ((case-fold-search t)
  14616. (file-extension-re (image-file-name-regexp))
  14617. (link-abbrevs (mapcar #'car
  14618. (append org-link-abbrev-alist-local
  14619. org-link-abbrev-alist)))
  14620. ;; Check absolute, relative file names and explicit
  14621. ;; "file:" links. Also check link abbreviations since
  14622. ;; some might expand to "file" links.
  14623. (file-types-re
  14624. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14625. (if (not link-abbrevs) ""
  14626. (concat "\\|" (regexp-opt link-abbrevs))))))
  14627. (while (re-search-forward file-types-re end t)
  14628. (let* ((link (org-element-lineage
  14629. (save-match-data (org-element-context))
  14630. '(link) t))
  14631. (linktype (org-element-property :type link))
  14632. (inner-start (match-beginning 1))
  14633. (path
  14634. (cond
  14635. ;; No link at point; no inline image.
  14636. ((not link) nil)
  14637. ;; File link without a description. Also handle
  14638. ;; INCLUDE-LINKED here since it should have
  14639. ;; precedence over the next case. I.e., if link
  14640. ;; contains filenames in both the path and the
  14641. ;; description, prioritize the path only when
  14642. ;; INCLUDE-LINKED is non-nil.
  14643. ((or (not (org-element-property :contents-begin link))
  14644. include-linked)
  14645. (and (or (equal "file" linktype)
  14646. (equal "attachment" linktype))
  14647. (org-element-property :path link)))
  14648. ;; Link with a description. Check if description
  14649. ;; is a filename. Even if Org doesn't have syntax
  14650. ;; for those -- clickable image -- constructs, fake
  14651. ;; them, as in `org-export-insert-image-links'.
  14652. ((not inner-start) nil)
  14653. (t
  14654. (org-with-point-at inner-start
  14655. (and (looking-at
  14656. (if (char-equal ?< (char-after inner-start))
  14657. org-link-angle-re
  14658. org-link-plain-re))
  14659. ;; File name must fill the whole
  14660. ;; description.
  14661. (= (org-element-property :contents-end link)
  14662. (match-end 0))
  14663. (match-string 2)))))))
  14664. (when (and path (string-match-p file-extension-re path))
  14665. (let ((file (if (equal "attachment" linktype)
  14666. (progn
  14667. (require 'org-attach)
  14668. (ignore-errors (org-attach-expand path)))
  14669. (expand-file-name path))))
  14670. (when (and file (file-exists-p file))
  14671. (let ((width
  14672. ;; Apply `org-image-actual-width' specifications.
  14673. (cond
  14674. ((eq org-image-actual-width t) nil)
  14675. ((listp org-image-actual-width)
  14676. (or
  14677. ;; First try to find a width among
  14678. ;; attributes associated to the paragraph
  14679. ;; containing link.
  14680. (pcase (org-element-lineage link '(paragraph))
  14681. (`nil nil)
  14682. (p
  14683. (let* ((case-fold-search t)
  14684. (end (org-element-property :post-affiliated p))
  14685. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14686. (when (org-with-point-at
  14687. (org-element-property :begin p)
  14688. (re-search-forward re end t))
  14689. (string-to-number (match-string 1))))))
  14690. ;; Otherwise, fall-back to provided number.
  14691. (car org-image-actual-width)))
  14692. ((numberp org-image-actual-width)
  14693. org-image-actual-width)
  14694. (t nil)))
  14695. (old (get-char-property-and-overlay
  14696. (org-element-property :begin link)
  14697. 'org-image-overlay)))
  14698. (if (and (car-safe old) refresh)
  14699. (image-refresh (overlay-get (cdr old) 'display))
  14700. (let ((image (org--create-inline-image file width)))
  14701. (when image
  14702. (let ((ov (make-overlay
  14703. (org-element-property :begin link)
  14704. (progn
  14705. (goto-char
  14706. (org-element-property :end link))
  14707. (skip-chars-backward " \t")
  14708. (point)))))
  14709. (overlay-put ov 'display image)
  14710. (overlay-put ov 'face 'default)
  14711. (overlay-put ov 'org-image-overlay t)
  14712. (overlay-put
  14713. ov 'modification-hooks
  14714. (list 'org-display-inline-remove-overlay))
  14715. (when (<= 26 emacs-major-version)
  14716. (cl-assert (boundp 'image-map))
  14717. (overlay-put ov 'keymap image-map))
  14718. (push ov org-inline-image-overlays))))))))))))))))
  14719. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14720. "Remove inline-display overlay if a corresponding region is modified."
  14721. (let ((inhibit-modification-hooks t))
  14722. (when (and ov after)
  14723. (delete ov org-inline-image-overlays)
  14724. (delete-overlay ov))))
  14725. (defun org-remove-inline-images ()
  14726. "Remove inline display of images."
  14727. (interactive)
  14728. (mapc #'delete-overlay org-inline-image-overlays)
  14729. (setq org-inline-image-overlays nil))
  14730. (defvar org-self-insert-command-undo-counter 0)
  14731. (defvar org-speed-command nil)
  14732. (defun org-self-insert-command (N)
  14733. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14734. If the cursor is in a table looking at whitespace, the whitespace is
  14735. overwritten, and the table is not marked as requiring realignment."
  14736. (interactive "p")
  14737. (org-check-before-invisible-edit 'insert)
  14738. (cond
  14739. ((and org-use-speed-commands
  14740. (let ((kv (this-command-keys-vector)))
  14741. (setq org-speed-command
  14742. (run-hook-with-args-until-success
  14743. 'org-speed-command-hook
  14744. (make-string 1 (aref kv (1- (length kv))))))))
  14745. (cond
  14746. ((commandp org-speed-command)
  14747. (setq this-command org-speed-command)
  14748. (call-interactively org-speed-command))
  14749. ((functionp org-speed-command)
  14750. (funcall org-speed-command))
  14751. ((and org-speed-command (listp org-speed-command))
  14752. (eval org-speed-command))
  14753. (t (let (org-use-speed-commands)
  14754. (call-interactively 'org-self-insert-command)))))
  14755. ((and
  14756. (= N 1)
  14757. (not (org-region-active-p))
  14758. (org-at-table-p)
  14759. (progn
  14760. ;; Check if we blank the field, and if that triggers align.
  14761. (and (featurep 'org-table)
  14762. org-table-auto-blank-field
  14763. (memq last-command
  14764. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14765. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14766. ;; Got extra space, this field does not determine
  14767. ;; column width.
  14768. (let (org-table-may-need-update) (org-table-blank-field))
  14769. ;; No extra space, this field may determine column
  14770. ;; width.
  14771. (org-table-blank-field)))
  14772. t)
  14773. (looking-at "[^|\n]* |"))
  14774. ;; There is room for insertion without re-aligning the table.
  14775. (self-insert-command N)
  14776. (org-table-with-shrunk-field
  14777. (save-excursion
  14778. (skip-chars-forward "^|")
  14779. ;; Do not delete last space, which is
  14780. ;; `org-table-separator-space', but the regular space before
  14781. ;; it.
  14782. (delete-region (- (point) 2) (1- (point))))))
  14783. (t
  14784. (setq org-table-may-need-update t)
  14785. (self-insert-command N)
  14786. (org-fix-tags-on-the-fly)
  14787. (when org-self-insert-cluster-for-undo
  14788. (if (not (eq last-command 'org-self-insert-command))
  14789. (setq org-self-insert-command-undo-counter 1)
  14790. (if (>= org-self-insert-command-undo-counter 20)
  14791. (setq org-self-insert-command-undo-counter 1)
  14792. (and (> org-self-insert-command-undo-counter 0)
  14793. buffer-undo-list (listp buffer-undo-list)
  14794. (not (cadr buffer-undo-list)) ; remove nil entry
  14795. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14796. (setq org-self-insert-command-undo-counter
  14797. (1+ org-self-insert-command-undo-counter))))))))
  14798. (defun org-check-before-invisible-edit (kind)
  14799. "Check is editing if kind KIND would be dangerous with invisible text around.
  14800. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  14801. ;; First, try to get out of here as quickly as possible, to reduce overhead
  14802. (when (and org-catch-invisible-edits
  14803. (or (not (boundp 'visible-mode)) (not visible-mode))
  14804. (or (get-char-property (point) 'invisible)
  14805. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  14806. ;; OK, we need to take a closer look. Do not consider
  14807. ;; invisibility obtained through text properties (e.g., link
  14808. ;; fontification), as it cannot be toggled.
  14809. (let* ((invisible-at-point
  14810. (pcase (get-char-property-and-overlay (point) 'invisible)
  14811. (`(,_ . ,(and (pred overlayp) o)) o)))
  14812. ;; Assume that point cannot land in the middle of an
  14813. ;; overlay, or between two overlays.
  14814. (invisible-before-point
  14815. (and (not invisible-at-point)
  14816. (not (bobp))
  14817. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  14818. (`(,_ . ,(and (pred overlayp) o)) o))))
  14819. (border-and-ok-direction
  14820. (or
  14821. ;; Check if we are acting predictably before invisible
  14822. ;; text.
  14823. (and invisible-at-point
  14824. (memq kind '(insert delete-backward)))
  14825. ;; Check if we are acting predictably after invisible text
  14826. ;; This works not well, and I have turned it off. It seems
  14827. ;; better to always show and stop after invisible text.
  14828. ;; (and (not invisible-at-point) invisible-before-point
  14829. ;; (memq kind '(insert delete)))
  14830. )))
  14831. (when (or invisible-at-point invisible-before-point)
  14832. (when (eq org-catch-invisible-edits 'error)
  14833. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  14834. (if (and org-custom-properties-overlays
  14835. (y-or-n-p "Display invisible properties in this buffer? "))
  14836. (org-toggle-custom-properties-visibility)
  14837. ;; Make the area visible
  14838. (save-excursion
  14839. (when invisible-before-point
  14840. (goto-char
  14841. (previous-single-char-property-change (point) 'invisible)))
  14842. ;; Remove whatever overlay is currently making yet-to-be
  14843. ;; edited text invisible. Also remove nested invisibility
  14844. ;; related overlays.
  14845. (delete-overlay (or invisible-at-point invisible-before-point))
  14846. (let ((origin (if invisible-at-point (point) (1- (point)))))
  14847. (while (pcase (get-char-property-and-overlay origin 'invisible)
  14848. (`(,_ . ,(and (pred overlayp) o))
  14849. (delete-overlay o)
  14850. t)))))
  14851. (cond
  14852. ((eq org-catch-invisible-edits 'show)
  14853. ;; That's it, we do the edit after showing
  14854. (message
  14855. "Unfolding invisible region around point before editing")
  14856. (sit-for 1))
  14857. ((and (eq org-catch-invisible-edits 'smart)
  14858. border-and-ok-direction)
  14859. (message "Unfolding invisible region around point before editing"))
  14860. (t
  14861. ;; Don't do the edit, make the user repeat it in full visibility
  14862. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  14863. (defun org-fix-tags-on-the-fly ()
  14864. "Align tags in headline at point.
  14865. Unlike `org-align-tags', this function does nothing if point is
  14866. either not currently on a tagged headline or on a tag."
  14867. (when (and (org-match-line org-tag-line-re)
  14868. (< (point) (match-beginning 1)))
  14869. (org-align-tags)))
  14870. (defun org-delete-backward-char (N)
  14871. "Like `delete-backward-char', insert whitespace at field end in tables.
  14872. When deleting backwards, in tables this function will insert whitespace in
  14873. front of the next \"|\" separator, to keep the table aligned. The table will
  14874. still be marked for re-alignment if the field did fill the entire column,
  14875. because, in this case the deletion might narrow the column."
  14876. (interactive "p")
  14877. (save-match-data
  14878. (org-check-before-invisible-edit 'delete-backward)
  14879. (if (and (= N 1)
  14880. (not overwrite-mode)
  14881. (not (org-region-active-p))
  14882. (not (eq (char-before) ?|))
  14883. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14884. (looking-at-p ".*?|")
  14885. (org-at-table-p))
  14886. (progn (forward-char -1) (org-delete-char 1))
  14887. (backward-delete-char N)
  14888. (org-fix-tags-on-the-fly))))
  14889. (defun org-delete-char (N)
  14890. "Like `delete-char', but insert whitespace at field end in tables.
  14891. When deleting characters, in tables this function will insert whitespace in
  14892. front of the next \"|\" separator, to keep the table aligned. The table will
  14893. still be marked for re-alignment if the field did fill the entire column,
  14894. because, in this case the deletion might narrow the column."
  14895. (interactive "p")
  14896. (save-match-data
  14897. (org-check-before-invisible-edit 'delete)
  14898. (cond
  14899. ((or (/= N 1)
  14900. (eq (char-after) ?|)
  14901. (save-excursion (skip-chars-backward " \t") (bolp))
  14902. (not (org-at-table-p)))
  14903. (delete-char N)
  14904. (org-fix-tags-on-the-fly))
  14905. ((looking-at ".\\(.*?\\)|")
  14906. (let* ((update? org-table-may-need-update)
  14907. (noalign (looking-at-p ".*? |")))
  14908. (delete-char 1)
  14909. (org-table-with-shrunk-field
  14910. (save-excursion
  14911. ;; Last space is `org-table-separator-space', so insert
  14912. ;; a regular one before it instead.
  14913. (goto-char (- (match-end 0) 2))
  14914. (insert " ")))
  14915. ;; If there were two spaces at the end, this field does not
  14916. ;; determine the width of the column.
  14917. (when noalign (setq org-table-may-need-update update?))))
  14918. (t
  14919. (delete-char N)))))
  14920. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14921. (put 'org-self-insert-command 'delete-selection
  14922. (lambda ()
  14923. (not (run-hook-with-args-until-success
  14924. 'self-insert-uses-region-functions))))
  14925. (put 'orgtbl-self-insert-command 'delete-selection
  14926. (lambda ()
  14927. (not (run-hook-with-args-until-success
  14928. 'self-insert-uses-region-functions))))
  14929. (put 'org-delete-char 'delete-selection 'supersede)
  14930. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14931. (put 'org-yank 'delete-selection 'yank)
  14932. ;; Make `flyspell-mode' delay after some commands
  14933. (put 'org-self-insert-command 'flyspell-delayed t)
  14934. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14935. (put 'org-delete-char 'flyspell-delayed t)
  14936. (put 'org-delete-backward-char 'flyspell-delayed t)
  14937. ;; Make pabbrev-mode expand after Org mode commands
  14938. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14939. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14940. (defun org-transpose-words ()
  14941. "Transpose words for Org.
  14942. This uses the `org-mode-transpose-word-syntax-table' syntax
  14943. table, which interprets characters in `org-emphasis-alist' as
  14944. word constituents."
  14945. (interactive)
  14946. (with-syntax-table org-mode-transpose-word-syntax-table
  14947. (call-interactively 'transpose-words)))
  14948. (defvar org-ctrl-c-ctrl-c-hook nil
  14949. "Hook for functions attaching themselves to `C-c C-c'.
  14950. This can be used to add additional functionality to the C-c C-c
  14951. key which executes context-dependent commands. This hook is run
  14952. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14953. run after the last test.
  14954. Each function will be called with no arguments. The function
  14955. must check if the context is appropriate for it to act. If yes,
  14956. it should do its thing and then return a non-nil value. If the
  14957. context is wrong, just do nothing and return nil.")
  14958. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14959. "Hook for functions attaching themselves to `C-c C-c'.
  14960. This can be used to add additional functionality to the C-c C-c
  14961. key which executes context-dependent commands. This hook is run
  14962. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14963. before the first test.
  14964. Each function will be called with no arguments. The function
  14965. must check if the context is appropriate for it to act. If yes,
  14966. it should do its thing and then return a non-nil value. If the
  14967. context is wrong, just do nothing and return nil.")
  14968. (defvar org-tab-first-hook nil
  14969. "Hook for functions to attach themselves to TAB.
  14970. See `org-ctrl-c-ctrl-c-hook' for more information.
  14971. This hook runs as the first action when TAB is pressed, even before
  14972. `org-cycle' messes around with the `outline-regexp' to cater for
  14973. inline tasks and plain list item folding.
  14974. If any function in this hook returns t, any other actions that
  14975. would have been caused by TAB (such as table field motion or visibility
  14976. cycling) will not occur.")
  14977. (defvar org-tab-after-check-for-table-hook nil
  14978. "Hook for functions to attach themselves to TAB.
  14979. See `org-ctrl-c-ctrl-c-hook' for more information.
  14980. This hook runs after it has been established that the cursor is not in a
  14981. table, but before checking if the cursor is in a headline or if global cycling
  14982. should be done.
  14983. If any function in this hook returns t, not other actions like visibility
  14984. cycling will be done.")
  14985. (defvar org-tab-after-check-for-cycling-hook nil
  14986. "Hook for functions to attach themselves to TAB.
  14987. See `org-ctrl-c-ctrl-c-hook' for more information.
  14988. This hook runs after it has been established that not table field motion and
  14989. not visibility should be done because of current context. This is probably
  14990. the place where a package like yasnippets can hook in.")
  14991. (defvar org-tab-before-tab-emulation-hook nil
  14992. "Hook for functions to attach themselves to TAB.
  14993. See `org-ctrl-c-ctrl-c-hook' for more information.
  14994. This hook runs after every other options for TAB have been exhausted, but
  14995. before indentation and \t insertion takes place.")
  14996. (defvar org-metaleft-hook nil
  14997. "Hook for functions attaching themselves to `M-left'.
  14998. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14999. (defvar org-metaright-hook nil
  15000. "Hook for functions attaching themselves to `M-right'.
  15001. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15002. (defvar org-metaup-hook nil
  15003. "Hook for functions attaching themselves to `M-up'.
  15004. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15005. (defvar org-metadown-hook nil
  15006. "Hook for functions attaching themselves to `M-down'.
  15007. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15008. (defvar org-shiftmetaleft-hook nil
  15009. "Hook for functions attaching themselves to `M-S-left'.
  15010. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15011. (defvar org-shiftmetaright-hook nil
  15012. "Hook for functions attaching themselves to `M-S-right'.
  15013. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15014. (defvar org-shiftmetaup-hook nil
  15015. "Hook for functions attaching themselves to `M-S-up'.
  15016. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15017. (defvar org-shiftmetadown-hook nil
  15018. "Hook for functions attaching themselves to `M-S-down'.
  15019. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15020. (defvar org-metareturn-hook nil
  15021. "Hook for functions attaching themselves to `M-RET'.
  15022. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15023. (defvar org-shiftup-hook nil
  15024. "Hook for functions attaching themselves to `S-up'.
  15025. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15026. (defvar org-shiftup-final-hook nil
  15027. "Hook for functions attaching themselves to `S-up'.
  15028. This one runs after all other options except shift-select have been excluded.
  15029. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15030. (defvar org-shiftdown-hook nil
  15031. "Hook for functions attaching themselves to `S-down'.
  15032. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15033. (defvar org-shiftdown-final-hook nil
  15034. "Hook for functions attaching themselves to `S-down'.
  15035. This one runs after all other options except shift-select have been excluded.
  15036. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15037. (defvar org-shiftleft-hook nil
  15038. "Hook for functions attaching themselves to `S-left'.
  15039. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15040. (defvar org-shiftleft-final-hook nil
  15041. "Hook for functions attaching themselves to `S-left'.
  15042. This one runs after all other options except shift-select have been excluded.
  15043. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15044. (defvar org-shiftright-hook nil
  15045. "Hook for functions attaching themselves to `S-right'.
  15046. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15047. (defvar org-shiftright-final-hook nil
  15048. "Hook for functions attaching themselves to `S-right'.
  15049. This one runs after all other options except shift-select have been excluded.
  15050. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15051. (defun org-modifier-cursor-error ()
  15052. "Throw an error, a modified cursor command was applied in wrong context."
  15053. (user-error "This command is active in special context like tables, headlines or items"))
  15054. (defun org-shiftselect-error ()
  15055. "Throw an error because Shift-Cursor command was applied in wrong context."
  15056. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15057. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15058. (user-error "This command works only in special context like headlines or timestamps")))
  15059. (defun org-call-for-shift-select (cmd)
  15060. (let ((this-command-keys-shift-translated t))
  15061. (call-interactively cmd)))
  15062. (defun org-shifttab (&optional arg)
  15063. "Global visibility cycling or move to previous table field.
  15064. Call `org-table-previous-field' within a table.
  15065. When ARG is nil, cycle globally through visibility states.
  15066. When ARG is a numeric prefix, show contents of this level."
  15067. (interactive "P")
  15068. (cond
  15069. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15070. ((integerp arg)
  15071. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15072. (message "Content view to level: %d" arg)
  15073. (org-content (prefix-numeric-value arg2))
  15074. (org-cycle-show-empty-lines t)
  15075. (setq org-cycle-global-status 'overview)))
  15076. (t (call-interactively 'org-global-cycle))))
  15077. (defun org-shiftmetaleft ()
  15078. "Promote subtree or delete table column.
  15079. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15080. `org-table-delete-column', depending on context. See the
  15081. individual commands for more information."
  15082. (interactive)
  15083. (cond
  15084. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15085. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15086. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15087. ((if (not (org-region-active-p)) (org-at-item-p)
  15088. (save-excursion (goto-char (region-beginning))
  15089. (org-at-item-p)))
  15090. (call-interactively 'org-outdent-item-tree))
  15091. (t (org-modifier-cursor-error))))
  15092. (defun org-shiftmetaright ()
  15093. "Demote subtree or insert table column.
  15094. Calls `org-demote-subtree', `org-indent-item-tree', or
  15095. `org-table-insert-column', depending on context. See the
  15096. individual commands for more information."
  15097. (interactive)
  15098. (cond
  15099. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15100. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15101. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15102. ((if (not (org-region-active-p)) (org-at-item-p)
  15103. (save-excursion (goto-char (region-beginning))
  15104. (org-at-item-p)))
  15105. (call-interactively 'org-indent-item-tree))
  15106. (t (org-modifier-cursor-error))))
  15107. (defun org-shiftmetaup (&optional _arg)
  15108. "Drag the line at point up.
  15109. In a table, kill the current row.
  15110. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15111. but also adjust the previous clocked item in the clock history.
  15112. Everywhere else, drag the line at point up."
  15113. (interactive "P")
  15114. (cond
  15115. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15116. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15117. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15118. (call-interactively 'org-timestamp-up)))
  15119. (t (call-interactively 'org-drag-line-backward))))
  15120. (defun org-shiftmetadown (&optional _arg)
  15121. "Drag the line at point down.
  15122. In a table, insert an empty row at the current line.
  15123. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15124. but also adjust the previous clocked item in the clock history.
  15125. Everywhere else, drag the line at point down."
  15126. (interactive "P")
  15127. (cond
  15128. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15129. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15130. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15131. (call-interactively 'org-timestamp-down)))
  15132. (t (call-interactively 'org-drag-line-forward))))
  15133. (defsubst org-hidden-tree-error ()
  15134. (user-error
  15135. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15136. (defun org-metaleft (&optional _arg)
  15137. "Promote heading, list item at point or move table column left.
  15138. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15139. depending on context. With no specific context, calls the Emacs
  15140. default `backward-word'. See the individual commands for more
  15141. information.
  15142. This function runs the hook `org-metaleft-hook' as a first step,
  15143. and returns at first non-nil value."
  15144. (interactive "P")
  15145. (cond
  15146. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15147. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15148. ((org-with-limited-levels
  15149. (or (org-at-heading-p)
  15150. (and (org-region-active-p)
  15151. (save-excursion
  15152. (goto-char (region-beginning))
  15153. (org-at-heading-p)))))
  15154. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15155. (call-interactively 'org-do-promote))
  15156. ;; At an inline task.
  15157. ((org-at-heading-p)
  15158. (call-interactively 'org-inlinetask-promote))
  15159. ((or (org-at-item-p)
  15160. (and (org-region-active-p)
  15161. (save-excursion
  15162. (goto-char (region-beginning))
  15163. (org-at-item-p))))
  15164. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15165. (call-interactively 'org-outdent-item))
  15166. (t (call-interactively 'backward-word))))
  15167. (defun org-metaright (&optional _arg)
  15168. "Demote heading, list item at point or move table column right.
  15169. In front of a drawer or a block keyword, indent it correctly.
  15170. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15171. `org-indent-drawer' or `org-indent-block' depending on context.
  15172. With no specific context, calls the Emacs default `forward-word'.
  15173. See the individual commands for more information.
  15174. This function runs the hook `org-metaright-hook' as a first step,
  15175. and returns at first non-nil value."
  15176. (interactive "P")
  15177. (cond
  15178. ((run-hook-with-args-until-success 'org-metaright-hook))
  15179. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15180. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15181. ((org-at-block-p) (call-interactively 'org-indent-block))
  15182. ((org-with-limited-levels
  15183. (or (org-at-heading-p)
  15184. (and (org-region-active-p)
  15185. (save-excursion
  15186. (goto-char (region-beginning))
  15187. (org-at-heading-p)))))
  15188. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15189. (call-interactively 'org-do-demote))
  15190. ;; At an inline task.
  15191. ((org-at-heading-p)
  15192. (call-interactively 'org-inlinetask-demote))
  15193. ((or (org-at-item-p)
  15194. (and (org-region-active-p)
  15195. (save-excursion
  15196. (goto-char (region-beginning))
  15197. (org-at-item-p))))
  15198. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15199. (call-interactively 'org-indent-item))
  15200. (t (call-interactively 'forward-word))))
  15201. (defun org-check-for-hidden (what)
  15202. "Check if there are hidden headlines/items in the current visual line.
  15203. WHAT can be either `headlines' or `items'. If the current line is
  15204. an outline or item heading and it has a folded subtree below it,
  15205. this function returns t, nil otherwise."
  15206. (let ((re (cond
  15207. ((eq what 'headlines) org-outline-regexp-bol)
  15208. ((eq what 'items) (org-item-beginning-re))
  15209. (t (error "This should not happen"))))
  15210. beg end)
  15211. (save-excursion
  15212. (catch 'exit
  15213. (unless (org-region-active-p)
  15214. (setq beg (point-at-bol))
  15215. (beginning-of-line 2)
  15216. (while (and (not (eobp)) ;; this is like `next-line'
  15217. (get-char-property (1- (point)) 'invisible))
  15218. (beginning-of-line 2))
  15219. (setq end (point))
  15220. (goto-char beg)
  15221. (goto-char (point-at-eol))
  15222. (setq end (max end (point)))
  15223. (while (re-search-forward re end t)
  15224. (when (get-char-property (match-beginning 0) 'invisible)
  15225. (throw 'exit t))))
  15226. nil))))
  15227. (defun org-metaup (&optional _arg)
  15228. "Move subtree up or move table row up.
  15229. Calls `org-move-subtree-up' or `org-table-move-row' or
  15230. `org-move-item-up', depending on context. See the individual commands
  15231. for more information."
  15232. (interactive "P")
  15233. (cond
  15234. ((run-hook-with-args-until-success 'org-metaup-hook))
  15235. ((org-region-active-p)
  15236. (let* ((a (save-excursion
  15237. (goto-char (min (region-beginning) (region-end)))
  15238. (line-beginning-position)))
  15239. (b (save-excursion
  15240. (goto-char (max (region-beginning) (region-end)))
  15241. (if (bolp) (1- (point)) (line-end-position))))
  15242. (c (save-excursion
  15243. (goto-char a)
  15244. (move-beginning-of-line 0)
  15245. (point)))
  15246. (d (save-excursion
  15247. (goto-char a)
  15248. (move-end-of-line 0)
  15249. (point))))
  15250. (transpose-regions a b c d)
  15251. (goto-char c)))
  15252. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15253. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15254. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15255. (t (org-drag-element-backward))))
  15256. (defun org-metadown (&optional _arg)
  15257. "Move subtree down or move table row down.
  15258. Calls `org-move-subtree-down' or `org-table-move-row' or
  15259. `org-move-item-down', depending on context. See the individual
  15260. commands for more information."
  15261. (interactive "P")
  15262. (cond
  15263. ((run-hook-with-args-until-success 'org-metadown-hook))
  15264. ((org-region-active-p)
  15265. (let* ((a (save-excursion
  15266. (goto-char (min (region-beginning) (region-end)))
  15267. (line-beginning-position)))
  15268. (b (save-excursion
  15269. (goto-char (max (region-beginning) (region-end)))
  15270. (if (bolp) (1- (point)) (line-end-position))))
  15271. (c (save-excursion
  15272. (goto-char b)
  15273. (move-beginning-of-line (if (bolp) 1 2))
  15274. (point)))
  15275. (d (save-excursion
  15276. (goto-char b)
  15277. (move-end-of-line (if (bolp) 1 2))
  15278. (point))))
  15279. (transpose-regions a b c d)
  15280. (goto-char d)))
  15281. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15282. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15283. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15284. (t (org-drag-element-forward))))
  15285. (defun org-shiftup (&optional arg)
  15286. "Act on current element according to context.
  15287. Call `org-timestamp-up' or `org-priority-up', or
  15288. `org-previous-item', or `org-table-move-cell-up'. See the
  15289. individual commands for more information."
  15290. (interactive "P")
  15291. (cond
  15292. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15293. ((and org-support-shift-select (org-region-active-p))
  15294. (org-call-for-shift-select 'previous-line))
  15295. ((org-at-timestamp-p 'lax)
  15296. (call-interactively (if org-edit-timestamp-down-means-later
  15297. 'org-timestamp-down 'org-timestamp-up)))
  15298. ((and (not (eq org-support-shift-select 'always))
  15299. org-priority-enable-commands
  15300. (org-at-heading-p))
  15301. (call-interactively 'org-priority-up))
  15302. ((and (not org-support-shift-select) (org-at-item-p))
  15303. (call-interactively 'org-previous-item))
  15304. ((org-clocktable-try-shift 'up arg))
  15305. ((org-at-table-p) (org-table-move-cell-up))
  15306. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15307. (org-support-shift-select
  15308. (org-call-for-shift-select 'previous-line))
  15309. (t (org-shiftselect-error))))
  15310. (defun org-shiftdown (&optional arg)
  15311. "Act on current element according to context.
  15312. Call `org-timestamp-down' or `org-priority-down', or
  15313. `org-next-item', or `org-table-move-cell-down'. See the
  15314. individual commands for more information."
  15315. (interactive "P")
  15316. (cond
  15317. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15318. ((and org-support-shift-select (org-region-active-p))
  15319. (org-call-for-shift-select 'next-line))
  15320. ((org-at-timestamp-p 'lax)
  15321. (call-interactively (if org-edit-timestamp-down-means-later
  15322. 'org-timestamp-up 'org-timestamp-down)))
  15323. ((and (not (eq org-support-shift-select 'always))
  15324. org-priority-enable-commands
  15325. (org-at-heading-p))
  15326. (call-interactively 'org-priority-down))
  15327. ((and (not org-support-shift-select) (org-at-item-p))
  15328. (call-interactively 'org-next-item))
  15329. ((org-clocktable-try-shift 'down arg))
  15330. ((org-at-table-p) (org-table-move-cell-down))
  15331. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15332. (org-support-shift-select
  15333. (org-call-for-shift-select 'next-line))
  15334. (t (org-shiftselect-error))))
  15335. (defun org-shiftright (&optional arg)
  15336. "Act on the current element according to context.
  15337. This does one of the following:
  15338. - switch a timestamp at point one day into the future
  15339. - on a headline, switch to the next TODO keyword
  15340. - on an item, switch entire list to the next bullet type
  15341. - on a property line, switch to the next allowed value
  15342. - on a clocktable definition line, move time block into the future
  15343. - in a table, move a single cell right"
  15344. (interactive "P")
  15345. (cond
  15346. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15347. ((and org-support-shift-select (org-region-active-p))
  15348. (org-call-for-shift-select 'forward-char))
  15349. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15350. ((and (not (eq org-support-shift-select 'always))
  15351. (org-at-heading-p))
  15352. (let ((org-inhibit-logging
  15353. (not org-treat-S-cursor-todo-selection-as-state-change))
  15354. (org-inhibit-blocking
  15355. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15356. (org-call-with-arg 'org-todo 'right)))
  15357. ((or (and org-support-shift-select
  15358. (not (eq org-support-shift-select 'always))
  15359. (org-at-item-bullet-p))
  15360. (and (not org-support-shift-select) (org-at-item-p)))
  15361. (org-call-with-arg 'org-cycle-list-bullet nil))
  15362. ((and (not (eq org-support-shift-select 'always))
  15363. (org-at-property-p))
  15364. (call-interactively 'org-property-next-allowed-value))
  15365. ((org-clocktable-try-shift 'right arg))
  15366. ((org-at-table-p) (org-table-move-cell-right))
  15367. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15368. (org-support-shift-select
  15369. (org-call-for-shift-select 'forward-char))
  15370. (t (org-shiftselect-error))))
  15371. (defun org-shiftleft (&optional arg)
  15372. "Act on current element according to context.
  15373. This does one of the following:
  15374. - switch a timestamp at point one day into the past
  15375. - on a headline, switch to the previous TODO keyword.
  15376. - on an item, switch entire list to the previous bullet type
  15377. - on a property line, switch to the previous allowed value
  15378. - on a clocktable definition line, move time block into the past
  15379. - in a table, move a single cell left"
  15380. (interactive "P")
  15381. (cond
  15382. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15383. ((and org-support-shift-select (org-region-active-p))
  15384. (org-call-for-shift-select 'backward-char))
  15385. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15386. ((and (not (eq org-support-shift-select 'always))
  15387. (org-at-heading-p))
  15388. (let ((org-inhibit-logging
  15389. (not org-treat-S-cursor-todo-selection-as-state-change))
  15390. (org-inhibit-blocking
  15391. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15392. (org-call-with-arg 'org-todo 'left)))
  15393. ((or (and org-support-shift-select
  15394. (not (eq org-support-shift-select 'always))
  15395. (org-at-item-bullet-p))
  15396. (and (not org-support-shift-select) (org-at-item-p)))
  15397. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15398. ((and (not (eq org-support-shift-select 'always))
  15399. (org-at-property-p))
  15400. (call-interactively 'org-property-previous-allowed-value))
  15401. ((org-clocktable-try-shift 'left arg))
  15402. ((org-at-table-p) (org-table-move-cell-left))
  15403. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15404. (org-support-shift-select
  15405. (org-call-for-shift-select 'backward-char))
  15406. (t (org-shiftselect-error))))
  15407. (defun org-shiftcontrolright ()
  15408. "Switch to next TODO set."
  15409. (interactive)
  15410. (cond
  15411. ((and org-support-shift-select (org-region-active-p))
  15412. (org-call-for-shift-select 'forward-word))
  15413. ((and (not (eq org-support-shift-select 'always))
  15414. (org-at-heading-p))
  15415. (org-call-with-arg 'org-todo 'nextset))
  15416. (org-support-shift-select
  15417. (org-call-for-shift-select 'forward-word))
  15418. (t (org-shiftselect-error))))
  15419. (defun org-shiftcontrolleft ()
  15420. "Switch to previous TODO set."
  15421. (interactive)
  15422. (cond
  15423. ((and org-support-shift-select (org-region-active-p))
  15424. (org-call-for-shift-select 'backward-word))
  15425. ((and (not (eq org-support-shift-select 'always))
  15426. (org-at-heading-p))
  15427. (org-call-with-arg 'org-todo 'previousset))
  15428. (org-support-shift-select
  15429. (org-call-for-shift-select 'backward-word))
  15430. (t (org-shiftselect-error))))
  15431. (defun org-shiftcontrolup (&optional n)
  15432. "Change timestamps synchronously up in CLOCK log lines.
  15433. Optional argument N tells to change by that many units."
  15434. (interactive "P")
  15435. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15436. (let (org-support-shift-select)
  15437. (org-clock-timestamps-up n))
  15438. (user-error "Not at a clock log")))
  15439. (defun org-shiftcontroldown (&optional n)
  15440. "Change timestamps synchronously down in CLOCK log lines.
  15441. Optional argument N tells to change by that many units."
  15442. (interactive "P")
  15443. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15444. (let (org-support-shift-select)
  15445. (org-clock-timestamps-down n))
  15446. (user-error "Not at a clock log")))
  15447. (defun org-increase-number-at-point (&optional inc)
  15448. "Increment the number at point.
  15449. With an optional prefix numeric argument INC, increment using
  15450. this numeric value."
  15451. (interactive "p")
  15452. (if (not (number-at-point))
  15453. (user-error "Not on a number")
  15454. (unless inc (setq inc 1))
  15455. (let ((pos (point))
  15456. (beg (skip-chars-backward "-+^/*0-9eE."))
  15457. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15458. (setq nap (buffer-substring-no-properties
  15459. (+ pos beg) (+ pos beg end)))
  15460. (delete-region (+ pos beg) (+ pos beg end))
  15461. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15462. (when (org-at-table-p)
  15463. (org-table-align)
  15464. (org-table-end-of-field 1))))
  15465. (defun org-decrease-number-at-point (&optional inc)
  15466. "Decrement the number at point.
  15467. With an optional prefix numeric argument INC, decrement using
  15468. this numeric value."
  15469. (interactive "p")
  15470. (org-increase-number-at-point (- (or inc 1))))
  15471. (defun org-ctrl-c-ret ()
  15472. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  15473. (interactive)
  15474. (cond
  15475. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15476. (t (call-interactively 'org-insert-heading))))
  15477. (defun org-copy-visible (beg end)
  15478. "Copy the visible parts of the region."
  15479. (interactive "r")
  15480. (let ((result ""))
  15481. (while (/= beg end)
  15482. (when (get-char-property beg 'invisible)
  15483. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15484. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15485. (setq result (concat result (buffer-substring beg next)))
  15486. (setq beg next)))
  15487. (setq deactivate-mark t)
  15488. (kill-new result)
  15489. (message "Visible strings have been copied to the kill ring.")))
  15490. (defun org-copy-special ()
  15491. "Copy region in table or copy current subtree.
  15492. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15493. context. See the individual commands for more information."
  15494. (interactive)
  15495. (call-interactively
  15496. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15497. (defun org-cut-special ()
  15498. "Cut region in table or cut current subtree.
  15499. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15500. context. See the individual commands for more information."
  15501. (interactive)
  15502. (call-interactively
  15503. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15504. (defun org-paste-special (arg)
  15505. "Paste rectangular region into table, or past subtree relative to level.
  15506. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15507. See the individual commands for more information."
  15508. (interactive "P")
  15509. (if (org-at-table-p)
  15510. (org-table-paste-rectangle)
  15511. (org-paste-subtree arg)))
  15512. (defun org-edit-special (&optional arg)
  15513. "Call a special editor for the element at point.
  15514. When at a table, call the formula editor with `org-table-edit-formulas'.
  15515. When in a source code block, call `org-edit-src-code'.
  15516. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15517. When in an export block, call `org-edit-export-block'.
  15518. When in a LaTeX environment, call `org-edit-latex-environment'.
  15519. When at an #+INCLUDE keyword, visit the included file.
  15520. When at a footnote reference, call `org-edit-footnote-reference'.
  15521. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15522. When at an active timestamp, call `org-time-stamp'.
  15523. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15524. On a link, call `ffap' to visit the link at point.
  15525. Otherwise, return a user error."
  15526. (interactive "P")
  15527. (let ((element (org-element-at-point)))
  15528. (barf-if-buffer-read-only)
  15529. (pcase (org-element-type element)
  15530. (`src-block
  15531. (if (not arg) (org-edit-src-code)
  15532. (let* ((info (org-babel-get-src-block-info))
  15533. (lang (nth 0 info))
  15534. (params (nth 2 info))
  15535. (session (cdr (assq :session params))))
  15536. (if (not session) (org-edit-src-code)
  15537. ;; At a source block with a session and function called
  15538. ;; with an ARG: switch to the buffer related to the
  15539. ;; inferior process.
  15540. (switch-to-buffer
  15541. (funcall (intern (concat "org-babel-prep-session:" lang))
  15542. session params))))))
  15543. (`keyword
  15544. (unless (member (org-element-property :key element)
  15545. '("INCLUDE" "SETUPFILE"))
  15546. (user-error "No special environment to edit here"))
  15547. (let ((value (org-element-property :value element)))
  15548. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15549. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15550. (or (match-string 1 value)
  15551. (match-string 0 value)))))
  15552. (when (org-file-url-p file)
  15553. (user-error "Files located with a URL cannot be edited"))
  15554. (org-link-open-from-string
  15555. (format "[[%s]]" (expand-file-name file))))))
  15556. (`table
  15557. (if (eq (org-element-property :type element) 'table.el)
  15558. (org-edit-table.el)
  15559. (call-interactively 'org-table-edit-formulas)))
  15560. ;; Only Org tables contain `table-row' type elements.
  15561. (`table-row (call-interactively 'org-table-edit-formulas))
  15562. (`example-block (org-edit-src-code))
  15563. (`export-block (org-edit-export-block))
  15564. (`fixed-width (org-edit-fixed-width-region))
  15565. (`latex-environment (org-edit-latex-environment))
  15566. (`planning
  15567. (let ((proplist (cadr element)))
  15568. (mapc #'call-interactively
  15569. (remq nil
  15570. (list
  15571. (when (plist-get proplist :deadline) #'org-deadline)
  15572. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15573. (_
  15574. ;; No notable element at point. Though, we may be at a link or
  15575. ;; a footnote reference, which are objects. Thus, scan deeper.
  15576. (let ((context (org-element-context element)))
  15577. (pcase (org-element-type context)
  15578. (`footnote-reference (org-edit-footnote-reference))
  15579. (`inline-src-block (org-edit-inline-src-code))
  15580. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15581. (call-interactively #'org-time-stamp-inactive)
  15582. (call-interactively #'org-time-stamp)))
  15583. (`link (call-interactively #'ffap))
  15584. (_ (user-error "No special environment to edit here"))))))))
  15585. (defun org-ctrl-c-ctrl-c (&optional arg)
  15586. "Set tags in headline, or update according to changed information at point.
  15587. This command does many different things, depending on context:
  15588. - If column view is active, in agenda or org buffers, quit it.
  15589. - If there are highlights, remove them.
  15590. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15591. this is what we do.
  15592. - If the cursor is on a statistics cookie, update it.
  15593. - If the cursor is in a headline, in an agenda or an org buffer,
  15594. prompt for tags and insert them into the current line, aligned
  15595. to `org-tags-column'. When called with prefix arg, realign all
  15596. tags in the current buffer.
  15597. - If the cursor is in one of the special #+KEYWORD lines, this
  15598. triggers scanning the buffer for these lines and updating the
  15599. information.
  15600. - If the cursor is inside a table, realign the table. This command
  15601. works even if the automatic table editor has been turned off.
  15602. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15603. the entire table.
  15604. - If the cursor is at a footnote reference or definition, jump to
  15605. the corresponding definition or references, respectively.
  15606. - If the cursor is a the beginning of a dynamic block, update it.
  15607. - If the current buffer is a capture buffer, close note and file it.
  15608. - If the cursor is on a <<<target>>>, update radio targets and
  15609. corresponding links in this buffer.
  15610. - If the cursor is on a numbered item in a plain list, renumber the
  15611. ordered list.
  15612. - If the cursor is on a checkbox, toggle it.
  15613. - If the cursor is on a code block, evaluate it. The variable
  15614. `org-confirm-babel-evaluate' can be used to control prompting
  15615. before code block evaluation, by default every code block
  15616. evaluation requires confirmation. Code block evaluation can be
  15617. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15618. (interactive "P")
  15619. (cond
  15620. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15621. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15622. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15623. (org-remove-occur-highlights)
  15624. (message "Temporary highlights/overlays removed from current buffer"))
  15625. ((and (local-variable-p 'org-finish-function)
  15626. (fboundp org-finish-function))
  15627. (funcall org-finish-function))
  15628. ((org-babel-hash-at-point))
  15629. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15630. (t
  15631. (let* ((context
  15632. (org-element-lineage
  15633. (org-element-context)
  15634. ;; Limit to supported contexts.
  15635. '(babel-call clock dynamic-block footnote-definition
  15636. footnote-reference inline-babel-call inline-src-block
  15637. inlinetask item keyword node-property paragraph
  15638. plain-list planning property-drawer radio-target
  15639. src-block statistics-cookie table table-cell table-row
  15640. timestamp)
  15641. t))
  15642. (radio-list-p (org-at-radio-list-p))
  15643. (type (org-element-type context)))
  15644. ;; For convenience: at the first line of a paragraph on the same
  15645. ;; line as an item, apply function on that item instead.
  15646. (when (eq type 'paragraph)
  15647. (let ((parent (org-element-property :parent context)))
  15648. (when (and (eq (org-element-type parent) 'item)
  15649. (= (line-beginning-position)
  15650. (org-element-property :begin parent)))
  15651. (setq context parent)
  15652. (setq type 'item))))
  15653. ;; Act according to type of element or object at point.
  15654. ;;
  15655. ;; Do nothing on a blank line, except if it is contained in
  15656. ;; a source block. Hence, we first check if point is in such
  15657. ;; a block and then if it is at a blank line.
  15658. (pcase type
  15659. ((or `inline-src-block `src-block)
  15660. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15661. (org-babel-eval-wipe-error-buffer)
  15662. (org-babel-execute-src-block
  15663. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15664. ((guard (org-match-line "[ \t]*$"))
  15665. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15666. (user-error
  15667. (substitute-command-keys
  15668. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15669. ((or `babel-call `inline-babel-call)
  15670. (let ((info (org-babel-lob-get-info context)))
  15671. (when info (org-babel-execute-src-block nil info))))
  15672. (`clock (org-clock-update-time-maybe))
  15673. (`dynamic-block
  15674. (save-excursion
  15675. (goto-char (org-element-property :post-affiliated context))
  15676. (org-update-dblock)))
  15677. (`footnote-definition
  15678. (goto-char (org-element-property :post-affiliated context))
  15679. (call-interactively 'org-footnote-action))
  15680. (`footnote-reference (call-interactively #'org-footnote-action))
  15681. ((or `headline `inlinetask)
  15682. (save-excursion (goto-char (org-element-property :begin context))
  15683. (call-interactively #'org-set-tags-command)))
  15684. (`item
  15685. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15686. ;; unconditionally, whereas `C-u' will toggle its presence.
  15687. ;; Without a universal argument, if the item has a checkbox,
  15688. ;; toggle it. Otherwise repair the list.
  15689. (if (or radio-list-p
  15690. (and (boundp org-list-checkbox-radio-mode)
  15691. org-list-checkbox-radio-mode))
  15692. (org-toggle-radio-button arg)
  15693. (let* ((box (org-element-property :checkbox context))
  15694. (struct (org-element-property :structure context))
  15695. (old-struct (copy-tree struct))
  15696. (parents (org-list-parents-alist struct))
  15697. (prevs (org-list-prevs-alist struct))
  15698. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15699. (org-list-set-checkbox
  15700. (org-element-property :begin context) struct
  15701. (cond ((equal arg '(16)) "[-]")
  15702. ((and (not box) (equal arg '(4))) "[ ]")
  15703. ((or (not box) (equal arg '(4))) nil)
  15704. ((eq box 'on) "[ ]")
  15705. (t "[X]")))
  15706. ;; Mimic `org-list-write-struct' but with grabbing a return
  15707. ;; value from `org-list-struct-fix-box'.
  15708. (org-list-struct-fix-ind struct parents 2)
  15709. (org-list-struct-fix-item-end struct)
  15710. (org-list-struct-fix-bul struct prevs)
  15711. (org-list-struct-fix-ind struct parents)
  15712. (let ((block-item
  15713. (org-list-struct-fix-box struct parents prevs orderedp)))
  15714. (if (and box (equal struct old-struct))
  15715. (if (equal arg '(16))
  15716. (message "Checkboxes already reset")
  15717. (user-error "Cannot toggle this checkbox: %s"
  15718. (if (eq box 'on)
  15719. "all subitems checked"
  15720. "unchecked subitems")))
  15721. (org-list-struct-apply-struct struct old-struct)
  15722. (org-update-checkbox-count-maybe))
  15723. (when block-item
  15724. (message "Checkboxes were removed due to empty box at line %d"
  15725. (org-current-line block-item)))))))
  15726. (`plain-list
  15727. ;; At a plain list, with a double C-u argument, set
  15728. ;; checkboxes of each item to "[-]", whereas a single one
  15729. ;; will toggle their presence according to the state of the
  15730. ;; first item in the list. Without an argument, repair the
  15731. ;; list.
  15732. (if (or radio-list-p
  15733. (and (boundp org-list-checkbox-radio-mode)
  15734. org-list-checkbox-radio-mode))
  15735. (org-toggle-radio-button arg)
  15736. (let* ((begin (org-element-property :contents-begin context))
  15737. (struct (org-element-property :structure context))
  15738. (old-struct (copy-tree struct))
  15739. (first-box (save-excursion
  15740. (goto-char begin)
  15741. (looking-at org-list-full-item-re)
  15742. (match-string-no-properties 3)))
  15743. (new-box (cond ((equal arg '(16)) "[-]")
  15744. ((equal arg '(4)) (unless first-box "[ ]"))
  15745. ((equal first-box "[X]") "[ ]")
  15746. (t "[X]"))))
  15747. (cond
  15748. (arg
  15749. (dolist (pos
  15750. (org-list-get-all-items
  15751. begin struct (org-list-prevs-alist struct)))
  15752. (org-list-set-checkbox pos struct new-box)))
  15753. ((and first-box (eq (point) begin))
  15754. ;; For convenience, when point is at bol on the first
  15755. ;; item of the list and no argument is provided, simply
  15756. ;; toggle checkbox of that item, if any.
  15757. (org-list-set-checkbox begin struct new-box)))
  15758. (when (equal
  15759. (org-list-write-struct
  15760. struct (org-list-parents-alist struct) old-struct)
  15761. old-struct)
  15762. (message "Cannot update this checkbox"))
  15763. (org-update-checkbox-count-maybe))))
  15764. (`keyword
  15765. (let ((org-inhibit-startup-visibility-stuff t)
  15766. (org-startup-align-all-tables nil))
  15767. (when (boundp 'org-table-coordinate-overlays)
  15768. (mapc #'delete-overlay org-table-coordinate-overlays)
  15769. (setq org-table-coordinate-overlays nil))
  15770. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15771. (message "Local setup has been refreshed"))
  15772. ((or `property-drawer `node-property)
  15773. (call-interactively #'org-property-action))
  15774. (`radio-target
  15775. (call-interactively #'org-update-radio-target-regexp))
  15776. (`statistics-cookie
  15777. (call-interactively #'org-update-statistics-cookies))
  15778. ((or `table `table-cell `table-row)
  15779. ;; At a table, recalculate every field and align it. Also
  15780. ;; send the table if necessary. If the table has
  15781. ;; a `table.el' type, just give up. At a table row or cell,
  15782. ;; maybe recalculate line but always align table.
  15783. (if (eq (org-element-property :type context) 'table.el)
  15784. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15785. Use `\\[org-edit-special]' to edit table.el tables"))
  15786. (if (or (eq type 'table)
  15787. ;; Check if point is at a TBLFM line.
  15788. (and (eq type 'table-row)
  15789. (= (point) (org-element-property :end context))))
  15790. (save-excursion
  15791. (if (org-at-TBLFM-p)
  15792. (progn (require 'org-table)
  15793. (org-table-calc-current-TBLFM))
  15794. (goto-char (org-element-property :contents-begin context))
  15795. (org-call-with-arg 'org-table-recalculate (or arg t))
  15796. (orgtbl-send-table 'maybe)))
  15797. (org-table-maybe-eval-formula)
  15798. (cond (arg (call-interactively #'org-table-recalculate))
  15799. ((org-table-maybe-recalculate-line))
  15800. (t (org-table-align))))))
  15801. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15802. (org-timestamp-change 0 'day))
  15803. ((and `nil (guard (org-at-heading-p)))
  15804. ;; When point is on an unsupported object type, we can miss
  15805. ;; the fact that it also is at a heading. Handle it here.
  15806. (call-interactively #'org-set-tags-command))
  15807. ((guard
  15808. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15809. (_
  15810. (user-error
  15811. (substitute-command-keys
  15812. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15813. (defun org-mode-restart ()
  15814. (interactive)
  15815. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15816. (funcall major-mode)
  15817. (hack-local-variables)
  15818. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15819. (org-indent-mode -1))
  15820. (org-reset-file-cache))
  15821. (message "%s restarted" major-mode))
  15822. (defun org-flag-above-first-heading (&optional arg)
  15823. "Hide from bob up to the first heading.
  15824. Move point to the beginning of first heading or end of buffer."
  15825. (goto-char (point-min))
  15826. (unless (org-at-heading-p)
  15827. (outline-next-heading))
  15828. (unless (bobp)
  15829. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  15830. (defun org-show-branches-buffer ()
  15831. "Show all branches in the buffer."
  15832. (org-flag-above-first-heading)
  15833. (outline-hide-sublevels 1)
  15834. (unless (eobp)
  15835. (outline-show-branches)
  15836. (while (outline-get-next-sibling)
  15837. (outline-show-branches)))
  15838. (goto-char (point-min)))
  15839. (defun org-kill-note-or-show-branches ()
  15840. "Abort storing current note, or show just branches."
  15841. (interactive)
  15842. (cond (org-finish-function
  15843. (let ((org-note-abort t)) (funcall org-finish-function)))
  15844. ((org-before-first-heading-p)
  15845. (org-show-branches-buffer)
  15846. (org-hide-archived-subtrees (point-min) (point-max)))
  15847. (t
  15848. (let ((beg (progn (org-back-to-heading) (point)))
  15849. (end (save-excursion (org-end-of-subtree t t) (point))))
  15850. (outline-hide-subtree)
  15851. (outline-show-branches)
  15852. (org-hide-archived-subtrees beg end)))))
  15853. (defun org-delete-indentation (&optional arg)
  15854. "Join current line to previous and fix whitespace at join.
  15855. If previous line is a headline add to headline title. Otherwise
  15856. the function calls `delete-indentation'.
  15857. With a non-nil optional argument, join it to the following one."
  15858. (interactive "*P")
  15859. (if (save-excursion
  15860. (beginning-of-line (if arg 1 0))
  15861. (let ((case-fold-search nil))
  15862. (looking-at org-complex-heading-regexp)))
  15863. ;; At headline.
  15864. (let ((tags-column (when (match-beginning 5)
  15865. (save-excursion (goto-char (match-beginning 5))
  15866. (current-column))))
  15867. (string (concat " " (progn (when arg (forward-line 1))
  15868. (org-trim (delete-and-extract-region
  15869. (line-beginning-position)
  15870. (line-end-position)))))))
  15871. (unless (bobp) (delete-region (point) (1- (point))))
  15872. (goto-char (or (match-end 4)
  15873. (match-beginning 5)
  15874. (match-end 0)))
  15875. (skip-chars-backward " \t")
  15876. (save-excursion (insert string))
  15877. ;; Adjust alignment of tags.
  15878. (cond
  15879. ((not tags-column)) ;no tags
  15880. (org-auto-align-tags (org-align-tags))
  15881. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15882. (delete-indentation arg)))
  15883. (defun org-open-line (n)
  15884. "Insert a new row in tables, call `open-line' elsewhere.
  15885. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15886. As a special case, when a document starts with a table, allow to
  15887. call `open-line' on the very first character."
  15888. (interactive "*p")
  15889. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15890. (org-table-insert-row)
  15891. (open-line n)))
  15892. (defun org-return (&optional indent)
  15893. "Goto next table row or insert a newline.
  15894. Calls `org-table-next-row' or `newline', depending on context.
  15895. When optional INDENT argument is non-nil, call
  15896. `newline-and-indent' instead of `newline'.
  15897. When `org-return-follows-link' is non-nil and point is on
  15898. a timestamp or a link, call `org-open-at-point'. However, it
  15899. will not happen if point is in a table or on a \"dead\"
  15900. object (e.g., within a comment). In these case, you need to use
  15901. `org-open-at-point' directly."
  15902. (interactive)
  15903. (let ((context (if org-return-follows-link (org-element-context)
  15904. (org-element-at-point))))
  15905. (cond
  15906. ;; In a table, call `org-table-next-row'. However, before first
  15907. ;; column or after last one, split the table.
  15908. ((or (and (eq 'table (org-element-type context))
  15909. (not (eq 'table.el (org-element-property :type context)))
  15910. (>= (point) (org-element-property :contents-begin context))
  15911. (< (point) (org-element-property :contents-end context)))
  15912. (org-element-lineage context '(table-row table-cell) t))
  15913. (if (or (looking-at-p "[ \t]*$")
  15914. (save-excursion (skip-chars-backward " \t") (bolp)))
  15915. (insert "\n")
  15916. (org-table-justify-field-maybe)
  15917. (call-interactively #'org-table-next-row)))
  15918. ;; On a link or a timestamp, call `org-open-at-point' if
  15919. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15920. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15921. ((and org-return-follows-link
  15922. (or (and (eq 'link (org-element-type context))
  15923. ;; Ensure point is not on the white spaces after
  15924. ;; the link.
  15925. (let ((origin (point)))
  15926. (org-with-point-at (org-element-property :end context)
  15927. (skip-chars-backward " \t")
  15928. (> (point) origin))))
  15929. (org-in-regexp org-ts-regexp-both nil t)
  15930. (org-in-regexp org-tsr-regexp-both nil t)
  15931. (org-in-regexp org-link-any-re nil t)))
  15932. (call-interactively #'org-open-at-point))
  15933. ;; Insert newline in heading, but preserve tags.
  15934. ((and (not (bolp))
  15935. (let ((case-fold-search nil))
  15936. (org-match-line org-complex-heading-regexp)))
  15937. ;; At headline. Split line. However, if point is on keyword,
  15938. ;; priority cookie or tags, do not break any of them: add
  15939. ;; a newline after the headline instead.
  15940. (let ((tags-column (and (match-beginning 5)
  15941. (save-excursion (goto-char (match-beginning 5))
  15942. (current-column))))
  15943. (string
  15944. (when (and (match-end 4) (org-point-in-group (point) 4))
  15945. (delete-and-extract-region (point) (match-end 4)))))
  15946. ;; Adjust tag alignment.
  15947. (cond
  15948. ((not (and tags-column string)))
  15949. (org-auto-align-tags (org-align-tags))
  15950. (t (org--align-tags-here tags-column))) ;preserve tags column
  15951. (end-of-line)
  15952. (org-show-entry)
  15953. (if indent (newline-and-indent) (newline))
  15954. (when string (save-excursion (insert (org-trim string))))))
  15955. ;; In a list, make sure indenting keeps trailing text within.
  15956. ((and indent
  15957. (not (eolp))
  15958. (org-element-lineage context '(item)))
  15959. (let ((trailing-data
  15960. (delete-and-extract-region (point) (line-end-position))))
  15961. (newline-and-indent)
  15962. (save-excursion (insert trailing-data))))
  15963. (t
  15964. ;; Do not auto-fill when point is in an Org property drawer.
  15965. (let ((auto-fill-function (and (not (org-at-property-p))
  15966. auto-fill-function)))
  15967. (if indent
  15968. (newline-and-indent)
  15969. (newline)))))))
  15970. (defun org-return-indent ()
  15971. "Goto next table row or insert a newline and indent.
  15972. Calls `org-table-next-row' or `newline-and-indent', depending on
  15973. context. See the individual commands for more information."
  15974. (interactive)
  15975. (org-return t))
  15976. (defun org-ctrl-c-tab (&optional arg)
  15977. "Toggle columns width in a table, or show children.
  15978. Call `org-table-toggle-column-width' if point is in a table.
  15979. Otherwise, call `org-show-children'. ARG is the level to hide."
  15980. (interactive "p")
  15981. (if (org-at-table-p)
  15982. (call-interactively #'org-table-toggle-column-width)
  15983. (if (org-before-first-heading-p)
  15984. (progn
  15985. (org-flag-above-first-heading)
  15986. (outline-hide-sublevels (or arg 1))
  15987. (goto-char (point-min)))
  15988. (outline-hide-subtree)
  15989. (org-show-children arg))))
  15990. (defun org-ctrl-c-star ()
  15991. "Compute table, or change heading status of lines.
  15992. Calls `org-table-recalculate' or `org-toggle-heading',
  15993. depending on context."
  15994. (interactive)
  15995. (cond
  15996. ((org-at-table-p)
  15997. (call-interactively 'org-table-recalculate))
  15998. (t
  15999. ;; Convert all lines in region to list items
  16000. (call-interactively 'org-toggle-heading))))
  16001. (defun org-ctrl-c-minus ()
  16002. "Insert separator line in table or modify bullet status of line.
  16003. Also turns a plain line or a region of lines into list items.
  16004. Calls `org-table-insert-hline', `org-toggle-item', or
  16005. `org-cycle-list-bullet', depending on context."
  16006. (interactive)
  16007. (cond
  16008. ((org-at-table-p)
  16009. (call-interactively 'org-table-insert-hline))
  16010. ((org-region-active-p)
  16011. (call-interactively 'org-toggle-item))
  16012. ((org-in-item-p)
  16013. (call-interactively 'org-cycle-list-bullet))
  16014. (t
  16015. (call-interactively 'org-toggle-item))))
  16016. (defun org-toggle-heading (&optional nstars)
  16017. "Convert headings to normal text, or items or text to headings.
  16018. If there is no active region, only convert the current line.
  16019. With a `\\[universal-argument]' prefix, convert the whole list at
  16020. point into heading.
  16021. In a region:
  16022. - If the first non blank line is a headline, remove the stars
  16023. from all headlines in the region.
  16024. - If it is a normal line, turn each and every normal line (i.e.,
  16025. not an heading or an item) in the region into headings. If you
  16026. want to convert only the first line of this region, use one
  16027. universal prefix argument.
  16028. - If it is a plain list item, turn all plain list items into headings.
  16029. When converting a line into a heading, the number of stars is chosen
  16030. such that the lines become children of the current entry. However,
  16031. when a numeric prefix argument is given, its value determines the
  16032. number of stars to add."
  16033. (interactive "P")
  16034. (let ((skip-blanks
  16035. (function
  16036. ;; Return beginning of first non-blank line, starting from
  16037. ;; line at POS.
  16038. (lambda (pos)
  16039. (save-excursion
  16040. (goto-char pos)
  16041. (while (org-at-comment-p) (forward-line))
  16042. (skip-chars-forward " \r\t\n")
  16043. (point-at-bol)))))
  16044. beg end toggled)
  16045. ;; Determine boundaries of changes. If a universal prefix has
  16046. ;; been given, put the list in a region. If region ends at a bol,
  16047. ;; do not consider the last line to be in the region.
  16048. (when (and current-prefix-arg (org-at-item-p))
  16049. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16050. (org-mark-element))
  16051. (if (org-region-active-p)
  16052. (setq beg (funcall skip-blanks (region-beginning))
  16053. end (copy-marker (save-excursion
  16054. (goto-char (region-end))
  16055. (if (bolp) (point) (point-at-eol)))))
  16056. (setq beg (funcall skip-blanks (point-at-bol))
  16057. end (copy-marker (point-at-eol))))
  16058. ;; Ensure inline tasks don't count as headings.
  16059. (org-with-limited-levels
  16060. (save-excursion
  16061. (goto-char beg)
  16062. (cond
  16063. ;; Case 1. Started at an heading: de-star headings.
  16064. ((org-at-heading-p)
  16065. (while (< (point) end)
  16066. (when (org-at-heading-p t)
  16067. (looking-at org-outline-regexp) (replace-match "")
  16068. (setq toggled t))
  16069. (forward-line)))
  16070. ;; Case 2. Started at an item: change items into headlines.
  16071. ;; One star will be added by `org-list-to-subtree'.
  16072. ((org-at-item-p)
  16073. (while (< (point) end)
  16074. (when (org-at-item-p)
  16075. ;; Pay attention to cases when region ends before list.
  16076. (let* ((struct (org-list-struct))
  16077. (list-end
  16078. (min (org-list-get-bottom-point struct) (1+ end))))
  16079. (save-restriction
  16080. (narrow-to-region (point) list-end)
  16081. (insert (org-list-to-subtree
  16082. (org-list-to-lisp t)
  16083. (pcase (org-current-level)
  16084. (`nil 1)
  16085. (l (1+ (org-reduced-level l)))))
  16086. "\n")))
  16087. (setq toggled t))
  16088. (forward-line)))
  16089. ;; Case 3. Started at normal text: make every line an heading,
  16090. ;; skipping headlines and items.
  16091. (t (let* ((stars
  16092. (make-string
  16093. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16094. (add-stars
  16095. (cond (nstars "") ; stars from prefix only
  16096. ((equal stars "") "*") ; before first heading
  16097. (org-odd-levels-only "**") ; inside heading, odd
  16098. (t "*"))) ; inside heading, oddeven
  16099. (rpl (concat stars add-stars " "))
  16100. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16101. (while (< (point) (if (equal nstars '(4)) lend end))
  16102. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16103. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16104. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16105. (forward-line)))))))
  16106. (unless toggled (message "Cannot toggle heading from here"))))
  16107. (defun org-meta-return (&optional arg)
  16108. "Insert a new heading or wrap a region in a table.
  16109. Calls `org-insert-heading', `org-insert-item' or
  16110. `org-table-wrap-region', depending on context. When called with
  16111. an argument, unconditionally call `org-insert-heading'."
  16112. (interactive "P")
  16113. (org-check-before-invisible-edit 'insert)
  16114. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16115. (call-interactively (cond (arg #'org-insert-heading)
  16116. ((org-at-table-p) #'org-table-wrap-region)
  16117. ((org-in-item-p) #'org-insert-item)
  16118. (t #'org-insert-heading)))))
  16119. ;;; Menu entries
  16120. (defsubst org-in-subtree-not-table-p ()
  16121. "Are we in a subtree and not in a table?"
  16122. (and (not (org-before-first-heading-p))
  16123. (not (org-at-table-p))))
  16124. ;; Define the Org mode menus
  16125. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16126. `("Org"
  16127. ("Show/Hide"
  16128. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16129. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16130. ["Sparse Tree..." org-sparse-tree t]
  16131. ["Reveal Context" org-reveal t]
  16132. ["Show All" org-show-all t]
  16133. "--"
  16134. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16135. "--"
  16136. ["New Heading" org-insert-heading t]
  16137. ("Navigate Headings"
  16138. ["Up" outline-up-heading t]
  16139. ["Next" outline-next-visible-heading t]
  16140. ["Previous" outline-previous-visible-heading t]
  16141. ["Next Same Level" outline-forward-same-level t]
  16142. ["Previous Same Level" outline-backward-same-level t]
  16143. "--"
  16144. ["Jump" org-goto t])
  16145. ("Edit Structure"
  16146. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16147. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16148. "--"
  16149. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16150. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16151. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16152. "--"
  16153. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16154. "--"
  16155. ["Copy visible text" org-copy-visible t]
  16156. "--"
  16157. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16158. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16159. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16160. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16161. "--"
  16162. ["Sort Region/Children" org-sort t]
  16163. "--"
  16164. ["Convert to odd levels" org-convert-to-odd-levels t]
  16165. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16166. ("Editing"
  16167. ["Emphasis..." org-emphasize t]
  16168. ["Edit Source Example" org-edit-special t]
  16169. "--"
  16170. ["Footnote new/jump" org-footnote-action t]
  16171. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16172. ("Archive"
  16173. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16174. "--"
  16175. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16176. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16177. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16178. "--"
  16179. ("Hyperlinks"
  16180. ["Store Link (Global)" org-store-link t]
  16181. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16182. ["Insert Link" org-insert-link t]
  16183. ["Follow Link" org-open-at-point t]
  16184. "--"
  16185. ["Next link" org-next-link t]
  16186. ["Previous link" org-previous-link t]
  16187. "--"
  16188. ["Descriptive Links"
  16189. org-toggle-link-display
  16190. :style radio
  16191. :selected org-descriptive-links
  16192. ]
  16193. ["Literal Links"
  16194. org-toggle-link-display
  16195. :style radio
  16196. :selected (not org-descriptive-links)])
  16197. "--"
  16198. ("TODO Lists"
  16199. ["TODO/DONE/-" org-todo t]
  16200. ("Select keyword"
  16201. ["Next keyword" org-shiftright (org-at-heading-p)]
  16202. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16203. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16204. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16205. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16206. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16207. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16208. "--"
  16209. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16210. :selected org-enforce-todo-dependencies :style toggle :active t]
  16211. "Settings for tree at point"
  16212. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16213. :selected (org-entry-get nil "ORDERED")
  16214. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16215. ["Do Children parallel" org-toggle-ordered-property :style radio
  16216. :selected (not (org-entry-get nil "ORDERED"))
  16217. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16218. "--"
  16219. ["Set Priority" org-priority t]
  16220. ["Priority Up" org-shiftup t]
  16221. ["Priority Down" org-shiftdown t]
  16222. "--"
  16223. ["Get news from all feeds" org-feed-update-all t]
  16224. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16225. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16226. ("TAGS and Properties"
  16227. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16228. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16229. "--"
  16230. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16231. ["Column view of properties" org-columns t]
  16232. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16233. ("Dates and Scheduling"
  16234. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16235. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16236. ("Change Date"
  16237. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16238. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16239. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16240. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16241. ["Compute Time Range" org-evaluate-time-range t]
  16242. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16243. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16244. "--"
  16245. ["Custom time format" org-toggle-time-stamp-overlays
  16246. :style radio :selected org-display-custom-times]
  16247. "--"
  16248. ["Goto Calendar" org-goto-calendar t]
  16249. ["Date from Calendar" org-date-from-calendar t]
  16250. "--"
  16251. ["Start/Restart Timer" org-timer-start t]
  16252. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16253. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16254. ["Insert Timer String" org-timer t]
  16255. ["Insert Timer Item" org-timer-item t])
  16256. ("Logging work"
  16257. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16258. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16259. ["Clock out" org-clock-out t]
  16260. ["Clock cancel" org-clock-cancel t]
  16261. "--"
  16262. ["Mark as default task" org-clock-mark-default-task t]
  16263. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16264. ["Goto running clock" org-clock-goto t]
  16265. "--"
  16266. ["Display times" org-clock-display t]
  16267. ["Create clock table" org-clock-report t]
  16268. "--"
  16269. ["Record DONE time"
  16270. (progn (setq org-log-done (not org-log-done))
  16271. (message "Switching to %s will %s record a timestamp"
  16272. (car org-done-keywords)
  16273. (if org-log-done "automatically" "not")))
  16274. :style toggle :selected org-log-done])
  16275. "--"
  16276. ["Agenda Command..." org-agenda t]
  16277. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16278. ("File List for Agenda")
  16279. ("Special views current file"
  16280. ["TODO Tree" org-show-todo-tree t]
  16281. ["Check Deadlines" org-check-deadlines t]
  16282. ["Tags/Property tree" org-match-sparse-tree t])
  16283. "--"
  16284. ["Export/Publish..." org-export-dispatch t]
  16285. ("LaTeX"
  16286. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16287. :style toggle :selected org-cdlatex-mode]
  16288. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16289. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16290. ["Modify math symbol" org-cdlatex-math-modify
  16291. (org-inside-LaTeX-fragment-p)]
  16292. ["Insert citation" org-reftex-citation t])
  16293. "--"
  16294. ("Documentation"
  16295. ["Show Version" org-version t]
  16296. ["Info Documentation" org-info t]
  16297. ["Browse Org News" org-browse-news t])
  16298. ("Customize"
  16299. ["Browse Org Group" org-customize t]
  16300. "--"
  16301. ["Expand This Menu" org-create-customize-menu
  16302. (fboundp 'customize-menu-create)])
  16303. ["Send bug report" org-submit-bug-report t]
  16304. "--"
  16305. ("Refresh/Reload"
  16306. ["Refresh setup current buffer" org-mode-restart t]
  16307. ["Reload Org (after update)" org-reload t]
  16308. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16309. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16310. '("Table"
  16311. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16312. ["Next Field" org-cycle (org-at-table-p)]
  16313. ["Previous Field" org-shifttab (org-at-table-p)]
  16314. ["Next Row" org-return (org-at-table-p)]
  16315. "--"
  16316. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16317. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16318. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16319. "--"
  16320. ("Column"
  16321. ["Move Column Left" org-metaleft (org-at-table-p)]
  16322. ["Move Column Right" org-metaright (org-at-table-p)]
  16323. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16324. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16325. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16326. ("Row"
  16327. ["Move Row Up" org-metaup (org-at-table-p)]
  16328. ["Move Row Down" org-metadown (org-at-table-p)]
  16329. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16330. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16331. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16332. "--"
  16333. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16334. ("Rectangle"
  16335. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16336. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16337. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16338. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16339. "--"
  16340. ("Calculate"
  16341. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16342. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16343. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16344. "--"
  16345. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16346. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16347. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16348. "--"
  16349. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16350. "--"
  16351. ["Sum Column/Rectangle" org-table-sum
  16352. (or (org-at-table-p) (org-region-active-p))]
  16353. ["Which Column?" org-table-current-column (org-at-table-p)])
  16354. ["Debug Formulas"
  16355. org-table-toggle-formula-debugger
  16356. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16357. ["Show Col/Row Numbers"
  16358. org-table-toggle-coordinate-overlays
  16359. :style toggle
  16360. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16361. "--"
  16362. ["Create" org-table-create (not (org-at-table-p))]
  16363. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16364. ["Import from File" org-table-import (not (org-at-table-p))]
  16365. ["Export to File" org-table-export (org-at-table-p)]
  16366. "--"
  16367. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16368. "--"
  16369. ("Plot"
  16370. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16371. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16372. (defun org-info (&optional node)
  16373. "Read documentation for Org in the info system.
  16374. With optional NODE, go directly to that node."
  16375. (interactive)
  16376. (info (format "(org)%s" (or node ""))))
  16377. (defun org-browse-news ()
  16378. "Browse the news for the latest major release."
  16379. (interactive)
  16380. (browse-url "https://orgmode.org/Changes.html"))
  16381. ;;;###autoload
  16382. (defun org-submit-bug-report ()
  16383. "Submit a bug report on Org via mail.
  16384. Don't hesitate to report any problems or inaccurate documentation.
  16385. If you don't have setup sending mail from (X)Emacs, please copy the
  16386. output buffer into your mail program, as it gives us important
  16387. information about your Org version and configuration."
  16388. (interactive)
  16389. (require 'reporter)
  16390. (defvar reporter-prompt-for-summary-p)
  16391. (org-load-modules-maybe)
  16392. (org-require-autoloaded-modules)
  16393. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16394. (reporter-submit-bug-report
  16395. "emacs-orgmode@gnu.org"
  16396. (org-version nil 'full)
  16397. (let (list)
  16398. (save-window-excursion
  16399. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16400. (delete-other-windows)
  16401. (erase-buffer)
  16402. (insert "You are about to submit a bug report to the Org mailing list.
  16403. If your report is about Org installation, please read this section:
  16404. https://orgmode.org/org.html#Installation
  16405. Please read https://orgmode.org/org.html#Feedback on how to make
  16406. a good report, it will help Org contributors fixing your problem.
  16407. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16408. if the issue you are about to raise has already been dealt with.
  16409. We also would like to add your full Org and Outline configuration
  16410. to the bug report. It will help us debugging the issue.
  16411. *HOWEVER*, some variables you have customized may contain private
  16412. information. The names of customers, colleagues, or friends, might
  16413. appear in the form of file names, tags, todo states or search strings.
  16414. If you answer \"yes\" to the prompt, you might want to check and remove
  16415. such private information before sending the email.")
  16416. (add-text-properties (point-min) (point-max) '(face org-warning))
  16417. (when (yes-or-no-p "Include your Org configuration ")
  16418. (mapatoms
  16419. (lambda (v)
  16420. (and (boundp v)
  16421. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16422. (or (and (symbol-value v)
  16423. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16424. (and
  16425. (get v 'custom-type) (get v 'standard-value)
  16426. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16427. (push v list)))))
  16428. (kill-buffer (get-buffer "*Warn about privacy*"))
  16429. list))
  16430. nil nil
  16431. "Remember to cover the basics, that is, what you expected to happen and
  16432. what in fact did happen. You don't know how to make a good report? See
  16433. https://orgmode.org/manual/Feedback.html#Feedback
  16434. Your bug report will be posted to the Org mailing list.
  16435. ------------------------------------------------------------------------")
  16436. (save-excursion
  16437. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16438. (replace-match "\\1Bug: \\3 [\\2]")))))
  16439. (defun org-install-agenda-files-menu ()
  16440. (let ((bl (buffer-list)))
  16441. (save-excursion
  16442. (while bl
  16443. (set-buffer (pop bl))
  16444. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16445. (when (derived-mode-p 'org-mode)
  16446. (easy-menu-change
  16447. '("Org") "File List for Agenda"
  16448. (append
  16449. (list
  16450. ["Edit File List" (org-edit-agenda-file-list) t]
  16451. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16452. ["Remove Current File from List" org-remove-file t]
  16453. ["Cycle through agenda files" org-cycle-agenda-files t]
  16454. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16455. "--")
  16456. (mapcar 'org-file-menu-entry
  16457. ;; Prevent initialization from failing.
  16458. (ignore-errors (org-agenda-files t)))))))))
  16459. ;;;; Documentation
  16460. (defun org-require-autoloaded-modules ()
  16461. (interactive)
  16462. (mapc #'require
  16463. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16464. org-table org-timer)))
  16465. ;;;###autoload
  16466. (defun org-reload (&optional uncompiled)
  16467. "Reload all Org Lisp files.
  16468. With prefix arg UNCOMPILED, load the uncompiled versions."
  16469. (interactive "P")
  16470. (require 'loadhist)
  16471. (let* ((org-dir (org-find-library-dir "org"))
  16472. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16473. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16474. (remove-re (format "\\`%s\\'"
  16475. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16476. (feats (delete-dups
  16477. (mapcar 'file-name-sans-extension
  16478. (mapcar 'file-name-nondirectory
  16479. (delq nil
  16480. (mapcar 'feature-file
  16481. features))))))
  16482. (lfeat (append
  16483. (sort
  16484. (setq feats
  16485. (delq nil (mapcar
  16486. (lambda (f)
  16487. (if (and (string-match feature-re f)
  16488. (not (string-match remove-re f)))
  16489. f nil))
  16490. feats)))
  16491. 'string-lessp)
  16492. (list "org-version" "org")))
  16493. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16494. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16495. load-uncore load-misses)
  16496. (setq load-misses
  16497. (delq 't
  16498. (mapcar (lambda (f)
  16499. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16500. (and (string= org-dir contrib-dir)
  16501. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16502. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16503. (push f load-uncore)
  16504. 't)
  16505. f))
  16506. lfeat)))
  16507. (when load-uncore
  16508. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16509. (if (> (length load-uncore) 1) "s were" " was")
  16510. (reverse load-uncore)))
  16511. (if load-misses
  16512. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16513. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16514. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16515. ;;;###autoload
  16516. (defun org-customize ()
  16517. "Call the customize function with org as argument."
  16518. (interactive)
  16519. (org-load-modules-maybe)
  16520. (org-require-autoloaded-modules)
  16521. (customize-browse 'org))
  16522. (defun org-create-customize-menu ()
  16523. "Create a full customization menu for Org mode, insert it into the menu."
  16524. (interactive)
  16525. (org-load-modules-maybe)
  16526. (org-require-autoloaded-modules)
  16527. (if (fboundp 'customize-menu-create)
  16528. (progn
  16529. (easy-menu-change
  16530. '("Org") "Customize"
  16531. `(["Browse Org group" org-customize t]
  16532. "--"
  16533. ,(customize-menu-create 'org)
  16534. ["Set" Custom-set t]
  16535. ["Save" Custom-save t]
  16536. ["Reset to Current" Custom-reset-current t]
  16537. ["Reset to Saved" Custom-reset-saved t]
  16538. ["Reset to Standard Settings" Custom-reset-standard t]))
  16539. (message "\"Org\"-menu now contains full customization menu"))
  16540. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  16541. ;;;; Miscellaneous stuff
  16542. ;;; Generally useful functions
  16543. (defun org-in-clocktable-p ()
  16544. "Check if the cursor is in a clocktable."
  16545. (let ((pos (point)) start)
  16546. (save-excursion
  16547. (end-of-line 1)
  16548. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16549. (setq start (match-beginning 0))
  16550. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16551. (>= (match-end 0) pos)
  16552. start))))
  16553. (defun org-in-verbatim-emphasis ()
  16554. (save-match-data
  16555. (and (org-in-regexp org-verbatim-re 2)
  16556. (>= (point) (match-beginning 3))
  16557. (<= (point) (match-end 4)))))
  16558. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16559. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16560. (if (and marker (marker-buffer marker)
  16561. (buffer-live-p (marker-buffer marker)))
  16562. (progn
  16563. (pop-to-buffer-same-window (marker-buffer marker))
  16564. (when (or (> marker (point-max)) (< marker (point-min)))
  16565. (widen))
  16566. (goto-char marker)
  16567. (org-show-context 'org-goto))
  16568. (if bookmark
  16569. (bookmark-jump bookmark)
  16570. (error "Cannot find location"))))
  16571. (defun org-quote-csv-field (s)
  16572. "Quote field for inclusion in CSV material."
  16573. (if (string-match "[\",]" s)
  16574. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16575. s))
  16576. (defun org-force-self-insert (N)
  16577. "Needed to enforce self-insert under remapping."
  16578. (interactive "p")
  16579. (self-insert-command N))
  16580. (defun org-quote-vert (s)
  16581. "Replace \"|\" with \"\\vert\"."
  16582. (while (string-match "|" s)
  16583. (setq s (replace-match "\\vert" t t s)))
  16584. s)
  16585. (defun org-uuidgen-p (s)
  16586. "Is S an ID created by UUIDGEN?"
  16587. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16588. (defun org-in-src-block-p (&optional inside)
  16589. "Whether point is in a code source block.
  16590. When INSIDE is non-nil, don't consider we are within a source
  16591. block when point is at #+BEGIN_SRC or #+END_SRC."
  16592. (let ((case-fold-search t))
  16593. (or (and (eq (get-char-property (point) 'src-block) t))
  16594. (and (not inside)
  16595. (save-match-data
  16596. (save-excursion
  16597. (beginning-of-line)
  16598. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16599. (defun org-context ()
  16600. "Return a list of contexts of the current cursor position.
  16601. If several contexts apply, all are returned.
  16602. Each context entry is a list with a symbol naming the context, and
  16603. two positions indicating start and end of the context. Possible
  16604. contexts are:
  16605. :headline anywhere in a headline
  16606. :headline-stars on the leading stars in a headline
  16607. :todo-keyword on a TODO keyword (including DONE) in a headline
  16608. :tags on the TAGS in a headline
  16609. :priority on the priority cookie in a headline
  16610. :item on the first line of a plain list item
  16611. :item-bullet on the bullet/number of a plain list item
  16612. :checkbox on the checkbox in a plain list item
  16613. :table in an Org table
  16614. :table-special on a special filed in a table
  16615. :table-table in a table.el table
  16616. :clocktable in a clocktable
  16617. :src-block in a source block
  16618. :link on a hyperlink
  16619. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16620. :latex-fragment on a LaTeX fragment
  16621. :latex-preview on a LaTeX fragment with overlaid preview image
  16622. This function expects the position to be visible because it uses font-lock
  16623. faces as a help to recognize the following contexts: :table-special, :link,
  16624. and :keyword."
  16625. (let* ((f (get-text-property (point) 'face))
  16626. (faces (if (listp f) f (list f)))
  16627. (case-fold-search t)
  16628. (p (point)) clist o)
  16629. ;; First the large context
  16630. (cond
  16631. ((org-at-heading-p t)
  16632. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16633. (when (progn
  16634. (beginning-of-line 1)
  16635. (looking-at org-todo-line-tags-regexp))
  16636. (push (org-point-in-group p 1 :headline-stars) clist)
  16637. (push (org-point-in-group p 2 :todo-keyword) clist)
  16638. (push (org-point-in-group p 4 :tags) clist))
  16639. (goto-char p)
  16640. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16641. (when (looking-at "\\[#[A-Z0-9]\\]")
  16642. (push (org-point-in-group p 0 :priority) clist)))
  16643. ((org-at-item-p)
  16644. (push (org-point-in-group p 2 :item-bullet) clist)
  16645. (push (list :item (point-at-bol)
  16646. (save-excursion (org-end-of-item) (point)))
  16647. clist)
  16648. (and (org-at-item-checkbox-p)
  16649. (push (org-point-in-group p 0 :checkbox) clist)))
  16650. ((org-at-table-p)
  16651. (push (list :table (org-table-begin) (org-table-end)) clist)
  16652. (when (memq 'org-formula faces)
  16653. (push (list :table-special
  16654. (previous-single-property-change p 'face)
  16655. (next-single-property-change p 'face)) clist)))
  16656. ((org-at-table-p 'any)
  16657. (push (list :table-table) clist)))
  16658. (goto-char p)
  16659. (let ((case-fold-search t))
  16660. ;; New the "medium" contexts: clocktables, source blocks
  16661. (cond ((org-in-clocktable-p)
  16662. (push (list :clocktable
  16663. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16664. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16665. (match-beginning 1))
  16666. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16667. (match-end 0))) clist))
  16668. ((org-in-src-block-p)
  16669. (push (list :src-block
  16670. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16671. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16672. (match-beginning 1))
  16673. (and (search-forward "#+END_SRC" nil t)
  16674. (match-beginning 0))) clist))))
  16675. (goto-char p)
  16676. ;; Now the small context
  16677. (cond
  16678. ((org-at-timestamp-p)
  16679. (push (org-point-in-group p 0 :timestamp) clist))
  16680. ((memq 'org-link faces)
  16681. (push (list :link
  16682. (previous-single-property-change p 'face)
  16683. (next-single-property-change p 'face)) clist))
  16684. ((memq 'org-special-keyword faces)
  16685. (push (list :keyword
  16686. (previous-single-property-change p 'face)
  16687. (next-single-property-change p 'face)) clist))
  16688. ((setq o (cl-some
  16689. (lambda (o)
  16690. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16691. o))
  16692. (overlays-at (point))))
  16693. (push (list :latex-fragment
  16694. (overlay-start o) (overlay-end o)) clist)
  16695. (push (list :latex-preview
  16696. (overlay-start o) (overlay-end o)) clist))
  16697. ((org-inside-LaTeX-fragment-p)
  16698. ;; FIXME: positions wrong.
  16699. (push (list :latex-fragment (point) (point)) clist)))
  16700. (setq clist (nreverse (delq nil clist)))
  16701. clist))
  16702. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16703. "Non-nil when point is between matches of START-RE and END-RE.
  16704. Also return a non-nil value when point is on one of the matches.
  16705. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16706. buffer positions. Default values are the positions of headlines
  16707. surrounding the point.
  16708. The functions returns a cons cell whose car (resp. cdr) is the
  16709. position before START-RE (resp. after END-RE)."
  16710. (save-match-data
  16711. (let ((pos (point))
  16712. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16713. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16714. beg end)
  16715. (save-excursion
  16716. ;; Point is on a block when on START-RE or if START-RE can be
  16717. ;; found before it...
  16718. (and (or (org-in-regexp start-re)
  16719. (re-search-backward start-re limit-up t))
  16720. (setq beg (match-beginning 0))
  16721. ;; ... and END-RE after it...
  16722. (goto-char (match-end 0))
  16723. (re-search-forward end-re limit-down t)
  16724. (> (setq end (match-end 0)) pos)
  16725. ;; ... without another START-RE in-between.
  16726. (goto-char (match-beginning 0))
  16727. (not (re-search-backward start-re (1+ beg) t))
  16728. ;; Return value.
  16729. (cons beg end))))))
  16730. (defun org-in-block-p (names)
  16731. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16732. NAMES is a list of strings containing names of blocks.
  16733. Return first block name matched, or nil. Beware that in case of
  16734. nested blocks, the returned name may not belong to the closest
  16735. block from point."
  16736. (save-match-data
  16737. (catch 'exit
  16738. (let ((case-fold-search t)
  16739. (lim-up (save-excursion (outline-previous-heading)))
  16740. (lim-down (save-excursion (outline-next-heading))))
  16741. (dolist (name names)
  16742. (let ((n (regexp-quote name)))
  16743. (when (org-between-regexps-p
  16744. (concat "^[ \t]*#\\+begin_" n)
  16745. (concat "^[ \t]*#\\+end_" n)
  16746. lim-up lim-down)
  16747. (throw 'exit n)))))
  16748. nil)))
  16749. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16750. "Call `multi-occur' with buffers for all agenda files."
  16751. (interactive "sOrg-files matching: ")
  16752. (let* ((files (org-agenda-files))
  16753. (tnames (mapcar #'file-truename files))
  16754. (extra org-agenda-text-search-extra-files))
  16755. (when (eq (car extra) 'agenda-archives)
  16756. (setq extra (cdr extra))
  16757. (setq files (org-add-archive-files files)))
  16758. (dolist (f extra)
  16759. (unless (member (file-truename f) tnames)
  16760. (unless (member f files) (setq files (append files (list f))))
  16761. (setq tnames (append tnames (list (file-truename f))))))
  16762. (multi-occur
  16763. (mapcar (lambda (x)
  16764. (with-current-buffer
  16765. ;; FIXME: Why not just (find-file-noselect x)?
  16766. ;; Is it to avoid the "revert buffer" prompt?
  16767. (or (get-file-buffer x) (find-file-noselect x))
  16768. (widen)
  16769. (current-buffer)))
  16770. files)
  16771. regexp)))
  16772. (add-hook 'occur-mode-find-occurrence-hook
  16773. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  16774. (defun org-occur-link-in-agenda-files ()
  16775. "Create a link and search for it in the agendas.
  16776. The link is not stored in `org-stored-links', it is just created
  16777. for the search purpose."
  16778. (interactive)
  16779. (let ((link (condition-case nil
  16780. (org-store-link nil)
  16781. (error "Unable to create a link to here"))))
  16782. (org-occur-in-agenda-files (regexp-quote link))))
  16783. (defun org-back-over-empty-lines ()
  16784. "Move backwards over whitespace, to the beginning of the first empty line.
  16785. Returns the number of empty lines passed."
  16786. (let ((pos (point)))
  16787. (if (cdr (assq 'heading org-blank-before-new-entry))
  16788. (skip-chars-backward " \t\n\r")
  16789. (unless (eobp)
  16790. (forward-line -1)))
  16791. (beginning-of-line 2)
  16792. (goto-char (min (point) pos))
  16793. (count-lines (point) pos)))
  16794. ;;; TODO: Only called once, from ox-odt which should probably use
  16795. ;;; org-export-inline-image-p or something.
  16796. (defun org-file-image-p (file)
  16797. "Return non-nil if FILE is an image."
  16798. (save-match-data
  16799. (string-match (image-file-name-regexp) file)))
  16800. (defun org-get-cursor-date (&optional with-time)
  16801. "Return the date at cursor in as a time.
  16802. This works in the calendar and in the agenda, anywhere else it just
  16803. returns the current time.
  16804. If WITH-TIME is non-nil, returns the time of the event at point (in
  16805. the agenda) or the current time of the day; otherwise returns the
  16806. earliest time on the cursor date that Org treats as that date
  16807. (bearing in mind `org-extend-today-until')."
  16808. (let (date day defd tp hod mod)
  16809. (when with-time
  16810. (setq tp (get-text-property (point) 'time))
  16811. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  16812. (setq hod (string-to-number (match-string 1 tp))
  16813. mod (string-to-number (match-string 2 tp))))
  16814. (or tp (let ((now (decode-time)))
  16815. (setq hod (nth 2 now)
  16816. mod (nth 1 now)))))
  16817. (cond
  16818. ((eq major-mode 'calendar-mode)
  16819. (setq date (calendar-cursor-to-date)
  16820. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16821. (nth 1 date) (nth 0 date) (nth 2 date))))
  16822. ((eq major-mode 'org-agenda-mode)
  16823. (setq day (get-text-property (point) 'day))
  16824. (when day
  16825. (setq date (calendar-gregorian-from-absolute day)
  16826. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16827. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16828. (or defd (current-time))))
  16829. (defun org-mark-subtree (&optional up)
  16830. "Mark the current subtree.
  16831. This puts point at the start of the current subtree, and mark at
  16832. the end. If a numeric prefix UP is given, move up into the
  16833. hierarchy of headlines by UP levels before marking the subtree."
  16834. (interactive "P")
  16835. (org-with-limited-levels
  16836. (cond ((org-at-heading-p) (beginning-of-line))
  16837. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16838. (t (outline-previous-visible-heading 1))))
  16839. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16840. (if (called-interactively-p 'any)
  16841. (call-interactively 'org-mark-element)
  16842. (org-mark-element)))
  16843. ;;; Indentation
  16844. (defvar org-element-greater-elements)
  16845. (defun org--get-expected-indentation (element contentsp)
  16846. "Expected indentation column for current line, according to ELEMENT.
  16847. ELEMENT is an element containing point. CONTENTSP is non-nil
  16848. when indentation is to be computed according to contents of
  16849. ELEMENT."
  16850. (let ((type (org-element-type element))
  16851. (start (org-element-property :begin element))
  16852. (post-affiliated (org-element-property :post-affiliated element)))
  16853. (org-with-wide-buffer
  16854. (cond
  16855. (contentsp
  16856. (cl-case type
  16857. ((diary-sexp footnote-definition) 0)
  16858. ((headline inlinetask nil)
  16859. (if (not org-adapt-indentation) 0
  16860. (let ((level (org-current-level)))
  16861. (if level (1+ level) 0))))
  16862. ((item plain-list) (org-list-item-body-column post-affiliated))
  16863. (t
  16864. (goto-char start)
  16865. (current-indentation))))
  16866. ((and
  16867. (eq org-adapt-indentation 'headline-data)
  16868. (memq type '(planning clock node-property property-drawer drawer)))
  16869. (org--get-expected-indentation
  16870. (org-element-property :parent element) t))
  16871. ((memq type '(headline inlinetask nil))
  16872. (if (org-match-line "[ \t]*$")
  16873. (org--get-expected-indentation element t)
  16874. 0))
  16875. ((memq type '(diary-sexp footnote-definition)) 0)
  16876. ;; First paragraph of a footnote definition or an item.
  16877. ;; Indent like parent.
  16878. ((< (line-beginning-position) start)
  16879. (org--get-expected-indentation
  16880. (org-element-property :parent element) t))
  16881. ;; At first line: indent according to previous sibling, if any,
  16882. ;; ignoring footnote definitions and inline tasks, or parent's
  16883. ;; contents.
  16884. ((and ( = (line-beginning-position) start)
  16885. (eq org-adapt-indentation t))
  16886. (catch 'exit
  16887. (while t
  16888. (if (= (point-min) start) (throw 'exit 0)
  16889. (goto-char (1- start))
  16890. (let* ((previous (org-element-at-point))
  16891. (parent previous))
  16892. (while (and parent (<= (org-element-property :end parent) start))
  16893. (setq previous parent
  16894. parent (org-element-property :parent parent)))
  16895. (cond
  16896. ((not previous) (throw 'exit 0))
  16897. ((> (org-element-property :end previous) start)
  16898. (throw 'exit (org--get-expected-indentation previous t)))
  16899. ((memq (org-element-type previous)
  16900. '(footnote-definition inlinetask))
  16901. (setq start (org-element-property :begin previous)))
  16902. (t (goto-char (org-element-property :begin previous))
  16903. (throw 'exit
  16904. (if (bolp) (current-indentation)
  16905. ;; At first paragraph in an item or
  16906. ;; a footnote definition.
  16907. (org--get-expected-indentation
  16908. (org-element-property :parent previous) t))))))))))
  16909. ;; Otherwise, move to the first non-blank line above.
  16910. ((not (eq org-adapt-indentation 'headline-data))
  16911. (beginning-of-line)
  16912. (let ((pos (point)))
  16913. (skip-chars-backward " \r\t\n")
  16914. (cond
  16915. ;; Two blank lines end a footnote definition or a plain
  16916. ;; list. When we indent an empty line after them, the
  16917. ;; containing list or footnote definition is over, so it
  16918. ;; qualifies as a previous sibling. Therefore, we indent
  16919. ;; like its first line.
  16920. ((and (memq type '(footnote-definition plain-list))
  16921. (> (count-lines (point) pos) 2))
  16922. (goto-char start)
  16923. (current-indentation))
  16924. ;; Line above is the first one of a paragraph at the
  16925. ;; beginning of an item or a footnote definition. Indent
  16926. ;; like parent.
  16927. ((< (line-beginning-position) start)
  16928. (org--get-expected-indentation
  16929. (org-element-property :parent element) t))
  16930. ;; Line above is the beginning of an element, i.e., point
  16931. ;; was originally on the blank lines between element's start
  16932. ;; and contents.
  16933. ((= (line-beginning-position) post-affiliated)
  16934. (org--get-expected-indentation element t))
  16935. ;; POS is after contents in a greater element. Indent like
  16936. ;; the beginning of the element.
  16937. ((and (memq type org-element-greater-elements)
  16938. (let ((cend (org-element-property :contents-end element)))
  16939. (and cend (<= cend pos))))
  16940. ;; As a special case, if point is at the end of a footnote
  16941. ;; definition or an item, indent like the very last element
  16942. ;; within. If that last element is an item, indent like
  16943. ;; its contents.
  16944. (if (memq type '(footnote-definition item plain-list))
  16945. (let ((last (org-element-at-point)))
  16946. (goto-char pos)
  16947. (org--get-expected-indentation
  16948. last (eq (org-element-type last) 'item)))
  16949. (goto-char start)
  16950. (current-indentation)))
  16951. ;; In any other case, indent like the current line.
  16952. (t (current-indentation)))))
  16953. ;; Finally, no indentation is needed, fall back to 0.
  16954. (t (current-indentation))))))
  16955. (defun org--align-node-property ()
  16956. "Align node property at point.
  16957. Alignment is done according to `org-property-format', which see."
  16958. (when (save-excursion
  16959. (beginning-of-line)
  16960. (looking-at org-property-re))
  16961. (replace-match
  16962. (concat (match-string 4)
  16963. (org-trim
  16964. (format org-property-format (match-string 1) (match-string 3))))
  16965. t t)))
  16966. (defun org-indent-line ()
  16967. "Indent line depending on context.
  16968. Indentation is done according to the following rules:
  16969. - Footnote definitions, diary sexps, headlines and inline tasks
  16970. have to start at column 0.
  16971. - On the very first line of an element, consider, in order, the
  16972. next rules until one matches:
  16973. 1. If there's a sibling element before, ignoring footnote
  16974. definitions and inline tasks, indent like its first line.
  16975. 2. If element has a parent, indent like its contents. More
  16976. precisely, if parent is an item, indent after the bullet.
  16977. Else, indent like parent's first line.
  16978. 3. Otherwise, indent relatively to current level, if
  16979. `org-adapt-indentation' is non-nil, or to left margin.
  16980. - On a blank line at the end of an element, indent according to
  16981. the type of the element. More precisely
  16982. 1. If element is a plain list, an item, or a footnote
  16983. definition, indent like the very last element within.
  16984. 2. If element is a paragraph, indent like its last non blank
  16985. line.
  16986. 3. Otherwise, indent like its very first line.
  16987. - In the code part of a source block, use language major mode
  16988. to indent current line if `org-src-tab-acts-natively' is
  16989. non-nil. If it is nil, do nothing.
  16990. - Otherwise, indent like the first non-blank line above.
  16991. The function doesn't indent an item as it could break the whole
  16992. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  16993. `\\[org-shiftmetaright]'.
  16994. Also align node properties according to `org-property-format'."
  16995. (interactive)
  16996. (if (org-at-heading-p) 'noindent
  16997. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  16998. (type (org-element-type element)))
  16999. (cond ((and (memq type '(plain-list item))
  17000. (= (line-beginning-position)
  17001. (org-element-property :post-affiliated element)))
  17002. 'noindent)
  17003. ((and (eq type 'latex-environment)
  17004. (>= (point) (org-element-property :post-affiliated element))
  17005. (< (point) (org-with-wide-buffer
  17006. (goto-char (org-element-property :end element))
  17007. (skip-chars-backward " \r\t\n")
  17008. (line-beginning-position 2))))
  17009. 'noindent)
  17010. ((and (eq type 'src-block)
  17011. org-src-tab-acts-natively
  17012. (> (line-beginning-position)
  17013. (org-element-property :post-affiliated element))
  17014. (< (line-beginning-position)
  17015. (org-with-wide-buffer
  17016. (goto-char (org-element-property :end element))
  17017. (skip-chars-backward " \r\t\n")
  17018. (line-beginning-position))))
  17019. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17020. (t
  17021. (let ((column (org--get-expected-indentation element nil)))
  17022. ;; Preserve current column.
  17023. (if (<= (current-column) (current-indentation))
  17024. (indent-line-to column)
  17025. (save-excursion (indent-line-to column))))
  17026. ;; Align node property. Also preserve current column.
  17027. (when (eq type 'node-property)
  17028. (let ((column (current-column)))
  17029. (org--align-node-property)
  17030. (org-move-to-column column))))))))
  17031. (defun org-indent-region (start end)
  17032. "Indent each non-blank line in the region.
  17033. Called from a program, START and END specify the region to
  17034. indent. The function will not indent contents of example blocks,
  17035. verse blocks and export blocks as leading white spaces are
  17036. assumed to be significant there."
  17037. (interactive "r")
  17038. (save-excursion
  17039. (goto-char start)
  17040. (skip-chars-forward " \r\t\n")
  17041. (unless (eobp) (beginning-of-line))
  17042. (let ((indent-to
  17043. (lambda (ind pos)
  17044. ;; Set IND as indentation for all lines between point and
  17045. ;; POS. Blank lines are ignored. Leave point after POS
  17046. ;; once done.
  17047. (let ((limit (copy-marker pos)))
  17048. (while (< (point) limit)
  17049. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17050. (forward-line))
  17051. (set-marker limit nil))))
  17052. (end (copy-marker end)))
  17053. (while (< (point) end)
  17054. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17055. (let* ((element (org-element-at-point))
  17056. (type (org-element-type element))
  17057. (element-end (copy-marker (org-element-property :end element)))
  17058. (ind (org--get-expected-indentation element nil)))
  17059. (cond
  17060. ;; Element indented as a single block. Example blocks
  17061. ;; preserving indentation are a special case since the
  17062. ;; "contents" must not be indented whereas the block
  17063. ;; boundaries can.
  17064. ((or (memq type '(export-block latex-environment))
  17065. (and (eq type 'example-block)
  17066. (not
  17067. (or org-src-preserve-indentation
  17068. (org-element-property :preserve-indent element)))))
  17069. (let ((offset (- ind (current-indentation))))
  17070. (unless (zerop offset)
  17071. (indent-rigidly (org-element-property :begin element)
  17072. (org-element-property :end element)
  17073. offset)))
  17074. (goto-char element-end))
  17075. ;; Elements indented line wise. Be sure to exclude
  17076. ;; example blocks (preserving indentation) and source
  17077. ;; blocks from this category as they are treated
  17078. ;; specially later.
  17079. ((or (memq type '(paragraph table table-row))
  17080. (not (or (org-element-property :contents-begin element)
  17081. (memq type '(example-block src-block)))))
  17082. (when (eq type 'node-property)
  17083. (org--align-node-property)
  17084. (beginning-of-line))
  17085. (funcall indent-to ind (min element-end end)))
  17086. ;; Elements consisting of three parts: before the
  17087. ;; contents, the contents, and after the contents. The
  17088. ;; contents are treated specially, according to the
  17089. ;; element type, or not indented at all. Other parts are
  17090. ;; indented as a single block.
  17091. (t
  17092. (let* ((post (copy-marker
  17093. (org-element-property :post-affiliated element)))
  17094. (cbeg
  17095. (copy-marker
  17096. (cond
  17097. ((not (org-element-property :contents-begin element))
  17098. ;; Fake contents for source blocks.
  17099. (org-with-wide-buffer
  17100. (goto-char post)
  17101. (line-beginning-position 2)))
  17102. ((memq type '(footnote-definition item plain-list))
  17103. ;; Contents in these elements could start on
  17104. ;; the same line as the beginning of the
  17105. ;; element. Make sure we start indenting
  17106. ;; from the second line.
  17107. (org-with-wide-buffer
  17108. (goto-char post)
  17109. (end-of-line)
  17110. (skip-chars-forward " \r\t\n")
  17111. (if (eobp) (point) (line-beginning-position))))
  17112. (t (org-element-property :contents-begin element)))))
  17113. (cend (copy-marker
  17114. (or (org-element-property :contents-end element)
  17115. ;; Fake contents for source blocks.
  17116. (org-with-wide-buffer
  17117. (goto-char element-end)
  17118. (skip-chars-backward " \r\t\n")
  17119. (line-beginning-position)))
  17120. t)))
  17121. ;; Do not change items indentation individually as it
  17122. ;; might break the list as a whole. On the other
  17123. ;; hand, when at a plain list, indent it as a whole.
  17124. (cond ((eq type 'plain-list)
  17125. (let ((offset (- ind (current-indentation))))
  17126. (unless (zerop offset)
  17127. (indent-rigidly (org-element-property :begin element)
  17128. (org-element-property :end element)
  17129. offset))
  17130. (goto-char cbeg)))
  17131. ((eq type 'item) (goto-char cbeg))
  17132. (t (funcall indent-to ind (min cbeg end))))
  17133. (when (< (point) end)
  17134. (cl-case type
  17135. ((example-block verse-block))
  17136. (src-block
  17137. ;; In a source block, indent source code
  17138. ;; according to language major mode, but only if
  17139. ;; `org-src-tab-acts-natively' is non-nil.
  17140. (when (and (< (point) end) org-src-tab-acts-natively)
  17141. (ignore-errors
  17142. (org-babel-do-in-edit-buffer
  17143. (indent-region (point-min) (point-max))))))
  17144. (t (org-indent-region (point) (min cend end))))
  17145. (goto-char (min cend end))
  17146. (when (< (point) end)
  17147. (funcall indent-to ind (min element-end end))))
  17148. (set-marker post nil)
  17149. (set-marker cbeg nil)
  17150. (set-marker cend nil))))
  17151. (set-marker element-end nil))))
  17152. (set-marker end nil))))
  17153. (defun org-indent-drawer ()
  17154. "Indent the drawer at point."
  17155. (interactive)
  17156. (unless (save-excursion
  17157. (beginning-of-line)
  17158. (looking-at-p org-drawer-regexp))
  17159. (user-error "Not at a drawer"))
  17160. (let ((element (org-element-at-point)))
  17161. (unless (memq (org-element-type element) '(drawer property-drawer))
  17162. (user-error "Not at a drawer"))
  17163. (org-with-wide-buffer
  17164. (org-indent-region (org-element-property :begin element)
  17165. (org-element-property :end element))))
  17166. (message "Drawer at point indented"))
  17167. (defun org-indent-block ()
  17168. "Indent the block at point."
  17169. (interactive)
  17170. (unless (save-excursion
  17171. (beginning-of-line)
  17172. (let ((case-fold-search t))
  17173. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17174. (user-error "Not at a block"))
  17175. (let ((element (org-element-at-point)))
  17176. (unless (memq (org-element-type element)
  17177. '(comment-block center-block dynamic-block example-block
  17178. export-block quote-block special-block
  17179. src-block verse-block))
  17180. (user-error "Not at a block"))
  17181. (org-with-wide-buffer
  17182. (org-indent-region (org-element-property :begin element)
  17183. (org-element-property :end element))))
  17184. (message "Block at point indented"))
  17185. ;;; Filling
  17186. ;; We use our own fill-paragraph and auto-fill functions.
  17187. ;; `org-fill-paragraph' relies on adaptive filling and context
  17188. ;; checking. Appropriate `fill-prefix' is computed with
  17189. ;; `org-adaptive-fill-function'.
  17190. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17191. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17192. ;; `org-adaptive-fill-function' value. Internally,
  17193. ;; `org-comment-line-break-function' breaks the line.
  17194. ;; `org-setup-filling' installs filling and auto-filling related
  17195. ;; variables during `org-mode' initialization.
  17196. (defun org-setup-filling ()
  17197. (require 'org-element)
  17198. ;; Prevent auto-fill from inserting unwanted new items.
  17199. (when (boundp 'fill-nobreak-predicate)
  17200. (setq-local
  17201. fill-nobreak-predicate
  17202. (org-uniquify
  17203. (append fill-nobreak-predicate
  17204. '(org-fill-line-break-nobreak-p
  17205. org-fill-n-macro-as-item-nobreak-p
  17206. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17207. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17208. (setq-local paragraph-start paragraph-ending)
  17209. (setq-local paragraph-separate paragraph-ending))
  17210. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17211. (setq-local auto-fill-inhibit-regexp nil)
  17212. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17213. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17214. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17215. (defun org-fill-line-break-nobreak-p ()
  17216. "Non-nil when a new line at point would create an Org line break."
  17217. (save-excursion
  17218. (skip-chars-backward " \t")
  17219. (skip-chars-backward "\\\\")
  17220. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17221. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17222. "Non-nil when a new line at point would split a timestamp."
  17223. (and (org-at-timestamp-p 'lax)
  17224. (not (looking-at org-ts-regexp-both))))
  17225. (defun org-fill-n-macro-as-item-nobreak-p ()
  17226. "Non-nil when a new line at point would create a new list."
  17227. ;; During export, a "n" macro followed by a dot or a closing
  17228. ;; parenthesis can end up being parsed as a new list item.
  17229. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17230. (defun org-adaptive-fill-function ()
  17231. "Compute a fill prefix for the current line.
  17232. Return fill prefix, as a string, or nil if current line isn't
  17233. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17234. matches in paragraphs or comments, use it."
  17235. (org-with-wide-buffer
  17236. (unless (org-at-heading-p)
  17237. (let* ((p (line-beginning-position))
  17238. (element (save-excursion
  17239. (beginning-of-line)
  17240. (org-element-at-point)))
  17241. (type (org-element-type element))
  17242. (post-affiliated (org-element-property :post-affiliated element)))
  17243. (unless (< p post-affiliated)
  17244. (cl-case type
  17245. (comment
  17246. (save-excursion
  17247. (beginning-of-line)
  17248. (looking-at "[ \t]*")
  17249. (concat (match-string 0) "# ")))
  17250. (footnote-definition "")
  17251. ((item plain-list)
  17252. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17253. (paragraph
  17254. ;; Fill prefix is usually the same as the current line,
  17255. ;; unless the paragraph is at the beginning of an item.
  17256. (let ((parent (org-element-property :parent element)))
  17257. (save-excursion
  17258. (beginning-of-line)
  17259. (cond ((eq (org-element-type parent) 'item)
  17260. (make-string (org-list-item-body-column
  17261. (org-element-property :begin parent))
  17262. ?\s))
  17263. ((and adaptive-fill-regexp
  17264. ;; Locally disable
  17265. ;; `adaptive-fill-function' to let
  17266. ;; `fill-context-prefix' handle
  17267. ;; `adaptive-fill-regexp' variable.
  17268. (let (adaptive-fill-function)
  17269. (fill-context-prefix
  17270. post-affiliated
  17271. (org-element-property :end element)))))
  17272. ((looking-at "[ \t]+") (match-string 0))
  17273. (t "")))))
  17274. (comment-block
  17275. ;; Only fill contents if P is within block boundaries.
  17276. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17277. (forward-line)
  17278. (point)))
  17279. (cend (save-excursion
  17280. (goto-char (org-element-property :end element))
  17281. (skip-chars-backward " \r\t\n")
  17282. (line-beginning-position))))
  17283. (when (and (>= p cbeg) (< p cend))
  17284. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17285. (match-string 0)
  17286. ""))))))))))
  17287. (defun org-fill-element (&optional justify)
  17288. "Fill element at point, when applicable.
  17289. This function only applies to comment blocks, comments, example
  17290. blocks and paragraphs. Also, as a special case, re-align table
  17291. when point is at one.
  17292. If JUSTIFY is non-nil (interactively, with prefix argument),
  17293. justify as well. If `sentence-end-double-space' is non-nil, then
  17294. period followed by one space does not end a sentence, so don't
  17295. break a line there. The variable `fill-column' controls the
  17296. width for filling.
  17297. For convenience, when point is at a plain list, an item or
  17298. a footnote definition, try to fill the first paragraph within."
  17299. (with-syntax-table org-mode-transpose-word-syntax-table
  17300. ;; Move to end of line in order to get the first paragraph within
  17301. ;; a plain list or a footnote definition.
  17302. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17303. ;; First check if point is in a blank line at the beginning of
  17304. ;; the buffer. In that case, ignore filling.
  17305. (cl-case (org-element-type element)
  17306. ;; Use major mode filling function is source blocks.
  17307. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17308. ;; Align Org tables, leave table.el tables as-is.
  17309. (table-row (org-table-align) t)
  17310. (table
  17311. (when (eq (org-element-property :type element) 'org)
  17312. (save-excursion
  17313. (goto-char (org-element-property :post-affiliated element))
  17314. (org-table-align)))
  17315. t)
  17316. (paragraph
  17317. ;; Paragraphs may contain `line-break' type objects.
  17318. (let ((beg (max (point-min)
  17319. (org-element-property :contents-begin element)))
  17320. (end (min (point-max)
  17321. (org-element-property :contents-end element))))
  17322. ;; Do nothing if point is at an affiliated keyword.
  17323. (if (< (line-end-position) beg) t
  17324. ;; Fill paragraph, taking line breaks into account.
  17325. (save-excursion
  17326. (goto-char beg)
  17327. (let ((cuts (list beg)))
  17328. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17329. (when (eq 'line-break
  17330. (org-element-type
  17331. (save-excursion (backward-char)
  17332. (org-element-context))))
  17333. (push (point) cuts)))
  17334. (dolist (c (delq end cuts))
  17335. (fill-region-as-paragraph c end justify)
  17336. (setq end c))))
  17337. t)))
  17338. ;; Contents of `comment-block' type elements should be
  17339. ;; filled as plain text, but only if point is within block
  17340. ;; markers.
  17341. (comment-block
  17342. (let* ((case-fold-search t)
  17343. (beg (save-excursion
  17344. (goto-char (org-element-property :begin element))
  17345. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17346. (forward-line)
  17347. (point)))
  17348. (end (save-excursion
  17349. (goto-char (org-element-property :end element))
  17350. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17351. (line-beginning-position))))
  17352. (if (or (< (point) beg) (> (point) end)) t
  17353. (fill-region-as-paragraph
  17354. (save-excursion (end-of-line)
  17355. (re-search-backward "^[ \t]*$" beg 'move)
  17356. (line-beginning-position))
  17357. (save-excursion (beginning-of-line)
  17358. (re-search-forward "^[ \t]*$" end 'move)
  17359. (line-beginning-position))
  17360. justify))))
  17361. ;; Fill comments.
  17362. (comment
  17363. (let ((begin (org-element-property :post-affiliated element))
  17364. (end (org-element-property :end element)))
  17365. (when (and (>= (point) begin) (<= (point) end))
  17366. (let ((begin (save-excursion
  17367. (end-of-line)
  17368. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17369. (progn (forward-line) (point))
  17370. begin)))
  17371. (end (save-excursion
  17372. (end-of-line)
  17373. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17374. (1- (line-beginning-position))
  17375. (skip-chars-backward " \r\t\n")
  17376. (line-end-position)))))
  17377. ;; Do not fill comments when at a blank line.
  17378. (when (> end begin)
  17379. (let ((fill-prefix
  17380. (save-excursion
  17381. (beginning-of-line)
  17382. (looking-at "[ \t]*#")
  17383. (let ((comment-prefix (match-string 0)))
  17384. (goto-char (match-end 0))
  17385. (if (looking-at adaptive-fill-regexp)
  17386. (concat comment-prefix (match-string 0))
  17387. (concat comment-prefix " "))))))
  17388. (save-excursion
  17389. (fill-region-as-paragraph begin end justify))))))
  17390. t))
  17391. ;; Ignore every other element.
  17392. (otherwise t)))))
  17393. (defun org-fill-paragraph (&optional justify region)
  17394. "Fill element at point, when applicable.
  17395. This function only applies to comment blocks, comments, example
  17396. blocks and paragraphs. Also, as a special case, re-align table
  17397. when point is at one.
  17398. For convenience, when point is at a plain list, an item or
  17399. a footnote definition, try to fill the first paragraph within.
  17400. If JUSTIFY is non-nil (interactively, with prefix argument),
  17401. justify as well. If `sentence-end-double-space' is non-nil, then
  17402. period followed by one space does not end a sentence, so don't
  17403. break a line there. The variable `fill-column' controls the
  17404. width for filling.
  17405. The REGION argument is non-nil if called interactively; in that
  17406. case, if Transient Mark mode is enabled and the mark is active,
  17407. fill each of the elements in the active region, instead of just
  17408. filling the current element."
  17409. (interactive (progn
  17410. (barf-if-buffer-read-only)
  17411. (list (when current-prefix-arg 'full) t)))
  17412. (let ((hash (and (not (buffer-modified-p))
  17413. (org-buffer-hash))))
  17414. (cond
  17415. ((and region transient-mark-mode mark-active
  17416. (not (eq (region-beginning) (region-end))))
  17417. (let ((origin (point-marker))
  17418. (start (region-beginning)))
  17419. (unwind-protect
  17420. (progn
  17421. (goto-char (region-end))
  17422. (while (> (point) start)
  17423. (org-backward-paragraph)
  17424. (org-fill-element justify)))
  17425. (goto-char origin)
  17426. (set-marker origin nil))))
  17427. (t (org-fill-element justify)))
  17428. ;; If we didn't change anything in the buffer (and the buffer was
  17429. ;; previously unmodified), then flip the modification status back
  17430. ;; to "unchanged".
  17431. (when (and hash (equal hash (org-buffer-hash)))
  17432. (set-buffer-modified-p nil))))
  17433. (defun org-auto-fill-function ()
  17434. "Auto-fill function."
  17435. ;; Check if auto-filling is meaningful.
  17436. (let ((fc (current-fill-column)))
  17437. (when (and fc (> (current-column) fc))
  17438. (let* ((fill-prefix (org-adaptive-fill-function))
  17439. ;; Enforce empty fill prefix, if required. Otherwise, it
  17440. ;; will be computed again.
  17441. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17442. (when fill-prefix (do-auto-fill))))))
  17443. (defun org-comment-line-break-function (&optional soft)
  17444. "Break line at point and indent, continuing comment if within one.
  17445. The inserted newline is marked hard if variable
  17446. `use-hard-newlines' is true, unless optional argument SOFT is
  17447. non-nil."
  17448. (if soft (insert-and-inherit ?\n) (newline 1))
  17449. (save-excursion (forward-char -1) (delete-horizontal-space))
  17450. (delete-horizontal-space)
  17451. (indent-to-left-margin)
  17452. (insert-before-markers-and-inherit fill-prefix))
  17453. ;;; Fixed Width Areas
  17454. (defun org-toggle-fixed-width ()
  17455. "Toggle fixed-width markup.
  17456. Add or remove fixed-width markup on current line, whenever it
  17457. makes sense. Return an error otherwise.
  17458. If a region is active and if it contains only fixed-width areas
  17459. or blank lines, remove all fixed-width markup in it. If the
  17460. region contains anything else, convert all non-fixed-width lines
  17461. to fixed-width ones.
  17462. Blank lines at the end of the region are ignored unless the
  17463. region only contains such lines."
  17464. (interactive)
  17465. (if (not (org-region-active-p))
  17466. ;; No region:
  17467. ;;
  17468. ;; Remove fixed width marker only in a fixed-with element.
  17469. ;;
  17470. ;; Add fixed width maker in paragraphs, in blank lines after
  17471. ;; elements or at the beginning of a headline or an inlinetask,
  17472. ;; and before any one-line elements (e.g., a clock).
  17473. (progn
  17474. (beginning-of-line)
  17475. (let* ((element (org-element-at-point))
  17476. (type (org-element-type element)))
  17477. (cond
  17478. ((and (eq type 'fixed-width)
  17479. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17480. (replace-match
  17481. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17482. ((and (memq type '(babel-call clock comment diary-sexp headline
  17483. horizontal-rule keyword paragraph
  17484. planning))
  17485. (<= (org-element-property :post-affiliated element) (point)))
  17486. (skip-chars-forward " \t")
  17487. (insert ": "))
  17488. ((and (looking-at-p "[ \t]*$")
  17489. (or (eq type 'inlinetask)
  17490. (save-excursion
  17491. (skip-chars-forward " \r\t\n")
  17492. (<= (org-element-property :end element) (point)))))
  17493. (delete-region (point) (line-end-position))
  17494. (org-indent-line)
  17495. (insert ": "))
  17496. (t (user-error "Cannot insert a fixed-width line here")))))
  17497. ;; Region active.
  17498. (let* ((begin (save-excursion
  17499. (goto-char (region-beginning))
  17500. (line-beginning-position)))
  17501. (end (copy-marker
  17502. (save-excursion
  17503. (goto-char (region-end))
  17504. (unless (eolp) (beginning-of-line))
  17505. (if (save-excursion (re-search-backward "\\S-" begin t))
  17506. (progn (skip-chars-backward " \r\t\n") (point))
  17507. (point)))))
  17508. (all-fixed-width-p
  17509. (catch 'not-all-p
  17510. (save-excursion
  17511. (goto-char begin)
  17512. (skip-chars-forward " \r\t\n")
  17513. (when (eobp) (throw 'not-all-p nil))
  17514. (while (< (point) end)
  17515. (let ((element (org-element-at-point)))
  17516. (if (eq (org-element-type element) 'fixed-width)
  17517. (goto-char (org-element-property :end element))
  17518. (throw 'not-all-p nil))))
  17519. t))))
  17520. (if all-fixed-width-p
  17521. (save-excursion
  17522. (goto-char begin)
  17523. (while (< (point) end)
  17524. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17525. (replace-match
  17526. "" nil nil nil
  17527. (if (= (line-end-position) (match-end 0)) 0 1)))
  17528. (forward-line)))
  17529. (let ((min-ind (point-max)))
  17530. ;; Find minimum indentation across all lines.
  17531. (save-excursion
  17532. (goto-char begin)
  17533. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17534. (setq min-ind 0)
  17535. (catch 'zerop
  17536. (while (< (point) end)
  17537. (unless (looking-at-p "[ \t]*$")
  17538. (let ((ind (current-indentation)))
  17539. (setq min-ind (min min-ind ind))
  17540. (when (zerop ind) (throw 'zerop t))))
  17541. (forward-line)))))
  17542. ;; Loop over all lines and add fixed-width markup everywhere
  17543. ;; but in fixed-width lines.
  17544. (save-excursion
  17545. (goto-char begin)
  17546. (while (< (point) end)
  17547. (cond
  17548. ((org-at-heading-p)
  17549. (insert ": ")
  17550. (forward-line)
  17551. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17552. (insert ":")
  17553. (forward-line)))
  17554. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17555. (let* ((element (org-element-at-point))
  17556. (element-end (org-element-property :end element)))
  17557. (if (eq (org-element-type element) 'fixed-width)
  17558. (progn (goto-char element-end)
  17559. (skip-chars-backward " \r\t\n")
  17560. (forward-line))
  17561. (let ((limit (min end element-end)))
  17562. (while (< (point) limit)
  17563. (org-move-to-column min-ind t)
  17564. (insert ": ")
  17565. (forward-line))))))
  17566. (t
  17567. (org-move-to-column min-ind t)
  17568. (insert ": ")
  17569. (forward-line)))))))
  17570. (set-marker end nil))))
  17571. ;;; Blocks
  17572. (defun org-block-map (function &optional start end)
  17573. "Call FUNCTION at the head of all source blocks in the current buffer.
  17574. Optional arguments START and END can be used to limit the range."
  17575. (let ((start (or start (point-min)))
  17576. (end (or end (point-max))))
  17577. (save-excursion
  17578. (goto-char start)
  17579. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17580. (save-excursion
  17581. (save-match-data
  17582. (goto-char (match-beginning 0))
  17583. (funcall function)))))))
  17584. (defun org-next-block (arg &optional backward block-regexp)
  17585. "Jump to the next block.
  17586. With a prefix argument ARG, jump forward ARG many blocks.
  17587. When BACKWARD is non-nil, jump to the previous block.
  17588. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17589. Match data is set according to this regexp when the function
  17590. returns.
  17591. Return point at beginning of the opening line of found block.
  17592. Throw an error if no block is found."
  17593. (interactive "p")
  17594. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17595. (case-fold-search t)
  17596. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17597. (count (or arg 1))
  17598. (origin (point))
  17599. last-element)
  17600. (if backward (beginning-of-line) (end-of-line))
  17601. (while (and (> count 0) (funcall search-fn re nil t))
  17602. (let ((element (save-excursion
  17603. (goto-char (match-beginning 0))
  17604. (save-match-data (org-element-at-point)))))
  17605. (when (and (memq (org-element-type element)
  17606. '(center-block comment-block dynamic-block
  17607. example-block export-block quote-block
  17608. special-block src-block verse-block))
  17609. (<= (match-beginning 0)
  17610. (org-element-property :post-affiliated element)))
  17611. (setq last-element element)
  17612. (cl-decf count))))
  17613. (if (= count 0)
  17614. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17615. (save-match-data (org-show-context)))
  17616. (goto-char origin)
  17617. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17618. (defun org-previous-block (arg &optional block-regexp)
  17619. "Jump to the previous block.
  17620. With a prefix argument ARG, jump backward ARG many source blocks.
  17621. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17622. (interactive "p")
  17623. (org-next-block arg t block-regexp))
  17624. ;;; Comments
  17625. ;; Org comments syntax is quite complex. It requires the entire line
  17626. ;; to be just a comment. Also, even with the right syntax at the
  17627. ;; beginning of line, some elements (e.g., verse-block or
  17628. ;; example-block) don't accept comments. Usual Emacs comment commands
  17629. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17630. ;; Org still relies on `comment-dwim', but cannot trust
  17631. ;; `comment-only-p'. So, `comment-region-function' and
  17632. ;; `uncomment-region-function' both point
  17633. ;; to`org-comment-or-uncomment-region'. Eventually,
  17634. ;; `org-insert-comment' takes care of insertion of comments at the
  17635. ;; beginning of line.
  17636. ;; `org-setup-comments-handling' install comments related variables
  17637. ;; during `org-mode' initialization.
  17638. (defun org-setup-comments-handling ()
  17639. (interactive)
  17640. (setq-local comment-use-syntax nil)
  17641. (setq-local comment-start "# ")
  17642. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17643. (setq-local comment-insert-comment-function 'org-insert-comment)
  17644. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17645. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17646. (defun org-insert-comment ()
  17647. "Insert an empty comment above current line.
  17648. If the line is empty, insert comment at its beginning. When
  17649. point is within a source block, comment according to the related
  17650. major mode."
  17651. (if (let ((element (org-element-at-point)))
  17652. (and (eq (org-element-type element) 'src-block)
  17653. (< (save-excursion
  17654. (goto-char (org-element-property :post-affiliated element))
  17655. (line-end-position))
  17656. (point))
  17657. (> (save-excursion
  17658. (goto-char (org-element-property :end element))
  17659. (skip-chars-backward " \r\t\n")
  17660. (line-beginning-position))
  17661. (point))))
  17662. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17663. (beginning-of-line)
  17664. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17665. (open-line 1))
  17666. (org-indent-line)
  17667. (insert "# ")))
  17668. (defvar comment-empty-lines) ; From newcomment.el.
  17669. (defun org-comment-or-uncomment-region (beg end &rest _)
  17670. "Comment or uncomment each non-blank line in the region.
  17671. Uncomment each non-blank line between BEG and END if it only
  17672. contains commented lines. Otherwise, comment them. If region is
  17673. strictly within a source block, use appropriate comment syntax."
  17674. (if (let ((element (org-element-at-point)))
  17675. (and (eq (org-element-type element) 'src-block)
  17676. (< (save-excursion
  17677. (goto-char (org-element-property :post-affiliated element))
  17678. (line-end-position))
  17679. beg)
  17680. (>= (save-excursion
  17681. (goto-char (org-element-property :end element))
  17682. (skip-chars-backward " \r\t\n")
  17683. (line-beginning-position))
  17684. end)))
  17685. ;; Translate region boundaries for the Org buffer to the source
  17686. ;; buffer.
  17687. (let ((offset (- end beg)))
  17688. (save-excursion
  17689. (goto-char beg)
  17690. (org-babel-do-in-edit-buffer
  17691. (comment-or-uncomment-region (point) (+ offset (point))))))
  17692. (save-restriction
  17693. ;; Restrict region
  17694. (narrow-to-region (save-excursion (goto-char beg)
  17695. (skip-chars-forward " \r\t\n" end)
  17696. (line-beginning-position))
  17697. (save-excursion (goto-char end)
  17698. (skip-chars-backward " \r\t\n" beg)
  17699. (line-end-position)))
  17700. (let ((uncommentp
  17701. ;; UNCOMMENTP is non-nil when every non blank line between
  17702. ;; BEG and END is a comment.
  17703. (save-excursion
  17704. (goto-char (point-min))
  17705. (while (and (not (eobp))
  17706. (let ((element (org-element-at-point)))
  17707. (and (eq (org-element-type element) 'comment)
  17708. (goto-char (min (point-max)
  17709. (org-element-property
  17710. :end element)))))))
  17711. (eobp))))
  17712. (if uncommentp
  17713. ;; Only blank lines and comments in region: uncomment it.
  17714. (save-excursion
  17715. (goto-char (point-min))
  17716. (while (not (eobp))
  17717. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17718. (replace-match "" nil nil nil 1))
  17719. (forward-line)))
  17720. ;; Comment each line in region.
  17721. (let ((min-indent (point-max)))
  17722. ;; First find the minimum indentation across all lines.
  17723. (save-excursion
  17724. (goto-char (point-min))
  17725. (while (and (not (eobp)) (not (zerop min-indent)))
  17726. (unless (looking-at "[ \t]*$")
  17727. (setq min-indent (min min-indent (current-indentation))))
  17728. (forward-line)))
  17729. ;; Then loop over all lines.
  17730. (save-excursion
  17731. (goto-char (point-min))
  17732. (while (not (eobp))
  17733. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17734. ;; Don't get fooled by invisible text (e.g. link path)
  17735. ;; when moving to column MIN-INDENT.
  17736. (let ((buffer-invisibility-spec nil))
  17737. (org-move-to-column min-indent t))
  17738. (insert comment-start))
  17739. (forward-line)))))))))
  17740. (defun org-comment-dwim (_arg)
  17741. "Call the comment command you mean.
  17742. Call `org-toggle-comment' if on a heading, otherwise call
  17743. `comment-dwim', within a source edit buffer if needed."
  17744. (interactive "*P")
  17745. (cond ((org-at-heading-p)
  17746. (call-interactively #'org-toggle-comment))
  17747. ((org-in-src-block-p)
  17748. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17749. (t (call-interactively #'comment-dwim))))
  17750. ;;; Timestamps API
  17751. ;; This section contains tools to operate on, or create, timestamp
  17752. ;; objects, as returned by, e.g. `org-element-context'.
  17753. (defun org-timestamp-from-string (s)
  17754. "Convert Org timestamp S, as a string, into a timestamp object.
  17755. Return nil if S is not a valid timestamp string."
  17756. (when (org-string-nw-p s)
  17757. (with-temp-buffer
  17758. (save-excursion (insert s))
  17759. (org-element-timestamp-parser))))
  17760. (defun org-timestamp-from-time (time &optional with-time inactive)
  17761. "Convert a time value into a timestamp object.
  17762. TIME is an Emacs internal time representation, as returned, e.g.,
  17763. by `current-time'.
  17764. When optional argument WITH-TIME is non-nil, return a timestamp
  17765. object with a time part, i.e., with hours and minutes.
  17766. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17767. return an active timestamp."
  17768. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17769. (org-element-create 'timestamp
  17770. (list :type (if inactive 'inactive 'active)
  17771. :year-start year
  17772. :month-start month
  17773. :day-start day
  17774. :hour-start (and with-time hour)
  17775. :minute-start (and with-time minute)))))
  17776. (defun org-timestamp-to-time (timestamp &optional end)
  17777. "Convert TIMESTAMP object into an Emacs internal time value.
  17778. Use end of date range or time range when END is non-nil.
  17779. Otherwise, use its start."
  17780. (apply #'encode-time 0
  17781. (mapcar
  17782. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17783. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17784. '(:minute-start :hour-start :day-start :month-start
  17785. :year-start)))))
  17786. (defun org-timestamp-has-time-p (timestamp)
  17787. "Non-nil when TIMESTAMP has a time specified."
  17788. (org-element-property :hour-start timestamp))
  17789. (defun org-timestamp-format (timestamp format &optional end utc)
  17790. "Format a TIMESTAMP object into a string.
  17791. FORMAT is a format specifier to be passed to
  17792. `format-time-string'.
  17793. When optional argument END is non-nil, use end of date-range or
  17794. time-range, if possible.
  17795. When optional argument UTC is non-nil, time is be expressed as
  17796. Universal Time."
  17797. (format-time-string format (org-timestamp-to-time timestamp end)
  17798. (and utc t)))
  17799. (defun org-timestamp-split-range (timestamp &optional end)
  17800. "Extract a TIMESTAMP object from a date or time range.
  17801. END, when non-nil, means extract the end of the range.
  17802. Otherwise, extract its start.
  17803. Return a new timestamp object."
  17804. (let ((type (org-element-property :type timestamp)))
  17805. (if (memq type '(active inactive diary)) timestamp
  17806. (let ((split-ts (org-element-copy timestamp)))
  17807. ;; Set new type.
  17808. (org-element-put-property
  17809. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17810. ;; Copy start properties over end properties if END is
  17811. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17812. (let ((p-alist '((:minute-start . :minute-end)
  17813. (:hour-start . :hour-end)
  17814. (:day-start . :day-end)
  17815. (:month-start . :month-end)
  17816. (:year-start . :year-end))))
  17817. (dolist (p-cell p-alist)
  17818. (org-element-put-property
  17819. split-ts
  17820. (funcall (if end #'car #'cdr) p-cell)
  17821. (org-element-property
  17822. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17823. ;; Eventually refresh `:raw-value'.
  17824. (org-element-put-property split-ts :raw-value nil)
  17825. (org-element-put-property
  17826. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17827. (defun org-timestamp-translate (timestamp &optional boundary)
  17828. "Translate TIMESTAMP object to custom format.
  17829. Format string is defined in `org-time-stamp-custom-formats',
  17830. which see.
  17831. When optional argument BOUNDARY is non-nil, it is either the
  17832. symbol `start' or `end'. In this case, only translate the
  17833. starting or ending part of TIMESTAMP if it is a date or time
  17834. range. Otherwise, translate both parts.
  17835. Return timestamp as-is if `org-display-custom-times' is nil or if
  17836. it has a `diary' type."
  17837. (let ((type (org-element-property :type timestamp)))
  17838. (if (or (not org-display-custom-times) (eq type 'diary))
  17839. (org-element-interpret-data timestamp)
  17840. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17841. org-time-stamp-custom-formats)))
  17842. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17843. (concat (org-timestamp-format timestamp fmt)
  17844. "--"
  17845. (org-timestamp-format timestamp fmt t))
  17846. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17847. ;;; Other stuff
  17848. (defvar reftex-docstruct-symbol)
  17849. (defvar org--rds)
  17850. (defun org-reftex-citation ()
  17851. "Use reftex-citation to insert a citation into the buffer.
  17852. This looks for a line like
  17853. #+BIBLIOGRAPHY: foo plain option:-d
  17854. and derives from it that foo.bib is the bibliography file relevant
  17855. for this document. It then installs the necessary environment for RefTeX
  17856. to work in this buffer and calls `reftex-citation' to insert a citation
  17857. into the buffer.
  17858. Export of such citations to both LaTeX and HTML is handled by the contributed
  17859. package ox-bibtex by Taru Karttunen."
  17860. (interactive)
  17861. (let ((reftex-docstruct-symbol 'org--rds)
  17862. org--rds bib)
  17863. (org-with-wide-buffer
  17864. (let ((case-fold-search t)
  17865. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17866. (if (not (save-excursion
  17867. (or (re-search-forward re nil t)
  17868. (re-search-backward re nil t))))
  17869. (user-error "No bibliography defined in file")
  17870. (setq bib (concat (match-string 1) ".bib")
  17871. org--rds (list (list 'bib bib))))))
  17872. (call-interactively 'reftex-citation)))
  17873. ;;;; Functions extending outline functionality
  17874. (defun org-beginning-of-line (&optional n)
  17875. "Go to the beginning of the current visible line.
  17876. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17877. symbol `reversed', on the first attempt move to where the
  17878. headline text starts, and only move to beginning of line when the
  17879. cursor is already before the start of the text of the headline.
  17880. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17881. start of the text on the second attempt.
  17882. With argument N not nil or 1, move forward N - 1 lines first."
  17883. (interactive "^p")
  17884. (let ((origin (point))
  17885. (special (pcase org-special-ctrl-a/e
  17886. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17887. deactivate-mark)
  17888. ;; First move to a visible line.
  17889. (if (bound-and-true-p visual-line-mode)
  17890. (beginning-of-visual-line n)
  17891. (move-beginning-of-line n)
  17892. ;; `move-beginning-of-line' may leave point after invisible
  17893. ;; characters if line starts with such of these (e.g., with
  17894. ;; a link at column 0). Really move to the beginning of the
  17895. ;; current visible line.
  17896. (beginning-of-line))
  17897. (cond
  17898. ;; No special behavior. Point is already at the beginning of
  17899. ;; a line, logical or visual.
  17900. ((not special))
  17901. ;; `beginning-of-visual-line' left point before logical beginning
  17902. ;; of line: point is at the beginning of a visual line. Bail
  17903. ;; out.
  17904. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17905. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17906. ;; At a headline, special position is before the title, but
  17907. ;; after any TODO keyword or priority cookie.
  17908. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17909. (line-end-position)))
  17910. (bol (point)))
  17911. (if (eq special 'reversed)
  17912. (when (and (= origin bol) (eq last-command this-command))
  17913. (goto-char refpos))
  17914. (when (or (> origin refpos) (= origin bol))
  17915. (goto-char refpos)))))
  17916. ((and (looking-at org-list-full-item-re)
  17917. (memq (org-element-type (save-match-data (org-element-at-point)))
  17918. '(item plain-list)))
  17919. ;; Set special position at first white space character after
  17920. ;; bullet, and check-box, if any.
  17921. (let ((after-bullet
  17922. (let ((box (match-end 3)))
  17923. (cond ((not box) (match-end 1))
  17924. ((eq (char-after box) ?\s) (1+ box))
  17925. (t box)))))
  17926. (if (eq special 'reversed)
  17927. (when (and (= (point) origin) (eq last-command this-command))
  17928. (goto-char after-bullet))
  17929. (when (or (> origin after-bullet) (= (point) origin))
  17930. (goto-char after-bullet)))))
  17931. ;; No special context. Point is already at beginning of line.
  17932. (t nil))))
  17933. (defun org-end-of-line (&optional n)
  17934. "Go to the end of the line, but before ellipsis, if any.
  17935. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17936. symbol `reversed', ignore tags on the first attempt, and only
  17937. move to after the tags when the cursor is already beyond the end
  17938. of the headline.
  17939. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17940. on the second attempt.
  17941. With argument N not nil or 1, move forward N - 1 lines first."
  17942. (interactive "^p")
  17943. (let ((origin (point))
  17944. (special (pcase org-special-ctrl-a/e
  17945. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17946. deactivate-mark)
  17947. ;; First move to a visible line.
  17948. (if (bound-and-true-p visual-line-mode)
  17949. (beginning-of-visual-line n)
  17950. (move-beginning-of-line n))
  17951. (cond
  17952. ;; At a headline, with tags.
  17953. ((and special
  17954. (save-excursion
  17955. (beginning-of-line)
  17956. (let ((case-fold-search nil))
  17957. (looking-at org-complex-heading-regexp)))
  17958. (match-end 5))
  17959. (let ((tags (save-excursion
  17960. (goto-char (match-beginning 5))
  17961. (skip-chars-backward " \t")
  17962. (point)))
  17963. (visual-end (and (bound-and-true-p visual-line-mode)
  17964. (save-excursion
  17965. (end-of-visual-line)
  17966. (point)))))
  17967. ;; If `end-of-visual-line' brings us before end of line or
  17968. ;; even tags, i.e., the headline spans over multiple visual
  17969. ;; lines, move there.
  17970. (cond ((and visual-end
  17971. (< visual-end tags)
  17972. (<= origin visual-end))
  17973. (goto-char visual-end))
  17974. ((eq special 'reversed)
  17975. (if (and (= origin (line-end-position))
  17976. (eq this-command last-command))
  17977. (goto-char tags)
  17978. (end-of-line)))
  17979. (t
  17980. (if (or (< origin tags) (= origin (line-end-position)))
  17981. (goto-char tags)
  17982. (end-of-line))))))
  17983. ((bound-and-true-p visual-line-mode)
  17984. (let ((bol (line-beginning-position)))
  17985. (end-of-visual-line)
  17986. ;; If `end-of-visual-line' gets us past the ellipsis at the
  17987. ;; end of a line, backtrack and use `end-of-line' instead.
  17988. (when (/= bol (line-beginning-position))
  17989. (goto-char bol)
  17990. (end-of-line))))
  17991. (t (end-of-line)))))
  17992. (defun org-backward-sentence (&optional _arg)
  17993. "Go to beginning of sentence, or beginning of table field.
  17994. This will call `backward-sentence' or `org-table-beginning-of-field',
  17995. depending on context."
  17996. (interactive)
  17997. (let* ((element (org-element-at-point))
  17998. (contents-begin (org-element-property :contents-begin element))
  17999. (table (org-element-lineage element '(table) t)))
  18000. (if (and table
  18001. (> (point) contents-begin)
  18002. (<= (point) (org-element-property :contents-end table)))
  18003. (call-interactively #'org-table-beginning-of-field)
  18004. (save-restriction
  18005. (when (and contents-begin
  18006. (< (point-min) contents-begin)
  18007. (> (point) contents-begin))
  18008. (narrow-to-region contents-begin
  18009. (org-element-property :contents-end element)))
  18010. (call-interactively #'backward-sentence)))))
  18011. (defun org-forward-sentence (&optional _arg)
  18012. "Go to end of sentence, or end of table field.
  18013. This will call `forward-sentence' or `org-table-end-of-field',
  18014. depending on context."
  18015. (interactive)
  18016. (if (and (org-at-heading-p)
  18017. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18018. (save-restriction
  18019. (narrow-to-region (line-beginning-position) (line-end-position))
  18020. (call-interactively #'forward-sentence))
  18021. (let* ((element (org-element-at-point))
  18022. (contents-end (org-element-property :contents-end element))
  18023. (table (org-element-lineage element '(table) t)))
  18024. (if (and table
  18025. (>= (point) (org-element-property :contents-begin table))
  18026. (< (point) contents-end))
  18027. (call-interactively #'org-table-end-of-field)
  18028. (save-restriction
  18029. (when (and contents-end
  18030. (> (point-max) contents-end)
  18031. ;; Skip blank lines between elements.
  18032. (< (org-element-property :end element)
  18033. (save-excursion (goto-char contents-end)
  18034. (skip-chars-forward " \r\t\n"))))
  18035. (narrow-to-region (org-element-property :contents-begin element)
  18036. contents-end))
  18037. ;; End of heading is considered as the end of a sentence.
  18038. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18039. (call-interactively #'forward-sentence)))))))
  18040. (defun org-kill-line (&optional _arg)
  18041. "Kill line, to tags or end of line."
  18042. (interactive)
  18043. (cond
  18044. ((or (not org-special-ctrl-k)
  18045. (bolp)
  18046. (not (org-at-heading-p)))
  18047. (when (and (get-char-property (line-end-position) 'invisible)
  18048. org-ctrl-k-protect-subtree
  18049. (or (eq org-ctrl-k-protect-subtree 'error)
  18050. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18051. (user-error
  18052. (substitute-command-keys
  18053. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18054. (call-interactively
  18055. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18056. ((org-match-line org-tag-line-re)
  18057. (let ((end (save-excursion
  18058. (goto-char (match-beginning 1))
  18059. (skip-chars-backward " \t")
  18060. (point))))
  18061. (if (<= end (point)) ;on tags part
  18062. (kill-region (point) (line-end-position))
  18063. (kill-region (point) end)))
  18064. (org-align-tags))
  18065. (t (kill-region (point) (line-end-position)))))
  18066. (defun org-yank (&optional arg)
  18067. "Yank. If the kill is a subtree, treat it specially.
  18068. This command will look at the current kill and check if is a single
  18069. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18070. cursor is at the beginning of a line or after the stars of a currently
  18071. empty headline, then the yank is handled specially. How exactly depends
  18072. on the value of the following variables.
  18073. `org-yank-folded-subtrees'
  18074. By default, this variable is non-nil, which results in
  18075. subtree(s) being folded after insertion, except if doing so
  18076. would swallow text after the yanked text.
  18077. `org-yank-adjusted-subtrees'
  18078. When non-nil (the default value is nil), the subtree will be
  18079. promoted or demoted in order to fit into the local outline tree
  18080. structure, which means that the level will be adjusted so that it
  18081. becomes the smaller one of the two *visible* surrounding headings.
  18082. Any prefix to this command will cause `yank' to be called directly with
  18083. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18084. will just
  18085. plainly yank the text as it is.
  18086. \[1] The test checks if the first non-white line is a heading
  18087. and if there are no other headings with fewer stars."
  18088. (interactive "P")
  18089. (org-yank-generic 'yank arg))
  18090. (defun org-yank-generic (command arg)
  18091. "Perform some yank-like command.
  18092. This function implements the behavior described in the `org-yank'
  18093. documentation. However, it has been generalized to work for any
  18094. interactive command with similar behavior."
  18095. ;; pretend to be command COMMAND
  18096. (setq this-command command)
  18097. (if arg
  18098. (call-interactively command)
  18099. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18100. (and (org-kill-is-subtree-p)
  18101. (or (bolp)
  18102. (and (looking-at "[ \t]*$")
  18103. (string-match
  18104. "\\`\\*+\\'"
  18105. (buffer-substring (point-at-bol) (point)))))))
  18106. swallowp)
  18107. (cond
  18108. ((and subtreep org-yank-folded-subtrees)
  18109. (let ((beg (point))
  18110. end)
  18111. (if (and subtreep org-yank-adjusted-subtrees)
  18112. (org-paste-subtree nil nil 'for-yank)
  18113. (call-interactively command))
  18114. (setq end (point))
  18115. (goto-char beg)
  18116. (when (and (bolp) subtreep
  18117. (not (setq swallowp
  18118. (org-yank-folding-would-swallow-text beg end))))
  18119. (org-with-limited-levels
  18120. (or (looking-at org-outline-regexp)
  18121. (re-search-forward org-outline-regexp-bol end t))
  18122. (while (and (< (point) end) (looking-at org-outline-regexp))
  18123. (org-flag-subtree t)
  18124. (org-cycle-show-empty-lines 'folded)
  18125. (condition-case nil
  18126. (outline-forward-same-level 1)
  18127. (error (goto-char end))))))
  18128. (when swallowp
  18129. (message
  18130. "Inserted text not folded because that would swallow text"))
  18131. (goto-char end)
  18132. (skip-chars-forward " \t\n\r")
  18133. (beginning-of-line 1)
  18134. (push-mark beg 'nomsg)))
  18135. ((and subtreep org-yank-adjusted-subtrees)
  18136. (let ((beg (point-at-bol)))
  18137. (org-paste-subtree nil nil 'for-yank)
  18138. (push-mark beg 'nomsg)))
  18139. (t
  18140. (call-interactively command))))))
  18141. (defun org-yank-folding-would-swallow-text (beg end)
  18142. "Would hide-subtree at BEG swallow any text after END?"
  18143. (let (level)
  18144. (org-with-limited-levels
  18145. (save-excursion
  18146. (goto-char beg)
  18147. (when (or (looking-at org-outline-regexp)
  18148. (re-search-forward org-outline-regexp-bol end t))
  18149. (setq level (org-outline-level)))
  18150. (goto-char end)
  18151. (skip-chars-forward " \t\r\n\v\f")
  18152. (not (or (eobp)
  18153. (and (bolp) (looking-at-p org-outline-regexp)
  18154. (<= (org-outline-level) level))))))))
  18155. (defun org-back-to-heading (&optional invisible-ok)
  18156. "Call `outline-back-to-heading', but provide a better error message."
  18157. (condition-case nil
  18158. (outline-back-to-heading invisible-ok)
  18159. (error
  18160. (user-error "Before first headline at position %d in buffer %s"
  18161. (point) (current-buffer)))))
  18162. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18163. "Go back to heading or first point in buffer.
  18164. If point is before first heading go to first point in buffer
  18165. instead of back to heading."
  18166. (condition-case nil
  18167. (outline-back-to-heading invisible-ok)
  18168. (error
  18169. (goto-char (point-min)))))
  18170. (defun org-before-first-heading-p ()
  18171. "Before first heading?"
  18172. (org-with-limited-levels
  18173. (save-excursion
  18174. (end-of-line)
  18175. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18176. (defun org-at-heading-p (&optional _)
  18177. "Non-nil when on a headline."
  18178. (outline-on-heading-p t))
  18179. (defun org-in-commented-heading-p (&optional no-inheritance)
  18180. "Non-nil if point is under a commented heading.
  18181. This function also checks ancestors of the current headline,
  18182. unless optional argument NO-INHERITANCE is non-nil."
  18183. (cond
  18184. ((org-before-first-heading-p) nil)
  18185. ((let ((headline (nth 4 (org-heading-components))))
  18186. (and headline
  18187. (let ((case-fold-search nil))
  18188. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18189. headline)))))
  18190. (no-inheritance nil)
  18191. (t
  18192. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18193. (defun org-at-comment-p nil
  18194. "Return t if cursor is in a commented line."
  18195. (save-excursion
  18196. (save-match-data
  18197. (beginning-of-line)
  18198. (looking-at "^[ \t]*# "))))
  18199. (defun org-at-keyword-p nil
  18200. "Return t if cursor is at a keyword-line."
  18201. (save-excursion
  18202. (move-beginning-of-line 1)
  18203. (looking-at org-keyword-regexp)))
  18204. (defun org-at-drawer-p nil
  18205. "Return t if cursor is at a drawer keyword."
  18206. (save-excursion
  18207. (move-beginning-of-line 1)
  18208. (looking-at org-drawer-regexp)))
  18209. (defun org-at-block-p nil
  18210. "Return t if cursor is at a block keyword."
  18211. (save-excursion
  18212. (move-beginning-of-line 1)
  18213. (looking-at org-block-regexp)))
  18214. (defun org-point-at-end-of-empty-headline ()
  18215. "If point is at the end of an empty headline, return t, else nil.
  18216. If the heading only contains a TODO keyword, it is still still considered
  18217. empty."
  18218. (let ((case-fold-search nil))
  18219. (and (looking-at "[ \t]*$")
  18220. org-todo-line-regexp
  18221. (save-excursion
  18222. (beginning-of-line)
  18223. (looking-at org-todo-line-regexp)
  18224. (string= (match-string 3) "")))))
  18225. (defun org-at-heading-or-item-p ()
  18226. (or (org-at-heading-p) (org-at-item-p)))
  18227. (defun org-up-heading-all (arg)
  18228. "Move to the heading line of which the present line is a subheading.
  18229. This function considers both visible and invisible heading lines.
  18230. With argument, move up ARG levels."
  18231. (outline-up-heading arg t))
  18232. (defun org-up-heading-safe ()
  18233. "Move to the heading line of which the present line is a subheading.
  18234. This version will not throw an error. It will return the level of the
  18235. headline found, or nil if no higher level is found.
  18236. Also, this function will be a lot faster than `outline-up-heading',
  18237. because it relies on stars being the outline starters. This can really
  18238. make a significant difference in outlines with very many siblings."
  18239. (when (ignore-errors (org-back-to-heading t))
  18240. (let ((level-up (1- (funcall outline-level))))
  18241. (and (> level-up 0)
  18242. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18243. (funcall outline-level)))))
  18244. (defun org-up-heading-or-point-min ()
  18245. "Move to the heading line of which the present is a subheading, or point-min.
  18246. This version is needed to make point-min behave like a virtual
  18247. heading of level 0 for property-inheritance. It will return the
  18248. level of the headline found (down to 0) or nil if already at a
  18249. point before the first headline or at point-min."
  18250. (when (ignore-errors (org-back-to-heading t))
  18251. (if (< 1 (funcall outline-level))
  18252. (org-up-heading-safe)
  18253. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18254. (defun org-first-sibling-p ()
  18255. "Is this heading the first child of its parents?"
  18256. (interactive)
  18257. (let ((re org-outline-regexp-bol)
  18258. level l)
  18259. (unless (org-at-heading-p t)
  18260. (user-error "Not at a heading"))
  18261. (setq level (funcall outline-level))
  18262. (save-excursion
  18263. (if (not (re-search-backward re nil t))
  18264. t
  18265. (setq l (funcall outline-level))
  18266. (< l level)))))
  18267. (defun org-goto-sibling (&optional previous)
  18268. "Goto the next sibling, even if it is invisible.
  18269. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18270. when a sibling was found. When none is found, return nil and don't
  18271. move point."
  18272. (let ((fun (if previous 're-search-backward 're-search-forward))
  18273. (pos (point))
  18274. (re org-outline-regexp-bol)
  18275. level l)
  18276. (when (ignore-errors (org-back-to-heading t))
  18277. (setq level (funcall outline-level))
  18278. (catch 'exit
  18279. (or previous (forward-char 1))
  18280. (while (funcall fun re nil t)
  18281. (setq l (funcall outline-level))
  18282. (when (< l level) (goto-char pos) (throw 'exit nil))
  18283. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18284. (goto-char pos)
  18285. nil))))
  18286. (defun org-show-siblings ()
  18287. "Show all siblings of the current headline."
  18288. (save-excursion
  18289. (while (org-goto-sibling) (org-flag-heading nil)))
  18290. (save-excursion
  18291. (while (org-goto-sibling 'previous)
  18292. (org-flag-heading nil))))
  18293. (defun org-goto-first-child ()
  18294. "Goto the first child, even if it is invisible.
  18295. Return t when a child was found. Otherwise don't move point and
  18296. return nil."
  18297. (let (level (pos (point)) (re org-outline-regexp-bol))
  18298. (when (ignore-errors (org-back-to-heading t))
  18299. (setq level (outline-level))
  18300. (forward-char 1)
  18301. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18302. (progn (goto-char (match-beginning 0)) t)
  18303. (goto-char pos) nil))))
  18304. (defun org-show-hidden-entry ()
  18305. "Show an entry where even the heading is hidden."
  18306. (save-excursion
  18307. (org-show-entry)))
  18308. (defun org-flag-heading (flag &optional entry)
  18309. "Flag the current heading. FLAG non-nil means make invisible.
  18310. When ENTRY is non-nil, show the entire entry."
  18311. (save-excursion
  18312. (org-back-to-heading t)
  18313. ;; Check if we should show the entire entry
  18314. (if (not entry)
  18315. (org-flag-region
  18316. (line-end-position 0) (line-end-position) flag 'outline)
  18317. (org-show-entry)
  18318. (save-excursion
  18319. (and (outline-next-heading)
  18320. (org-flag-heading nil))))))
  18321. (defun org-get-next-sibling ()
  18322. "Move to next heading of the same level, and return point.
  18323. If there is no such heading, return nil.
  18324. This is like outline-next-sibling, but invisible headings are ok."
  18325. (let ((level (funcall outline-level)))
  18326. (outline-next-heading)
  18327. (while (and (not (eobp)) (> (funcall outline-level) level))
  18328. (outline-next-heading))
  18329. (unless (or (eobp) (< (funcall outline-level) level))
  18330. (point))))
  18331. (defun org-get-last-sibling ()
  18332. "Move to previous heading of the same level, and return point.
  18333. If there is no such heading, return nil."
  18334. (let ((opoint (point))
  18335. (level (funcall outline-level)))
  18336. (outline-previous-heading)
  18337. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18338. (while (and (> (funcall outline-level) level)
  18339. (not (bobp)))
  18340. (outline-previous-heading))
  18341. (unless (< (funcall outline-level) level)
  18342. (point)))))
  18343. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18344. "Goto to the end of a subtree."
  18345. ;; This contains an exact copy of the original function, but it uses
  18346. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18347. ;; trees and before first headline. And is uses an invisible-ok argument.
  18348. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18349. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18350. ;; with many children and grandchildren etc, this can be much faster
  18351. ;; than the outline version.
  18352. (org-back-to-heading-or-point-min invisible-ok)
  18353. (let ((first t)
  18354. (level (funcall outline-level)))
  18355. (cond ((= level 0)
  18356. (goto-char (point-max)))
  18357. ((and (derived-mode-p 'org-mode) (< level 1000))
  18358. ;; A true heading (not a plain list item), in Org
  18359. ;; This means we can easily find the end by looking
  18360. ;; only for the right number of stars. Using a regexp to do
  18361. ;; this is so much faster than using a Lisp loop.
  18362. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18363. (forward-char 1)
  18364. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18365. (t
  18366. ;; something else, do it the slow way
  18367. (while (and (not (eobp))
  18368. (or first (> (funcall outline-level) level)))
  18369. (setq first nil)
  18370. (outline-next-heading))))
  18371. (unless to-heading
  18372. (when (memq (preceding-char) '(?\n ?\^M))
  18373. ;; Go to end of line before heading
  18374. (forward-char -1)
  18375. (when (memq (preceding-char) '(?\n ?\^M))
  18376. ;; leave blank line before heading
  18377. (forward-char -1)))))
  18378. (point))
  18379. (defun org-end-of-meta-data (&optional full)
  18380. "Skip planning line and properties drawer in current entry.
  18381. When optional argument FULL is non-nil, also skip empty lines,
  18382. clocking lines and regular drawers at the beginning of the
  18383. entry."
  18384. (org-back-to-heading t)
  18385. (forward-line)
  18386. (when (looking-at-p org-planning-line-re) (forward-line))
  18387. (when (looking-at org-property-drawer-re)
  18388. (goto-char (match-end 0))
  18389. (forward-line))
  18390. (when (and full (not (org-at-heading-p)))
  18391. (catch 'exit
  18392. (let ((end (save-excursion (outline-next-heading) (point)))
  18393. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18394. (while (not (eobp))
  18395. (cond ((looking-at-p org-drawer-regexp)
  18396. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18397. (forward-line)
  18398. (throw 'exit t)))
  18399. ((looking-at-p re) (forward-line))
  18400. (t (throw 'exit t))))))))
  18401. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18402. "Move forward to the ARG'th subheading at same level as this one.
  18403. Stop at the first and last subheadings of a superior heading.
  18404. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18405. non-nil it will also look at invisible ones."
  18406. (interactive "p")
  18407. (let ((backward? (and arg (< arg 0))))
  18408. (if (org-before-first-heading-p)
  18409. (if backward? (goto-char (point-min)) (outline-next-heading))
  18410. (org-back-to-heading invisible-ok)
  18411. (unless backward? (end-of-line)) ;do not match current headline
  18412. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18413. (f (if backward? #'re-search-backward #'re-search-forward))
  18414. (count (if arg (abs arg) 1))
  18415. (result (point)))
  18416. (while (and (> count 0)
  18417. (funcall f org-outline-regexp-bol nil 'move))
  18418. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18419. (cond ((< l level) (setq count 0))
  18420. ((and (= l level)
  18421. (or invisible-ok
  18422. (not (org-invisible-p
  18423. (line-beginning-position)))))
  18424. (cl-decf count)
  18425. (when (= l level) (setq result (point)))))))
  18426. (goto-char result))
  18427. (beginning-of-line))))
  18428. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18429. "Move backward to the ARG'th subheading at same level as this one.
  18430. Stop at the first and last subheadings of a superior heading."
  18431. (interactive "p")
  18432. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18433. (defun org-next-visible-heading (arg)
  18434. "Move to the next visible heading.
  18435. This function wraps `outline-next-visible-heading' with
  18436. `org-with-limited-levels' in order to skip over inline tasks and
  18437. respect customization of `org-odd-levels-only'."
  18438. (interactive "p")
  18439. (org-with-limited-levels
  18440. (outline-next-visible-heading arg)))
  18441. (defun org-previous-visible-heading (arg)
  18442. "Move to the previous visible heading.
  18443. This function wraps `outline-previous-visible-heading' with
  18444. `org-with-limited-levels' in order to skip over inline tasks and
  18445. respect customization of `org-odd-levels-only'."
  18446. (interactive "p")
  18447. (org-with-limited-levels
  18448. (outline-previous-visible-heading arg)))
  18449. (defun org-forward-paragraph ()
  18450. "Move forward to beginning of next paragraph or equivalent.
  18451. The function moves point to the beginning of the next visible
  18452. structural element, which can be a paragraph, a table, a list
  18453. item, etc. It also provides some special moves for convenience:
  18454. - On an affiliated keyword, jump to the beginning of the
  18455. relative element.
  18456. - On an item or a footnote definition, move to the second
  18457. element inside, if any.
  18458. - On a table or a property drawer, jump after it.
  18459. - On a verse or source block, stop after blank lines."
  18460. (interactive)
  18461. (unless (eobp)
  18462. (let* ((deactivate-mark nil)
  18463. (element (org-element-at-point))
  18464. (type (org-element-type element))
  18465. (post-affiliated (org-element-property :post-affiliated element))
  18466. (contents-begin (org-element-property :contents-begin element))
  18467. (contents-end (org-element-property :contents-end element))
  18468. (end (let ((end (org-element-property :end element)) (parent element))
  18469. (while (and (setq parent (org-element-property :parent parent))
  18470. (= (org-element-property :contents-end parent) end))
  18471. (setq end (org-element-property :end parent)))
  18472. end)))
  18473. (cond ((not element)
  18474. (skip-chars-forward " \r\t\n")
  18475. (or (eobp) (beginning-of-line)))
  18476. ;; On affiliated keywords, move to element's beginning.
  18477. ((< (point) post-affiliated)
  18478. (goto-char post-affiliated))
  18479. ;; At a table row, move to the end of the table. Similarly,
  18480. ;; at a node property, move to the end of the property
  18481. ;; drawer.
  18482. ((memq type '(node-property table-row))
  18483. (goto-char (org-element-property
  18484. :end (org-element-property :parent element))))
  18485. ((memq type '(property-drawer table)) (goto-char end))
  18486. ;; Consider blank lines as separators in verse and source
  18487. ;; blocks to ease editing.
  18488. ((memq type '(src-block verse-block))
  18489. (when (eq type 'src-block)
  18490. (setq contents-end
  18491. (save-excursion (goto-char end)
  18492. (skip-chars-backward " \r\t\n")
  18493. (line-beginning-position))))
  18494. (beginning-of-line)
  18495. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  18496. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  18497. (goto-char end)
  18498. (skip-chars-forward " \r\t\n")
  18499. (if (= (point) contents-end) (goto-char end)
  18500. (beginning-of-line))))
  18501. ;; With no contents, just skip element.
  18502. ((not contents-begin) (goto-char end))
  18503. ;; If contents are invisible, skip the element altogether.
  18504. ((org-invisible-p (line-end-position))
  18505. (cl-case type
  18506. (headline
  18507. (org-with-limited-levels (outline-next-visible-heading 1)))
  18508. ;; At a plain list, make sure we move to the next item
  18509. ;; instead of skipping the whole list.
  18510. (plain-list (forward-char)
  18511. (org-forward-paragraph))
  18512. (otherwise (goto-char end))))
  18513. ((>= (point) contents-end) (goto-char end))
  18514. ((>= (point) contents-begin)
  18515. ;; This can only happen on paragraphs and plain lists.
  18516. (cl-case type
  18517. (paragraph (goto-char end))
  18518. ;; At a plain list, try to move to second element in
  18519. ;; first item, if possible.
  18520. (plain-list (end-of-line)
  18521. (org-forward-paragraph))))
  18522. ;; When contents start on the middle of a line (e.g. in
  18523. ;; items and footnote definitions), try to reach first
  18524. ;; element starting after current line.
  18525. ((> (line-end-position) contents-begin)
  18526. (end-of-line)
  18527. (org-forward-paragraph))
  18528. (t (goto-char contents-begin))))))
  18529. (defun org-backward-paragraph ()
  18530. "Move backward to start of previous paragraph or equivalent.
  18531. The function moves point to the beginning of the current
  18532. structural element, which can be a paragraph, a table, a list
  18533. item, etc., or to the beginning of the previous visible one if
  18534. point is already there. It also provides some special moves for
  18535. convenience:
  18536. - On an affiliated keyword, jump to the first one.
  18537. - On a table or a property drawer, move to its beginning.
  18538. - On comment, example, export, src and verse blocks, stop
  18539. before blank lines."
  18540. (interactive)
  18541. (unless (bobp)
  18542. (let* ((deactivate-mark nil)
  18543. (element (org-element-at-point))
  18544. (type (org-element-type element))
  18545. (contents-end (org-element-property :contents-end element))
  18546. (post-affiliated (org-element-property :post-affiliated element))
  18547. (begin (org-element-property :begin element))
  18548. (special? ;blocks handled specially
  18549. (memq type '(comment-block example-block export-block src-block
  18550. verse-block)))
  18551. (contents-begin
  18552. (if special?
  18553. ;; These types have no proper contents. Fake line
  18554. ;; below the block opening line as contents beginning.
  18555. (save-excursion (goto-char begin) (line-beginning-position 2))
  18556. (org-element-property :contents-begin element))))
  18557. (cond
  18558. ((not element) (goto-char (point-min)))
  18559. ((= (point) begin)
  18560. (backward-char)
  18561. (org-backward-paragraph))
  18562. ((<= (point) post-affiliated) (goto-char begin))
  18563. ;; Special behavior: on a table or a property drawer, move to
  18564. ;; its beginning.
  18565. ((memq type '(node-property table-row))
  18566. (goto-char (org-element-property
  18567. :post-affiliated (org-element-property :parent element))))
  18568. (special?
  18569. (if (<= (point) contents-begin) (goto-char post-affiliated)
  18570. ;; Inside a verse block, see blank lines as paragraph
  18571. ;; separators.
  18572. (let ((origin (point)))
  18573. (skip-chars-backward " \r\t\n" contents-begin)
  18574. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  18575. (skip-chars-forward " \r\t\n" origin)
  18576. (if (= (point) origin) (goto-char contents-begin)
  18577. (beginning-of-line))))))
  18578. ((eq type 'paragraph) (goto-char contents-begin)
  18579. ;; When at first paragraph in an item or a footnote definition,
  18580. ;; move directly to beginning of line.
  18581. (let ((parent-contents
  18582. (org-element-property
  18583. :contents-begin (org-element-property :parent element))))
  18584. (when (and parent-contents (= parent-contents contents-begin))
  18585. (beginning-of-line))))
  18586. ;; At the end of a greater element, move to the beginning of
  18587. ;; the last element within.
  18588. ((and contents-end (>= (point) contents-end))
  18589. (goto-char (1- contents-end))
  18590. (org-backward-paragraph))
  18591. (t (goto-char (or post-affiliated begin))))
  18592. ;; Ensure we never leave point invisible.
  18593. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  18594. (defun org-forward-element ()
  18595. "Move forward by one element.
  18596. Move to the next element at the same level, when possible."
  18597. (interactive)
  18598. (cond ((eobp) (user-error "Cannot move further down"))
  18599. ((org-with-limited-levels (org-at-heading-p))
  18600. (let ((origin (point)))
  18601. (goto-char (org-end-of-subtree nil t))
  18602. (unless (org-with-limited-levels (org-at-heading-p))
  18603. (goto-char origin)
  18604. (user-error "Cannot move further down"))))
  18605. (t
  18606. (let* ((elem (org-element-at-point))
  18607. (end (org-element-property :end elem))
  18608. (parent (org-element-property :parent elem)))
  18609. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18610. (goto-char (org-element-property :end parent)))
  18611. ((integer-or-marker-p end) (goto-char end))
  18612. (t (message "No element at point")))))))
  18613. (defun org-backward-element ()
  18614. "Move backward by one element.
  18615. Move to the previous element at the same level, when possible."
  18616. (interactive)
  18617. (cond ((bobp) (user-error "Cannot move further up"))
  18618. ((org-with-limited-levels (org-at-heading-p))
  18619. ;; At a headline, move to the previous one, if any, or stay
  18620. ;; here.
  18621. (let ((origin (point)))
  18622. (org-with-limited-levels (org-backward-heading-same-level 1))
  18623. ;; When current headline has no sibling above, move to its
  18624. ;; parent.
  18625. (when (= (point) origin)
  18626. (or (org-with-limited-levels (org-up-heading-safe))
  18627. (progn (goto-char origin)
  18628. (user-error "Cannot move further up"))))))
  18629. (t
  18630. (let* ((elem (org-element-at-point))
  18631. (beg (org-element-property :begin elem)))
  18632. (cond
  18633. ;; Move to beginning of current element if point isn't
  18634. ;; there already.
  18635. ((null beg) (message "No element at point"))
  18636. ((/= (point) beg) (goto-char beg))
  18637. (t (goto-char beg)
  18638. (skip-chars-backward " \r\t\n")
  18639. (unless (bobp)
  18640. (let ((prev (org-element-at-point)))
  18641. (goto-char (org-element-property :begin prev))
  18642. (while (and (setq prev (org-element-property :parent prev))
  18643. (<= (org-element-property :end prev) beg))
  18644. (goto-char (org-element-property :begin prev)))))))))))
  18645. (defun org-up-element ()
  18646. "Move to upper element."
  18647. (interactive)
  18648. (if (org-with-limited-levels (org-at-heading-p))
  18649. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  18650. (let* ((elem (org-element-at-point))
  18651. (parent (org-element-property :parent elem)))
  18652. (if parent (goto-char (org-element-property :begin parent))
  18653. (if (org-with-limited-levels (org-before-first-heading-p))
  18654. (user-error "No surrounding element")
  18655. (org-with-limited-levels (org-back-to-heading)))))))
  18656. (defun org-down-element ()
  18657. "Move to inner element."
  18658. (interactive)
  18659. (let ((element (org-element-at-point)))
  18660. (cond
  18661. ((memq (org-element-type element) '(plain-list table))
  18662. (goto-char (org-element-property :contents-begin element))
  18663. (forward-char))
  18664. ((memq (org-element-type element) org-element-greater-elements)
  18665. ;; If contents are hidden, first disclose them.
  18666. (when (org-invisible-p (line-end-position)) (org-cycle))
  18667. (goto-char (or (org-element-property :contents-begin element)
  18668. (user-error "No content for this element"))))
  18669. (t (user-error "No inner element")))))
  18670. (defun org-drag-element-backward ()
  18671. "Move backward element at point."
  18672. (interactive)
  18673. (let ((elem (or (org-element-at-point)
  18674. (user-error "No element at point"))))
  18675. (if (eq (org-element-type elem) 'headline)
  18676. ;; Preserve point when moving a whole tree, even if point was
  18677. ;; on blank lines below the headline.
  18678. (let ((offset (skip-chars-backward " \t\n")))
  18679. (unwind-protect (org-move-subtree-up)
  18680. (forward-char (- offset))))
  18681. (let ((prev-elem
  18682. (save-excursion
  18683. (goto-char (org-element-property :begin elem))
  18684. (skip-chars-backward " \r\t\n")
  18685. (unless (bobp)
  18686. (let* ((beg (org-element-property :begin elem))
  18687. (prev (org-element-at-point))
  18688. (up prev))
  18689. (while (and (setq up (org-element-property :parent up))
  18690. (<= (org-element-property :end up) beg))
  18691. (setq prev up))
  18692. prev)))))
  18693. ;; Error out if no previous element or previous element is
  18694. ;; a parent of the current one.
  18695. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  18696. (user-error "Cannot drag element backward")
  18697. (let ((pos (point)))
  18698. (org-element-swap-A-B prev-elem elem)
  18699. (goto-char (+ (org-element-property :begin prev-elem)
  18700. (- pos (org-element-property :begin elem))))))))))
  18701. (defun org-drag-element-forward ()
  18702. "Move forward element at point."
  18703. (interactive)
  18704. (let* ((pos (point))
  18705. (elem (or (org-element-at-point)
  18706. (user-error "No element at point"))))
  18707. (when (= (point-max) (org-element-property :end elem))
  18708. (user-error "Cannot drag element forward"))
  18709. (goto-char (org-element-property :end elem))
  18710. (let ((next-elem (org-element-at-point)))
  18711. (when (or (org-element-nested-p elem next-elem)
  18712. (and (eq (org-element-type next-elem) 'headline)
  18713. (not (eq (org-element-type elem) 'headline))))
  18714. (goto-char pos)
  18715. (user-error "Cannot drag element forward"))
  18716. ;; Compute new position of point: it's shifted by NEXT-ELEM
  18717. ;; body's length (without final blanks) and by the length of
  18718. ;; blanks between ELEM and NEXT-ELEM.
  18719. (let ((size-next (- (save-excursion
  18720. (goto-char (org-element-property :end next-elem))
  18721. (skip-chars-backward " \r\t\n")
  18722. (forward-line)
  18723. ;; Small correction if buffer doesn't end
  18724. ;; with a newline character.
  18725. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  18726. (org-element-property :begin next-elem)))
  18727. (size-blank (- (org-element-property :end elem)
  18728. (save-excursion
  18729. (goto-char (org-element-property :end elem))
  18730. (skip-chars-backward " \r\t\n")
  18731. (forward-line)
  18732. (point)))))
  18733. (org-element-swap-A-B elem next-elem)
  18734. (goto-char (+ pos size-next size-blank))))))
  18735. (defun org-drag-line-forward (arg)
  18736. "Drag the line at point ARG lines forward."
  18737. (interactive "p")
  18738. (dotimes (_ (abs arg))
  18739. (let ((c (current-column)))
  18740. (if (< 0 arg)
  18741. (progn
  18742. (beginning-of-line 2)
  18743. (transpose-lines 1)
  18744. (beginning-of-line 0))
  18745. (transpose-lines 1)
  18746. (beginning-of-line -1))
  18747. (org-move-to-column c))))
  18748. (defun org-drag-line-backward (arg)
  18749. "Drag the line at point ARG lines backward."
  18750. (interactive "p")
  18751. (org-drag-line-forward (- arg)))
  18752. (defun org-mark-element ()
  18753. "Put point at beginning of this element, mark at end.
  18754. Interactively, if this command is repeated or (in Transient Mark
  18755. mode) if the mark is active, it marks the next element after the
  18756. ones already marked."
  18757. (interactive)
  18758. (let (deactivate-mark)
  18759. (if (and (called-interactively-p 'any)
  18760. (or (and (eq last-command this-command) (mark t))
  18761. (and transient-mark-mode mark-active)))
  18762. (set-mark
  18763. (save-excursion
  18764. (goto-char (mark))
  18765. (goto-char (org-element-property :end (org-element-at-point)))))
  18766. (let ((element (org-element-at-point)))
  18767. (end-of-line)
  18768. (push-mark (org-element-property :end element) t t)
  18769. (goto-char (org-element-property :begin element))))))
  18770. (defun org-narrow-to-element ()
  18771. "Narrow buffer to current element."
  18772. (interactive)
  18773. (let ((elem (org-element-at-point)))
  18774. (cond
  18775. ((eq (car elem) 'headline)
  18776. (narrow-to-region
  18777. (org-element-property :begin elem)
  18778. (org-element-property :end elem)))
  18779. ((memq (car elem) org-element-greater-elements)
  18780. (narrow-to-region
  18781. (org-element-property :contents-begin elem)
  18782. (org-element-property :contents-end elem)))
  18783. (t
  18784. (narrow-to-region
  18785. (org-element-property :begin elem)
  18786. (org-element-property :end elem))))))
  18787. (defun org-transpose-element ()
  18788. "Transpose current and previous elements, keeping blank lines between.
  18789. Point is moved after both elements."
  18790. (interactive)
  18791. (org-skip-whitespace)
  18792. (let ((end (org-element-property :end (org-element-at-point))))
  18793. (org-drag-element-backward)
  18794. (goto-char end)))
  18795. (defun org-unindent-buffer ()
  18796. "Un-indent the visible part of the buffer.
  18797. Relative indentation (between items, inside blocks, etc.) isn't
  18798. modified."
  18799. (interactive)
  18800. (unless (eq major-mode 'org-mode)
  18801. (user-error "Cannot un-indent a buffer not in Org mode"))
  18802. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  18803. (unindent-tree
  18804. (lambda (contents)
  18805. (dolist (element (reverse contents))
  18806. (if (memq (org-element-type element) '(headline section))
  18807. (funcall unindent-tree (org-element-contents element))
  18808. (save-excursion
  18809. (save-restriction
  18810. (narrow-to-region
  18811. (org-element-property :begin element)
  18812. (org-element-property :end element))
  18813. (org-do-remove-indentation))))))))
  18814. (funcall unindent-tree (org-element-contents parse-tree))))
  18815. (defun org-make-options-regexp (kwds &optional extra)
  18816. "Make a regular expression for keyword lines.
  18817. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  18818. when non-nil, is a regexp matching keywords names."
  18819. (concat "^[ \t]*#\\+\\("
  18820. (regexp-opt kwds)
  18821. (and extra (concat (and kwds "\\|") extra))
  18822. "\\):[ \t]*\\(.*\\)"))
  18823. ;;; Conveniently switch to Info nodes
  18824. (defun org-info-find-node (&optional nodename)
  18825. "Find Info documentation NODENAME or Org documentation according context.
  18826. Started from `gnus-info-find-node'."
  18827. (interactive)
  18828. (Info-goto-node
  18829. (or nodename
  18830. (let ((default-org-info-node "(org) Top"))
  18831. (cond
  18832. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  18833. ((eq 'org-mode major-mode)
  18834. (let* ((context (org-element-at-point))
  18835. (element-info-nodes ; compare to `org-element-all-elements'.
  18836. `((babel-call . "(org) Evaluating Code Blocks")
  18837. (center-block . "(org) Paragraphs")
  18838. (clock . ,default-org-info-node)
  18839. (comment . "(org) Comment Lines")
  18840. (comment-block . "(org) Comment Lines")
  18841. (diary-sexp . ,default-org-info-node)
  18842. (drawer . "(org) Drawers")
  18843. (dynamic-block . "(org) Dynamic Blocks")
  18844. (example-block . "(org) Literal Examples")
  18845. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  18846. (fixed-width . ,default-org-info-node)
  18847. (footnote-definition . "(org) Creating Footnotes")
  18848. (headline . "(org) Document Structure")
  18849. (horizontal-rule . "(org) Built-in Table Editor")
  18850. (inlinetask . ,default-org-info-node)
  18851. (item . "(org) Plain Lists")
  18852. (keyword . "(org) Per-file keywords")
  18853. (latex-environment . "(org) LaTeX Export")
  18854. (node-property . "(org) Properties and Columns")
  18855. (paragraph . "(org) Paragraphs")
  18856. (plain-list . "(org) Plain Lists")
  18857. (planning . "(org) Deadlines and Scheduling")
  18858. (property-drawer . "(org) Properties and Columns")
  18859. (quote-block . "(org) Paragraphs")
  18860. (section . ,default-org-info-node)
  18861. (special-block . ,default-org-info-node)
  18862. (src-block . "(org) Working with Source Code")
  18863. (table . "(org) Tables")
  18864. (table-row . "(org) Tables")
  18865. (verse-block . "(org) Paragraphs"))))
  18866. (or (cdr (assoc (car context) element-info-nodes))
  18867. default-org-info-node)))
  18868. (t default-org-info-node))))))
  18869. ;;; Finish up
  18870. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  18871. (lambda () (add-hook 'change-major-mode-hook
  18872. 'org-show-all 'append 'local)))
  18873. (provide 'org)
  18874. (run-hooks 'org-load-hook)
  18875. ;;; org.el ends here