org.el 783 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682
  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-startup-numeroted nil
  844. "Non-nil means turn on `org-num-mode' on startup.
  845. This can also be configured on a per-file basis by adding one of
  846. the following lines anywhere in the buffer:
  847. #+STARTUP: num
  848. #+STARTUP: nonum"
  849. :group 'org-structure
  850. :package-version '(Org . "9.4")
  851. :type '(choice
  852. (const :tag "Not" nil)
  853. (const :tag "Globally" t)))
  854. (defcustom org-use-sub-superscripts t
  855. "Non-nil means interpret \"_\" and \"^\" for display.
  856. If you want to control how Org exports those characters, see
  857. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  858. used to be an alias for `org-export-with-sub-superscripts' in
  859. Org <8.0, it is not anymore.
  860. When this option is turned on, you can use TeX-like syntax for
  861. sub- and superscripts within the buffer. Several characters after
  862. \"_\" or \"^\" will be considered as a single item - so grouping
  863. with {} is normally not needed. For example, the following things
  864. will be parsed as single sub- or superscripts:
  865. 10^24 or 10^tau several digits will be considered 1 item.
  866. 10^-12 or 10^-tau a leading sign with digits or a word
  867. x^2-y^3 will be read as x^2 - y^3, because items are
  868. terminated by almost any nonword/nondigit char.
  869. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  870. Still, ambiguity is possible. So when in doubt, use {} to enclose
  871. the sub/superscript. If you set this variable to the symbol `{}',
  872. the braces are *required* in order to trigger interpretations as
  873. sub/superscript. This can be helpful in documents that need \"_\"
  874. frequently in plain text."
  875. :group 'org-startup
  876. :version "24.4"
  877. :package-version '(Org . "8.0")
  878. :type '(choice
  879. (const :tag "Always interpret" t)
  880. (const :tag "Only with braces" {})
  881. (const :tag "Never interpret" nil)))
  882. (defcustom org-startup-with-beamer-mode nil
  883. "Non-nil means turn on `org-beamer-mode' on startup.
  884. This can also be configured on a per-file basis by adding one of
  885. the following lines anywhere in the buffer:
  886. #+STARTUP: beamer"
  887. :group 'org-startup
  888. :version "24.1"
  889. :type 'boolean)
  890. (defcustom org-startup-align-all-tables nil
  891. "Non-nil means align all tables when visiting a file.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: align
  895. #+STARTUP: noalign"
  896. :group 'org-startup
  897. :type 'boolean)
  898. (defcustom org-startup-shrink-all-tables nil
  899. "Non-nil means shrink all table columns with a width cookie.
  900. This can also be configured on a per-file basis by adding one of
  901. the following lines anywhere in the buffer:
  902. #+STARTUP: shrink"
  903. :group 'org-startup
  904. :type 'boolean
  905. :version "27.1"
  906. :package-version '(Org . "9.2")
  907. :safe #'booleanp)
  908. (defcustom org-startup-with-inline-images nil
  909. "Non-nil means show inline images when loading a new Org file.
  910. This can also be configured on a per-file basis by adding one of
  911. the following lines anywhere in the buffer:
  912. #+STARTUP: inlineimages
  913. #+STARTUP: noinlineimages"
  914. :group 'org-startup
  915. :version "24.1"
  916. :type 'boolean)
  917. (defcustom org-startup-with-latex-preview nil
  918. "Non-nil means preview LaTeX fragments when loading a new Org file.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: latexpreview
  922. #+STARTUP: nolatexpreview"
  923. :group 'org-startup
  924. :version "24.4"
  925. :package-version '(Org . "8.0")
  926. :type 'boolean)
  927. (defcustom org-insert-mode-line-in-empty-file nil
  928. "Non-nil means insert the first line setting Org mode in empty files.
  929. When the function `org-mode' is called interactively in an empty file, this
  930. normally means that the file name does not automatically trigger Org mode.
  931. To ensure that the file will always be in Org mode in the future, a
  932. line enforcing Org mode will be inserted into the buffer, if this option
  933. has been set."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defcustom org-ellipsis nil
  937. "The ellipsis to use in the Org mode outline.
  938. When nil, just use the standard three dots. When a non-empty string,
  939. use that string instead.
  940. The change affects only Org mode (which will then use its own display table).
  941. Changing this requires executing `\\[org-mode]' in a buffer to become
  942. effective."
  943. :group 'org-startup
  944. :type '(choice (const :tag "Default" nil)
  945. (string :tag "String" :value "...#"))
  946. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  947. (defvar org-display-table nil
  948. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  949. (defgroup org-keywords nil
  950. "Keywords in Org mode."
  951. :tag "Org Keywords"
  952. :group 'org)
  953. (defcustom org-closed-keep-when-no-todo nil
  954. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  955. :group 'org-todo
  956. :group 'org-keywords
  957. :version "24.4"
  958. :package-version '(Org . "8.0")
  959. :type 'boolean)
  960. (defgroup org-structure nil
  961. "Options concerning the general structure of Org files."
  962. :tag "Org Structure"
  963. :group 'org)
  964. (defgroup org-reveal-location nil
  965. "Options about how to make context of a location visible."
  966. :tag "Org Reveal Location"
  967. :group 'org-structure)
  968. (defcustom org-show-context-detail '((agenda . local)
  969. (bookmark-jump . lineage)
  970. (isearch . lineage)
  971. (default . ancestors))
  972. "Alist between context and visibility span when revealing a location.
  973. \\<org-mode-map>Some actions may move point into invisible
  974. locations. As a consequence, Org always expose a neighborhood
  975. around point. How much is shown depends on the initial action,
  976. or context. Valid contexts are
  977. agenda when exposing an entry from the agenda
  978. org-goto when using the command `org-goto' (`\\[org-goto]')
  979. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  980. tags-tree when constructing a sparse tree based on tags matches
  981. link-search when exposing search matches associated with a link
  982. mark-goto when exposing the jump goal of a mark
  983. bookmark-jump when exposing a bookmark location
  984. isearch when exiting from an incremental search
  985. default default for all contexts not set explicitly
  986. Allowed visibility spans are
  987. minimal show current headline; if point is not on headline,
  988. also show entry
  989. local show current headline, entry and next headline
  990. ancestors show current headline and its direct ancestors; if
  991. point is not on headline, also show entry
  992. lineage show current headline, its direct ancestors and all
  993. their children; if point is not on headline, also show
  994. entry and first child
  995. tree show current headline, its direct ancestors and all
  996. their children; if point is not on headline, also show
  997. entry and all children
  998. canonical show current headline, its direct ancestors along with
  999. their entries and children; if point is not located on
  1000. the headline, also show current entry and all children
  1001. As special cases, a nil or t value means show all contexts in
  1002. `minimal' or `canonical' view, respectively.
  1003. Some views can make displayed information very compact, but also
  1004. make it harder to edit the location of the match. In such
  1005. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1006. more context."
  1007. :group 'org-reveal-location
  1008. :version "26.1"
  1009. :package-version '(Org . "9.0")
  1010. :type '(choice
  1011. (const :tag "Canonical" t)
  1012. (const :tag "Minimal" nil)
  1013. (repeat :greedy t :tag "Individual contexts"
  1014. (cons
  1015. (choice :tag "Context"
  1016. (const agenda)
  1017. (const org-goto)
  1018. (const occur-tree)
  1019. (const tags-tree)
  1020. (const link-search)
  1021. (const mark-goto)
  1022. (const bookmark-jump)
  1023. (const isearch)
  1024. (const default))
  1025. (choice :tag "Detail level"
  1026. (const minimal)
  1027. (const local)
  1028. (const ancestors)
  1029. (const lineage)
  1030. (const tree)
  1031. (const canonical))))))
  1032. (defcustom org-indirect-buffer-display 'other-window
  1033. "How should indirect tree buffers be displayed?
  1034. This applies to indirect buffers created with the commands
  1035. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1036. Valid values are:
  1037. current-window Display in the current window
  1038. other-window Just display in another window.
  1039. dedicated-frame Create one new frame, and re-use it each time.
  1040. new-frame Make a new frame each time. Note that in this case
  1041. previously-made indirect buffers are kept, and you need to
  1042. kill these buffers yourself."
  1043. :group 'org-structure
  1044. :group 'org-agenda-windows
  1045. :type '(choice
  1046. (const :tag "In current window" current-window)
  1047. (const :tag "In current frame, other window" other-window)
  1048. (const :tag "Each time a new frame" new-frame)
  1049. (const :tag "One dedicated frame" dedicated-frame)))
  1050. (defconst org-file-apps-gnu
  1051. '((remote . emacs)
  1052. (system . mailcap)
  1053. (t . mailcap))
  1054. "Default file applications on a UNIX or GNU/Linux system.
  1055. See `org-file-apps'.")
  1056. (defconst org-file-apps-macos
  1057. '((remote . emacs)
  1058. (system . "open %s")
  1059. ("ps.gz" . "gv %s")
  1060. ("eps.gz" . "gv %s")
  1061. ("dvi" . "xdvi %s")
  1062. ("fig" . "xfig %s")
  1063. (t . "open %s"))
  1064. "Default file applications on a macOS system.
  1065. The system \"open\" is known as a default, but we use X11 applications
  1066. for some files for which the OS does not have a good default.
  1067. See `org-file-apps'.")
  1068. (defconst org-file-apps-windowsnt
  1069. (list '(remote . emacs)
  1070. (cons 'system (lambda (file _path)
  1071. (with-no-warnings (w32-shell-execute "open" file))))
  1072. (cons t (lambda (file _path)
  1073. (with-no-warnings (w32-shell-execute "open" file)))))
  1074. "Default file applications on a Windows NT system.
  1075. The system \"open\" is used for most files.
  1076. See `org-file-apps'.")
  1077. (defcustom org-file-apps
  1078. '((auto-mode . emacs)
  1079. (directory . emacs)
  1080. ("\\.mm\\'" . default)
  1081. ("\\.x?html?\\'" . default)
  1082. ("\\.pdf\\'" . default))
  1083. "Applications for opening `file:path' items in a document.
  1084. \\<org-mode-map>
  1085. Org mode uses system defaults for different file types, but you
  1086. can use this variable to set the application for a given file
  1087. extension. The entries in this list are cons cells where the car
  1088. identifies files and the cdr the corresponding command.
  1089. Possible values for the file identifier are:
  1090. \"string\" A string as a file identifier can be interpreted in different
  1091. ways, depending on its contents:
  1092. - Alphanumeric characters only:
  1093. Match links with this file extension.
  1094. Example: (\"pdf\" . \"evince %s\")
  1095. to open PDFs with evince.
  1096. - Regular expression: Match links where the
  1097. filename matches the regexp. If you want to
  1098. use groups here, use shy groups.
  1099. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1100. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1101. to open *.html and *.xhtml with firefox.
  1102. - Regular expression which contains (non-shy) groups:
  1103. Match links where the whole link, including \"::\", and
  1104. anything after that, matches the regexp.
  1105. In a custom command string, %1, %2, etc. are replaced with
  1106. the parts of the link that were matched by the groups.
  1107. For backwards compatibility, if a command string is given
  1108. that does not use any of the group matches, this case is
  1109. handled identically to the second one (i.e. match against
  1110. file name only).
  1111. In a custom function, you can access the group matches with
  1112. (match-string n link).
  1113. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1114. \"evince -p %1 %s\")
  1115. to open [[file:document.pdf::5]] with evince at page 5.
  1116. `directory' Matches a directory
  1117. `remote' Matches a remote file, accessible through tramp or efs.
  1118. Remote files most likely should be visited through Emacs
  1119. because external applications cannot handle such paths.
  1120. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1121. so all files Emacs knows how to handle. Using this with
  1122. command `emacs' will open most files in Emacs. Beware that this
  1123. will also open html files inside Emacs, unless you add
  1124. (\"html\" . default) to the list as well.
  1125. `system' The system command to open files, like `open' on Windows
  1126. and macOS, and mailcap under GNU/Linux. This is the command
  1127. that will be selected if you call `org-open-at-point' with a
  1128. double prefix argument (`\\[universal-argument] \
  1129. \\[universal-argument] \\[org-open-at-point]').
  1130. t Default for files not matched by any of the other options.
  1131. Possible values for the command are:
  1132. `emacs' The file will be visited by the current Emacs process.
  1133. `default' Use the default application for this file type, which is the
  1134. association for t in the list, most likely in the system-specific
  1135. part. This can be used to overrule an unwanted setting in the
  1136. system-specific variable.
  1137. `system' Use the system command for opening files, like \"open\".
  1138. This command is specified by the entry whose car is `system'.
  1139. Most likely, the system-specific version of this variable
  1140. does define this command, but you can overrule/replace it
  1141. here.
  1142. `mailcap' Use command specified in the mailcaps.
  1143. string A command to be executed by a shell; %s will be replaced
  1144. by the path to the file.
  1145. function A Lisp function, which will be called with two arguments:
  1146. the file path and the original link string, without the
  1147. \"file:\" prefix.
  1148. For more examples, see the system specific constants
  1149. `org-file-apps-macos'
  1150. `org-file-apps-windowsnt'
  1151. `org-file-apps-gnu'."
  1152. :group 'org
  1153. :package-version '(Org . "9.4")
  1154. :type '(repeat
  1155. (cons (choice :value ""
  1156. (string :tag "Extension")
  1157. (const :tag "System command to open files" system)
  1158. (const :tag "Default for unrecognized files" t)
  1159. (const :tag "Remote file" remote)
  1160. (const :tag "Links to a directory" directory)
  1161. (const :tag "Any files that have Emacs modes"
  1162. auto-mode))
  1163. (choice :value ""
  1164. (const :tag "Visit with Emacs" emacs)
  1165. (const :tag "Use default" default)
  1166. (const :tag "Use the system command" system)
  1167. (string :tag "Command")
  1168. (function :tag "Function")))))
  1169. (defcustom org-open-non-existing-files nil
  1170. "Non-nil means `org-open-file' opens non-existing files.
  1171. When nil, an error is thrown.
  1172. This variable applies only to external applications because they
  1173. might choke on non-existing files. If the link is to a file that
  1174. will be opened in Emacs, the variable is ignored."
  1175. :group 'org
  1176. :type 'boolean
  1177. :safe #'booleanp)
  1178. (defcustom org-open-directory-means-index-dot-org nil
  1179. "When non-nil a link to a directory really means to \"index.org\".
  1180. When nil, following a directory link runs Dired or opens
  1181. a finder/explorer window on that directory."
  1182. :group 'org
  1183. :type 'boolean
  1184. :safe #'booleanp)
  1185. (defcustom org-bookmark-names-plist
  1186. '(:last-capture "org-capture-last-stored"
  1187. :last-refile "org-refile-last-stored"
  1188. :last-capture-marker "org-capture-last-stored-marker")
  1189. "Names for bookmarks automatically set by some Org commands.
  1190. This can provide strings as names for a number of bookmarks Org sets
  1191. automatically. The following keys are currently implemented:
  1192. :last-capture
  1193. :last-capture-marker
  1194. :last-refile
  1195. When a key does not show up in the property list, the corresponding bookmark
  1196. is not set."
  1197. :group 'org-structure
  1198. :type 'plist)
  1199. (defgroup org-cycle nil
  1200. "Options concerning visibility cycling in Org mode."
  1201. :tag "Org Cycle"
  1202. :group 'org-structure)
  1203. (defcustom org-cycle-skip-children-state-if-no-children t
  1204. "Non-nil means skip CHILDREN state in entries that don't have any."
  1205. :group 'org-cycle
  1206. :type 'boolean)
  1207. (defcustom org-cycle-max-level nil
  1208. "Maximum level which should still be subject to visibility cycling.
  1209. Levels higher than this will, for cycling, be treated as text, not a headline.
  1210. When `org-odd-levels-only' is set, a value of N in this variable actually
  1211. means 2N-1 stars as the limiting headline.
  1212. When nil, cycle all levels.
  1213. Note that the limiting level of cycling is also influenced by
  1214. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1215. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1216. than its value."
  1217. :group 'org-cycle
  1218. :type '(choice
  1219. (const :tag "No limit" nil)
  1220. (integer :tag "Maximum level")))
  1221. (defcustom org-hide-block-startup nil
  1222. "Non-nil means entering Org mode will fold all blocks.
  1223. This can also be set in on a per-file basis with
  1224. #+STARTUP: hideblocks
  1225. #+STARTUP: showblocks"
  1226. :group 'org-startup
  1227. :group 'org-cycle
  1228. :type 'boolean)
  1229. (defcustom org-cycle-global-at-bob nil
  1230. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1231. This makes it possible to do global cycling without having to use `S-TAB'
  1232. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1233. line of the buffer
  1234. must not be a headline -- it may be empty or some other text.
  1235. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1236. sure the cursor stays at the beginning of the buffer.
  1237. When this option is nil, don't do anything special at the beginning of
  1238. the buffer."
  1239. :group 'org-cycle
  1240. :type 'boolean)
  1241. (defcustom org-cycle-level-after-item/entry-creation t
  1242. "Non-nil means cycle entry level or item indentation in new empty entries.
  1243. When the cursor is at the end of an empty headline, i.e., with only stars
  1244. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1245. and then all possible ancestor states, before returning to the original state.
  1246. This makes data entry extremely fast: M-RET to create a new headline,
  1247. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1248. When the cursor is at the end of an empty plain list item, one TAB will
  1249. make it a subitem, two or more tabs will back up to make this an item
  1250. higher up in the item hierarchy."
  1251. :group 'org-cycle
  1252. :type 'boolean)
  1253. (defcustom org-cycle-emulate-tab t
  1254. "Where should `org-cycle' emulate TAB.
  1255. nil Never
  1256. white Only in completely white lines
  1257. whitestart Only at the beginning of lines, before the first non-white char
  1258. t Everywhere except in headlines
  1259. exc-hl-bol Everywhere except at the start of a headline
  1260. If TAB is used in a place where it does not emulate TAB, the current subtree
  1261. visibility is cycled."
  1262. :group 'org-cycle
  1263. :type '(choice (const :tag "Never" nil)
  1264. (const :tag "Only in completely white lines" white)
  1265. (const :tag "Before first char in a line" whitestart)
  1266. (const :tag "Everywhere except in headlines" t)
  1267. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1268. (defcustom org-cycle-separator-lines 2
  1269. "Number of empty lines needed to keep an empty line between collapsed trees.
  1270. If you leave an empty line between the end of a subtree and the following
  1271. headline, this empty line is hidden when the subtree is folded.
  1272. Org mode will leave (exactly) one empty line visible if the number of
  1273. empty lines is equal or larger to the number given in this variable.
  1274. So the default 2 means at least 2 empty lines after the end of a subtree
  1275. are needed to produce free space between a collapsed subtree and the
  1276. following headline.
  1277. If the number is negative, and the number of empty lines is at least -N,
  1278. all empty lines are shown.
  1279. Special case: when 0, never leave empty lines in collapsed view."
  1280. :group 'org-cycle
  1281. :type 'integer)
  1282. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1283. (defcustom org-pre-cycle-hook nil
  1284. "Hook that is run before visibility cycling is happening.
  1285. The function(s) in this hook must accept a single argument which indicates
  1286. the new state that will be set right after running this hook. The
  1287. argument is a symbol. Before a global state change, it can have the values
  1288. `overview', `content', or `all'. Before a local state change, it can have
  1289. the values `folded', `children', or `subtree'."
  1290. :group 'org-cycle
  1291. :type 'hook)
  1292. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1293. org-cycle-show-empty-lines
  1294. org-optimize-window-after-visibility-change)
  1295. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1296. The function(s) in this hook must accept a single argument which indicates
  1297. the new state that was set by the most recent `org-cycle' command. The
  1298. argument is a symbol. After a global state change, it can have the values
  1299. `overview', `contents', or `all'. After a local state change, it can have
  1300. the values `folded', `children', or `subtree'."
  1301. :group 'org-cycle
  1302. :type 'hook
  1303. :version "26.1"
  1304. :package-version '(Org . "8.3"))
  1305. (defgroup org-edit-structure nil
  1306. "Options concerning structure editing in Org mode."
  1307. :tag "Org Edit Structure"
  1308. :group 'org-structure)
  1309. (defcustom org-odd-levels-only nil
  1310. "Non-nil means skip even levels and only use odd levels for the outline.
  1311. This has the effect that two stars are being added/taken away in
  1312. promotion/demotion commands. It also influences how levels are
  1313. handled by the exporters.
  1314. Changing it requires restart of `font-lock-mode' to become effective
  1315. for fontification also in regions already fontified.
  1316. You may also set this on a per-file basis by adding one of the following
  1317. lines to the buffer:
  1318. #+STARTUP: odd
  1319. #+STARTUP: oddeven"
  1320. :group 'org-edit-structure
  1321. :group 'org-appearance
  1322. :type 'boolean)
  1323. (defcustom org-adapt-indentation t
  1324. "Non-nil means adapt indentation to outline node level.
  1325. When this variable is set to t, Org assumes that you write
  1326. outlines by indenting text in each node to align with the
  1327. headline (after the stars).
  1328. When this variable is set to 'headline-data, only adapt the
  1329. indentation of the data lines right below the headline, such as
  1330. planning/clock lines and property/logbook drawers.
  1331. The following issues are influenced by this variable:
  1332. - The indentation is increased by one space in a demotion
  1333. command, and decreased by one in a promotion command. However,
  1334. in the latter case, if shifting some line in the entry body
  1335. would alter document structure (e.g., insert a new headline),
  1336. indentation is not changed at all.
  1337. - Property drawers and planning information is inserted indented
  1338. when this variable is set. When nil, they will not be indented.
  1339. - TAB indents a line relative to current level. The lines below
  1340. a headline will be indented when this variable is set to t.
  1341. Note that this is all about true indentation, by adding and
  1342. removing space characters. See also \"org-indent.el\" which does
  1343. level-dependent indentation in a virtual way, i.e. at display
  1344. time in Emacs."
  1345. :group 'org-edit-structure
  1346. :type '(choice
  1347. (const :tag "Adapt indentation for all lines" t)
  1348. (const :tag "Adapt indentation for headline data lines"
  1349. 'headline-data)
  1350. (const :tag "Do not adapt indentation at all" nil))
  1351. :safe #'booleanp)
  1352. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1353. (defcustom org-special-ctrl-a/e nil
  1354. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1355. When t, `C-a' will bring back the cursor to the beginning of the
  1356. headline text, i.e. after the stars and after a possible TODO
  1357. keyword. In an item, this will be the position after bullet and
  1358. check-box, if any. When the cursor is already at that position,
  1359. another `C-a' will bring it to the beginning of the line.
  1360. `C-e' will jump to the end of the headline, ignoring the presence
  1361. of tags in the headline. A second `C-e' will then jump to the
  1362. true end of the line, after any tags. This also means that, when
  1363. this variable is non-nil, `C-e' also will never jump beyond the
  1364. end of the heading of a folded section, i.e. not after the
  1365. ellipses.
  1366. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1367. normally, going to the true line boundary first. Only a directly
  1368. following, identical keypress will bring the cursor to the
  1369. special positions.
  1370. This may also be a cons cell where the behavior for `C-a' and
  1371. `C-e' is set separately."
  1372. :group 'org-edit-structure
  1373. :type '(choice
  1374. (const :tag "off" nil)
  1375. (const :tag "on: after stars/bullet and before tags first" t)
  1376. (const :tag "reversed: true line boundary first" reversed)
  1377. (cons :tag "Set C-a and C-e separately"
  1378. (choice :tag "Special C-a"
  1379. (const :tag "off" nil)
  1380. (const :tag "on: after stars/bullet first" t)
  1381. (const :tag "reversed: before stars/bullet first" reversed))
  1382. (choice :tag "Special C-e"
  1383. (const :tag "off" nil)
  1384. (const :tag "on: before tags first" t)
  1385. (const :tag "reversed: after tags first" reversed)))))
  1386. (defcustom org-special-ctrl-k nil
  1387. "Non-nil means `C-k' will behave specially in headlines.
  1388. When nil, `C-k' will call the default `kill-line' command.
  1389. When t, the following will happen while the cursor is in the headline:
  1390. - When the cursor is at the beginning of a headline, kill the entire
  1391. line and possible the folded subtree below the line.
  1392. - When in the middle of the headline text, kill the headline up to the tags.
  1393. - When after the headline text, kill the tags."
  1394. :group 'org-edit-structure
  1395. :type 'boolean)
  1396. (defcustom org-ctrl-k-protect-subtree nil
  1397. "Non-nil means, do not delete a hidden subtree with C-k.
  1398. When set to the symbol `error', simply throw an error when C-k is
  1399. used to kill (part-of) a headline that has hidden text behind it.
  1400. Any other non-nil value will result in a query to the user, if it is
  1401. OK to kill that hidden subtree. When nil, kill without remorse."
  1402. :group 'org-edit-structure
  1403. :version "24.1"
  1404. :type '(choice
  1405. (const :tag "Do not protect hidden subtrees" nil)
  1406. (const :tag "Protect hidden subtrees with a security query" t)
  1407. (const :tag "Never kill a hidden subtree with C-k" error)))
  1408. (defcustom org-special-ctrl-o t
  1409. "Non-nil means, make `C-o' insert a row in tables."
  1410. :group 'org-edit-structure
  1411. :type 'boolean)
  1412. (defcustom org-catch-invisible-edits nil
  1413. "Check if in invisible region before inserting or deleting a character.
  1414. Valid values are:
  1415. nil Do not check, so just do invisible edits.
  1416. error Throw an error and do nothing.
  1417. show Make point visible, and do the requested edit.
  1418. show-and-error Make point visible, then throw an error and abort the edit.
  1419. smart Make point visible, and do insertion/deletion if it is
  1420. adjacent to visible text and the change feels predictable.
  1421. Never delete a previously invisible character or add in the
  1422. middle or right after an invisible region. Basically, this
  1423. allows insertion and backward-delete right before ellipses.
  1424. FIXME: maybe in this case we should not even show?"
  1425. :group 'org-edit-structure
  1426. :version "24.1"
  1427. :type '(choice
  1428. (const :tag "Do not check" nil)
  1429. (const :tag "Throw error when trying to edit" error)
  1430. (const :tag "Unhide, but do not do the edit" show-and-error)
  1431. (const :tag "Show invisible part and do the edit" show)
  1432. (const :tag "Be smart and do the right thing" smart)))
  1433. (defcustom org-yank-folded-subtrees t
  1434. "Non-nil means when yanking subtrees, fold them.
  1435. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1436. it starts with a heading and all other headings in it are either children
  1437. or siblings, then fold all the subtrees. However, do this only if no
  1438. text after the yank would be swallowed into a folded tree by this action."
  1439. :group 'org-edit-structure
  1440. :type 'boolean)
  1441. (defcustom org-yank-adjusted-subtrees nil
  1442. "Non-nil means when yanking subtrees, adjust the level.
  1443. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1444. this function for details."
  1445. :group 'org-edit-structure
  1446. :type 'boolean)
  1447. (defcustom org-M-RET-may-split-line '((default . t))
  1448. "Non-nil means M-RET will split the line at the cursor position.
  1449. When nil, it will go to the end of the line before making a
  1450. new line.
  1451. You may also set this option in a different way for different
  1452. contexts. Valid contexts are:
  1453. headline when creating a new headline
  1454. item when creating a new item
  1455. table in a table field
  1456. default the value to be used for all contexts not explicitly
  1457. customized"
  1458. :group 'org-structure
  1459. :group 'org-table
  1460. :type '(choice
  1461. (const :tag "Always" t)
  1462. (const :tag "Never" nil)
  1463. (repeat :greedy t :tag "Individual contexts"
  1464. (cons
  1465. (choice :tag "Context"
  1466. (const headline)
  1467. (const item)
  1468. (const table)
  1469. (const default))
  1470. (boolean)))))
  1471. (defcustom org-insert-heading-respect-content nil
  1472. "Non-nil means insert new headings after the current subtree.
  1473. \\<org-mode-map>
  1474. When nil, the new heading is created directly after the current line.
  1475. The commands `\\[org-insert-heading-respect-content]' and \
  1476. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1477. for the duration of the command."
  1478. :group 'org-structure
  1479. :type 'boolean)
  1480. (defcustom org-blank-before-new-entry '((heading . auto)
  1481. (plain-list-item . auto))
  1482. "Should `org-insert-heading' leave a blank line before new heading/item?
  1483. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1484. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1485. which case Org will look at the surrounding headings/items and try to
  1486. make an intelligent decision whether to insert a blank line or not."
  1487. :group 'org-edit-structure
  1488. :type '(list
  1489. (cons (const heading)
  1490. (choice (const :tag "Never" nil)
  1491. (const :tag "Always" t)
  1492. (const :tag "Auto" auto)))
  1493. (cons (const plain-list-item)
  1494. (choice (const :tag "Never" nil)
  1495. (const :tag "Always" t)
  1496. (const :tag "Auto" auto)))))
  1497. (defcustom org-insert-heading-hook nil
  1498. "Hook being run after inserting a new heading."
  1499. :group 'org-edit-structure
  1500. :type 'hook)
  1501. (defgroup org-sparse-trees nil
  1502. "Options concerning sparse trees in Org mode."
  1503. :tag "Org Sparse Trees"
  1504. :group 'org-structure)
  1505. (defcustom org-highlight-sparse-tree-matches t
  1506. "Non-nil means highlight all matches that define a sparse tree.
  1507. The highlights will automatically disappear the next time the buffer is
  1508. changed by an edit command."
  1509. :group 'org-sparse-trees
  1510. :type 'boolean)
  1511. (defcustom org-remove-highlights-with-change t
  1512. "Non-nil means any change to the buffer will remove temporary highlights.
  1513. \\<org-mode-map>\
  1514. Such highlights are created by `org-occur' and `org-clock-display'.
  1515. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1516. to get rid of the highlights.
  1517. The highlights created by `org-latex-preview' always need
  1518. `\\[org-latex-preview]' to be removed."
  1519. :group 'org-sparse-trees
  1520. :group 'org-time
  1521. :type 'boolean)
  1522. (defcustom org-occur-case-fold-search t
  1523. "Non-nil means `org-occur' should be case-insensitive.
  1524. If set to `smart' the search will be case-insensitive only if it
  1525. doesn't specify any upper case character."
  1526. :group 'org-sparse-trees
  1527. :version "26.1"
  1528. :type '(choice
  1529. (const :tag "Case-sensitive" nil)
  1530. (const :tag "Case-insensitive" t)
  1531. (const :tag "Case-insensitive for lower case searches only" smart)))
  1532. (defcustom org-occur-hook '(org-first-headline-recenter)
  1533. "Hook that is run after `org-occur' has constructed a sparse tree.
  1534. This can be used to recenter the window to show as much of the structure
  1535. as possible."
  1536. :group 'org-sparse-trees
  1537. :type 'hook)
  1538. (defcustom org-self-insert-cluster-for-undo nil
  1539. "Non-nil means cluster self-insert commands for undo when possible.
  1540. If this is set, then, like in the Emacs command loop, 20 consecutive
  1541. characters will be undone together.
  1542. This is configurable, because there is some impact on typing performance."
  1543. :group 'org-table
  1544. :type 'boolean)
  1545. (defvaralias 'org-activate-links 'org-highlight-links)
  1546. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1547. "Types of links that should be highlighted in Org files.
  1548. This is a list of symbols, each one of them leading to the
  1549. highlighting of a certain link type.
  1550. You can still open links that are not highlighted.
  1551. In principle, it does not hurt to turn on highlighting for all
  1552. link types. There may be a small gain when turning off unused
  1553. link types. The types are:
  1554. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1555. angle Links in angular brackets that may contain whitespace like
  1556. <bbdb:Carsten Dominik>.
  1557. plain Plain links in normal text, no whitespace, like http://google.com.
  1558. radio Text that is matched by a radio target, see manual for details.
  1559. tag Tag settings in a headline (link to tag search).
  1560. date Time stamps (link to calendar).
  1561. footnote Footnote labels.
  1562. If you set this variable during an Emacs session, use `org-mode-restart'
  1563. in the Org buffer so that the change takes effect."
  1564. :group 'org-appearance
  1565. :type '(set :greedy t
  1566. (const :tag "Double bracket links" bracket)
  1567. (const :tag "Angular bracket links" angle)
  1568. (const :tag "Plain text links" plain)
  1569. (const :tag "Radio target matches" radio)
  1570. (const :tag "Tags" tag)
  1571. (const :tag "Timestamps" date)
  1572. (const :tag "Footnotes" footnote)))
  1573. (defcustom org-mark-ring-length 4
  1574. "Number of different positions to be recorded in the ring.
  1575. Changing this requires a restart of Emacs to work correctly."
  1576. :group 'org-link-follow
  1577. :type 'integer)
  1578. (defgroup org-todo nil
  1579. "Options concerning TODO items in Org mode."
  1580. :tag "Org TODO"
  1581. :group 'org)
  1582. (defgroup org-progress nil
  1583. "Options concerning Progress logging in Org mode."
  1584. :tag "Org Progress"
  1585. :group 'org-time)
  1586. (defvar org-todo-interpretation-widgets
  1587. '((:tag "Sequence (cycling hits every state)" sequence)
  1588. (:tag "Type (cycling directly to DONE)" type))
  1589. "The available interpretation symbols for customizing `org-todo-keywords'.
  1590. Interested libraries should add to this list.")
  1591. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1592. "List of TODO entry keyword sequences and their interpretation.
  1593. \\<org-mode-map>This is a list of sequences.
  1594. Each sequence starts with a symbol, either `sequence' or `type',
  1595. indicating if the keywords should be interpreted as a sequence of
  1596. action steps, or as different types of TODO items. The first
  1597. keywords are states requiring action - these states will select a headline
  1598. for inclusion into the global TODO list Org produces. If one of the
  1599. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1600. signify that no further action is necessary. If \"|\" is not found,
  1601. the last keyword is treated as the only DONE state of the sequence.
  1602. The command `\\[org-todo]' cycles an entry through these states, and one
  1603. additional state where no keyword is present. For details about this
  1604. cycling, see the manual.
  1605. TODO keywords and interpretation can also be set on a per-file basis with
  1606. the special #+SEQ_TODO and #+TYP_TODO lines.
  1607. Each keyword can optionally specify a character for fast state selection
  1608. \(in combination with the variable `org-use-fast-todo-selection')
  1609. and specifiers for state change logging, using the same syntax that
  1610. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1611. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1612. indicates to record a time stamp each time this state is selected.
  1613. Each keyword may also specify if a timestamp or a note should be
  1614. recorded when entering or leaving the state, by adding additional
  1615. characters in the parenthesis after the keyword. This looks like this:
  1616. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1617. record only the time of the state change. With X and Y being either
  1618. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1619. Y when leaving the state if and only if the *target* state does not
  1620. define X. You may omit any of the fast-selection key or X or /Y,
  1621. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1622. For backward compatibility, this variable may also be just a list
  1623. of keywords. In this case the interpretation (sequence or type) will be
  1624. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1625. :group 'org-todo
  1626. :group 'org-keywords
  1627. :type '(choice
  1628. (repeat :tag "Old syntax, just keywords"
  1629. (string :tag "Keyword"))
  1630. (repeat :tag "New syntax"
  1631. (cons
  1632. (choice
  1633. :tag "Interpretation"
  1634. ;;Quick and dirty way to see
  1635. ;;`org-todo-interpretations'. This takes the
  1636. ;;place of item arguments
  1637. :convert-widget
  1638. (lambda (widget)
  1639. (widget-put widget
  1640. :args (mapcar
  1641. (lambda (x)
  1642. (widget-convert
  1643. (cons 'const x)))
  1644. org-todo-interpretation-widgets))
  1645. widget))
  1646. (repeat
  1647. (string :tag "Keyword"))))))
  1648. (defvar-local org-todo-keywords-1 nil
  1649. "All TODO and DONE keywords active in a buffer.")
  1650. (defvar org-todo-keywords-for-agenda nil)
  1651. (defvar org-done-keywords-for-agenda nil)
  1652. (defvar org-todo-keyword-alist-for-agenda nil)
  1653. (defvar org-tag-alist-for-agenda nil
  1654. "Alist of all tags from all agenda files.")
  1655. (defvar org-tag-groups-alist-for-agenda nil
  1656. "Alist of all groups tags from all current agenda files.")
  1657. (defvar-local org-tag-groups-alist nil)
  1658. (defvar org-agenda-contributing-files nil)
  1659. (defvar-local org-current-tag-alist nil
  1660. "Alist of all tag groups in current buffer.
  1661. This variable takes into consideration `org-tag-alist',
  1662. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1663. (defvar-local org-not-done-keywords nil)
  1664. (defvar-local org-done-keywords nil)
  1665. (defvar-local org-todo-heads nil)
  1666. (defvar-local org-todo-sets nil)
  1667. (defvar-local org-todo-log-states nil)
  1668. (defvar-local org-todo-kwd-alist nil)
  1669. (defvar-local org-todo-key-alist nil)
  1670. (defvar-local org-todo-key-trigger nil)
  1671. (defcustom org-todo-interpretation 'sequence
  1672. "Controls how TODO keywords are interpreted.
  1673. This variable is in principle obsolete and is only used for
  1674. backward compatibility, if the interpretation of todo keywords is
  1675. not given already in `org-todo-keywords'. See that variable for
  1676. more information."
  1677. :group 'org-todo
  1678. :group 'org-keywords
  1679. :type '(choice (const sequence)
  1680. (const type)))
  1681. (defcustom org-use-fast-todo-selection 'auto
  1682. "\\<org-mode-map>\
  1683. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1684. This variable describes if and under what circumstances the cycling
  1685. mechanism for TODO keywords will be replaced by a single-key, direct
  1686. selection scheme, where the choices are displayed in a little window.
  1687. When nil, fast selection is never used. This means that the command
  1688. will always switch to the next state.
  1689. When it is the symbol `auto', fast selection is whenever selection
  1690. keys have been defined.
  1691. `expert' is like `auto', but no special window with the keyword
  1692. will be shown, choices will only be listed in the prompt.
  1693. In all cases, the special interface is only used if access keys have
  1694. actually been assigned by the user, i.e. if keywords in the configuration
  1695. are followed by a letter in parenthesis, like TODO(t)."
  1696. :group 'org-todo
  1697. :set (lambda (var val)
  1698. (cond
  1699. ((eq var t) (set var 'auto))
  1700. ((eq var 'prefix) (set var nil))
  1701. (t (set var val))))
  1702. :type '(choice
  1703. (const :tag "Never" nil)
  1704. (const :tag "Automatically, when key letter have been defined" auto)
  1705. (const :tag "Automatically, but don't show the selection window" expert)))
  1706. (defcustom org-provide-todo-statistics t
  1707. "Non-nil means update todo statistics after insert and toggle.
  1708. ALL-HEADLINES means update todo statistics by including headlines
  1709. with no TODO keyword as well, counting them as not done.
  1710. A list of TODO keywords means the same, but skip keywords that are
  1711. not in this list.
  1712. When set to a list of two lists, the first list contains keywords
  1713. to consider as TODO keywords, the second list contains keywords
  1714. to consider as DONE keywords.
  1715. When this is set, todo statistics is updated in the parent of the
  1716. current entry each time a todo state is changed."
  1717. :group 'org-todo
  1718. :type '(choice
  1719. (const :tag "Yes, only for TODO entries" t)
  1720. (const :tag "Yes, including all entries" all-headlines)
  1721. (repeat :tag "Yes, for TODOs in this list"
  1722. (string :tag "TODO keyword"))
  1723. (list :tag "Yes, for TODOs and DONEs in these lists"
  1724. (repeat (string :tag "TODO keyword"))
  1725. (repeat (string :tag "DONE keyword")))
  1726. (other :tag "No TODO statistics" nil)))
  1727. (defcustom org-hierarchical-todo-statistics t
  1728. "Non-nil means TODO statistics covers just direct children.
  1729. When nil, all entries in the subtree are considered.
  1730. This has only an effect if `org-provide-todo-statistics' is set.
  1731. To set this to nil for only a single subtree, use a COOKIE_DATA
  1732. property and include the word \"recursive\" into the value."
  1733. :group 'org-todo
  1734. :type 'boolean)
  1735. (defcustom org-after-todo-state-change-hook nil
  1736. "Hook which is run after the state of a TODO item was changed.
  1737. The new state (a string with a TODO keyword, or nil) is available in the
  1738. Lisp variable `org-state'."
  1739. :group 'org-todo
  1740. :type 'hook)
  1741. (defvar org-blocker-hook nil
  1742. "Hook for functions that are allowed to block a state change.
  1743. Functions in this hook should not modify the buffer.
  1744. Each function gets as its single argument a property list,
  1745. see `org-trigger-hook' for more information about this list.
  1746. If any of the functions in this hook returns nil, the state change
  1747. is blocked.")
  1748. (defvar org-trigger-hook nil
  1749. "Hook for functions that are triggered by a state change.
  1750. Each function gets as its single argument a property list with at
  1751. least the following elements:
  1752. (:type type-of-change :position pos-at-entry-start
  1753. :from old-state :to new-state)
  1754. Depending on the type, more properties may be present.
  1755. This mechanism is currently implemented for:
  1756. TODO state changes
  1757. ------------------
  1758. :type todo-state-change
  1759. :from previous state (keyword as a string), or nil, or a symbol
  1760. `todo' or `done', to indicate the general type of state.
  1761. :to new state, like in :from")
  1762. (defcustom org-enforce-todo-dependencies nil
  1763. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1764. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1765. be blocked if any prior sibling is not yet done.
  1766. Finally, if the parent is blocked because of ordered siblings of its own,
  1767. the child will also be blocked."
  1768. :set (lambda (var val)
  1769. (set var val)
  1770. (if val
  1771. (add-hook 'org-blocker-hook
  1772. 'org-block-todo-from-children-or-siblings-or-parent)
  1773. (remove-hook 'org-blocker-hook
  1774. 'org-block-todo-from-children-or-siblings-or-parent)))
  1775. :group 'org-todo
  1776. :type 'boolean)
  1777. (defcustom org-enforce-todo-checkbox-dependencies nil
  1778. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1779. When this is nil, checkboxes have no influence on switching TODO states.
  1780. When non-nil, you first need to check off all check boxes before the TODO
  1781. entry can be switched to DONE.
  1782. This variable needs to be set before org.el is loaded, and you need to
  1783. restart Emacs after a change to make the change effective. The only way
  1784. to change it while Emacs is running is through the customize interface."
  1785. :set (lambda (var val)
  1786. (set var val)
  1787. (if val
  1788. (add-hook 'org-blocker-hook
  1789. 'org-block-todo-from-checkboxes)
  1790. (remove-hook 'org-blocker-hook
  1791. 'org-block-todo-from-checkboxes)))
  1792. :group 'org-todo
  1793. :type 'boolean)
  1794. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1795. "Non-nil means inserting a TODO heading is treated as state change.
  1796. So when the command `\\[org-insert-todo-heading]' is used, state change
  1797. logging will apply if appropriate. When nil, the new TODO item will
  1798. be inserted directly, and no logging will take place."
  1799. :group 'org-todo
  1800. :type 'boolean)
  1801. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1802. "Non-nil means switching TODO states with S-cursor counts as state change.
  1803. This is the default behavior. However, setting this to nil allows a
  1804. convenient way to select a TODO state and bypass any logging associated
  1805. with that."
  1806. :group 'org-todo
  1807. :type 'boolean)
  1808. (defcustom org-todo-state-tags-triggers nil
  1809. "Tag changes that should be triggered by TODO state changes.
  1810. This is a list. Each entry is
  1811. (state-change (tag . flag) .......)
  1812. State-change can be a string with a state, and empty string to indicate the
  1813. state that has no TODO keyword, or it can be one of the symbols `todo'
  1814. or `done', meaning any not-done or done state, respectively."
  1815. :group 'org-todo
  1816. :group 'org-tags
  1817. :type '(repeat
  1818. (cons (choice :tag "When changing to"
  1819. (const :tag "Not-done state" todo)
  1820. (const :tag "Done state" done)
  1821. (string :tag "State"))
  1822. (repeat
  1823. (cons :tag "Tag action"
  1824. (string :tag "Tag")
  1825. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1826. (defcustom org-log-done nil
  1827. "Information to record when a task moves to the DONE state.
  1828. Possible values are:
  1829. nil Don't add anything, just change the keyword
  1830. time Add a time stamp to the task
  1831. note Prompt for a note and add it with template `org-log-note-headings'
  1832. This option can also be set with on a per-file-basis with
  1833. #+STARTUP: nologdone
  1834. #+STARTUP: logdone
  1835. #+STARTUP: lognotedone
  1836. You can have local logging settings for a subtree by setting the LOGGING
  1837. property to one or more of these keywords."
  1838. :group 'org-todo
  1839. :group 'org-progress
  1840. :type '(choice
  1841. (const :tag "No logging" nil)
  1842. (const :tag "Record CLOSED timestamp" time)
  1843. (const :tag "Record CLOSED timestamp with note." note)))
  1844. ;; Normalize old uses of org-log-done.
  1845. (cond
  1846. ((eq org-log-done t) (setq org-log-done 'time))
  1847. ((and (listp org-log-done) (memq 'done org-log-done))
  1848. (setq org-log-done 'note)))
  1849. (defcustom org-log-reschedule nil
  1850. "Information to record when the scheduling date of a task is modified.
  1851. Possible values are:
  1852. nil Don't add anything, just change the date
  1853. time Add a time stamp to the task
  1854. note Prompt for a note and add it with template `org-log-note-headings'
  1855. This option can also be set with on a per-file-basis with
  1856. #+STARTUP: nologreschedule
  1857. #+STARTUP: logreschedule
  1858. #+STARTUP: lognotereschedule
  1859. You can have local logging settings for a subtree by setting the LOGGING
  1860. property to one or more of these keywords.
  1861. This variable has an effect when calling `org-schedule' or
  1862. `org-agenda-schedule' only."
  1863. :group 'org-todo
  1864. :group 'org-progress
  1865. :type '(choice
  1866. (const :tag "No logging" nil)
  1867. (const :tag "Record timestamp" time)
  1868. (const :tag "Record timestamp with note" note)))
  1869. (defcustom org-log-redeadline nil
  1870. "Information to record when the deadline date of a task is modified.
  1871. Possible values are:
  1872. nil Don't add anything, just change the date
  1873. time Add a time stamp to the task
  1874. note Prompt for a note and add it with template `org-log-note-headings'
  1875. This option can also be set with on a per-file-basis with
  1876. #+STARTUP: nologredeadline
  1877. #+STARTUP: logredeadline
  1878. #+STARTUP: lognoteredeadline
  1879. You can have local logging settings for a subtree by setting the LOGGING
  1880. property to one or more of these keywords.
  1881. This variable has an effect when calling `org-deadline' or
  1882. `org-agenda-deadline' only."
  1883. :group 'org-todo
  1884. :group 'org-progress
  1885. :type '(choice
  1886. (const :tag "No logging" nil)
  1887. (const :tag "Record timestamp" time)
  1888. (const :tag "Record timestamp with note." note)))
  1889. (defcustom org-log-note-clock-out nil
  1890. "Non-nil means record a note when clocking out of an item.
  1891. This can also be configured on a per-file basis by adding one of
  1892. the following lines anywhere in the buffer:
  1893. #+STARTUP: lognoteclock-out
  1894. #+STARTUP: nolognoteclock-out"
  1895. :group 'org-todo
  1896. :group 'org-progress
  1897. :type 'boolean)
  1898. (defcustom org-log-done-with-time t
  1899. "Non-nil means the CLOSED time stamp will contain date and time.
  1900. When nil, only the date will be recorded."
  1901. :group 'org-progress
  1902. :type 'boolean)
  1903. (defcustom org-log-note-headings
  1904. '((done . "CLOSING NOTE %t")
  1905. (state . "State %-12s from %-12S %t")
  1906. (note . "Note taken on %t")
  1907. (reschedule . "Rescheduled from %S on %t")
  1908. (delschedule . "Not scheduled, was %S on %t")
  1909. (redeadline . "New deadline from %S on %t")
  1910. (deldeadline . "Removed deadline, was %S on %t")
  1911. (refile . "Refiled on %t")
  1912. (clock-out . ""))
  1913. "Headings for notes added to entries.
  1914. The value is an alist, with the car being a symbol indicating the
  1915. note context, and the cdr is the heading to be used. The heading
  1916. may also be the empty string. The following placeholders can be
  1917. used:
  1918. %t a time stamp.
  1919. %T an active time stamp instead the default inactive one
  1920. %d a short-format time stamp.
  1921. %D an active short-format time stamp.
  1922. %s the new TODO state or time stamp (inactive), in double quotes.
  1923. %S the old TODO state or time stamp (inactive), in double quotes.
  1924. %u the user name.
  1925. %U full user name.
  1926. In fact, it is not a good idea to change the `state' entry,
  1927. because Agenda Log mode depends on the format of these entries."
  1928. :group 'org-todo
  1929. :group 'org-progress
  1930. :type '(list :greedy t
  1931. (cons (const :tag "Heading when closing an item" done) string)
  1932. (cons (const :tag
  1933. "Heading when changing todo state (todo sequence only)"
  1934. state) string)
  1935. (cons (const :tag "Heading when just taking a note" note) string)
  1936. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1937. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1938. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1939. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1940. (cons (const :tag "Heading when refiling" refile) string)
  1941. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1942. (unless (assq 'note org-log-note-headings)
  1943. (push '(note . "%t") org-log-note-headings))
  1944. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1945. (defcustom org-log-into-drawer nil
  1946. "Non-nil means insert state change notes and time stamps into a drawer.
  1947. When nil, state changes notes will be inserted after the headline and
  1948. any scheduling and clock lines, but not inside a drawer.
  1949. The value of this variable should be the name of the drawer to use.
  1950. LOGBOOK is proposed as the default drawer for this purpose, you can
  1951. also set this to a string to define the drawer of your choice.
  1952. A value of t is also allowed, representing \"LOGBOOK\".
  1953. A value of t or nil can also be set with on a per-file-basis with
  1954. #+STARTUP: logdrawer
  1955. #+STARTUP: nologdrawer
  1956. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1957. will be ignored.
  1958. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1959. a subtree.
  1960. Do not check directly this variable in a Lisp program. Call
  1961. function `org-log-into-drawer' instead."
  1962. :group 'org-todo
  1963. :group 'org-progress
  1964. :type '(choice
  1965. (const :tag "Not into a drawer" nil)
  1966. (const :tag "LOGBOOK" t)
  1967. (string :tag "Other")))
  1968. (defun org-log-into-drawer ()
  1969. "Name of the log drawer, as a string, or nil.
  1970. This is the value of `org-log-into-drawer'. However, if the
  1971. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1972. be used instead of the default value."
  1973. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1974. (cond ((equal p "nil") nil)
  1975. ((equal p "t") "LOGBOOK")
  1976. ((stringp p) p)
  1977. (p "LOGBOOK")
  1978. ((stringp org-log-into-drawer) org-log-into-drawer)
  1979. (org-log-into-drawer "LOGBOOK"))))
  1980. (defcustom org-log-state-notes-insert-after-drawers nil
  1981. "Non-nil means insert state change notes after any drawers in entry.
  1982. Only the drawers that *immediately* follow the headline and the
  1983. deadline/scheduled line are skipped.
  1984. When nil, insert notes right after the heading and perhaps the line
  1985. with deadline/scheduling if present.
  1986. This variable will have no effect if `org-log-into-drawer' is
  1987. set."
  1988. :group 'org-todo
  1989. :group 'org-progress
  1990. :type 'boolean)
  1991. (defcustom org-log-states-order-reversed t
  1992. "Non-nil means the latest state note will be directly after heading.
  1993. When nil, the state change notes will be ordered according to time.
  1994. This option can also be set with on a per-file-basis with
  1995. #+STARTUP: logstatesreversed
  1996. #+STARTUP: nologstatesreversed"
  1997. :group 'org-todo
  1998. :group 'org-progress
  1999. :type 'boolean)
  2000. (defcustom org-todo-repeat-to-state nil
  2001. "The TODO state to which a repeater should return the repeating task.
  2002. By default this is the first task of a TODO sequence or the
  2003. previous state of a TYPE_TODO set. But you can specify to use
  2004. the previous state in a TODO sequence or a string.
  2005. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2006. entry, which has precedence over this option."
  2007. :group 'org-todo
  2008. :version "24.1"
  2009. :type '(choice (const :tag "Use the previous TODO state" t)
  2010. (const :tag "Use the head of the TODO sequence" nil)
  2011. (string :tag "Use a specific TODO state")))
  2012. (defcustom org-log-repeat 'time
  2013. "Non-nil means record moving through the DONE state when triggering repeat.
  2014. An auto-repeating task is immediately switched back to TODO when
  2015. marked DONE. If you are not logging state changes (by adding \"@\"
  2016. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2017. record a closing note, there will be no record of the task moving
  2018. through DONE. This variable forces taking a note anyway.
  2019. nil Don't force a record
  2020. time Record a time stamp
  2021. note Prompt for a note and add it with template `org-log-note-headings'
  2022. This option can also be set with on a per-file-basis with
  2023. #+STARTUP: nologrepeat
  2024. #+STARTUP: logrepeat
  2025. #+STARTUP: lognoterepeat
  2026. You can have local logging settings for a subtree by setting the LOGGING
  2027. property to one or more of these keywords."
  2028. :group 'org-todo
  2029. :group 'org-progress
  2030. :type '(choice
  2031. (const :tag "Don't force a record" nil)
  2032. (const :tag "Force recording the DONE state" time)
  2033. (const :tag "Force recording a note with the DONE state" note)))
  2034. (defcustom org-todo-repeat-hook nil
  2035. "Hook that is run after a task has been repeated."
  2036. :package-version '(Org . "9.2")
  2037. :group 'org-todo
  2038. :type 'hook)
  2039. (defgroup org-priorities nil
  2040. "Priorities in Org mode."
  2041. :tag "Org Priorities"
  2042. :group 'org-todo)
  2043. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2044. (defcustom org-priority-enable-commands t
  2045. "Non-nil means priority commands are active.
  2046. When nil, these commands will be disabled, so that you never accidentally
  2047. set a priority."
  2048. :group 'org-priorities
  2049. :type 'boolean)
  2050. (defvaralias 'org-highest-priority 'org-priority-highest)
  2051. (defcustom org-priority-highest ?A
  2052. "The highest priority of TODO items.
  2053. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2054. Must be smaller than `org-priority-lowest'."
  2055. :group 'org-priorities
  2056. :type '(choice
  2057. (character :tag "Character")
  2058. (integer :tag "Integer (< 65)")))
  2059. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2060. (defcustom org-priority-lowest ?C
  2061. "The lowest priority of TODO items.
  2062. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2063. Must be higher than `org-priority-highest'."
  2064. :group 'org-priorities
  2065. :type '(choice
  2066. (character :tag "Character")
  2067. (integer :tag "Integer (< 65)")))
  2068. (defvaralias 'org-default-priority 'org-priority-default)
  2069. (defcustom org-priority-default ?B
  2070. "The default priority of TODO items.
  2071. This is the priority an item gets if no explicit priority is given.
  2072. When starting to cycle on an empty priority the first step in the cycle
  2073. depends on `org-priority-start-cycle-with-default'. The resulting first
  2074. step priority must not exceed the range from `org-priority-highest' to
  2075. `org-priority-lowest' which means that `org-priority-default' has to be
  2076. in this range exclusive or inclusive to the range boundaries. Else the
  2077. first step refuses to set the default and the second will fall back on
  2078. (depending on the command used) the highest or lowest priority."
  2079. :group 'org-priorities
  2080. :type '(choice
  2081. (character :tag "Character")
  2082. (integer :tag "Integer (< 65)")))
  2083. (defcustom org-priority-start-cycle-with-default t
  2084. "Non-nil means start with default priority when starting to cycle.
  2085. When this is nil, the first step in the cycle will be (depending on the
  2086. command used) one higher or lower than the default priority.
  2087. See also `org-priority-default'."
  2088. :group 'org-priorities
  2089. :type 'boolean)
  2090. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2091. (defcustom org-priority-get-priority-function nil
  2092. "Function to extract the priority from a string.
  2093. The string is normally the headline. If this is nil, Org
  2094. computes the priority from the priority cookie like [#A] in the
  2095. headline. It returns an integer, increasing by 1000 for each
  2096. priority level.
  2097. The user can set a different function here, which should take a
  2098. string as an argument and return the numeric priority."
  2099. :group 'org-priorities
  2100. :version "24.1"
  2101. :type '(choice
  2102. (const nil)
  2103. (function)))
  2104. (defgroup org-time nil
  2105. "Options concerning time stamps and deadlines in Org mode."
  2106. :tag "Org Time"
  2107. :group 'org)
  2108. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2109. "Number of minutes to round time stamps to.
  2110. \\<org-mode-map>\
  2111. These are two values, the first applies when first creating a time stamp.
  2112. The second applies when changing it with the commands `S-up' and `S-down'.
  2113. When changing the time stamp, this means that it will change in steps
  2114. of N minutes, as given by the second value.
  2115. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2116. numbers should be factors of 60, so for example 5, 10, 15.
  2117. When this is larger than 1, you can still force an exact time stamp by using
  2118. a double prefix argument to a time stamp command like \
  2119. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2120. and by using a prefix arg to `S-up/down' to specify the exact number
  2121. of minutes to shift."
  2122. :group 'org-time
  2123. :get (lambda (var) ; Make sure both elements are there
  2124. (if (integerp (default-value var))
  2125. (list (default-value var) 5)
  2126. (default-value var)))
  2127. :type '(list
  2128. (integer :tag "when inserting times")
  2129. (integer :tag "when modifying times")))
  2130. ;; Normalize old customizations of this variable.
  2131. (when (integerp org-time-stamp-rounding-minutes)
  2132. (setq org-time-stamp-rounding-minutes
  2133. (list org-time-stamp-rounding-minutes
  2134. org-time-stamp-rounding-minutes)))
  2135. (defcustom org-display-custom-times nil
  2136. "Non-nil means overlay custom formats over all time stamps.
  2137. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2138. To turn this on on a per-file basis, insert anywhere in the file:
  2139. #+STARTUP: customtime"
  2140. :group 'org-time
  2141. :set 'set-default
  2142. :type 'sexp)
  2143. (make-variable-buffer-local 'org-display-custom-times)
  2144. (defcustom org-time-stamp-custom-formats
  2145. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2146. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2147. These are overlaid over the default ISO format if the variable
  2148. `org-display-custom-times' is set. Time like %H:%M should be at the
  2149. end of the second format. The custom formats are also honored by export
  2150. commands, if custom time display is turned on at the time of export."
  2151. :group 'org-time
  2152. :type 'sexp)
  2153. (defun org-time-stamp-format (&optional long inactive)
  2154. "Get the right format for a time string."
  2155. (let ((f (if long (cdr org-time-stamp-formats)
  2156. (car org-time-stamp-formats))))
  2157. (if inactive
  2158. (concat "[" (substring f 1 -1) "]")
  2159. f)))
  2160. (defcustom org-deadline-warning-days 14
  2161. "Number of days before expiration during which a deadline becomes active.
  2162. This variable governs the display in sparse trees and in the agenda.
  2163. When 0 or negative, it means use this number (the absolute value of it)
  2164. even if a deadline has a different individual lead time specified.
  2165. Custom commands can set this variable in the options section."
  2166. :group 'org-time
  2167. :group 'org-agenda-daily/weekly
  2168. :type 'integer)
  2169. (defcustom org-scheduled-delay-days 0
  2170. "Number of days before a scheduled item becomes active.
  2171. This variable governs the display in sparse trees and in the agenda.
  2172. The default value (i.e. 0) means: don't delay scheduled item.
  2173. When negative, it means use this number (the absolute value of it)
  2174. even if a scheduled item has a different individual delay time
  2175. specified.
  2176. Custom commands can set this variable in the options section."
  2177. :group 'org-time
  2178. :group 'org-agenda-daily/weekly
  2179. :version "24.4"
  2180. :package-version '(Org . "8.0")
  2181. :type 'integer)
  2182. (defcustom org-read-date-prefer-future t
  2183. "Non-nil means assume future for incomplete date input from user.
  2184. This affects the following situations:
  2185. 1. The user gives a month but not a year.
  2186. For example, if it is April and you enter \"feb 2\", this will be read
  2187. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2188. 2. The user gives a day, but no month.
  2189. For example, if today is the 15th, and you enter \"3\", Org will read
  2190. this as the third of *next* month. However, if you enter \"17\",
  2191. it will be considered as *this* month.
  2192. If you set this variable to the symbol `time', then also the following
  2193. will work:
  2194. 3. If the user gives a time.
  2195. If the time is before now, it will be interpreted as tomorrow.
  2196. Currently none of this works for ISO week specifications.
  2197. When this option is nil, the current day, month and year will always be
  2198. used as defaults.
  2199. See also `org-agenda-jump-prefer-future'."
  2200. :group 'org-time
  2201. :type '(choice
  2202. (const :tag "Never" nil)
  2203. (const :tag "Check month and day" t)
  2204. (const :tag "Check month, day, and time" time)))
  2205. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2206. "Should the agenda jump command prefer the future for incomplete dates?
  2207. The default is to do the same as configured in `org-read-date-prefer-future'.
  2208. But you can also set a deviating value here.
  2209. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2210. :group 'org-agenda
  2211. :group 'org-time
  2212. :version "24.1"
  2213. :type '(choice
  2214. (const :tag "Use org-read-date-prefer-future"
  2215. org-read-date-prefer-future)
  2216. (const :tag "Never" nil)
  2217. (const :tag "Always" t)))
  2218. (defcustom org-read-date-force-compatible-dates t
  2219. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2220. Depending on the system Emacs is running on, certain dates cannot
  2221. be represented with the type used internally to represent time.
  2222. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2223. correctly. Some systems allow for earlier dates, some for later,
  2224. some for both. One way to find out is to insert any date into an
  2225. Org buffer, putting the cursor on the year and hitting S-up and
  2226. S-down to test the range.
  2227. When this variable is set to t, the date/time prompt will not let
  2228. you specify dates outside the 1970-2037 range, so it is certain that
  2229. these dates will work in whatever version of Emacs you are
  2230. running, and also that you can move a file from one Emacs implementation
  2231. to another. Whenever Org is forcing the year for you, it will display
  2232. a message and beep.
  2233. When this variable is nil, Org will check if the date is
  2234. representable in the specific Emacs implementation you are using.
  2235. If not, it will force a year, usually the current year, and beep
  2236. to remind you. Currently this setting is not recommended because
  2237. the likelihood that you will open your Org files in an Emacs that
  2238. has limited date range is not negligible.
  2239. A workaround for this problem is to use diary sexp dates for time
  2240. stamps outside of this range."
  2241. :group 'org-time
  2242. :version "24.1"
  2243. :type 'boolean)
  2244. (defcustom org-read-date-display-live t
  2245. "Non-nil means display current interpretation of date prompt live.
  2246. This display will be in an overlay, in the minibuffer."
  2247. :group 'org-time
  2248. :type 'boolean)
  2249. (defvaralias 'org-popup-calendar-for-date-prompt
  2250. 'org-read-date-popup-calendar)
  2251. (defcustom org-read-date-popup-calendar t
  2252. "Non-nil means pop up a calendar when prompting for a date.
  2253. In the calendar, the date can be selected with mouse-1. However, the
  2254. minibuffer will also be active, and you can simply enter the date as well.
  2255. When nil, only the minibuffer will be available."
  2256. :group 'org-time
  2257. :type 'boolean)
  2258. (defcustom org-extend-today-until 0
  2259. "The hour when your day really ends. Must be an integer.
  2260. This has influence for the following applications:
  2261. - When switching the agenda to \"today\". If it is still earlier than
  2262. the time given here, the day recognized as TODAY is actually yesterday.
  2263. - When a date is read from the user and it is still before the time given
  2264. here, the current date and time will be assumed to be yesterday, 23:59.
  2265. Also, timestamps inserted in capture templates follow this rule.
  2266. IMPORTANT: This is a feature whose implementation is and likely will
  2267. remain incomplete. Really, it is only here because past midnight seems to
  2268. be the favorite working time of John Wiegley :-)"
  2269. :group 'org-time
  2270. :type 'integer)
  2271. (defcustom org-use-effective-time nil
  2272. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2273. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2274. \"effective time\" of any timestamps between midnight and 8am will be
  2275. 23:59 of the previous day."
  2276. :group 'org-time
  2277. :version "24.1"
  2278. :type 'boolean)
  2279. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2280. "When non-nil, use the last clock out time for `org-todo'.
  2281. Note that this option has precedence over the combined use of
  2282. `org-use-effective-time' and `org-extend-today-until'."
  2283. :group 'org-time
  2284. :version "24.4"
  2285. :package-version '(Org . "8.0")
  2286. :type 'boolean)
  2287. (defcustom org-edit-timestamp-down-means-later nil
  2288. "Non-nil means S-down will increase the time in a time stamp.
  2289. When nil, S-up will increase."
  2290. :group 'org-time
  2291. :type 'boolean)
  2292. (defcustom org-calendar-follow-timestamp-change t
  2293. "Non-nil means make the calendar window follow timestamp changes.
  2294. When a timestamp is modified and the calendar window is visible, it will be
  2295. moved to the new date."
  2296. :group 'org-time
  2297. :type 'boolean)
  2298. (defgroup org-tags nil
  2299. "Options concerning tags in Org mode."
  2300. :tag "Org Tags"
  2301. :group 'org)
  2302. (defcustom org-tag-alist nil
  2303. "Default tags available in Org files.
  2304. The value of this variable is an alist. Associations either:
  2305. (TAG)
  2306. (TAG . SELECT)
  2307. (SPECIAL)
  2308. where TAG is a tag as a string, SELECT is character, used to
  2309. select that tag through the fast tag selection interface, and
  2310. SPECIAL is one of the following keywords: `:startgroup',
  2311. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2312. `:newline'. These keywords are used to define a hierarchy of
  2313. tags. See manual for details.
  2314. When this variable is nil, Org mode bases tag input on what is
  2315. already in the buffer. The value can be overridden locally by
  2316. using a TAGS keyword, e.g.,
  2317. #+TAGS: tag1 tag2
  2318. See also `org-tag-persistent-alist' to sidestep this behavior."
  2319. :group 'org-tags
  2320. :type '(repeat
  2321. (choice
  2322. (cons :tag "Tag with key"
  2323. (string :tag "Tag name")
  2324. (character :tag "Access char"))
  2325. (list :tag "Tag" (string :tag "Tag name"))
  2326. (const :tag "Start radio group" (:startgroup))
  2327. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2328. (const :tag "Group tags delimiter" (:grouptags))
  2329. (const :tag "End radio group" (:endgroup))
  2330. (const :tag "End tag group, non distinct" (:endgrouptag))
  2331. (const :tag "New line" (:newline)))))
  2332. (defcustom org-tag-persistent-alist nil
  2333. "Tags always available in Org files.
  2334. The value of this variable is an alist. Associations either:
  2335. (TAG)
  2336. (TAG . SELECT)
  2337. (SPECIAL)
  2338. where TAG is a tag as a string, SELECT is a character, used to
  2339. select that tag through the fast tag selection interface, and
  2340. SPECIAL is one of the following keywords: `:startgroup',
  2341. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2342. `:newline'. These keywords are used to define a hierarchy of
  2343. tags. See manual for details.
  2344. Unlike to `org-tag-alist', tags defined in this variable do not
  2345. depend on a local TAGS keyword. Instead, to disable these tags
  2346. on a per-file basis, insert anywhere in the file:
  2347. #+STARTUP: noptag"
  2348. :group 'org-tags
  2349. :type '(repeat
  2350. (choice
  2351. (cons :tag "Tag with key"
  2352. (string :tag "Tag name")
  2353. (character :tag "Access char"))
  2354. (list :tag "Tag" (string :tag "Tag name"))
  2355. (const :tag "Start radio group" (:startgroup))
  2356. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2357. (const :tag "Group tags delimiter" (:grouptags))
  2358. (const :tag "End radio group" (:endgroup))
  2359. (const :tag "End tag group, non distinct" (:endgrouptag))
  2360. (const :tag "New line" (:newline)))))
  2361. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2362. "If non-nil, always offer completion for all tags of all agenda files.
  2363. Setting this variable locally allows for dynamic generation of tag
  2364. completions in capture buffers.
  2365. (add-hook \\='org-capture-mode-hook
  2366. (lambda ()
  2367. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2368. :group 'org-tags
  2369. :version "24.1"
  2370. :type 'boolean)
  2371. (defvar org-file-tags nil
  2372. "List of tags that can be inherited by all entries in the file.
  2373. The tags will be inherited if the variable `org-use-tag-inheritance'
  2374. says they should be.
  2375. This variable is populated from #+FILETAGS lines.")
  2376. (defcustom org-use-fast-tag-selection 'auto
  2377. "Non-nil means use fast tag selection scheme.
  2378. This is a special interface to select and deselect tags with single keys.
  2379. When nil, fast selection is never used.
  2380. When the symbol `auto', fast selection is used if and only if selection
  2381. characters for tags have been configured, either through the variable
  2382. `org-tag-alist' or through a #+TAGS line in the buffer.
  2383. When t, fast selection is always used and selection keys are assigned
  2384. automatically if necessary."
  2385. :group 'org-tags
  2386. :type '(choice
  2387. (const :tag "Always" t)
  2388. (const :tag "Never" nil)
  2389. (const :tag "When selection characters are configured" auto)))
  2390. (defcustom org-fast-tag-selection-single-key nil
  2391. "Non-nil means fast tag selection exits after first change.
  2392. When nil, you have to press RET to exit it.
  2393. During fast tag selection, you can toggle this flag with `C-c'.
  2394. This variable can also have the value `expert'. In this case, the window
  2395. displaying the tags menu is not even shown, until you press C-c again."
  2396. :group 'org-tags
  2397. :type '(choice
  2398. (const :tag "No" nil)
  2399. (const :tag "Yes" t)
  2400. (const :tag "Expert" expert)))
  2401. (defvar org-fast-tag-selection-include-todo nil
  2402. "Non-nil means fast tags selection interface will also offer TODO states.
  2403. This is an undocumented feature, you should not rely on it.")
  2404. (defcustom org-tags-column -77
  2405. "The column to which tags should be indented in a headline.
  2406. If this number is positive, it specifies the column. If it is negative,
  2407. it means that the tags should be flushright to that column. For example,
  2408. -80 works well for a normal 80 character screen.
  2409. When 0, place tags directly after headline text, with only one space in
  2410. between."
  2411. :group 'org-tags
  2412. :type 'integer)
  2413. (defcustom org-auto-align-tags t
  2414. "Non-nil keeps tags aligned when modifying headlines.
  2415. Some operations (i.e. demoting) change the length of a headline and
  2416. therefore shift the tags around. With this option turned on, after
  2417. each such operation the tags are again aligned to `org-tags-column'."
  2418. :group 'org-tags
  2419. :type 'boolean)
  2420. (defcustom org-use-tag-inheritance t
  2421. "Non-nil means tags in levels apply also for sublevels.
  2422. When nil, only the tags directly given in a specific line apply there.
  2423. This may also be a list of tags that should be inherited, or a regexp that
  2424. matches tags that should be inherited. Additional control is possible
  2425. with the variable `org-tags-exclude-from-inheritance' which gives an
  2426. explicit list of tags to be excluded from inheritance, even if the value of
  2427. `org-use-tag-inheritance' would select it for inheritance.
  2428. If this option is t, a match early-on in a tree can lead to a large
  2429. number of matches in the subtree when constructing the agenda or creating
  2430. a sparse tree. If you only want to see the first match in a tree during
  2431. a search, check out the variable `org-tags-match-list-sublevels'."
  2432. :group 'org-tags
  2433. :type '(choice
  2434. (const :tag "Not" nil)
  2435. (const :tag "Always" t)
  2436. (repeat :tag "Specific tags" (string :tag "Tag"))
  2437. (regexp :tag "Tags matched by regexp")))
  2438. (defcustom org-tags-exclude-from-inheritance nil
  2439. "List of tags that should never be inherited.
  2440. This is a way to exclude a few tags from inheritance. For way to do
  2441. the opposite, to actively allow inheritance for selected tags,
  2442. see the variable `org-use-tag-inheritance'."
  2443. :group 'org-tags
  2444. :type '(repeat (string :tag "Tag")))
  2445. (defun org-tag-inherit-p (tag)
  2446. "Check if TAG is one that should be inherited."
  2447. (cond
  2448. ((member tag org-tags-exclude-from-inheritance) nil)
  2449. ((eq org-use-tag-inheritance t) t)
  2450. ((not org-use-tag-inheritance) nil)
  2451. ((stringp org-use-tag-inheritance)
  2452. (string-match org-use-tag-inheritance tag))
  2453. ((listp org-use-tag-inheritance)
  2454. (member tag org-use-tag-inheritance))
  2455. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2456. (defcustom org-tags-match-list-sublevels t
  2457. "Non-nil means list also sublevels of headlines matching a search.
  2458. This variable applies to tags/property searches, and also to stuck
  2459. projects because this search is based on a tags match as well.
  2460. When set to the symbol `indented', sublevels are indented with
  2461. leading dots.
  2462. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2463. the sublevels of a headline matching a tag search often also match
  2464. the same search. Listing all of them can create very long lists.
  2465. Setting this variable to nil causes subtrees of a match to be skipped.
  2466. This variable is semi-obsolete and probably should always be true. It
  2467. is better to limit inheritance to certain tags using the variables
  2468. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2469. :group 'org-tags
  2470. :type '(choice
  2471. (const :tag "No, don't list them" nil)
  2472. (const :tag "Yes, do list them" t)
  2473. (const :tag "List them, indented with leading dots" indented)))
  2474. (defcustom org-tags-sort-function nil
  2475. "When set, tags are sorted using this function as a comparator."
  2476. :group 'org-tags
  2477. :type '(choice
  2478. (const :tag "No sorting" nil)
  2479. (const :tag "Alphabetical" org-string-collate-lessp)
  2480. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2481. (function :tag "Custom function" nil)))
  2482. (defvar org-tags-history nil
  2483. "History of minibuffer reads for tags.")
  2484. (defvar org-last-tags-completion-table nil
  2485. "The last used completion table for tags.")
  2486. (defvar org-after-tags-change-hook nil
  2487. "Hook that is run after the tags in a line have changed.")
  2488. (defgroup org-properties nil
  2489. "Options concerning properties in Org mode."
  2490. :tag "Org Properties"
  2491. :group 'org)
  2492. (defcustom org-property-format "%-10s %s"
  2493. "How property key/value pairs should be formatted by `indent-line'.
  2494. When `indent-line' hits a property definition, it will format the line
  2495. according to this format, mainly to make sure that the values are
  2496. lined-up with respect to each other."
  2497. :group 'org-properties
  2498. :type 'string)
  2499. (defcustom org-properties-postprocess-alist nil
  2500. "Alist of properties and functions to adjust inserted values.
  2501. Elements of this alist must be of the form
  2502. ([string] [function])
  2503. where [string] must be a property name and [function] must be a
  2504. lambda expression: this lambda expression must take one argument,
  2505. the value to adjust, and return the new value as a string.
  2506. For example, this element will allow the property \"Remaining\"
  2507. to be updated wrt the relation between the \"Effort\" property
  2508. and the clock summary:
  2509. ((\"Remaining\" (lambda(value)
  2510. (let ((clocksum (org-clock-sum-current-item))
  2511. (effort (org-duration-to-minutes
  2512. (org-entry-get (point) \"Effort\"))))
  2513. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2514. :group 'org-properties
  2515. :version "24.1"
  2516. :type '(alist :key-type (string :tag "Property")
  2517. :value-type (function :tag "Function")))
  2518. (defcustom org-use-property-inheritance nil
  2519. "Non-nil means properties apply also for sublevels.
  2520. This setting is chiefly used during property searches. Turning it on can
  2521. cause significant overhead when doing a search, which is why it is not
  2522. on by default.
  2523. When nil, only the properties directly given in the current entry count.
  2524. When t, every property is inherited. The value may also be a list of
  2525. properties that should have inheritance, or a regular expression matching
  2526. properties that should be inherited.
  2527. However, note that some special properties use inheritance under special
  2528. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2529. and the properties ending in \"_ALL\" when they are used as descriptor
  2530. for valid values of a property.
  2531. Note for programmers:
  2532. When querying an entry with `org-entry-get', you can control if inheritance
  2533. should be used. By default, `org-entry-get' looks only at the local
  2534. properties. You can request inheritance by setting the inherit argument
  2535. to t (to force inheritance) or to `selective' (to respect the setting
  2536. in this variable)."
  2537. :group 'org-properties
  2538. :type '(choice
  2539. (const :tag "Not" nil)
  2540. (const :tag "Always" t)
  2541. (repeat :tag "Specific properties" (string :tag "Property"))
  2542. (regexp :tag "Properties matched by regexp")))
  2543. (defun org-property-inherit-p (property)
  2544. "Return a non-nil value if PROPERTY should be inherited."
  2545. (cond
  2546. ((eq org-use-property-inheritance t) t)
  2547. ((not org-use-property-inheritance) nil)
  2548. ((stringp org-use-property-inheritance)
  2549. (string-match org-use-property-inheritance property))
  2550. ((listp org-use-property-inheritance)
  2551. (member-ignore-case property org-use-property-inheritance))
  2552. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2553. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2554. "The default column format, if no other format has been defined.
  2555. This variable can be set on the per-file basis by inserting a line
  2556. #+COLUMNS: %25ITEM ....."
  2557. :group 'org-properties
  2558. :type 'string)
  2559. (defcustom org-columns-default-format-for-agenda nil
  2560. "The default column format in an agenda buffer.
  2561. This will be used for column view in the agenda unless a format has
  2562. been set by adding `org-overriding-columns-format' to the local
  2563. settings list of a custom agenda view. When nil, the columns format
  2564. for the first item in the agenda list will be used, or as a fall-back,
  2565. `org-columns-default-format'."
  2566. :group 'org-properties
  2567. :type '(choice
  2568. (const :tag "No default" nil)
  2569. (string :tag "Format string")))
  2570. (defcustom org-columns-ellipses ".."
  2571. "The ellipses to be used when a field in column view is truncated.
  2572. When this is the empty string, as many characters as possible are shown,
  2573. but then there will be no visual indication that the field has been truncated.
  2574. When this is a string of length N, the last N characters of a truncated
  2575. field are replaced by this string. If the column is narrower than the
  2576. ellipses string, only part of the ellipses string will be shown."
  2577. :group 'org-properties
  2578. :type 'string)
  2579. (defconst org-global-properties-fixed
  2580. '(("VISIBILITY_ALL" . "folded children content all")
  2581. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2582. "List of property/value pairs that can be inherited by any entry.
  2583. These are fixed values, for the preset properties. The user variable
  2584. that can be used to add to this list is `org-global-properties'.
  2585. The entries in this list are cons cells where the car is a property
  2586. name and cdr is a string with the value. If the value represents
  2587. multiple items like an \"_ALL\" property, separate the items by
  2588. spaces.")
  2589. (defcustom org-global-properties nil
  2590. "List of property/value pairs that can be inherited by any entry.
  2591. This list will be combined with the constant `org-global-properties-fixed'.
  2592. The entries in this list are cons cells where the car is a property
  2593. name and cdr is a string with the value.
  2594. Buffer local properties are added either by a document property drawer
  2595. :PROPERTIES:
  2596. :NAME: VALUE
  2597. :END:
  2598. or by adding lines like
  2599. #+PROPERTY: NAME VALUE"
  2600. :group 'org-properties
  2601. :type '(repeat
  2602. (cons (string :tag "Property")
  2603. (string :tag "Value"))))
  2604. (defvar-local org-keyword-properties nil
  2605. "List of property/value pairs inherited by any entry.
  2606. Valid for the current buffer. This variable is populated from
  2607. PROPERTY keywords.
  2608. Note that properties are defined also in property drawers.
  2609. Properties defined there take precedence over properties defined
  2610. as keywords.")
  2611. (defgroup org-agenda nil
  2612. "Options concerning agenda views in Org mode."
  2613. :tag "Org Agenda"
  2614. :group 'org)
  2615. (defvar-local org-category nil
  2616. "Variable used by Org files to set a category for agenda display.
  2617. There are multiple ways to set the category. One way is to set
  2618. it in the document property drawer. For example:
  2619. :PROPERTIES:
  2620. :CATEGORY: ELisp
  2621. :END:
  2622. Other ways to define it is as an emacs file variable, for example
  2623. # -*- mode: org; org-category: \"ELisp\"
  2624. or for the file to contain a special line:
  2625. #+CATEGORY: ELisp
  2626. If the file does not specify a category, then file's base name
  2627. is used instead.")
  2628. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2629. (defcustom org-agenda-files nil
  2630. "The files to be used for agenda display.
  2631. If an entry is a directory, all files in that directory that are matched
  2632. by `org-agenda-file-regexp' will be part of the file list.
  2633. If the value of the variable is not a list but a single file name, then
  2634. the list of agenda files is actually stored and maintained in that file,
  2635. one agenda file per line. In this file paths can be given relative to
  2636. `org-directory'. Tilde expansion and environment variable substitution
  2637. are also made.
  2638. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2639. and removed with `\\[org-remove-file]'."
  2640. :group 'org-agenda
  2641. :type '(choice
  2642. (repeat :tag "List of files and directories" file)
  2643. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2644. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2645. "Regular expression to match files for `org-agenda-files'.
  2646. If any element in the list in that variable contains a directory instead
  2647. of a normal file, all files in that directory that are matched by this
  2648. regular expression will be included."
  2649. :group 'org-agenda
  2650. :type 'regexp)
  2651. (defvaralias 'org-agenda-multi-occur-extra-files
  2652. 'org-agenda-text-search-extra-files)
  2653. (defcustom org-agenda-text-search-extra-files nil
  2654. "List of extra files to be searched by text search commands.
  2655. These files will be searched in addition to the agenda files by the
  2656. commands `org-search-view' (`\\[org-agenda] s') \
  2657. and `org-occur-in-agenda-files'.
  2658. Note that these files will only be searched for text search commands,
  2659. not for the other agenda views like todo lists, tag searches or the weekly
  2660. agenda. This variable is intended to list notes and possibly archive files
  2661. that should also be searched by these two commands.
  2662. In fact, if the first element in the list is the symbol `agenda-archives',
  2663. then all archive files of all agenda files will be added to the search
  2664. scope."
  2665. :group 'org-agenda
  2666. :type '(set :greedy t
  2667. (const :tag "Agenda Archives" agenda-archives)
  2668. (repeat :inline t (file))))
  2669. (defcustom org-agenda-skip-unavailable-files nil
  2670. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2671. A nil value means to remove them, after a query, from the list."
  2672. :group 'org-agenda
  2673. :type 'boolean)
  2674. (defgroup org-latex nil
  2675. "Options for embedding LaTeX code into Org mode."
  2676. :tag "Org LaTeX"
  2677. :group 'org)
  2678. (defcustom org-format-latex-options
  2679. '(:foreground default :background default :scale 1.0
  2680. :html-foreground "Black" :html-background "Transparent"
  2681. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2682. "Options for creating images from LaTeX fragments.
  2683. This is a property list with the following properties:
  2684. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2685. `default' means use the foreground of the default face.
  2686. `auto' means use the foreground from the text face.
  2687. :background the background color, or \"Transparent\".
  2688. `default' means use the background of the default face.
  2689. `auto' means use the background from the text face.
  2690. :scale a scaling factor for the size of the images, to get more pixels
  2691. :html-foreground, :html-background, :html-scale
  2692. the same numbers for HTML export.
  2693. :matchers a list indicating which matchers should be used to
  2694. find LaTeX fragments. Valid members of this list are:
  2695. \"begin\" find environments
  2696. \"$1\" find single characters surrounded by $.$
  2697. \"$\" find math expressions surrounded by $...$
  2698. \"$$\" find math expressions surrounded by $$....$$
  2699. \"\\(\" find math expressions surrounded by \\(...\\)
  2700. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2701. :group 'org-latex
  2702. :type 'plist)
  2703. (defcustom org-format-latex-signal-error t
  2704. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2705. When nil, just push out a message."
  2706. :group 'org-latex
  2707. :version "24.1"
  2708. :type 'boolean)
  2709. (defcustom org-latex-to-mathml-jar-file nil
  2710. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2711. Use this to specify additional executable file say a jar file.
  2712. When using MathToWeb as the converter, specify the full-path to
  2713. your mathtoweb.jar file."
  2714. :group 'org-latex
  2715. :version "24.1"
  2716. :type '(choice
  2717. (const :tag "None" nil)
  2718. (file :tag "JAR file" :must-match t)))
  2719. (defcustom org-latex-to-mathml-convert-command nil
  2720. "Command to convert LaTeX fragments to MathML.
  2721. Replace format-specifiers in the command as noted below and use
  2722. `shell-command' to convert LaTeX to MathML.
  2723. %j: Executable file in fully expanded form as specified by
  2724. `org-latex-to-mathml-jar-file'.
  2725. %I: Input LaTeX file in fully expanded form.
  2726. %i: The latex fragment to be converted.
  2727. %o: Output MathML file.
  2728. This command is used by `org-create-math-formula'.
  2729. When using MathToWeb as the converter, set this option to
  2730. \"java -jar %j -unicode -force -df %o %I\".
  2731. When using LaTeXML set this option to
  2732. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2733. :group 'org-latex
  2734. :version "24.1"
  2735. :type '(choice
  2736. (const :tag "None" nil)
  2737. (string :tag "\nShell command")))
  2738. (defcustom org-preview-latex-default-process 'dvipng
  2739. "The default process to convert LaTeX fragments to image files.
  2740. All available processes and theirs documents can be found in
  2741. `org-preview-latex-process-alist', which see."
  2742. :group 'org-latex
  2743. :version "26.1"
  2744. :package-version '(Org . "9.0")
  2745. :type 'symbol)
  2746. (defcustom org-preview-latex-process-alist
  2747. '((dvipng
  2748. :programs ("latex" "dvipng")
  2749. :description "dvi > png"
  2750. :message "you need to install the programs: latex and dvipng."
  2751. :image-input-type "dvi"
  2752. :image-output-type "png"
  2753. :image-size-adjust (1.0 . 1.0)
  2754. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2755. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2756. (dvisvgm
  2757. :programs ("latex" "dvisvgm")
  2758. :description "dvi > svg"
  2759. :message "you need to install the programs: latex and dvisvgm."
  2760. :image-input-type "dvi"
  2761. :image-output-type "svg"
  2762. :image-size-adjust (1.7 . 1.5)
  2763. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2764. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2765. (imagemagick
  2766. :programs ("latex" "convert")
  2767. :description "pdf > png"
  2768. :message "you need to install the programs: latex and imagemagick."
  2769. :image-input-type "pdf"
  2770. :image-output-type "png"
  2771. :image-size-adjust (1.0 . 1.0)
  2772. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2773. :image-converter
  2774. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2775. "Definitions of external processes for LaTeX previewing.
  2776. Org mode can use some external commands to generate TeX snippet's images for
  2777. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2778. `org-create-formula-image' how to call them.
  2779. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2780. PROPERTIES accepts the following attributes:
  2781. :programs list of strings, required programs.
  2782. :description string, describe the process.
  2783. :message string, message it when required programs cannot be found.
  2784. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2785. :image-output-type string, output file type of image converter (e.g., \"png\").
  2786. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2787. image size showed in buffer and the cdr element is for
  2788. HTML file. This option is only useful for process
  2789. developers, users should use variable
  2790. `org-format-latex-options' instead.
  2791. :post-clean list of strings, files matched are to be cleaned up once
  2792. the image is generated. When nil, the files with \".dvi\",
  2793. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2794. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2795. be cleaned up.
  2796. :latex-header list of strings, the LaTeX header of the snippet file.
  2797. When nil, the fallback value is used instead, which is
  2798. controlled by `org-format-latex-header',
  2799. `org-latex-default-packages-alist' and
  2800. `org-latex-packages-alist', which see.
  2801. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2802. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2803. replaced with values defined below.
  2804. :image-converter list of image converter commands strings. Each of them is
  2805. given to the shell and supports any of the following
  2806. place-holders defined below.
  2807. Place-holders used by `:image-converter' and `:latex-compiler':
  2808. %f input file name
  2809. %b base name of input file
  2810. %o base directory of input file
  2811. %O absolute output file name
  2812. Place-holders only used by `:image-converter':
  2813. %D dpi, which is used to adjust image size by some processing commands.
  2814. %S the image size scale ratio, which is used to adjust image size by some
  2815. processing commands."
  2816. :group 'org-latex
  2817. :version "26.1"
  2818. :package-version '(Org . "9.0")
  2819. :type '(alist :tag "LaTeX to image backends"
  2820. :value-type (plist)))
  2821. (defcustom org-preview-latex-image-directory "ltximg/"
  2822. "Path to store latex preview images.
  2823. A relative path here creates many directories relative to the
  2824. processed Org files paths. An absolute path puts all preview
  2825. images at the same place."
  2826. :group 'org-latex
  2827. :version "26.1"
  2828. :package-version '(Org . "9.0")
  2829. :type 'string)
  2830. (defun org-format-latex-mathml-available-p ()
  2831. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2832. (save-match-data
  2833. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2834. org-latex-to-mathml-convert-command)
  2835. (let ((executable (car (split-string
  2836. org-latex-to-mathml-convert-command))))
  2837. (when (executable-find executable)
  2838. (if (string-match
  2839. "%j" org-latex-to-mathml-convert-command)
  2840. (file-readable-p org-latex-to-mathml-jar-file)
  2841. t))))))
  2842. (defcustom org-format-latex-header "\\documentclass{article}
  2843. \\usepackage[usenames]{color}
  2844. \[PACKAGES]
  2845. \[DEFAULT-PACKAGES]
  2846. \\pagestyle{empty} % do not remove
  2847. % The settings below are copied from fullpage.sty
  2848. \\setlength{\\textwidth}{\\paperwidth}
  2849. \\addtolength{\\textwidth}{-3cm}
  2850. \\setlength{\\oddsidemargin}{1.5cm}
  2851. \\addtolength{\\oddsidemargin}{-2.54cm}
  2852. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2853. \\setlength{\\textheight}{\\paperheight}
  2854. \\addtolength{\\textheight}{-\\headheight}
  2855. \\addtolength{\\textheight}{-\\headsep}
  2856. \\addtolength{\\textheight}{-\\footskip}
  2857. \\addtolength{\\textheight}{-3cm}
  2858. \\setlength{\\topmargin}{1.5cm}
  2859. \\addtolength{\\topmargin}{-2.54cm}"
  2860. "The document header used for processing LaTeX fragments.
  2861. It is imperative that this header make sure that no page number
  2862. appears on the page. The package defined in the variables
  2863. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2864. will either replace the placeholder \"[PACKAGES]\" in this
  2865. header, or they will be appended."
  2866. :group 'org-latex
  2867. :type 'string)
  2868. (defun org-set-packages-alist (var val)
  2869. "Set the packages alist and make sure it has 3 elements per entry."
  2870. (set var (mapcar (lambda (x)
  2871. (if (and (consp x) (= (length x) 2))
  2872. (list (car x) (nth 1 x) t)
  2873. x))
  2874. val)))
  2875. (defun org-get-packages-alist (var)
  2876. "Get the packages alist and make sure it has 3 elements per entry."
  2877. (mapcar (lambda (x)
  2878. (if (and (consp x) (= (length x) 2))
  2879. (list (car x) (nth 1 x) t)
  2880. x))
  2881. (default-value var)))
  2882. (defcustom org-latex-default-packages-alist
  2883. '(("AUTO" "inputenc" t ("pdflatex"))
  2884. ("T1" "fontenc" t ("pdflatex"))
  2885. ("" "graphicx" t)
  2886. ("" "grffile" t)
  2887. ("" "longtable" nil)
  2888. ("" "wrapfig" nil)
  2889. ("" "rotating" nil)
  2890. ("normalem" "ulem" t)
  2891. ("" "amsmath" t)
  2892. ("" "textcomp" t)
  2893. ("" "amssymb" t)
  2894. ("" "capt-of" nil)
  2895. ("" "hyperref" nil))
  2896. "Alist of default packages to be inserted in the header.
  2897. Change this only if one of the packages here causes an
  2898. incompatibility with another package you are using.
  2899. The packages in this list are needed by one part or another of
  2900. Org mode to function properly:
  2901. - inputenc, fontenc: for basic font and character selection
  2902. - graphicx: for including images
  2903. - grffile: allow periods and spaces in graphics file names
  2904. - longtable: For multipage tables
  2905. - wrapfig: for figure placement
  2906. - rotating: for sideways figures and tables
  2907. - ulem: for underline and strike-through
  2908. - amsmath: for subscript and superscript and math environments
  2909. - textcomp, amssymb: for various symbols used
  2910. for interpreting the entities in `org-entities'. You can skip
  2911. some of these packages if you don't use any of their symbols.
  2912. - capt-of: for captions outside of floats
  2913. - hyperref: for cross references
  2914. Therefore you should not modify this variable unless you know
  2915. what you are doing. The one reason to change it anyway is that
  2916. you might be loading some other package that conflicts with one
  2917. of the default packages. Each element is either a cell or
  2918. a string.
  2919. A cell is of the format
  2920. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2921. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2922. when compiling LaTeX snippets into images for inclusion into
  2923. non-LaTeX output.
  2924. COMPILERS is a list of compilers that should include the package,
  2925. see `org-latex-compiler'. If the document compiler is not in the
  2926. list, and the list is non-nil, the package will not be inserted
  2927. in the final document.
  2928. A string will be inserted as-is in the header of the document."
  2929. :group 'org-latex
  2930. :group 'org-export-latex
  2931. :set 'org-set-packages-alist
  2932. :get 'org-get-packages-alist
  2933. :version "26.1"
  2934. :package-version '(Org . "8.3")
  2935. :type '(repeat
  2936. (choice
  2937. (list :tag "options/package pair"
  2938. (string :tag "options")
  2939. (string :tag "package")
  2940. (boolean :tag "Snippet")
  2941. (choice
  2942. (const :tag "For all compilers" nil)
  2943. (repeat :tag "Allowed compiler" string)))
  2944. (string :tag "A line of LaTeX"))))
  2945. (defcustom org-latex-packages-alist nil
  2946. "Alist of packages to be inserted in every LaTeX header.
  2947. These will be inserted after `org-latex-default-packages-alist'.
  2948. Each element is either a cell or a string.
  2949. A cell is of the format:
  2950. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2951. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2952. needed when turning LaTeX snippets into images for inclusion into
  2953. non-LaTeX output.
  2954. COMPILERS is a list of compilers that should include the package,
  2955. see `org-latex-compiler'. If the document compiler is not in the
  2956. list, and the list is non-nil, the package will not be inserted
  2957. in the final document.
  2958. A string will be inserted as-is in the header of the document.
  2959. Make sure that you only list packages here which:
  2960. - you want in every file;
  2961. - do not conflict with the setup in `org-format-latex-header';
  2962. - do not conflict with the default packages in
  2963. `org-latex-default-packages-alist'."
  2964. :group 'org-latex
  2965. :group 'org-export-latex
  2966. :set 'org-set-packages-alist
  2967. :get 'org-get-packages-alist
  2968. :type '(repeat
  2969. (choice
  2970. (list :tag "options/package pair"
  2971. (string :tag "options")
  2972. (string :tag "package")
  2973. (boolean :tag "Snippet"))
  2974. (string :tag "A line of LaTeX"))))
  2975. (defgroup org-appearance nil
  2976. "Settings for Org mode appearance."
  2977. :tag "Org Appearance"
  2978. :group 'org)
  2979. (defcustom org-level-color-stars-only nil
  2980. "Non-nil means fontify only the stars in each headline.
  2981. When nil, the entire headline is fontified.
  2982. Changing it requires restart of `font-lock-mode' to become effective
  2983. also in regions already fontified."
  2984. :group 'org-appearance
  2985. :type 'boolean)
  2986. (defcustom org-hide-leading-stars nil
  2987. "Non-nil means hide the first N-1 stars in a headline.
  2988. This works by using the face `org-hide' for these stars. This
  2989. face is white for a light background, and black for a dark
  2990. background. You may have to customize the face `org-hide' to
  2991. make this work.
  2992. Changing it requires restart of `font-lock-mode' to become effective
  2993. also in regions already fontified.
  2994. You may also set this on a per-file basis by adding one of the following
  2995. lines to the buffer:
  2996. #+STARTUP: hidestars
  2997. #+STARTUP: showstars"
  2998. :group 'org-appearance
  2999. :type 'boolean)
  3000. (defcustom org-hidden-keywords nil
  3001. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3002. For example, a value \\='(title) for this list makes the document's title
  3003. appear in the buffer without the initial \"#+TITLE:\" part."
  3004. :group 'org-appearance
  3005. :version "24.1"
  3006. :type '(set (const :tag "#+AUTHOR" author)
  3007. (const :tag "#+DATE" date)
  3008. (const :tag "#+EMAIL" email)
  3009. (const :tag "#+TITLE" title)))
  3010. (defcustom org-custom-properties nil
  3011. "List of properties (as strings) with a special meaning.
  3012. The default use of these custom properties is to let the user
  3013. hide them with `org-toggle-custom-properties-visibility'."
  3014. :group 'org-properties
  3015. :group 'org-appearance
  3016. :version "24.3"
  3017. :type '(repeat (string :tag "Property Name")))
  3018. (defcustom org-fontify-todo-headline nil
  3019. "Non-nil means change the face of a headline if it is marked as TODO.
  3020. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3021. When this is non-nil, the headline after the keyword is set to the
  3022. `org-headline-todo' as an additional indication."
  3023. :group 'org-appearance
  3024. :package-version '(Org . "9.4")
  3025. :type 'boolean
  3026. :safe t)
  3027. (defcustom org-fontify-done-headline nil
  3028. "Non-nil means change the face of a headline if it is marked DONE.
  3029. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3030. When this is non-nil, the headline after the keyword is set to the
  3031. `org-headline-done' as an additional indication."
  3032. :group 'org-appearance
  3033. :type 'boolean)
  3034. (defcustom org-fontify-emphasized-text t
  3035. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3036. Changing this variable requires a restart of Emacs to take effect."
  3037. :group 'org-appearance
  3038. :type 'boolean)
  3039. (defcustom org-fontify-whole-heading-line nil
  3040. "Non-nil means fontify the whole line for headings.
  3041. This is useful when setting a background color for the
  3042. org-level-* faces."
  3043. :group 'org-appearance
  3044. :type 'boolean)
  3045. (defcustom org-fontify-whole-block-delimiter-line t
  3046. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3047. This is useful when setting a background color for the
  3048. org-block-begin-line and org-block-end-line faces."
  3049. :group 'org-appearance
  3050. :type 'boolean)
  3051. (defcustom org-highlight-latex-and-related nil
  3052. "Non-nil means highlight LaTeX related syntax in the buffer.
  3053. When non-nil, the value should be a list containing any of the
  3054. following symbols:
  3055. `native' Highlight LaTeX snippets and environments natively.
  3056. `latex' Highlight LaTeX snippets and environments.
  3057. `script' Highlight subscript and superscript.
  3058. `entities' Highlight entities."
  3059. :group 'org-appearance
  3060. :version "24.4"
  3061. :package-version '(Org . "8.0")
  3062. :type '(choice
  3063. (const :tag "No highlighting" nil)
  3064. (set :greedy t :tag "Highlight"
  3065. (const :tag "LaTeX snippets and environments (native)" native)
  3066. (const :tag "LaTeX snippets and environments" latex)
  3067. (const :tag "Subscript and superscript" script)
  3068. (const :tag "Entities" entities))))
  3069. (defcustom org-hide-emphasis-markers nil
  3070. "Non-nil mean font-lock should hide the emphasis marker characters."
  3071. :group 'org-appearance
  3072. :type 'boolean
  3073. :safe #'booleanp)
  3074. (defcustom org-hide-macro-markers nil
  3075. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3076. :group 'org-appearance
  3077. :type 'boolean)
  3078. (defcustom org-pretty-entities nil
  3079. "Non-nil means show entities as UTF8 characters.
  3080. When nil, the \\name form remains in the buffer."
  3081. :group 'org-appearance
  3082. :version "24.1"
  3083. :type 'boolean)
  3084. (defcustom org-pretty-entities-include-sub-superscripts t
  3085. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3086. :group 'org-appearance
  3087. :version "24.1"
  3088. :type 'boolean)
  3089. (defvar org-emph-re nil
  3090. "Regular expression for matching emphasis.
  3091. After a match, the match groups contain these elements:
  3092. 0 The match of the full regular expression, including the characters
  3093. before and after the proper match
  3094. 1 The character before the proper match, or empty at beginning of line
  3095. 2 The proper match, including the leading and trailing markers
  3096. 3 The leading marker like * or /, indicating the type of highlighting
  3097. 4 The text between the emphasis markers, not including the markers
  3098. 5 The character after the match, empty at the end of a line")
  3099. (defvar org-verbatim-re nil
  3100. "Regular expression for matching verbatim text.")
  3101. (defvar org-emphasis-regexp-components) ; defined just below
  3102. (defvar org-emphasis-alist) ; defined just below
  3103. (defun org-set-emph-re (var val)
  3104. "Set variable and compute the emphasis regular expression."
  3105. (set var val)
  3106. (when (and (boundp 'org-emphasis-alist)
  3107. (boundp 'org-emphasis-regexp-components)
  3108. org-emphasis-alist org-emphasis-regexp-components)
  3109. (pcase-let*
  3110. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3111. (body (if (<= nl 0) body
  3112. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3113. (template
  3114. (format (concat "\\([%s]\\|^\\)" ;before markers
  3115. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3116. "\\([%s]\\|$\\)") ;after markers
  3117. pre border border body border post)))
  3118. (setq org-emph-re (format template "*/_+"))
  3119. (setq org-verbatim-re (format template "=~")))))
  3120. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3121. ;; set this option proved cumbersome. See this message/thread:
  3122. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3123. (defvar org-emphasis-regexp-components
  3124. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3125. "Components used to build the regular expression for emphasis.
  3126. This is a list with five entries. Terminology: In an emphasis string
  3127. like \" *strong word* \", we call the initial space PREMATCH, the final
  3128. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3129. and \"trong wor\" is the body. The different components in this variable
  3130. specify what is allowed/forbidden in each part:
  3131. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3132. post Chars allowed as postmatch. End of line will be allowed too.
  3133. border The chars *forbidden* as border characters.
  3134. body-regexp A regexp like \".\" to match a body character. Don't use
  3135. non-shy groups here, and don't allow newline here.
  3136. newline The maximum number of newlines allowed in an emphasis exp.
  3137. You need to reload Org or to restart Emacs after setting this.")
  3138. (defcustom org-emphasis-alist
  3139. '(("*" bold)
  3140. ("/" italic)
  3141. ("_" underline)
  3142. ("=" org-verbatim verbatim)
  3143. ("~" org-code verbatim)
  3144. ("+" (:strike-through t)))
  3145. "Alist of characters and faces to emphasize text.
  3146. Text starting and ending with a special character will be emphasized,
  3147. for example *bold*, _underlined_ and /italic/. This variable sets the
  3148. marker characters and the face to be used by font-lock for highlighting
  3149. in Org buffers.
  3150. You need to reload Org or to restart Emacs after customizing this."
  3151. :group 'org-appearance
  3152. :set 'org-set-emph-re
  3153. :version "24.4"
  3154. :package-version '(Org . "8.0")
  3155. :type '(repeat
  3156. (list
  3157. (string :tag "Marker character")
  3158. (choice
  3159. (face :tag "Font-lock-face")
  3160. (plist :tag "Face property list"))
  3161. (option (const verbatim)))))
  3162. (defvar org-protecting-blocks '("src" "example" "export")
  3163. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3164. This is needed for font-lock setup.")
  3165. ;;; Functions and variables from their packages
  3166. ;; Declared here to avoid compiler warnings
  3167. (defvar mark-active)
  3168. ;; Various packages
  3169. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3170. (declare-function calendar-forward-day "cal-move" (arg))
  3171. (declare-function calendar-goto-date "cal-move" (date))
  3172. (declare-function calendar-goto-today "cal-move" ())
  3173. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3174. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3175. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3176. (declare-function cdlatex-tab "ext:cdlatex" ())
  3177. (declare-function dired-get-filename
  3178. "dired"
  3179. (&optional localp no-error-if-not-filep))
  3180. (declare-function iswitchb-read-buffer
  3181. "iswitchb"
  3182. (prompt &optional
  3183. default require-match _predicate start matches-set))
  3184. (declare-function org-agenda-change-all-lines
  3185. "org-agenda"
  3186. (newhead hdmarker &optional fixface just-this))
  3187. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3188. "org-agenda"
  3189. (&optional end))
  3190. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3191. (declare-function org-agenda-format-item
  3192. "org-agenda"
  3193. (extra txt &optional level category tags dotime
  3194. remove-re habitp))
  3195. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3196. (declare-function org-agenda-save-markers-for-cut-and-paste
  3197. "org-agenda"
  3198. (beg end))
  3199. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3200. (declare-function org-agenda-skip "org-agenda" ())
  3201. (declare-function org-attach-expand "org-attach" (file))
  3202. (declare-function org-attach-reveal "org-attach" ())
  3203. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3204. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3205. (declare-function org-indent-mode "org-indent" (&optional arg))
  3206. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3207. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3208. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3209. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3210. (declare-function parse-time-string "parse-time" (string))
  3211. (defvar align-mode-rules-list)
  3212. (defvar calc-embedded-close-formula)
  3213. (defvar calc-embedded-open-formula)
  3214. (defvar calc-embedded-open-mode)
  3215. (defvar font-lock-unfontify-region-function)
  3216. (defvar iswitchb-temp-buflist)
  3217. (defvar org-agenda-tags-todo-honor-ignore-options)
  3218. (defvar remember-data-file)
  3219. (defvar texmathp-why)
  3220. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3221. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3222. (declare-function org-resolve-clocks "org-clock"
  3223. (&optional also-non-dangling-p prompt last-valid))
  3224. (defvar org-clock-start-time)
  3225. (defvar org-clock-marker (make-marker)
  3226. "Marker recording the last clock-in.")
  3227. (defvar org-clock-hd-marker (make-marker)
  3228. "Marker recording the last clock-in, but the headline position.")
  3229. (defvar org-clock-heading ""
  3230. "The heading of the current clock entry.")
  3231. (defun org-clock-is-active ()
  3232. "Return the buffer where the clock is currently running.
  3233. Return nil if no clock is running."
  3234. (marker-buffer org-clock-marker))
  3235. (defun org-check-running-clock ()
  3236. "Check if the current buffer contains the running clock.
  3237. If yes, offer to stop it and to save the buffer with the changes."
  3238. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3239. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3240. (buffer-name))))
  3241. (org-clock-out)
  3242. (when (y-or-n-p "Save changed buffer?")
  3243. (save-buffer))))
  3244. (defun org-clocktable-try-shift (dir n)
  3245. "Check if this line starts a clock table, if yes, shift the time block."
  3246. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3247. (org-clocktable-shift dir n)))
  3248. ;;;###autoload
  3249. (defun org-clock-persistence-insinuate ()
  3250. "Set up hooks for clock persistence."
  3251. (require 'org-clock)
  3252. (add-hook 'org-mode-hook 'org-clock-load)
  3253. (add-hook 'kill-emacs-hook 'org-clock-save))
  3254. (defun org-clock-auto-clockout-insinuate ()
  3255. "Set up hook for auto clocking out when Emacs is idle.
  3256. See `org-clock-auto-clockout-timer'.
  3257. This function is meant to be added to the user configuration."
  3258. (require 'org-clock)
  3259. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3260. (defgroup org-archive nil
  3261. "Options concerning archiving in Org mode."
  3262. :tag "Org Archive"
  3263. :group 'org-structure)
  3264. (defcustom org-archive-location "%s_archive::"
  3265. "The location where subtrees should be archived.
  3266. The value of this variable is a string, consisting of two parts,
  3267. separated by a double-colon. The first part is a filename and
  3268. the second part is a headline.
  3269. When the filename is omitted, archiving happens in the same file.
  3270. %s in the filename will be replaced by the current file
  3271. name (without the directory part). Archiving to a different file
  3272. is useful to keep archived entries from contributing to the
  3273. Org Agenda.
  3274. The archived entries will be filed as subtrees of the specified
  3275. headline. When the headline is omitted, the subtrees are simply
  3276. filed away at the end of the file, as top-level entries. Also in
  3277. the heading you can use %s to represent the file name, this can be
  3278. useful when using the same archive for a number of different files.
  3279. Here are a few examples:
  3280. \"%s_archive::\"
  3281. If the current file is Projects.org, archive in file
  3282. Projects.org_archive, as top-level trees. This is the default.
  3283. \"::* Archived Tasks\"
  3284. Archive in the current file, under the top-level headline
  3285. \"* Archived Tasks\".
  3286. \"~/org/archive.org::\"
  3287. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3288. \"~/org/archive.org::* From %s\"
  3289. Archive in file ~/org/archive.org (absolute path), under headlines
  3290. \"From FILENAME\" where file name is the current file name.
  3291. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3292. The \"datetree/\" string is special, signifying to archive
  3293. items to the datetree. Items are placed in either the CLOSED
  3294. date of the item, or the current date if there is no CLOSED date.
  3295. The heading will be a subentry to the current date. There doesn't
  3296. need to be a heading, but there always needs to be a slash after
  3297. datetree. For example, to store archived items directly in the
  3298. datetree, use \"~/org/datetree.org::datetree/\".
  3299. \"basement::** Finished Tasks\"
  3300. Archive in file ./basement (relative path), as level 3 trees
  3301. below the level 2 heading \"** Finished Tasks\".
  3302. You may define it locally by setting an ARCHIVE property. If
  3303. such a property is found in the file or in an entry, and anywhere
  3304. up the hierarchy, it will be used.
  3305. You can also set it for the whole file using the keyword-syntax:
  3306. #+ARCHIVE: basement::** Finished Tasks"
  3307. :group 'org-archive
  3308. :type 'string)
  3309. (defcustom org-agenda-skip-archived-trees t
  3310. "Non-nil means the agenda will skip any items located in archived trees.
  3311. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3312. variable is no longer recommended, you should leave it at the value t.
  3313. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3314. :group 'org-archive
  3315. :group 'org-agenda-skip
  3316. :type 'boolean)
  3317. (defcustom org-columns-skip-archived-trees t
  3318. "Non-nil means ignore archived trees when creating column view."
  3319. :group 'org-archive
  3320. :group 'org-properties
  3321. :type 'boolean)
  3322. (defcustom org-cycle-open-archived-trees nil
  3323. "Non-nil means `org-cycle' will open archived trees.
  3324. An archived tree is a tree marked with the tag ARCHIVE.
  3325. When nil, archived trees will stay folded. You can still open them with
  3326. normal outline commands like `show-all', but not with the cycling commands."
  3327. :group 'org-archive
  3328. :group 'org-cycle
  3329. :type 'boolean)
  3330. (defcustom org-sparse-tree-open-archived-trees nil
  3331. "Non-nil means sparse tree construction shows matches in archived trees.
  3332. When nil, matches in these trees are highlighted, but the trees are kept in
  3333. collapsed state."
  3334. :group 'org-archive
  3335. :group 'org-sparse-trees
  3336. :type 'boolean)
  3337. (defcustom org-sparse-tree-default-date-type nil
  3338. "The default date type when building a sparse tree.
  3339. When this is nil, a date is a scheduled or a deadline timestamp.
  3340. Otherwise, these types are allowed:
  3341. all: all timestamps
  3342. active: only active timestamps (<...>)
  3343. inactive: only inactive timestamps ([...])
  3344. scheduled: only scheduled timestamps
  3345. deadline: only deadline timestamps"
  3346. :type '(choice (const :tag "Scheduled or deadline" nil)
  3347. (const :tag "All timestamps" all)
  3348. (const :tag "Only active timestamps" active)
  3349. (const :tag "Only inactive timestamps" inactive)
  3350. (const :tag "Only scheduled timestamps" scheduled)
  3351. (const :tag "Only deadline timestamps" deadline)
  3352. (const :tag "Only closed timestamps" closed))
  3353. :version "26.1"
  3354. :package-version '(Org . "8.3")
  3355. :group 'org-sparse-trees)
  3356. (defun org-cycle-hide-archived-subtrees (state)
  3357. "Re-hide all archived subtrees after a visibility state change.
  3358. STATE should be one of the symbols listed in the docstring of
  3359. `org-cycle-hook'."
  3360. (when (and (not org-cycle-open-archived-trees)
  3361. (not (memq state '(overview folded))))
  3362. (save-excursion
  3363. (let* ((globalp (memq state '(contents all)))
  3364. (beg (if globalp (point-min) (point)))
  3365. (end (if globalp (point-max) (org-end-of-subtree t))))
  3366. (org-hide-archived-subtrees beg end)
  3367. (goto-char beg)
  3368. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3369. (message "%s" (substitute-command-keys
  3370. "Subtree is archived and stays closed. Use \
  3371. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3372. (defun org-force-cycle-archived ()
  3373. "Cycle subtree even if it is archived."
  3374. (interactive)
  3375. (setq this-command 'org-cycle)
  3376. (let ((org-cycle-open-archived-trees t))
  3377. (call-interactively 'org-cycle)))
  3378. (defun org-hide-archived-subtrees (beg end)
  3379. "Re-hide all archived subtrees after a visibility state change."
  3380. (org-with-wide-buffer
  3381. (let ((case-fold-search nil)
  3382. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3383. (goto-char beg)
  3384. ;; Include headline point is currently on.
  3385. (beginning-of-line)
  3386. (while (and (< (point) end) (re-search-forward re end t))
  3387. (when (member org-archive-tag (org-get-tags nil t))
  3388. (org-flag-subtree t)
  3389. (org-end-of-subtree t))))))
  3390. (defun org-flag-subtree (flag)
  3391. (save-excursion
  3392. (org-back-to-heading t)
  3393. (org-flag-region (line-end-position)
  3394. (progn (org-end-of-subtree t) (point))
  3395. flag
  3396. 'outline)))
  3397. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3398. ;; Declare Column View Code
  3399. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3400. (declare-function org-columns-compute "org-colview" (property))
  3401. ;; Declare ID code
  3402. (declare-function org-id-store-link "org-id")
  3403. (declare-function org-id-locations-load "org-id")
  3404. (declare-function org-id-locations-save "org-id")
  3405. (defvar org-id-track-globally)
  3406. ;;; Variables for pre-computed regular expressions, all buffer local
  3407. (defvar-local org-todo-regexp nil
  3408. "Matches any of the TODO state keywords.
  3409. Since TODO keywords are case-sensitive, `case-fold-search' is
  3410. expected to be bound to nil when matching against this regexp.")
  3411. (defvar-local org-not-done-regexp nil
  3412. "Matches any of the TODO state keywords except the last one.
  3413. Since TODO keywords are case-sensitive, `case-fold-search' is
  3414. expected to be bound to nil when matching against this regexp.")
  3415. (defvar-local org-not-done-heading-regexp nil
  3416. "Matches a TODO headline that is not done.
  3417. Since TODO keywords are case-sensitive, `case-fold-search' is
  3418. expected to be bound to nil when matching against this regexp.")
  3419. (defvar-local org-todo-line-regexp nil
  3420. "Matches a headline and puts TODO state into group 2 if present.
  3421. Since TODO keywords are case-sensitive, `case-fold-search' is
  3422. expected to be bound to nil when matching against this regexp.")
  3423. (defvar-local org-complex-heading-regexp nil
  3424. "Matches a headline and puts everything into groups:
  3425. group 1: Stars
  3426. group 2: The TODO keyword, maybe
  3427. group 3: Priority cookie
  3428. group 4: True headline
  3429. group 5: Tags
  3430. Since TODO keywords are case-sensitive, `case-fold-search' is
  3431. expected to be bound to nil when matching against this regexp.")
  3432. (defvar-local org-complex-heading-regexp-format nil
  3433. "Printf format to make regexp to match an exact headline.
  3434. This regexp will match the headline of any node which has the
  3435. exact headline text that is put into the format, but may have any
  3436. TODO state, priority and tags.")
  3437. (defvar-local org-todo-line-tags-regexp nil
  3438. "Matches a headline and puts TODO state into group 2 if present.
  3439. Also put tags into group 4 if tags are present.")
  3440. (defconst org-plain-time-of-day-regexp
  3441. (concat
  3442. "\\(\\<[012]?[0-9]"
  3443. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3444. "\\(--?"
  3445. "\\(\\<[012]?[0-9]"
  3446. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3447. "\\)?")
  3448. "Regular expression to match a plain time or time range.
  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. 1 the first time, range or not
  3453. 8 the second time, if it is a range.")
  3454. (defconst org-plain-time-extension-regexp
  3455. (concat
  3456. "\\(\\<[012]?[0-9]"
  3457. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3458. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3459. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3460. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3461. groups carry important information:
  3462. 0 the full match
  3463. 7 hours of duration
  3464. 9 minutes of duration")
  3465. (defconst org-stamp-time-of-day-regexp
  3466. (concat
  3467. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3468. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3469. "\\(--?"
  3470. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3471. "Regular expression to match a timestamp time or time range.
  3472. After a match, the following groups carry important information:
  3473. 0 the full match
  3474. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3475. 2 the first time, range or not
  3476. 4 the second time, if it is a range.")
  3477. (defconst org-startup-options
  3478. '(("fold" org-startup-folded t)
  3479. ("overview" org-startup-folded t)
  3480. ("nofold" org-startup-folded nil)
  3481. ("showall" org-startup-folded nil)
  3482. ("showeverything" org-startup-folded showeverything)
  3483. ("content" org-startup-folded content)
  3484. ("indent" org-startup-indented t)
  3485. ("noindent" org-startup-indented nil)
  3486. ("num" org-startup-numeroted t)
  3487. ("nonum" org-startup-numeroted nil)
  3488. ("hidestars" org-hide-leading-stars t)
  3489. ("showstars" org-hide-leading-stars nil)
  3490. ("odd" org-odd-levels-only t)
  3491. ("oddeven" org-odd-levels-only nil)
  3492. ("align" org-startup-align-all-tables t)
  3493. ("noalign" org-startup-align-all-tables nil)
  3494. ("shrink" org-startup-shrink-all-tables t)
  3495. ("inlineimages" org-startup-with-inline-images t)
  3496. ("noinlineimages" org-startup-with-inline-images nil)
  3497. ("latexpreview" org-startup-with-latex-preview t)
  3498. ("nolatexpreview" org-startup-with-latex-preview nil)
  3499. ("customtime" org-display-custom-times t)
  3500. ("logdone" org-log-done time)
  3501. ("lognotedone" org-log-done note)
  3502. ("nologdone" org-log-done nil)
  3503. ("lognoteclock-out" org-log-note-clock-out t)
  3504. ("nolognoteclock-out" org-log-note-clock-out nil)
  3505. ("logrepeat" org-log-repeat state)
  3506. ("lognoterepeat" org-log-repeat note)
  3507. ("logdrawer" org-log-into-drawer t)
  3508. ("nologdrawer" org-log-into-drawer nil)
  3509. ("logstatesreversed" org-log-states-order-reversed t)
  3510. ("nologstatesreversed" org-log-states-order-reversed nil)
  3511. ("nologrepeat" org-log-repeat nil)
  3512. ("logreschedule" org-log-reschedule time)
  3513. ("lognotereschedule" org-log-reschedule note)
  3514. ("nologreschedule" org-log-reschedule nil)
  3515. ("logredeadline" org-log-redeadline time)
  3516. ("lognoteredeadline" org-log-redeadline note)
  3517. ("nologredeadline" org-log-redeadline nil)
  3518. ("logrefile" org-log-refile time)
  3519. ("lognoterefile" org-log-refile note)
  3520. ("nologrefile" org-log-refile nil)
  3521. ("fninline" org-footnote-define-inline t)
  3522. ("nofninline" org-footnote-define-inline nil)
  3523. ("fnlocal" org-footnote-section nil)
  3524. ("fnauto" org-footnote-auto-label t)
  3525. ("fnprompt" org-footnote-auto-label nil)
  3526. ("fnconfirm" org-footnote-auto-label confirm)
  3527. ("fnplain" org-footnote-auto-label plain)
  3528. ("fnadjust" org-footnote-auto-adjust t)
  3529. ("nofnadjust" org-footnote-auto-adjust nil)
  3530. ("constcgs" constants-unit-system cgs)
  3531. ("constSI" constants-unit-system SI)
  3532. ("noptag" org-tag-persistent-alist nil)
  3533. ("hideblocks" org-hide-block-startup t)
  3534. ("nohideblocks" org-hide-block-startup nil)
  3535. ("beamer" org-startup-with-beamer-mode t)
  3536. ("entitiespretty" org-pretty-entities t)
  3537. ("entitiesplain" org-pretty-entities nil))
  3538. "Variable associated with STARTUP options for Org.
  3539. Each element is a list of three items: the startup options (as written
  3540. in the #+STARTUP line), the corresponding variable, and the value to set
  3541. this variable to if the option is found. An optional forth element PUSH
  3542. means to push this value onto the list in the variable.")
  3543. (defcustom org-group-tags t
  3544. "When non-nil (the default), use group tags.
  3545. This can be turned on/off through `org-toggle-tags-groups'."
  3546. :group 'org-tags
  3547. :group 'org-startup
  3548. :type 'boolean)
  3549. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3550. (defun org-toggle-tags-groups ()
  3551. "Toggle support for group tags.
  3552. Support for group tags is controlled by the option
  3553. `org-group-tags', which is non-nil by default."
  3554. (interactive)
  3555. (setq org-group-tags (not org-group-tags))
  3556. (cond ((and (derived-mode-p 'org-agenda-mode)
  3557. org-group-tags)
  3558. (org-agenda-redo))
  3559. ((derived-mode-p 'org-mode)
  3560. (let ((org-inhibit-startup t)) (org-mode))))
  3561. (message "Groups tags support has been turned %s"
  3562. (if org-group-tags "on" "off")))
  3563. (defun org--tag-add-to-alist (alist1 alist2)
  3564. "Merge tags from ALIST1 into ALIST2.
  3565. Duplicates tags outside a group are removed. Keywords and order
  3566. are preserved.
  3567. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3568. See `org-tag-alist' for their structure."
  3569. (cond
  3570. ((null alist2) alist1)
  3571. ((null alist1) alist2)
  3572. (t
  3573. (let ((to-add nil)
  3574. (group-flag nil))
  3575. (dolist (tag-pair alist1)
  3576. (pcase tag-pair
  3577. (`(,(or :startgrouptag :startgroup))
  3578. (setq group-flag t)
  3579. (push tag-pair to-add))
  3580. (`(,(or :endgrouptag :endgroup))
  3581. (setq group-flag nil)
  3582. (push tag-pair to-add))
  3583. (`(,(or :grouptags :newline))
  3584. (push tag-pair to-add))
  3585. (`(,tag . ,_)
  3586. ;; Remove duplicates from ALIST1, unless they are in
  3587. ;; a group. Indeed, it makes sense to have a tag appear in
  3588. ;; multiple groups.
  3589. (when (or group-flag (not (assoc tag alist2)))
  3590. (push tag-pair to-add)))
  3591. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3592. ;; Preserve order of ALIST1.
  3593. (append (nreverse to-add) alist2)))))
  3594. (defun org-set-regexps-and-options (&optional tags-only)
  3595. "Precompute regular expressions used in the current buffer.
  3596. When optional argument TAGS-ONLY is non-nil, only compute tags
  3597. related expressions."
  3598. (when (derived-mode-p 'org-mode)
  3599. (let ((alist (org--setup-collect-keywords
  3600. (org-make-options-regexp
  3601. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3602. (and (not tags-only)
  3603. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3604. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3605. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3606. ;; Startup options. Get this early since it does change
  3607. ;; behavior for other options (e.g., tags).
  3608. (let ((startup (cdr (assq 'startup alist))))
  3609. (dolist (option startup)
  3610. (let ((entry (assoc-string option org-startup-options t)))
  3611. (when entry
  3612. (let ((var (nth 1 entry))
  3613. (val (nth 2 entry)))
  3614. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3615. (unless (listp (symbol-value var))
  3616. (set (make-local-variable var) nil))
  3617. (add-to-list var val)))))))
  3618. (setq-local org-file-tags
  3619. (mapcar #'org-add-prop-inherited
  3620. (cdr (assq 'filetags alist))))
  3621. (setq org-current-tag-alist
  3622. (org--tag-add-to-alist
  3623. org-tag-persistent-alist
  3624. (let ((tags (cdr (assq 'tags alist))))
  3625. (if tags (org-tag-string-to-alist tags)
  3626. org-tag-alist))))
  3627. (setq org-tag-groups-alist
  3628. (org-tag-alist-to-groups org-current-tag-alist))
  3629. (unless tags-only
  3630. ;; Properties.
  3631. (setq-local org-keyword-properties (cdr (assq 'property alist)))
  3632. ;; Archive location.
  3633. (let ((archive (cdr (assq 'archive alist))))
  3634. (when archive (setq-local org-archive-location archive)))
  3635. ;; Category.
  3636. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3637. (when cat
  3638. (setq-local org-category (intern cat))
  3639. (setq-local org-keyword-properties
  3640. (org--update-property-plist
  3641. "CATEGORY" cat org-keyword-properties))))
  3642. ;; Columns.
  3643. (let ((column (cdr (assq 'columns alist))))
  3644. (when column (setq-local org-columns-default-format column)))
  3645. ;; Constants.
  3646. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3647. ;; Link abbreviations.
  3648. (let ((links (cdr (assq 'link alist))))
  3649. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3650. ;; Priorities.
  3651. (let ((priorities (cdr (assq 'priorities alist))))
  3652. (when priorities
  3653. (setq-local org-priority-highest (nth 0 priorities))
  3654. (setq-local org-priority-lowest (nth 1 priorities))
  3655. (setq-local org-priority-default (nth 2 priorities))))
  3656. ;; Scripts.
  3657. (let ((scripts (assq 'scripts alist)))
  3658. (when scripts
  3659. (setq-local org-use-sub-superscripts (cdr scripts))))
  3660. ;; TODO keywords.
  3661. (setq-local org-todo-kwd-alist nil)
  3662. (setq-local org-todo-key-alist nil)
  3663. (setq-local org-todo-key-trigger nil)
  3664. (setq-local org-todo-keywords-1 nil)
  3665. (setq-local org-done-keywords nil)
  3666. (setq-local org-todo-heads nil)
  3667. (setq-local org-todo-sets nil)
  3668. (setq-local org-todo-log-states nil)
  3669. (let ((todo-sequences
  3670. (or (nreverse (cdr (assq 'todo alist)))
  3671. (let ((d (default-value 'org-todo-keywords)))
  3672. (if (not (stringp (car d))) d
  3673. ;; XXX: Backward compatibility code.
  3674. (list (cons org-todo-interpretation d)))))))
  3675. (dolist (sequence todo-sequences)
  3676. (let* ((sequence (or (run-hook-with-args-until-success
  3677. 'org-todo-setup-filter-hook sequence)
  3678. sequence))
  3679. (sequence-type (car sequence))
  3680. (keywords (cdr sequence))
  3681. (sep (member "|" keywords))
  3682. names alist)
  3683. (dolist (k (remove "|" keywords))
  3684. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3685. k)
  3686. (error "Invalid TODO keyword %s" k))
  3687. (let ((name (match-string 1 k))
  3688. (key (match-string 2 k))
  3689. (log (org-extract-log-state-settings k)))
  3690. (push name names)
  3691. (push (cons name (and key (string-to-char key))) alist)
  3692. (when log (push log org-todo-log-states))))
  3693. (let* ((names (nreverse names))
  3694. (done (if sep (org-remove-keyword-keys (cdr sep))
  3695. (last names)))
  3696. (head (car names))
  3697. (tail (list sequence-type head (car done) (org-last done))))
  3698. (add-to-list 'org-todo-heads head 'append)
  3699. (push names org-todo-sets)
  3700. (setq org-done-keywords (append org-done-keywords done nil))
  3701. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3702. (setq org-todo-key-alist
  3703. (append org-todo-key-alist
  3704. (and alist
  3705. (append '((:startgroup))
  3706. (nreverse alist)
  3707. '((:endgroup))))))
  3708. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3709. (setq org-todo-sets (nreverse org-todo-sets)
  3710. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3711. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3712. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3713. ;; Compute the regular expressions and other local variables.
  3714. ;; Using `org-outline-regexp-bol' would complicate them much,
  3715. ;; because of the fixed white space at the end of that string.
  3716. (unless org-done-keywords
  3717. (setq org-done-keywords
  3718. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3719. (setq org-not-done-keywords
  3720. (org-delete-all org-done-keywords
  3721. (copy-sequence org-todo-keywords-1))
  3722. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3723. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3724. org-not-done-heading-regexp
  3725. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3726. org-todo-line-regexp
  3727. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3728. org-complex-heading-regexp
  3729. (concat "^\\(\\*+\\)"
  3730. "\\(?: +" org-todo-regexp "\\)?"
  3731. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3732. "\\(?: +\\(.*?\\)\\)??"
  3733. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3734. "[ \t]*$")
  3735. org-complex-heading-regexp-format
  3736. (concat "^\\(\\*+\\)"
  3737. "\\(?: +" org-todo-regexp "\\)?"
  3738. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3739. "\\(?: +"
  3740. ;; Stats cookies can be stuck to body.
  3741. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3742. "\\(%s\\)"
  3743. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3744. "\\)"
  3745. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3746. "[ \t]*$")
  3747. org-todo-line-tags-regexp
  3748. (concat "^\\(\\*+\\)"
  3749. "\\(?: +" org-todo-regexp "\\)?"
  3750. "\\(?: +\\(.*?\\)\\)??"
  3751. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3752. "[ \t]*$"))
  3753. (org-compute-latex-and-related-regexp)))))
  3754. (defsubst org-priority-to-value (s)
  3755. "Convert priority string S to its numeric value."
  3756. (or (save-match-data
  3757. (and (string-match "\\([0-9]+\\)" s)
  3758. (string-to-number (match-string 1 s))))
  3759. (string-to-char s)))
  3760. (defun org--setup-collect-keywords (regexp &optional files alist)
  3761. "Return setup keywords values as an alist.
  3762. REGEXP matches a subset of setup keywords. FILES is a list of
  3763. file names already visited. It is used to avoid circular setup
  3764. files. ALIST, when non-nil, is the alist computed so far.
  3765. Return value contains the following keys: `archive', `category',
  3766. `columns', `constants', `filetags', `link', `priorities',
  3767. `property', `scripts', `startup', `tags' and `todo'."
  3768. (org-with-wide-buffer
  3769. (goto-char (point-min))
  3770. (let ((case-fold-search t))
  3771. (while (re-search-forward regexp nil t)
  3772. (let ((element (org-element-at-point)))
  3773. (when (eq (org-element-type element) 'keyword)
  3774. (let ((key (org-element-property :key element))
  3775. (value (org-element-property :value element)))
  3776. (cond
  3777. ((equal key "ARCHIVE")
  3778. (when (org-string-nw-p value)
  3779. (push (cons 'archive value) alist)))
  3780. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3781. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3782. ((equal key "CONSTANTS")
  3783. (let* ((constants (assq 'constants alist))
  3784. (store (cdr constants)))
  3785. (dolist (pair (split-string value))
  3786. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3787. pair)
  3788. (let* ((name (match-string 1 pair))
  3789. (value (match-string 2 pair))
  3790. (old (assoc name store)))
  3791. (if old (setcdr old value)
  3792. (push (cons name value) store)))))
  3793. (if constants (setcdr constants store)
  3794. (push (cons 'constants store) alist))))
  3795. ((equal key "FILETAGS")
  3796. (when (org-string-nw-p value)
  3797. (let ((old (assq 'filetags alist))
  3798. (new (apply #'nconc
  3799. (mapcar (lambda (x) (org-split-string x ":"))
  3800. (split-string value)))))
  3801. (if old (setcdr old (append new (cdr old)))
  3802. (push (cons 'filetags new) alist)))))
  3803. ((equal key "LINK")
  3804. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3805. (let ((links (assq 'link alist))
  3806. (pair (cons (match-string-no-properties 1 value)
  3807. (match-string-no-properties 2 value))))
  3808. (if links (push pair (cdr links))
  3809. (push (list 'link pair) alist)))))
  3810. ((equal key "OPTIONS")
  3811. (when (and (org-string-nw-p value)
  3812. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3813. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3814. ((equal key "PRIORITIES")
  3815. (push (cons 'priorities
  3816. (let ((prio (split-string value)))
  3817. (if (< (length prio) 3)
  3818. (list org-priority-highest
  3819. org-priority-lowest
  3820. org-priority-default)
  3821. (mapcar #'org-priority-to-value prio))))
  3822. alist))
  3823. ((equal key "PROPERTY")
  3824. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3825. (let* ((property (assq 'property alist))
  3826. (value (org--update-property-plist
  3827. (match-string-no-properties 1 value)
  3828. (match-string-no-properties 2 value)
  3829. (cdr property))))
  3830. (if property (setcdr property value)
  3831. (push (cons 'property value) alist)))))
  3832. ((equal key "STARTUP")
  3833. (let ((startup (assq 'startup alist)))
  3834. (if startup
  3835. (setcdr startup
  3836. (append (cdr startup) (split-string value)))
  3837. (push (cons 'startup (split-string value)) alist))))
  3838. ((equal key "TAGS")
  3839. (let ((tag-cell (assq 'tags alist)))
  3840. (if tag-cell
  3841. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3842. (push (cons 'tags value) alist))))
  3843. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3844. (let ((todo (assq 'todo alist))
  3845. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3846. (split-string value))))
  3847. (if todo (push value (cdr todo))
  3848. (push (list 'todo value) alist))))
  3849. ((equal key "SETUPFILE")
  3850. (unless buffer-read-only ; Do not check in Gnus messages.
  3851. (let ((f (and (org-string-nw-p value)
  3852. (expand-file-name (org-strip-quotes value)))))
  3853. (when (and f (file-readable-p f) (not (member f files)))
  3854. (with-temp-buffer
  3855. (setq default-directory (file-name-directory f))
  3856. (insert-file-contents f)
  3857. (setq alist
  3858. ;; Fake Org mode to benefit from cache
  3859. ;; without recurring needlessly.
  3860. (let ((major-mode 'org-mode))
  3861. (org--setup-collect-keywords
  3862. regexp (cons f files) alist)))))))))))))))
  3863. alist)
  3864. (defun org-tag-string-to-alist (s)
  3865. "Return tag alist associated to string S.
  3866. S is a value for TAGS keyword or produced with
  3867. `org-tag-alist-to-string'. Return value is an alist suitable for
  3868. `org-tag-alist' or `org-tag-persistent-alist'."
  3869. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3870. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3871. "\\(?:(\\(.\\))\\)?\\'"))
  3872. alist group-flag)
  3873. (dolist (tokens lines (cdr (nreverse alist)))
  3874. (push '(:newline) alist)
  3875. (while tokens
  3876. (let ((token (pop tokens)))
  3877. (pcase token
  3878. ("{"
  3879. (push '(:startgroup) alist)
  3880. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3881. ("}"
  3882. (push '(:endgroup) alist)
  3883. (setq group-flag nil))
  3884. ("["
  3885. (push '(:startgrouptag) alist)
  3886. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3887. ("]"
  3888. (push '(:endgrouptag) alist)
  3889. (setq group-flag nil))
  3890. (":"
  3891. (push '(:grouptags) alist))
  3892. ((guard (string-match tag-re token))
  3893. (let ((tag (match-string 1 token))
  3894. (key (and (match-beginning 2)
  3895. (string-to-char (match-string 2 token)))))
  3896. ;; Push all tags in groups, no matter if they already
  3897. ;; appear somewhere else in the list.
  3898. (when (or group-flag (not (assoc tag alist)))
  3899. (push (cons tag key) alist))))))))))
  3900. (defun org-tag-alist-to-string (alist &optional skip-key)
  3901. "Return tag string associated to ALIST.
  3902. ALIST is an alist, as defined in `org-tag-alist' or
  3903. `org-tag-persistent-alist', or produced with
  3904. `org-tag-string-to-alist'.
  3905. Return value is a string suitable as a value for \"TAGS\"
  3906. keyword.
  3907. When optional argument SKIP-KEY is non-nil, skip selection keys
  3908. next to tags."
  3909. (mapconcat (lambda (token)
  3910. (pcase token
  3911. (`(:startgroup) "{")
  3912. (`(:endgroup) "}")
  3913. (`(:startgrouptag) "[")
  3914. (`(:endgrouptag) "]")
  3915. (`(:grouptags) ":")
  3916. (`(:newline) "\\n")
  3917. ((and
  3918. (guard (not skip-key))
  3919. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3920. (format "%s(%c)" tag key))
  3921. (`(,(and tag (pred stringp)) . ,_) tag)
  3922. (_ (user-error "Invalid tag token: %S" token))))
  3923. alist
  3924. " "))
  3925. (defun org-tag-alist-to-groups (alist)
  3926. "Return group alist from tag ALIST.
  3927. ALIST is an alist, as defined in `org-tag-alist' or
  3928. `org-tag-persistent-alist', or produced with
  3929. `org-tag-string-to-alist'. Return value is an alist following
  3930. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3931. a string, summarizing TAGS, as a list of strings."
  3932. (let (groups group-status current-group)
  3933. (dolist (token alist (nreverse groups))
  3934. (pcase token
  3935. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3936. (`(,(or :endgroup :endgrouptag))
  3937. (when (eq group-status 'append)
  3938. (push (nreverse current-group) groups))
  3939. (setq group-status nil current-group nil))
  3940. (`(:grouptags) (setq group-status 'append))
  3941. ((and `(,tag . ,_) (guard group-status))
  3942. (if (eq group-status 'append) (push tag current-group)
  3943. (setq current-group (list tag))))
  3944. (_ nil)))))
  3945. (defvar org--file-cache (make-hash-table :test #'equal)
  3946. "Hash table to store contents of files referenced via a URL.
  3947. This is the cache of file URLs read using `org-file-contents'.")
  3948. (defun org-reset-file-cache ()
  3949. "Reset the cache of files downloaded by `org-file-contents'."
  3950. (clrhash org--file-cache))
  3951. (defun org-file-url-p (file)
  3952. "Non-nil if FILE is a URL."
  3953. (require 'ffap)
  3954. (string-match-p ffap-url-regexp file))
  3955. (defun org-file-contents (file &optional noerror nocache)
  3956. "Return the contents of FILE, as a string.
  3957. FILE can be a file name or URL.
  3958. If FILE is a URL, download the contents. If the URL contents are
  3959. already cached in the `org--file-cache' hash table, the download step
  3960. is skipped.
  3961. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3962. from file or URL.
  3963. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3964. is available. This option applies only if FILE is a URL."
  3965. (let* ((is-url (org-file-url-p file))
  3966. (cache (and is-url
  3967. (not nocache)
  3968. (gethash file org--file-cache))))
  3969. (cond
  3970. (cache)
  3971. (is-url
  3972. (with-current-buffer (url-retrieve-synchronously file)
  3973. (goto-char (point-min))
  3974. ;; Move point to after the url-retrieve header.
  3975. (search-forward "\n\n" nil :move)
  3976. ;; Search for the success code only in the url-retrieve header.
  3977. (if (save-excursion
  3978. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3979. ;; Update the cache `org--file-cache' and return contents.
  3980. (puthash file
  3981. (buffer-substring-no-properties (point) (point-max))
  3982. org--file-cache)
  3983. (funcall (if noerror #'message #'user-error)
  3984. "Unable to fetch file from %S"
  3985. file))))
  3986. (t
  3987. (with-temp-buffer
  3988. (condition-case nil
  3989. (progn
  3990. (insert-file-contents file)
  3991. (buffer-string))
  3992. (file-error
  3993. (funcall (if noerror #'message #'user-error)
  3994. "Unable to read file %S"
  3995. file))))))))
  3996. (defun org-extract-log-state-settings (x)
  3997. "Extract the log state setting from a TODO keyword string.
  3998. This will extract info from a string like \"WAIT(w@/!)\"."
  3999. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4000. (let ((kw (match-string 1 x))
  4001. (log1 (and (match-end 3) (match-string 3 x)))
  4002. (log2 (and (match-end 4) (match-string 4 x))))
  4003. (and (or log1 log2)
  4004. (list kw
  4005. (and log1 (if (equal log1 "!") 'time 'note))
  4006. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4007. (defun org-remove-keyword-keys (list)
  4008. "Remove a pair of parenthesis at the end of each string in LIST."
  4009. (mapcar (lambda (x)
  4010. (if (string-match "(.*)$" x)
  4011. (substring x 0 (match-beginning 0))
  4012. x))
  4013. list))
  4014. (defun org-assign-fast-keys (alist)
  4015. "Assign fast keys to a keyword-key alist.
  4016. Respect keys that are already there."
  4017. (let (new e (alt ?0))
  4018. (while (setq e (pop alist))
  4019. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4020. (cdr e)) ;; Key already assigned.
  4021. (push e new)
  4022. (let ((clist (string-to-list (downcase (car e))))
  4023. (used (append new alist)))
  4024. (when (= (car clist) ?@)
  4025. (pop clist))
  4026. (while (and clist (rassoc (car clist) used))
  4027. (pop clist))
  4028. (unless clist
  4029. (while (rassoc alt used)
  4030. (cl-incf alt)))
  4031. (push (cons (car e) (or (car clist) alt)) new))))
  4032. (nreverse new)))
  4033. ;;; Some variables used in various places
  4034. (defvar org-window-configuration nil
  4035. "Used in various places to store a window configuration.")
  4036. (defvar org-selected-window nil
  4037. "Used in various places to store a window configuration.")
  4038. (defvar org-finish-function nil
  4039. "Function to be called when `C-c C-c' is used.
  4040. This is for getting out of special buffers like capture.")
  4041. (defvar org-last-state)
  4042. ;; Defined somewhere in this file, but used before definition.
  4043. (defvar org-entities) ;; defined in org-entities.el
  4044. (defvar org-struct-menu)
  4045. (defvar org-org-menu)
  4046. (defvar org-tbl-menu)
  4047. ;;;; Define the Org mode
  4048. (defun org-before-change-function (_beg _end)
  4049. "Every change indicates that a table might need an update."
  4050. (setq org-table-may-need-update t))
  4051. (defvar org-mode-map)
  4052. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4053. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4054. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4055. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4056. (defvar bidi-paragraph-direction)
  4057. (defvar buffer-face-mode-face)
  4058. (require 'outline)
  4059. ;; Other stuff we need.
  4060. (require 'time-date)
  4061. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4062. (require 'easymenu)
  4063. (autoload 'easy-menu-add "easymenu")
  4064. (require 'overlay)
  4065. (require 'org-entities)
  4066. (require 'org-faces)
  4067. (require 'org-list)
  4068. (require 'org-pcomplete)
  4069. (require 'org-src)
  4070. (require 'org-footnote)
  4071. (require 'org-macro)
  4072. ;; babel
  4073. (require 'ob)
  4074. ;;;###autoload
  4075. (define-derived-mode org-mode outline-mode "Org"
  4076. "Outline-based notes management and organizer, alias
  4077. \"Carsten's outline-mode for keeping track of everything.\"
  4078. Org mode develops organizational tasks around a NOTES file which
  4079. contains information about projects as plain text. Org mode is
  4080. implemented on top of Outline mode, which is ideal to keep the content
  4081. of large files well structured. It supports ToDo items, deadlines and
  4082. time stamps, which magically appear in the diary listing of the Emacs
  4083. calendar. Tables are easily created with a built-in table editor.
  4084. Plain text URL-like links connect to websites, emails (VM), Usenet
  4085. messages (Gnus), BBDB entries, and any files related to the project.
  4086. For printing and sharing of notes, an Org file (or a part of it)
  4087. can be exported as a structured ASCII or HTML file.
  4088. The following commands are available:
  4089. \\{org-mode-map}"
  4090. (org-load-modules-maybe)
  4091. (org-install-agenda-files-menu)
  4092. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4093. (add-to-invisibility-spec '(org-hide-block . t))
  4094. (add-to-invisibility-spec '(org-hide-drawer . t))
  4095. (setq-local outline-regexp org-outline-regexp)
  4096. (setq-local outline-level 'org-outline-level)
  4097. (setq bidi-paragraph-direction 'left-to-right)
  4098. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4099. (unless org-display-table
  4100. (setq org-display-table (make-display-table)))
  4101. (set-display-table-slot
  4102. org-display-table 4
  4103. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4104. org-ellipsis)))
  4105. (setq buffer-display-table org-display-table))
  4106. (org-set-regexps-and-options)
  4107. (org-set-font-lock-defaults)
  4108. (when (and org-tag-faces (not org-tags-special-faces-re))
  4109. ;; tag faces set outside customize.... force initialization.
  4110. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4111. ;; Calc embedded
  4112. (setq-local calc-embedded-open-mode "# ")
  4113. ;; Modify a few syntax entries
  4114. (modify-syntax-entry ?\" "\"")
  4115. (modify-syntax-entry ?\\ "_")
  4116. (modify-syntax-entry ?~ "_")
  4117. (modify-syntax-entry ?< "(>")
  4118. (modify-syntax-entry ?> ")<")
  4119. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4120. ;; Activate before-change-function
  4121. (setq-local org-table-may-need-update t)
  4122. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4123. ;; Check for running clock before killing a buffer
  4124. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4125. ;; Initialize macros templates.
  4126. (org-macro-initialize-templates)
  4127. ;; Initialize radio targets.
  4128. (org-update-radio-target-regexp)
  4129. ;; Indentation.
  4130. (setq-local indent-line-function 'org-indent-line)
  4131. (setq-local indent-region-function 'org-indent-region)
  4132. ;; Filling and auto-filling.
  4133. (org-setup-filling)
  4134. ;; Comments.
  4135. (org-setup-comments-handling)
  4136. ;; Initialize cache.
  4137. (org-element-cache-reset)
  4138. ;; Beginning/end of defun
  4139. (setq-local beginning-of-defun-function 'org-backward-element)
  4140. (setq-local end-of-defun-function
  4141. (lambda ()
  4142. (if (not (org-at-heading-p))
  4143. (org-forward-element)
  4144. (org-forward-element)
  4145. (forward-char -1))))
  4146. ;; Next error for sparse trees
  4147. (setq-local next-error-function 'org-occur-next-match)
  4148. ;; Make commit log messages from Org documents easier.
  4149. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4150. ;; Make sure dependence stuff works reliably, even for users who set it
  4151. ;; too late :-(
  4152. (if org-enforce-todo-dependencies
  4153. (add-hook 'org-blocker-hook
  4154. 'org-block-todo-from-children-or-siblings-or-parent)
  4155. (remove-hook 'org-blocker-hook
  4156. 'org-block-todo-from-children-or-siblings-or-parent))
  4157. (if org-enforce-todo-checkbox-dependencies
  4158. (add-hook 'org-blocker-hook
  4159. 'org-block-todo-from-checkboxes)
  4160. (remove-hook 'org-blocker-hook
  4161. 'org-block-todo-from-checkboxes))
  4162. ;; Align options lines
  4163. (setq-local
  4164. align-mode-rules-list
  4165. '((org-in-buffer-settings
  4166. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4167. (modes . '(org-mode)))))
  4168. ;; Make isearch reveal context
  4169. (setq-local outline-isearch-open-invisible-function
  4170. (lambda (&rest _) (org-show-context 'isearch)))
  4171. ;; Setup the pcomplete hooks
  4172. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4173. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4174. (setq-local pcomplete-default-completion-function #'ignore)
  4175. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4176. (setq-local pcomplete-termination-string "")
  4177. (add-hook 'completion-at-point-functions
  4178. #'pcomplete-completions-at-point nil t)
  4179. (setq-local buffer-face-mode-face 'org-default)
  4180. ;; If empty file that did not turn on Org mode automatically, make
  4181. ;; it to.
  4182. (when (and org-insert-mode-line-in-empty-file
  4183. (called-interactively-p 'any)
  4184. (= (point-min) (point-max)))
  4185. (insert "# -*- mode: org -*-\n\n"))
  4186. (unless org-inhibit-startup
  4187. (org-unmodified
  4188. (when org-startup-with-beamer-mode (org-beamer-mode))
  4189. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4190. (org-table-map-tables
  4191. (cond ((and org-startup-align-all-tables
  4192. org-startup-shrink-all-tables)
  4193. (lambda () (org-table-align) (org-table-shrink)))
  4194. (org-startup-align-all-tables #'org-table-align)
  4195. (t #'org-table-shrink))
  4196. t))
  4197. (when org-startup-with-inline-images (org-display-inline-images))
  4198. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4199. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4200. (when org-startup-truncated (setq truncate-lines t))
  4201. (when org-startup-numeroted (require 'org-num) (org-num-mode 1))
  4202. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4203. ;; Activate `org-table-header-line-mode'
  4204. (when org-table-header-line-p
  4205. (org-table-header-line-mode 1))
  4206. ;; Try to set `org-hide' face correctly.
  4207. (let ((foreground (org-find-invisible-foreground)))
  4208. (when foreground
  4209. (set-face-foreground 'org-hide foreground))))
  4210. ;; Update `customize-package-emacs-version-alist'
  4211. (add-to-list 'customize-package-emacs-version-alist
  4212. '(Org ("8.0" . "24.4")
  4213. ("8.1" . "24.4")
  4214. ("8.2" . "24.4")
  4215. ("8.2.7" . "24.4")
  4216. ("8.3" . "26.1")
  4217. ("9.0" . "26.1")
  4218. ("9.1" . "26.1")
  4219. ("9.2" . "27.1")
  4220. ("9.3" . "27.1")))
  4221. (defvar org-mode-transpose-word-syntax-table
  4222. (let ((st (make-syntax-table text-mode-syntax-table)))
  4223. (dolist (c org-emphasis-alist st)
  4224. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4225. (when (fboundp 'abbrev-table-put)
  4226. (abbrev-table-put org-mode-abbrev-table
  4227. :parents (list text-mode-abbrev-table)))
  4228. (defun org-find-invisible-foreground ()
  4229. (let ((candidates (remove
  4230. "unspecified-bg"
  4231. (nconc
  4232. (list (face-background 'default)
  4233. (face-background 'org-default))
  4234. (mapcar
  4235. (lambda (alist)
  4236. (when (boundp alist)
  4237. (cdr (assq 'background-color (symbol-value alist)))))
  4238. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4239. (list (face-foreground 'org-hide))))))
  4240. (car (remove nil candidates))))
  4241. (defun org-current-time (&optional rounding-minutes past)
  4242. "Current time, possibly rounded to ROUNDING-MINUTES.
  4243. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4244. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4245. the rounding returns a past time."
  4246. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4247. (car org-time-stamp-rounding-minutes)))
  4248. (now (current-time)))
  4249. (if (< r 1)
  4250. now
  4251. (let* ((time (decode-time now))
  4252. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4253. (nthcdr 2 time))))
  4254. (if (or (not past) (org-time-less-p res now))
  4255. res
  4256. (org-time-subtract res (* r 60)))))))
  4257. (defun org-today ()
  4258. "Return today date, considering `org-extend-today-until'."
  4259. (time-to-days
  4260. (org-time-since (* 3600 org-extend-today-until))))
  4261. ;;;; Font-Lock stuff, including the activators
  4262. (require 'font-lock)
  4263. (defconst org-match-sexp-depth 3
  4264. "Number of stacked braces for sub/superscript matching.")
  4265. (defun org-create-multibrace-regexp (left right n)
  4266. "Create a regular expression which will match a balanced sexp.
  4267. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4268. as single character strings.
  4269. The regexp returned will match the entire expression including the
  4270. delimiters. It will also define a single group which contains the
  4271. match except for the outermost delimiters. The maximum depth of
  4272. stacked delimiters is N. Escaping delimiters is not possible."
  4273. (let* ((nothing (concat "[^" left right "]*?"))
  4274. (or "\\|")
  4275. (re nothing)
  4276. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4277. (while (> n 1)
  4278. (setq n (1- n)
  4279. re (concat re or next)
  4280. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4281. (concat left "\\(" re "\\)" right)))
  4282. (defconst org-match-substring-regexp
  4283. (concat
  4284. "\\(\\S-\\)\\([_^]\\)\\("
  4285. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4286. "\\|"
  4287. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4288. "\\|"
  4289. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4290. "The regular expression matching a sub- or superscript.")
  4291. (defconst org-match-substring-with-braces-regexp
  4292. (concat
  4293. "\\(\\S-\\)\\([_^]\\)"
  4294. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4295. "The regular expression matching a sub- or superscript, forcing braces.")
  4296. (defvar org-emph-face nil)
  4297. (defun org-do-emphasis-faces (limit)
  4298. "Run through the buffer and emphasize strings."
  4299. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4300. (car org-emphasis-regexp-components))))
  4301. (catch :exit
  4302. (while (re-search-forward quick-re limit t)
  4303. (let* ((marker (match-string 2))
  4304. (verbatim? (member marker '("~" "="))))
  4305. (when (save-excursion
  4306. (goto-char (match-beginning 0))
  4307. (and
  4308. ;; Do not match table hlines.
  4309. (not (and (equal marker "+")
  4310. (org-match-line
  4311. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4312. ;; Do not match headline stars. Do not consider
  4313. ;; stars of a headline as closing marker for bold
  4314. ;; markup either.
  4315. (not (and (equal marker "*")
  4316. (save-excursion
  4317. (forward-char)
  4318. (skip-chars-backward "*")
  4319. (looking-at-p org-outline-regexp-bol))))
  4320. ;; Match full emphasis markup regexp.
  4321. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4322. ;; Do not span over paragraph boundaries.
  4323. (not (string-match-p org-element-paragraph-separate
  4324. (match-string 2)))
  4325. ;; Do not span over cells in table rows.
  4326. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4327. (string-match-p "|" (match-string 4))))))
  4328. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4329. (m (if org-hide-emphasis-markers 4 2)))
  4330. (font-lock-prepend-text-property
  4331. (match-beginning m) (match-end m) 'face face)
  4332. (when verbatim?
  4333. (org-remove-flyspell-overlays-in
  4334. (match-beginning 0) (match-end 0))
  4335. (remove-text-properties (match-beginning 2) (match-end 2)
  4336. '(display t invisible t intangible t)))
  4337. (add-text-properties (match-beginning 2) (match-end 2)
  4338. '(font-lock-multiline t org-emphasis t))
  4339. (when (and org-hide-emphasis-markers
  4340. (not (org-at-comment-p)))
  4341. (add-text-properties (match-end 4) (match-beginning 5)
  4342. '(invisible org-link))
  4343. (add-text-properties (match-beginning 3) (match-end 3)
  4344. '(invisible org-link)))
  4345. (throw :exit t))))))))
  4346. (defun org-emphasize (&optional char)
  4347. "Insert or change an emphasis, i.e. a font like bold or italic.
  4348. If there is an active region, change that region to a new emphasis.
  4349. If there is no region, just insert the marker characters and position
  4350. the cursor between them.
  4351. CHAR should be the marker character. If it is a space, it means to
  4352. remove the emphasis of the selected region.
  4353. If CHAR is not given (for example in an interactive call) it will be
  4354. prompted for."
  4355. (interactive)
  4356. (let ((erc org-emphasis-regexp-components)
  4357. (string "") beg end move s)
  4358. (if (org-region-active-p)
  4359. (setq beg (region-beginning)
  4360. end (region-end)
  4361. string (buffer-substring beg end))
  4362. (setq move t))
  4363. (unless char
  4364. (message "Emphasis marker or tag: [%s]"
  4365. (mapconcat #'car org-emphasis-alist ""))
  4366. (setq char (read-char-exclusive)))
  4367. (if (equal char ?\s)
  4368. (setq s ""
  4369. move nil)
  4370. (unless (assoc (char-to-string char) org-emphasis-alist)
  4371. (user-error "No such emphasis marker: \"%c\"" char))
  4372. (setq s (char-to-string char)))
  4373. (while (and (> (length string) 1)
  4374. (equal (substring string 0 1) (substring string -1))
  4375. (assoc (substring string 0 1) org-emphasis-alist))
  4376. (setq string (substring string 1 -1)))
  4377. (setq string (concat s string s))
  4378. (when beg (delete-region beg end))
  4379. (unless (or (bolp)
  4380. (string-match (concat "[" (nth 0 erc) "\n]")
  4381. (char-to-string (char-before (point)))))
  4382. (insert " "))
  4383. (unless (or (eobp)
  4384. (string-match (concat "[" (nth 1 erc) "\n]")
  4385. (char-to-string (char-after (point)))))
  4386. (insert " ") (backward-char 1))
  4387. (insert string)
  4388. (and move (backward-char 1))))
  4389. (defconst org-nonsticky-props
  4390. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4391. (defsubst org-rear-nonsticky-at (pos)
  4392. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4393. (defun org-activate-links (limit)
  4394. "Add link properties to links.
  4395. This includes angle, plain, and bracket links."
  4396. (catch :exit
  4397. (while (re-search-forward org-link-any-re limit t)
  4398. (let* ((start (match-beginning 0))
  4399. (end (match-end 0))
  4400. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4401. (visible-end (or (match-end 3) (match-end 2)))
  4402. (style (cond ((eq ?< (char-after start)) 'angle)
  4403. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4404. (t 'plain))))
  4405. (when (and (memq style org-highlight-links)
  4406. ;; Do not span over paragraph boundaries.
  4407. (not (string-match-p org-element-paragraph-separate
  4408. (match-string 0)))
  4409. ;; Do not confuse plain links with tags.
  4410. (not (and (eq style 'plain)
  4411. (let ((face (get-text-property
  4412. (max (1- start) (point-min)) 'face)))
  4413. (if (consp face) (memq 'org-tag face)
  4414. (eq 'org-tag face))))))
  4415. (let* ((link-object (save-excursion
  4416. (goto-char start)
  4417. (save-match-data (org-element-link-parser))))
  4418. (link (org-element-property :raw-link link-object))
  4419. (type (org-element-property :type link-object))
  4420. (path (org-element-property :path link-object))
  4421. (properties ;for link's visible part
  4422. (list
  4423. 'face (pcase (org-link-get-parameter type :face)
  4424. ((and (pred functionp) face) (funcall face path))
  4425. ((and (pred facep) face) face)
  4426. ((and (pred consp) face) face) ;anonymous
  4427. (_ 'org-link))
  4428. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4429. 'highlight)
  4430. 'keymap (or (org-link-get-parameter type :keymap)
  4431. org-mouse-map)
  4432. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4433. ((and (pred stringp) echo) echo)
  4434. ((and (pred functionp) echo) echo)
  4435. (_ (concat "LINK: " link)))
  4436. 'htmlize-link (pcase (org-link-get-parameter type
  4437. :htmlize-link)
  4438. ((and (pred functionp) f) (funcall f))
  4439. (_ `(:uri ,link)))
  4440. 'font-lock-multiline t)))
  4441. (org-remove-flyspell-overlays-in start end)
  4442. (org-rear-nonsticky-at end)
  4443. (if (not (eq 'bracket style))
  4444. (add-text-properties start end properties)
  4445. ;; Handle invisible parts in bracket links.
  4446. (remove-text-properties start end '(invisible nil))
  4447. (let ((hidden
  4448. (append `(invisible
  4449. ,(or (org-link-get-parameter type :display)
  4450. 'org-link))
  4451. properties)))
  4452. (add-text-properties start visible-start hidden)
  4453. (add-text-properties visible-start visible-end properties)
  4454. (add-text-properties visible-end end hidden)
  4455. (org-rear-nonsticky-at visible-start)
  4456. (org-rear-nonsticky-at visible-end)))
  4457. (let ((f (org-link-get-parameter type :activate-func)))
  4458. (when (functionp f)
  4459. (funcall f start end path (eq style 'bracket))))
  4460. (throw :exit t))))) ;signal success
  4461. nil))
  4462. (defun org-activate-code (limit)
  4463. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4464. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4465. (remove-text-properties (match-beginning 0) (match-end 0)
  4466. '(display t invisible t intangible t))
  4467. t))
  4468. (defcustom org-src-fontify-natively t
  4469. "When non-nil, fontify code in code blocks.
  4470. See also the `org-block' face."
  4471. :type 'boolean
  4472. :version "26.1"
  4473. :package-version '(Org . "8.3")
  4474. :group 'org-appearance
  4475. :group 'org-babel)
  4476. (defcustom org-allow-promoting-top-level-subtree nil
  4477. "When non-nil, allow promoting a top level subtree.
  4478. The leading star of the top level headline will be replaced
  4479. by a #."
  4480. :type 'boolean
  4481. :version "24.1"
  4482. :group 'org-appearance)
  4483. (defun org-fontify-meta-lines-and-blocks (limit)
  4484. (condition-case nil
  4485. (org-fontify-meta-lines-and-blocks-1 limit)
  4486. (error (message "Org mode fontification error in %S at %d"
  4487. (current-buffer)
  4488. (line-number-at-pos)))))
  4489. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4490. "Fontify #+ lines and blocks."
  4491. (let ((case-fold-search t))
  4492. (when (re-search-forward
  4493. (rx bol (group (zero-or-more blank) "#"
  4494. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4495. space
  4496. eol))
  4497. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4498. (zero-or-more blank)
  4499. (group (group (zero-or-more (not (any " \t\n"))))
  4500. (zero-or-more blank)
  4501. (group (zero-or-more any)))))
  4502. limit t)
  4503. (let ((beg (match-beginning 0))
  4504. (end-of-beginline (match-end 0))
  4505. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4506. (block-end nil) ; will include \n after end of block content
  4507. (lang (match-string 7)) ; the language, if it is an src block
  4508. (bol-after-beginline (line-beginning-position 2))
  4509. (dc1 (downcase (match-string 2)))
  4510. (dc3 (downcase (match-string 3)))
  4511. (whole-blockline org-fontify-whole-block-delimiter-line)
  4512. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4513. (cond
  4514. ((and (match-end 4) (equal dc3 "+begin"))
  4515. ;; Truly a block
  4516. (setq block-type (downcase (match-string 5))
  4517. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4518. (when (re-search-forward
  4519. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4520. (seq (zero-or-more blank)
  4521. "#+end"
  4522. ,(match-string 4)
  4523. word-end
  4524. (zero-or-more any)))))
  4525. nil t) ;; on purpose, we look further than LIMIT
  4526. ;; We do have a matching #+end line
  4527. (setq beg-of-endline (match-beginning 0)
  4528. end-of-endline (match-end 0)
  4529. nl-before-endline (1- (match-beginning 0)))
  4530. (setq block-end (match-beginning 0)) ; includes the final newline.
  4531. (when quoting
  4532. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4533. (remove-text-properties beg end-of-endline
  4534. '(display t invisible t intangible t)))
  4535. (add-text-properties
  4536. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4537. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4538. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4539. (cond
  4540. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4541. (org-src-font-lock-fontify-block lang block-start block-end)
  4542. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4543. (quoting
  4544. (add-text-properties
  4545. bol-after-beginline beg-of-endline
  4546. (list 'face
  4547. (list :inherit
  4548. (let ((face-name
  4549. (intern (format "org-block-%s" lang))))
  4550. (append (and (facep face-name) (list face-name))
  4551. '(org-block)))))))
  4552. ((not org-fontify-quote-and-verse-blocks))
  4553. ((string= block-type "quote")
  4554. (add-face-text-property
  4555. bol-after-beginline beg-of-endline 'org-quote t))
  4556. ((string= block-type "verse")
  4557. (add-face-text-property
  4558. bol-after-beginline beg-of-endline 'org-verse t)))
  4559. ;; Fontify the #+begin and #+end lines of the blocks
  4560. (add-text-properties
  4561. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4562. '(face org-block-begin-line))
  4563. (unless (string-prefix-p "*" (match-string 1))
  4564. (add-text-properties
  4565. beg-of-endline
  4566. (if whole-blockline
  4567. (let ((beg-of-next-line (1+ end-of-endline)))
  4568. (min (point-max) beg-of-next-line))
  4569. (min (point-max) end-of-endline))
  4570. '(face org-block-end-line)))
  4571. t))
  4572. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4573. (org-remove-flyspell-overlays-in
  4574. (match-beginning 0)
  4575. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4576. (add-text-properties
  4577. beg (match-end 3)
  4578. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4579. '(font-lock-fontified t invisible t)
  4580. '(font-lock-fontified t face org-document-info-keyword)))
  4581. (add-text-properties
  4582. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4583. (if (string-equal dc1 "+title:")
  4584. '(font-lock-fontified t face org-document-title)
  4585. '(font-lock-fontified t face org-document-info))))
  4586. ((string-prefix-p "+caption" dc1)
  4587. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4588. (remove-text-properties (match-beginning 0) (match-end 0)
  4589. '(display t invisible t intangible t))
  4590. ;; Handle short captions.
  4591. (save-excursion
  4592. (beginning-of-line)
  4593. (looking-at (rx (group (zero-or-more blank)
  4594. "#+caption"
  4595. (optional "[" (zero-or-more any) "]")
  4596. ":")
  4597. (zero-or-more blank))))
  4598. (add-text-properties (line-beginning-position) (match-end 1)
  4599. '(font-lock-fontified t face org-meta-line))
  4600. (add-text-properties (match-end 0) (line-end-position)
  4601. '(font-lock-fontified t face org-block))
  4602. t)
  4603. ((member dc3 '(" " ""))
  4604. ; Just a comment, the plus was not there
  4605. (org-remove-flyspell-overlays-in beg (match-end 0))
  4606. (add-text-properties
  4607. beg (match-end 0)
  4608. '(font-lock-fontified t face font-lock-comment-face)))
  4609. (t ;; just any other in-buffer setting, but not indented
  4610. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4611. (remove-text-properties (match-beginning 0) (match-end 0)
  4612. '(display t invisible t intangible t))
  4613. (add-text-properties beg (match-end 0)
  4614. '(font-lock-fontified t face org-meta-line))
  4615. t))))))
  4616. (defun org-fontify-drawers (limit)
  4617. "Fontify drawers."
  4618. (when (re-search-forward org-drawer-regexp limit t)
  4619. (add-text-properties
  4620. (line-beginning-position) (line-beginning-position 2)
  4621. '(font-lock-fontified t face org-drawer))
  4622. (org-remove-flyspell-overlays-in
  4623. (line-beginning-position) (line-beginning-position 2))
  4624. t))
  4625. (defun org-fontify-macros (limit)
  4626. "Fontify macros."
  4627. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4628. (let ((begin (match-beginning 0))
  4629. (opening-end (match-beginning 1)))
  4630. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4631. (match-string 1))
  4632. (let ((end (match-end 1))
  4633. (closing-start (match-beginning 1)))
  4634. (add-text-properties
  4635. begin end
  4636. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4637. (org-remove-flyspell-overlays-in begin end)
  4638. (when org-hide-macro-markers
  4639. (add-text-properties begin opening-end '(invisible t))
  4640. (add-text-properties closing-start end '(invisible t)))
  4641. t)))))
  4642. (defun org-fontify-extend-region (beg end _old-len)
  4643. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4644. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4645. (extend (lambda (r1 r2 dir)
  4646. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4647. (replace-regexp-in-string "[][]" r2
  4648. (match-string-no-properties 0)))))
  4649. (re-search-forward (regexp-quote re) nil t dir)))))
  4650. (save-match-data
  4651. (save-excursion
  4652. (goto-char beg)
  4653. (back-to-indentation)
  4654. (cond ((looking-at end-re)
  4655. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4656. ((looking-at begin-re)
  4657. (cons beg (or (funcall extend "end" "]" 1) end)))
  4658. (t (cons beg end)))))))
  4659. (defun org-activate-footnote-links (limit)
  4660. "Add text properties for footnotes."
  4661. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4662. (when fn
  4663. (let* ((beg (nth 1 fn))
  4664. (end (nth 2 fn))
  4665. (label (car fn))
  4666. (referencep (/= (line-beginning-position) beg)))
  4667. (when (and referencep (nth 3 fn))
  4668. (save-excursion
  4669. (goto-char beg)
  4670. (search-forward (or label "fn:"))
  4671. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4672. (add-text-properties beg end
  4673. (list 'mouse-face 'highlight
  4674. 'keymap org-mouse-map
  4675. 'help-echo
  4676. (if referencep "Footnote reference"
  4677. "Footnote definition")
  4678. 'font-lock-fontified t
  4679. 'font-lock-multiline t
  4680. 'face 'org-footnote))))))
  4681. (defun org-activate-dates (limit)
  4682. "Add text properties for dates."
  4683. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4684. (not (equal (char-before (match-beginning 0)) 91)))
  4685. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4686. (add-text-properties (match-beginning 0) (match-end 0)
  4687. (list 'mouse-face 'highlight
  4688. 'keymap org-mouse-map))
  4689. (org-rear-nonsticky-at (match-end 0))
  4690. (when org-display-custom-times
  4691. ;; If it's a date range, activate custom time for second date.
  4692. (when (match-end 3)
  4693. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4694. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4695. t))
  4696. (defun org-activate-target-links (limit)
  4697. "Add text properties for target matches."
  4698. (when org-target-link-regexp
  4699. (let ((case-fold-search t))
  4700. ;; `org-target-link-regexp' matches one character before the
  4701. ;; actual target.
  4702. (unless (bolp) (forward-char -1))
  4703. (when (re-search-forward org-target-link-regexp limit t)
  4704. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4705. (add-text-properties (match-beginning 1) (match-end 1)
  4706. (list 'mouse-face 'highlight
  4707. 'keymap org-mouse-map
  4708. 'help-echo "Radio target link"
  4709. 'org-linked-text t))
  4710. (org-rear-nonsticky-at (match-end 1))
  4711. t))))
  4712. (defvar org-latex-and-related-regexp nil
  4713. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4714. (defun org-compute-latex-and-related-regexp ()
  4715. "Compute regular expression for LaTeX, entities and sub/superscript.
  4716. Result depends on variable `org-highlight-latex-and-related'."
  4717. (let ((re-sub
  4718. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4719. ((eq org-use-sub-superscripts '{})
  4720. (list org-match-substring-with-braces-regexp))
  4721. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4722. (re-latex
  4723. (when (or (memq 'latex org-highlight-latex-and-related)
  4724. (memq 'native org-highlight-latex-and-related))
  4725. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4726. (delq nil
  4727. (mapcar (lambda (x)
  4728. (and (member (car x) matchers) (nth 1 x)))
  4729. org-latex-regexps)))))
  4730. (re-entities
  4731. (when (memq 'entities org-highlight-latex-and-related)
  4732. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4733. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4734. (setq-local org-latex-and-related-regexp
  4735. (mapconcat #'identity
  4736. (append re-latex re-entities re-sub)
  4737. "\\|"))))
  4738. (defun org-do-latex-and-related (_limit)
  4739. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4740. Stop at first highlighted object, if any. Return t if some
  4741. highlighting was done, nil otherwise."
  4742. (when (org-string-nw-p org-latex-and-related-regexp)
  4743. (catch 'found
  4744. (while (re-search-forward org-latex-and-related-regexp
  4745. nil t) ;; on purpose, we ignore LIMIT
  4746. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4747. org-special-keyword)))
  4748. (save-excursion
  4749. (goto-char (1+ (match-beginning 0)))
  4750. (face-at-point nil t)))
  4751. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4752. '(?_ ?^))
  4753. 1
  4754. 0))
  4755. (start (+ offset (match-beginning 0)))
  4756. (end (match-end 0)))
  4757. (if (memq 'native org-highlight-latex-and-related)
  4758. (org-src-font-lock-fontify-block "latex" start end)
  4759. (font-lock-prepend-text-property start end
  4760. 'face 'org-latex-and-related))
  4761. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4762. '(font-lock-multiline t)))
  4763. (throw 'found t)))
  4764. nil)))
  4765. (defun org-restart-font-lock ()
  4766. "Restart `font-lock-mode', to force refontification."
  4767. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4768. (font-lock-mode -1)
  4769. (font-lock-mode 1)))
  4770. (defun org-activate-tags (limit)
  4771. (when (re-search-forward org-tag-line-re limit t)
  4772. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4773. (add-text-properties (match-beginning 1) (match-end 1)
  4774. (list 'mouse-face 'highlight
  4775. 'keymap org-mouse-map))
  4776. (org-rear-nonsticky-at (match-end 1))
  4777. t))
  4778. (defun org-outline-level ()
  4779. "Compute the outline level of the heading at point.
  4780. If this is called at a normal headline, the level is the number
  4781. of stars. Use `org-reduced-level' to remove the effect of
  4782. `org-odd-levels'. Unlike to `org-current-level', this function
  4783. takes into consideration inlinetasks."
  4784. (org-with-wide-buffer
  4785. (end-of-line)
  4786. (if (re-search-backward org-outline-regexp-bol nil t)
  4787. (1- (- (match-end 0) (match-beginning 0)))
  4788. 0)))
  4789. (defvar org-font-lock-keywords nil)
  4790. (defsubst org-re-property (property &optional literal allow-null value)
  4791. "Return a regexp matching a PROPERTY line.
  4792. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4793. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4794. non-nil, match properties even without a value.
  4795. Match group 3 is set to the value when it exists. If there is no
  4796. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4797. With optional argument VALUE, match only property lines with
  4798. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4799. unless LITERAL is non-nil."
  4800. (concat
  4801. "^\\(?4:[ \t]*\\)"
  4802. (format "\\(?1::\\(?2:%s\\):\\)"
  4803. (if literal property (regexp-quote property)))
  4804. (cond (value
  4805. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4806. (if literal value (regexp-quote value))))
  4807. (allow-null
  4808. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4809. (t
  4810. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4811. (defconst org-property-re
  4812. (org-re-property "\\S-+" 'literal t)
  4813. "Regular expression matching a property line.
  4814. There are four matching groups:
  4815. 1: :PROPKEY: including the leading and trailing colon,
  4816. 2: PROPKEY without the leading and trailing colon,
  4817. 3: PROPVAL without leading or trailing spaces,
  4818. 4: the indentation of the current line,
  4819. 5: trailing whitespace.")
  4820. (defvar org-font-lock-hook nil
  4821. "Functions to be called for special font lock stuff.")
  4822. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4823. (defvar org-font-lock-set-keywords-hook nil
  4824. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4825. This is called after `org-font-lock-extra-keywords' is defined, but before
  4826. it is installed to be used by font lock. This can be useful if something
  4827. needs to be inserted at a specific position in the font-lock sequence.")
  4828. (defun org-font-lock-hook (limit)
  4829. "Run `org-font-lock-hook' within LIMIT."
  4830. (run-hook-with-args 'org-font-lock-hook limit))
  4831. (defun org-set-font-lock-defaults ()
  4832. "Set font lock defaults for the current buffer."
  4833. (let* ((em org-fontify-emphasized-text)
  4834. (lk org-highlight-links)
  4835. (org-font-lock-extra-keywords
  4836. (list
  4837. ;; Call the hook
  4838. '(org-font-lock-hook)
  4839. ;; Headlines
  4840. `(,(if org-fontify-whole-heading-line
  4841. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4842. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4843. (1 (org-get-level-face 1))
  4844. (2 (org-get-level-face 2))
  4845. (3 (org-get-level-face 3)))
  4846. ;; Table lines
  4847. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4848. (1 'org-table t))
  4849. ;; Table internals
  4850. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4851. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4852. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4853. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4854. ;; Properties
  4855. (list org-property-re
  4856. '(1 'org-special-keyword t)
  4857. '(3 'org-property-value t))
  4858. ;; Drawers
  4859. '(org-fontify-drawers)
  4860. ;; Link related fontification.
  4861. '(org-activate-links)
  4862. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4863. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4864. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4865. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4866. ;; Targets.
  4867. (list org-radio-target-regexp '(0 'org-target t))
  4868. (list org-target-regexp '(0 'org-target t))
  4869. ;; Diary sexps.
  4870. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4871. ;; Macro
  4872. '(org-fontify-macros)
  4873. ;; TODO keyword
  4874. (list (format org-heading-keyword-regexp-format
  4875. org-todo-regexp)
  4876. '(2 (org-get-todo-face 2) t))
  4877. ;; TODO
  4878. (when org-fontify-todo-headline
  4879. (list (format org-heading-keyword-regexp-format
  4880. (concat
  4881. "\\(?:"
  4882. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4883. "\\)"))
  4884. '(2 'org-headline-todo t)))
  4885. ;; DONE
  4886. (when org-fontify-done-headline
  4887. (list (format org-heading-keyword-regexp-format
  4888. (concat
  4889. "\\(?:"
  4890. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4891. "\\)"))
  4892. '(2 'org-headline-done t)))
  4893. ;; Priorities
  4894. '(org-font-lock-add-priority-faces)
  4895. ;; Tags
  4896. '(org-font-lock-add-tag-faces)
  4897. ;; Tags groups
  4898. (when (and org-group-tags org-tag-groups-alist)
  4899. (list (concat org-outline-regexp-bol ".+\\(:"
  4900. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4901. ":\\).*$")
  4902. '(1 'org-tag-group prepend)))
  4903. ;; Special keywords
  4904. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4905. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4906. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4907. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4908. ;; Emphasis
  4909. (when em '(org-do-emphasis-faces))
  4910. ;; Checkboxes
  4911. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4912. 1 'org-checkbox prepend)
  4913. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4914. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4915. (0 (org-get-checkbox-statistics-face) t)))
  4916. ;; Description list items
  4917. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4918. 1 'org-list-dt prepend)
  4919. ;; ARCHIVEd headings
  4920. (list (concat
  4921. org-outline-regexp-bol
  4922. "\\(.*:" org-archive-tag ":.*\\)")
  4923. '(1 'org-archived prepend))
  4924. ;; Specials
  4925. '(org-do-latex-and-related)
  4926. '(org-fontify-entities)
  4927. '(org-raise-scripts)
  4928. ;; Code
  4929. '(org-activate-code (1 'org-code t))
  4930. ;; COMMENT
  4931. (list (format
  4932. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  4933. org-todo-regexp
  4934. org-comment-string)
  4935. '(9 'org-special-keyword t))
  4936. ;; Blocks and meta lines
  4937. '(org-fontify-meta-lines-and-blocks))))
  4938. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  4939. (run-hooks 'org-font-lock-set-keywords-hook)
  4940. ;; Now set the full font-lock-keywords
  4941. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  4942. (setq-local font-lock-defaults
  4943. '(org-font-lock-keywords t nil nil backward-paragraph))
  4944. (setq-local font-lock-extend-after-change-region-function
  4945. #'org-fontify-extend-region)
  4946. (kill-local-variable 'font-lock-keywords)
  4947. nil))
  4948. (defun org-toggle-pretty-entities ()
  4949. "Toggle the composition display of entities as UTF8 characters."
  4950. (interactive)
  4951. (setq-local org-pretty-entities (not org-pretty-entities))
  4952. (org-restart-font-lock)
  4953. (if org-pretty-entities
  4954. (message "Entities are now displayed as UTF8 characters")
  4955. (save-restriction
  4956. (widen)
  4957. (decompose-region (point-min) (point-max))
  4958. (message "Entities are now displayed as plain text"))))
  4959. (defvar-local org-custom-properties-overlays nil
  4960. "List of overlays used for custom properties.")
  4961. (defun org-toggle-custom-properties-visibility ()
  4962. "Display or hide properties in `org-custom-properties'."
  4963. (interactive)
  4964. (if org-custom-properties-overlays
  4965. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  4966. (setq org-custom-properties-overlays nil))
  4967. (when org-custom-properties
  4968. (org-with-wide-buffer
  4969. (goto-char (point-min))
  4970. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  4971. (while (re-search-forward regexp nil t)
  4972. (let ((end (cdr (save-match-data (org-get-property-block)))))
  4973. (when (and end (< (point) end))
  4974. ;; Hide first custom property in current drawer.
  4975. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  4976. (overlay-put o 'invisible t)
  4977. (overlay-put o 'org-custom-property t)
  4978. (push o org-custom-properties-overlays))
  4979. ;; Hide additional custom properties in the same drawer.
  4980. (while (re-search-forward regexp end t)
  4981. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  4982. (overlay-put o 'invisible t)
  4983. (overlay-put o 'org-custom-property t)
  4984. (push o org-custom-properties-overlays)))))
  4985. ;; Each entry is limited to a single property drawer.
  4986. (outline-next-heading)))))))
  4987. (defun org-fontify-entities (limit)
  4988. "Find an entity to fontify."
  4989. (let (ee)
  4990. (when org-pretty-entities
  4991. (catch 'match
  4992. ;; "\_ "-family is left out on purpose. Only the first one,
  4993. ;; i.e., "\_ ", could be fontified anyway, and it would be
  4994. ;; confusing when adding a second white space character.
  4995. (while (re-search-forward
  4996. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  4997. limit t)
  4998. (when (and (not (org-at-comment-p))
  4999. (setq ee (org-entity-get (match-string 1)))
  5000. (= (length (nth 6 ee)) 1))
  5001. (let* ((end (if (equal (match-string 2) "{}")
  5002. (match-end 2)
  5003. (match-end 1))))
  5004. (add-text-properties
  5005. (match-beginning 0) end
  5006. (list 'font-lock-fontified t))
  5007. (compose-region (match-beginning 0) end
  5008. (nth 6 ee) nil)
  5009. (backward-char 1)
  5010. (throw 'match t))))
  5011. nil))))
  5012. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5013. "Fontify string S like in Org mode."
  5014. (with-temp-buffer
  5015. (insert s)
  5016. (let ((org-odd-levels-only odd-levels))
  5017. (org-mode)
  5018. (org-font-lock-ensure)
  5019. (buffer-string))))
  5020. (defun org-get-level-face (n)
  5021. "Get the right face for match N in font-lock matching of headlines."
  5022. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5023. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5024. (org-f (if org-cycle-level-faces
  5025. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5026. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5027. (cond
  5028. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5029. ((eq n 2) org-f)
  5030. (t (unless org-level-color-stars-only org-f)))))
  5031. (defun org-face-from-face-or-color (context inherit face-or-color)
  5032. "Create a face list that inherits INHERIT, but sets the foreground color.
  5033. When FACE-OR-COLOR is not a string, just return it."
  5034. (if (stringp face-or-color)
  5035. (list :inherit inherit
  5036. (cdr (assoc context org-faces-easy-properties))
  5037. face-or-color)
  5038. face-or-color))
  5039. (defun org-get-todo-face (kwd)
  5040. "Get the right face for a TODO keyword KWD.
  5041. If KWD is a number, get the corresponding match group."
  5042. (when (numberp kwd) (setq kwd (match-string kwd)))
  5043. (or (org-face-from-face-or-color
  5044. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5045. (and (member kwd org-done-keywords) 'org-done)
  5046. 'org-todo))
  5047. (defun org-get-priority-face (priority)
  5048. "Get the right face for PRIORITY.
  5049. PRIORITY is a character."
  5050. (or (org-face-from-face-or-color
  5051. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5052. 'org-priority))
  5053. (defun org-get-tag-face (tag)
  5054. "Get the right face for TAG.
  5055. If TAG is a number, get the corresponding match group."
  5056. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5057. (or (org-face-from-face-or-color
  5058. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5059. 'org-tag)))
  5060. (defvar org-priority-regexp) ; defined later in the file
  5061. (defun org-font-lock-add-priority-faces (limit)
  5062. "Add the special priority faces."
  5063. (while (re-search-forward org-priority-regexp limit t)
  5064. (add-text-properties
  5065. (match-beginning 1) (match-end 1)
  5066. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5067. 'font-lock-fontified t))))
  5068. (defun org-font-lock-add-tag-faces (limit)
  5069. "Add the special tag faces."
  5070. (when (and org-tag-faces org-tags-special-faces-re)
  5071. (while (re-search-forward org-tags-special-faces-re limit t)
  5072. (add-text-properties (match-beginning 1) (match-end 1)
  5073. (list 'face (org-get-tag-face 1)
  5074. 'font-lock-fontified t))
  5075. (backward-char 1))))
  5076. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5077. "Remove fontification and activation overlays from links."
  5078. (font-lock-default-unfontify-region beg end)
  5079. (let* ((buffer-undo-list t)
  5080. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5081. (inhibit-modification-hooks t)
  5082. deactivate-mark buffer-file-name buffer-file-truename)
  5083. (decompose-region beg end)
  5084. (remove-text-properties beg end
  5085. '(mouse-face t keymap t org-linked-text t
  5086. invisible t intangible t
  5087. org-emphasis t))
  5088. (org-remove-font-lock-display-properties beg end)))
  5089. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5090. ((raise 0.3) (height 0.7))
  5091. ((raise -0.5))
  5092. ((raise 0.5)))
  5093. "Display properties for showing superscripts and subscripts.")
  5094. (defun org-remove-font-lock-display-properties (beg end)
  5095. "Remove specific display properties that have been added by font lock.
  5096. The will remove the raise properties that are used to show superscripts
  5097. and subscripts."
  5098. (let (next prop)
  5099. (while (< beg end)
  5100. (setq next (next-single-property-change beg 'display nil end)
  5101. prop (get-text-property beg 'display))
  5102. (when (member prop org-script-display)
  5103. (put-text-property beg next 'display nil))
  5104. (setq beg next))))
  5105. (defun org-raise-scripts (limit)
  5106. "Add raise properties to sub/superscripts."
  5107. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5108. (re-search-forward
  5109. (if (eq org-use-sub-superscripts t)
  5110. org-match-substring-regexp
  5111. org-match-substring-with-braces-regexp)
  5112. limit t))
  5113. (let* ((pos (point)) table-p comment-p
  5114. (mpos (match-beginning 3))
  5115. (emph-p (get-text-property mpos 'org-emphasis))
  5116. (link-p (get-text-property mpos 'mouse-face))
  5117. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5118. (goto-char (point-at-bol))
  5119. (setq table-p (looking-at-p org-table-dataline-regexp)
  5120. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5121. (goto-char pos)
  5122. ;; Handle a_b^c
  5123. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5124. (unless (or comment-p emph-p link-p keyw-p)
  5125. (put-text-property (match-beginning 3) (match-end 0)
  5126. 'display
  5127. (if (equal (char-after (match-beginning 2)) ?^)
  5128. (nth (if table-p 3 1) org-script-display)
  5129. (nth (if table-p 2 0) org-script-display)))
  5130. (add-text-properties (match-beginning 2) (match-end 2)
  5131. (list 'invisible t))
  5132. (when (and (eq (char-after (match-beginning 3)) ?{)
  5133. (eq (char-before (match-end 3)) ?}))
  5134. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5135. (list 'invisible t))
  5136. (add-text-properties (1- (match-end 3)) (match-end 3)
  5137. (list 'invisible t))))
  5138. t)))
  5139. (defun org-remove-empty-overlays-at (pos)
  5140. "Remove outline overlays that do not contain non-white stuff."
  5141. (dolist (o (overlays-at pos))
  5142. (and (eq 'outline (overlay-get o 'invisible))
  5143. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5144. (overlay-end o))))
  5145. (delete-overlay o))))
  5146. (defun org-show-empty-lines-in-parent ()
  5147. "Move to the parent and re-show empty lines before visible headlines."
  5148. (save-excursion
  5149. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5150. (org-cycle-show-empty-lines context))))
  5151. (defun org-files-list ()
  5152. "Return `org-agenda-files' list, plus all open Org files.
  5153. This is useful for operations that need to scan all of a user's
  5154. open and agenda-wise Org files."
  5155. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5156. (dolist (buf (buffer-list))
  5157. (with-current-buffer buf
  5158. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5159. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5160. :test #'equal))))
  5161. files))
  5162. (defsubst org-entry-beginning-position ()
  5163. "Return the beginning position of the current entry."
  5164. (save-excursion (org-back-to-heading t) (point)))
  5165. (defsubst org-entry-end-position ()
  5166. "Return the end position of the current entry."
  5167. (save-excursion (outline-next-heading) (point)))
  5168. (defun org-subtree-end-visible-p ()
  5169. "Is the end of the current subtree visible?"
  5170. (pos-visible-in-window-p
  5171. (save-excursion (org-end-of-subtree t) (point))))
  5172. (defun org-first-headline-recenter ()
  5173. "Move cursor to the first headline and recenter the headline."
  5174. (let ((window (get-buffer-window)))
  5175. (when window
  5176. (goto-char (point-min))
  5177. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5178. (set-window-start window (line-beginning-position))))))
  5179. ;;; Visibility (headlines, blocks, drawers)
  5180. ;;;; Headlines visibility
  5181. (defun org-show-entry ()
  5182. "Show the body directly following this heading.
  5183. Show the heading too, if it is currently invisible."
  5184. (interactive)
  5185. (save-excursion
  5186. (ignore-errors
  5187. (org-back-to-heading t)
  5188. (org-flag-region
  5189. (line-end-position 0)
  5190. (save-excursion
  5191. (if (re-search-forward
  5192. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5193. (match-beginning 1)
  5194. (point-max)))
  5195. nil
  5196. 'outline))))
  5197. (defun org-show-children (&optional level)
  5198. "Show all direct subheadings of this heading.
  5199. Prefix arg LEVEL is how many levels below the current level
  5200. should be shown. Default is enough to cause the following
  5201. heading to appear."
  5202. (interactive "p")
  5203. (save-excursion
  5204. (org-back-to-heading t)
  5205. (let* ((current-level (funcall outline-level))
  5206. (max-level (org-get-valid-level
  5207. current-level
  5208. (if level (prefix-numeric-value level) 1)))
  5209. (end (save-excursion (org-end-of-subtree t t)))
  5210. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5211. (past-first-child nil)
  5212. ;; Make sure to skip inlinetasks.
  5213. (re (format regexp-fmt
  5214. current-level
  5215. (cond
  5216. ((not (featurep 'org-inlinetask)) "")
  5217. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5218. 3))
  5219. (t (1- org-inlinetask-min-level))))))
  5220. ;; Display parent heading.
  5221. (org-flag-heading nil)
  5222. (forward-line)
  5223. ;; Display children. First child may be deeper than expected
  5224. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5225. ;; MAX-LEVEL accordingly.
  5226. (while (re-search-forward re end t)
  5227. (unless past-first-child
  5228. (setq re (format regexp-fmt
  5229. current-level
  5230. (max (funcall outline-level) max-level)))
  5231. (setq past-first-child t))
  5232. (org-flag-heading nil)))))
  5233. (defun org-show-subtree ()
  5234. "Show everything after this heading at deeper levels."
  5235. (interactive)
  5236. (org-flag-region
  5237. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5238. ;;;; Blocks visibility
  5239. (defun org-hide-block-toggle-maybe ()
  5240. "Toggle visibility of block at point.
  5241. Unlike to `org-hide-block-toggle', this function does not throw
  5242. an error. Return a non-nil value when toggling is successful."
  5243. (interactive)
  5244. (ignore-errors (org-hide-block-toggle)))
  5245. (defun org-hide-block-toggle (&optional force)
  5246. "Toggle the visibility of the current block.
  5247. When optional argument FORCE is `off', make block visible. If it
  5248. is non-nil, hide it unconditionally. Throw an error when not at
  5249. a block. Return a non-nil value when toggling is successful."
  5250. (interactive)
  5251. (let ((element (org-element-at-point)))
  5252. (unless (memq (org-element-type element)
  5253. '(center-block comment-block dynamic-block example-block
  5254. export-block quote-block special-block
  5255. src-block verse-block))
  5256. (user-error "Not at a block"))
  5257. (let* ((post (org-element-property :post-affiliated element))
  5258. (start (save-excursion
  5259. (goto-char post)
  5260. (line-end-position)))
  5261. (end (save-excursion
  5262. (goto-char (org-element-property :end element))
  5263. (skip-chars-backward " \t\n")
  5264. (line-end-position))))
  5265. ;; Do nothing when not before or at the block opening line or at
  5266. ;; the block closing line.
  5267. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5268. (cond ((eq force 'off)
  5269. (org-flag-region start end nil 'org-hide-block))
  5270. (force
  5271. (org-flag-region start end t 'org-hide-block))
  5272. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5273. (org-flag-region start end nil 'org-hide-block))
  5274. (t
  5275. (org-flag-region start end t 'org-hide-block)))
  5276. ;; When the block is hidden away, make sure point is left in
  5277. ;; a visible part of the buffer.
  5278. (when (invisible-p (max (1- (point)) (point-min)))
  5279. (goto-char post))
  5280. ;; Signal success.
  5281. t))))
  5282. (defun org-hide-block-toggle-all ()
  5283. "Toggle the visibility of all blocks in the current buffer."
  5284. (org-block-map 'org-hide-block-toggle))
  5285. (defun org-hide-block-all ()
  5286. "Fold all blocks in the current buffer."
  5287. (interactive)
  5288. (org-show-all '(blocks))
  5289. (org-block-map 'org-hide-block-toggle-maybe))
  5290. ;;;; Drawers visibility
  5291. (defun org-cycle-hide-drawers (state &optional exceptions)
  5292. "Re-hide all drawers after a visibility state change.
  5293. STATE should be one of the symbols listed in the docstring of
  5294. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5295. a list of strings specifying which drawers should not be hidden."
  5296. (when (and (derived-mode-p 'org-mode)
  5297. (not (memq state '(overview folded contents))))
  5298. (save-excursion
  5299. (let* ((globalp (eq state 'all))
  5300. (beg (if globalp (point-min) (point)))
  5301. (end (if globalp (point-max)
  5302. (if (eq state 'children)
  5303. (save-excursion (outline-next-heading) (point))
  5304. (org-end-of-subtree t)))))
  5305. (goto-char beg)
  5306. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5307. (unless (member-ignore-case (match-string 1) exceptions)
  5308. (let ((drawer (org-element-at-point)))
  5309. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5310. (org-flag-drawer t drawer)
  5311. ;; Make sure to skip drawer entirely or we might flag
  5312. ;; it another time when matching its ending line with
  5313. ;; `org-drawer-regexp'.
  5314. (goto-char (org-element-property :end drawer))))))))))
  5315. (defun org-flag-drawer (flag &optional element beg end)
  5316. "When FLAG is non-nil, hide the drawer we are at.
  5317. Otherwise make it visible.
  5318. When optional argument ELEMENT is a parsed drawer, as returned by
  5319. `org-element-at-point', hide or show that drawer instead.
  5320. When buffer positions BEG and END are provided, hide or show that
  5321. region as a drawer without further ado."
  5322. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5323. (let ((drawer (or element
  5324. (and (save-excursion
  5325. (beginning-of-line)
  5326. (looking-at-p org-drawer-regexp))
  5327. (org-element-at-point)))))
  5328. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5329. (let ((post (org-element-property :post-affiliated drawer)))
  5330. (org-flag-region
  5331. (save-excursion (goto-char post) (line-end-position))
  5332. (save-excursion (goto-char (org-element-property :end drawer))
  5333. (skip-chars-backward " \t\n")
  5334. (line-end-position))
  5335. flag 'org-hide-drawer)
  5336. ;; When the drawer is hidden away, make sure point lies in
  5337. ;; a visible part of the buffer.
  5338. (when (invisible-p (max (1- (point)) (point-min)))
  5339. (goto-char post)))))))
  5340. ;;;; Visibility cycling
  5341. (defvar-local org-cycle-global-status nil)
  5342. (put 'org-cycle-global-status 'org-state t)
  5343. (defvar-local org-cycle-subtree-status nil)
  5344. (put 'org-cycle-subtree-status 'org-state t)
  5345. (defun org-show-all (&optional types)
  5346. "Show all contents in the visible part of the buffer.
  5347. By default, the function expands headings, blocks and drawers.
  5348. When optional argument TYPE is a list of symbols among `blocks',
  5349. `drawers' and `headings', to only expand one specific type."
  5350. (interactive)
  5351. (dolist (type (or types '(blocks drawers headings)))
  5352. (org-flag-region (point-min) (point-max) nil
  5353. (pcase type
  5354. (`blocks 'org-hide-block)
  5355. (`drawers 'org-hide-drawer)
  5356. (`headings 'outline)
  5357. (_ (error "Invalid type: %S" type))))))
  5358. ;;;###autoload
  5359. (defun org-cycle (&optional arg)
  5360. "TAB-action and visibility cycling for Org mode.
  5361. This is the command invoked in Org mode by the `TAB' key. Its main
  5362. purpose is outline visibility cycling, but it also invokes other actions
  5363. in special contexts.
  5364. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5365. the entire
  5366. buffer through 3 states (global cycling)
  5367. 1. OVERVIEW: Show only top-level headlines.
  5368. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5369. 3. SHOW ALL: Show everything.
  5370. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5371. switch to the startup visibility,
  5372. determined by the variable `org-startup-folded', and by any VISIBILITY
  5373. properties in the buffer.
  5374. With a `\\[universal-argument] \\[universal-argument] \
  5375. \\[universal-argument]' prefix argument, show the entire buffer, including
  5376. any drawers.
  5377. When inside a table, re-align the table and move to the next field.
  5378. When point is at the beginning of a headline, rotate the subtree started
  5379. by this line through 3 different states (local cycling)
  5380. 1. FOLDED: Only the main headline is shown.
  5381. 2. CHILDREN: The main headline and the direct children are shown.
  5382. From this state, you can move to one of the children
  5383. and zoom in further.
  5384. 3. SUBTREE: Show the entire subtree, including body text.
  5385. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5386. When point is at the beginning of an empty headline and the variable
  5387. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5388. of the headline by demoting and promoting it to likely levels. This
  5389. speeds up creation document structure by pressing `TAB' once or several
  5390. times right after creating a new headline.
  5391. When there is a numeric prefix, go up to a heading with level ARG, do
  5392. a `show-subtree' and return to the previous cursor position. If ARG
  5393. is negative, go up that many levels.
  5394. When point is not at the beginning of a headline, execute the global
  5395. binding for `TAB', which is re-indenting the line. See the option
  5396. `org-cycle-emulate-tab' for details.
  5397. As a special case, if point is at the beginning of the buffer and there is
  5398. no headline in line 1, this function will act as if called with prefix arg
  5399. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5400. prefix arg, but only
  5401. if the variable `org-cycle-global-at-bob' is t."
  5402. (interactive "P")
  5403. (org-load-modules-maybe)
  5404. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5405. (and org-cycle-level-after-item/entry-creation
  5406. (or (org-cycle-level)
  5407. (org-cycle-item-indentation))))
  5408. (let* ((limit-level
  5409. (or org-cycle-max-level
  5410. (and (boundp 'org-inlinetask-min-level)
  5411. org-inlinetask-min-level
  5412. (1- org-inlinetask-min-level))))
  5413. (nstars (and limit-level
  5414. (if org-odd-levels-only
  5415. (and limit-level (1- (* limit-level 2)))
  5416. limit-level)))
  5417. (org-outline-regexp
  5418. (if (not (derived-mode-p 'org-mode))
  5419. outline-regexp
  5420. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5421. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5422. (not (looking-at org-outline-regexp))))
  5423. (org-cycle-hook
  5424. (if bob-special
  5425. (delq 'org-optimize-window-after-visibility-change
  5426. (copy-sequence org-cycle-hook))
  5427. org-cycle-hook))
  5428. (pos (point)))
  5429. (cond
  5430. ((equal arg '(16))
  5431. (setq last-command 'dummy)
  5432. (org-set-startup-visibility)
  5433. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5434. ((equal arg '(64))
  5435. (org-show-all)
  5436. (org-unlogged-message "Entire buffer visible, including drawers"))
  5437. ((equal arg '(4)) (org-cycle-internal-global))
  5438. ;; Try hiding block at point.
  5439. ((org-hide-block-toggle-maybe))
  5440. ;; Try cdlatex TAB completion
  5441. ((org-try-cdlatex-tab))
  5442. ;; Table: enter it or move to the next field.
  5443. ((org-at-table-p 'any)
  5444. (if (org-at-table.el-p)
  5445. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5446. Use `\\[org-edit-special]' to edit table.el tables"))
  5447. (if arg (org-table-edit-field t)
  5448. (org-table-justify-field-maybe)
  5449. (call-interactively 'org-table-next-field))))
  5450. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5451. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5452. (bob-special (org-cycle-internal-global))
  5453. ;; Drawers: delegate to `org-flag-drawer'.
  5454. ((save-excursion
  5455. (beginning-of-line 1)
  5456. (looking-at org-drawer-regexp))
  5457. (org-flag-drawer ; toggle block visibility
  5458. (not (get-char-property (match-end 0) 'invisible))))
  5459. ;; Show-subtree, ARG levels up from here.
  5460. ((integerp arg)
  5461. (save-excursion
  5462. (org-back-to-heading)
  5463. (outline-up-heading (if (< arg 0) (- arg)
  5464. (- (funcall outline-level) arg)))
  5465. (org-show-subtree)))
  5466. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5467. ((and (featurep 'org-inlinetask)
  5468. (org-inlinetask-at-task-p)
  5469. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5470. (org-inlinetask-toggle-visibility))
  5471. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5472. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5473. (save-excursion (move-beginning-of-line 1)
  5474. (looking-at org-outline-regexp)))
  5475. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5476. (org-cycle-internal-local))
  5477. ;; From there: TAB emulation and template completion.
  5478. (buffer-read-only (org-back-to-heading))
  5479. ((run-hook-with-args-until-success
  5480. 'org-tab-after-check-for-cycling-hook))
  5481. ((run-hook-with-args-until-success
  5482. 'org-tab-before-tab-emulation-hook))
  5483. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5484. (or (not (bolp))
  5485. (not (looking-at org-outline-regexp))))
  5486. (call-interactively (global-key-binding "\t")))
  5487. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5488. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5489. (or (and (eq org-cycle-emulate-tab 'white)
  5490. (= (match-end 0) (point-at-eol)))
  5491. (and (eq org-cycle-emulate-tab 'whitestart)
  5492. (>= (match-end 0) pos))))
  5493. t
  5494. (eq org-cycle-emulate-tab t))
  5495. (call-interactively (global-key-binding "\t")))
  5496. (t (save-excursion
  5497. (org-back-to-heading)
  5498. (org-cycle)))))))
  5499. (defun org-cycle-internal-global ()
  5500. "Do the global cycling action."
  5501. ;; Hack to avoid display of messages for .org attachments in Gnus
  5502. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5503. (cond
  5504. ((and (eq last-command this-command)
  5505. (eq org-cycle-global-status 'overview))
  5506. ;; We just created the overview - now do table of contents
  5507. ;; This can be slow in very large buffers, so indicate action
  5508. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5509. (unless ga (org-unlogged-message "CONTENTS..."))
  5510. (org-content)
  5511. (unless ga (org-unlogged-message "CONTENTS...done"))
  5512. (setq org-cycle-global-status 'contents)
  5513. (run-hook-with-args 'org-cycle-hook 'contents))
  5514. ((and (eq last-command this-command)
  5515. (eq org-cycle-global-status 'contents))
  5516. ;; We just showed the table of contents - now show everything
  5517. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5518. (org-show-all '(headings blocks))
  5519. (unless ga (org-unlogged-message "SHOW ALL"))
  5520. (setq org-cycle-global-status 'all)
  5521. (run-hook-with-args 'org-cycle-hook 'all))
  5522. (t
  5523. ;; Default action: go to overview
  5524. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5525. (org-overview)
  5526. (unless ga (org-unlogged-message "OVERVIEW"))
  5527. (setq org-cycle-global-status 'overview)
  5528. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5529. (defvar org-called-with-limited-levels nil
  5530. "Non-nil when `org-with-limited-levels' is currently active.")
  5531. (defun org-cycle-internal-local ()
  5532. "Do the local cycling action."
  5533. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5534. ;; First, determine end of headline (EOH), end of subtree or item
  5535. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5536. (save-excursion
  5537. (if (org-at-item-p)
  5538. (progn
  5539. (beginning-of-line)
  5540. (setq struct (org-list-struct))
  5541. (setq eoh (point-at-eol))
  5542. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5543. (setq has-children (org-list-has-child-p (point) struct)))
  5544. (org-back-to-heading)
  5545. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5546. (setq eos (save-excursion (org-end-of-subtree t t)
  5547. (when (bolp) (backward-char)) (point)))
  5548. (setq has-children
  5549. (or
  5550. (save-excursion
  5551. (let ((level (funcall outline-level)))
  5552. (outline-next-heading)
  5553. (and (org-at-heading-p t)
  5554. (> (funcall outline-level) level))))
  5555. (and (eq org-cycle-include-plain-lists 'integrate)
  5556. (save-excursion
  5557. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5558. ;; Determine end invisible part of buffer (EOL)
  5559. (beginning-of-line 2)
  5560. (while (and (not (eobp)) ;This is like `next-line'.
  5561. (get-char-property (1- (point)) 'invisible))
  5562. (goto-char (next-single-char-property-change (point) 'invisible))
  5563. (and (eolp) (beginning-of-line 2)))
  5564. (setq eol (point)))
  5565. ;; Find out what to do next and set `this-command'
  5566. (cond
  5567. ((= eos eoh)
  5568. ;; Nothing is hidden behind this heading
  5569. (unless (org-before-first-heading-p)
  5570. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5571. (org-unlogged-message "EMPTY ENTRY")
  5572. (setq org-cycle-subtree-status nil)
  5573. (save-excursion
  5574. (goto-char eos)
  5575. (outline-next-heading)
  5576. (when (org-invisible-p) (org-flag-heading nil))))
  5577. ((and (or (>= eol eos)
  5578. (not (string-match "\\S-" (buffer-substring eol eos))))
  5579. (or has-children
  5580. (not (setq children-skipped
  5581. org-cycle-skip-children-state-if-no-children))))
  5582. ;; Entire subtree is hidden in one line: children view
  5583. (unless (org-before-first-heading-p)
  5584. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5585. (if (org-at-item-p)
  5586. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5587. (org-show-entry)
  5588. (org-with-limited-levels (org-show-children))
  5589. (org-show-set-visibility 'canonical)
  5590. ;; Fold every list in subtree to top-level items.
  5591. (when (eq org-cycle-include-plain-lists 'integrate)
  5592. (save-excursion
  5593. (org-back-to-heading)
  5594. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5595. (beginning-of-line 1)
  5596. (let* ((struct (org-list-struct))
  5597. (prevs (org-list-prevs-alist struct))
  5598. (end (org-list-get-bottom-point struct)))
  5599. (dolist (e (org-list-get-all-items (point) struct prevs))
  5600. (org-list-set-item-visibility e struct 'folded))
  5601. (goto-char (if (< end eos) end eos)))))))
  5602. (org-unlogged-message "CHILDREN")
  5603. (save-excursion
  5604. (goto-char eos)
  5605. (outline-next-heading)
  5606. (when (org-invisible-p) (org-flag-heading nil)))
  5607. (setq org-cycle-subtree-status 'children)
  5608. (unless (org-before-first-heading-p)
  5609. (run-hook-with-args 'org-cycle-hook 'children)))
  5610. ((or children-skipped
  5611. (and (eq last-command this-command)
  5612. (eq org-cycle-subtree-status 'children)))
  5613. ;; We just showed the children, or no children are there,
  5614. ;; now show everything.
  5615. (unless (org-before-first-heading-p)
  5616. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5617. (org-flag-region eoh eos nil 'outline)
  5618. (org-unlogged-message
  5619. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5620. (setq org-cycle-subtree-status 'subtree)
  5621. (unless (org-before-first-heading-p)
  5622. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5623. (t
  5624. ;; Default action: hide the subtree.
  5625. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5626. (org-flag-region eoh eos t 'outline)
  5627. (org-unlogged-message "FOLDED")
  5628. (setq org-cycle-subtree-status 'folded)
  5629. (unless (org-before-first-heading-p)
  5630. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5631. ;;;###autoload
  5632. (defun org-global-cycle (&optional arg)
  5633. "Cycle the global visibility. For details see `org-cycle'.
  5634. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5635. With a numeric prefix, show all headlines up to that level."
  5636. (interactive "P")
  5637. (let ((org-cycle-include-plain-lists
  5638. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5639. (cond
  5640. ((integerp arg)
  5641. (org-show-all '(headings blocks))
  5642. (outline-hide-sublevels arg)
  5643. (setq org-cycle-global-status 'contents))
  5644. ((equal arg '(4))
  5645. (org-set-startup-visibility)
  5646. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5647. (t
  5648. (org-cycle '(4))))))
  5649. (defun org-set-startup-visibility ()
  5650. "Set the visibility required by startup options and properties."
  5651. (cond
  5652. ((eq org-startup-folded t)
  5653. (org-overview))
  5654. ((eq org-startup-folded 'content)
  5655. (org-content))
  5656. ((or (eq org-startup-folded 'showeverything)
  5657. (eq org-startup-folded nil))
  5658. (org-show-all)))
  5659. (unless (eq org-startup-folded 'showeverything)
  5660. (when org-hide-block-startup (org-hide-block-all))
  5661. (org-set-visibility-according-to-property)
  5662. (org-cycle-hide-archived-subtrees 'all)
  5663. (org-cycle-hide-drawers 'all)
  5664. (org-cycle-show-empty-lines t)))
  5665. (defun org-set-visibility-according-to-property ()
  5666. "Switch subtree visibility according to VISIBILITY property."
  5667. (interactive)
  5668. (let ((regexp (org-re-property "VISIBILITY")))
  5669. (org-with-point-at 1
  5670. (while (re-search-forward regexp nil t)
  5671. (let ((state (match-string 3)))
  5672. (if (not (org-at-property-p)) (outline-next-heading)
  5673. (save-excursion
  5674. (org-back-to-heading t)
  5675. (org-flag-subtree t)
  5676. (org-reveal)
  5677. (pcase state
  5678. ("folded"
  5679. (org-flag-subtree t))
  5680. ("children"
  5681. (org-show-hidden-entry)
  5682. (org-show-children))
  5683. ("content"
  5684. (save-excursion
  5685. (save-restriction
  5686. (org-narrow-to-subtree)
  5687. (org-content))))
  5688. ((or "all" "showall")
  5689. (outline-show-subtree))
  5690. (_ nil)))
  5691. (org-end-of-subtree)))))))
  5692. (defun org-overview ()
  5693. "Switch to overview mode, showing only top-level headlines.
  5694. This shows all headlines with a level equal or greater than the level
  5695. of the first headline in the buffer. This is important, because if the
  5696. first headline is not level one, then (hide-sublevels 1) gives confusing
  5697. results."
  5698. (interactive)
  5699. (save-excursion
  5700. (let ((level
  5701. (save-excursion
  5702. (goto-char (point-min))
  5703. (when (re-search-forward org-outline-regexp-bol nil t)
  5704. (goto-char (match-beginning 0))
  5705. (funcall outline-level)))))
  5706. (and level (outline-hide-sublevels level)))))
  5707. (defun org-content (&optional arg)
  5708. "Show all headlines in the buffer, like a table of contents.
  5709. With numerical argument N, show content up to level N."
  5710. (interactive "P")
  5711. (org-overview)
  5712. (save-excursion
  5713. ;; Visit all headings and show their offspring
  5714. (and (integerp arg) (org-overview))
  5715. (goto-char (point-max))
  5716. (catch 'exit
  5717. (while (and (progn (condition-case nil
  5718. (outline-previous-visible-heading 1)
  5719. (error (goto-char (point-min))))
  5720. t)
  5721. (looking-at org-outline-regexp))
  5722. (if (integerp arg)
  5723. (org-show-children (1- arg))
  5724. (outline-show-branches))
  5725. (when (bobp) (throw 'exit nil))))))
  5726. (defun org-optimize-window-after-visibility-change (state)
  5727. "Adjust the window after a change in outline visibility.
  5728. This function is the default value of the hook `org-cycle-hook'."
  5729. (when (get-buffer-window (current-buffer))
  5730. (cond
  5731. ((eq state 'content) nil)
  5732. ((eq state 'all) nil)
  5733. ((eq state 'folded) nil)
  5734. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5735. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5736. (defun org-clean-visibility-after-subtree-move ()
  5737. "Fix visibility issues after moving a subtree."
  5738. ;; First, find a reasonable region to look at:
  5739. ;; Start two siblings above, end three below
  5740. (let* ((beg (save-excursion
  5741. (and (org-get-last-sibling)
  5742. (org-get-last-sibling))
  5743. (point)))
  5744. (end (save-excursion
  5745. (and (org-get-next-sibling)
  5746. (org-get-next-sibling)
  5747. (org-get-next-sibling))
  5748. (if (org-at-heading-p)
  5749. (point-at-eol)
  5750. (point))))
  5751. (level (looking-at "\\*+"))
  5752. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5753. (save-excursion
  5754. (save-restriction
  5755. (narrow-to-region beg end)
  5756. (when re
  5757. ;; Properly fold already folded siblings
  5758. (goto-char (point-min))
  5759. (while (re-search-forward re nil t)
  5760. (when (and (not (org-invisible-p))
  5761. (org-invisible-p (line-end-position)))
  5762. (outline-hide-entry))))
  5763. (org-cycle-hide-drawers 'all)
  5764. (org-cycle-show-empty-lines 'overview)))))
  5765. (defun org-cycle-show-empty-lines (state)
  5766. "Show empty lines above all visible headlines.
  5767. The region to be covered depends on STATE when called through
  5768. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5769. entire buffer covered. Note that an empty line is only shown if there
  5770. are at least `org-cycle-separator-lines' empty lines before the headline."
  5771. (when (/= org-cycle-separator-lines 0)
  5772. (save-excursion
  5773. (let* ((n (abs org-cycle-separator-lines))
  5774. (re (cond
  5775. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5776. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5777. (t (let ((ns (number-to-string (- n 2))))
  5778. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5779. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5780. beg end)
  5781. (cond
  5782. ((memq state '(overview contents t))
  5783. (setq beg (point-min) end (point-max)))
  5784. ((memq state '(children folded))
  5785. (setq beg (point)
  5786. end (progn (org-end-of-subtree t t)
  5787. (line-beginning-position 2)))))
  5788. (when beg
  5789. (goto-char beg)
  5790. (while (re-search-forward re end t)
  5791. (unless (get-char-property (match-end 1) 'invisible)
  5792. (let ((e (match-end 1))
  5793. (b (if (>= org-cycle-separator-lines 0)
  5794. (match-beginning 1)
  5795. (save-excursion
  5796. (goto-char (match-beginning 0))
  5797. (skip-chars-backward " \t\n")
  5798. (line-end-position)))))
  5799. (org-flag-region b e nil 'outline))))))))
  5800. ;; Never hide empty lines at the end of the file.
  5801. (save-excursion
  5802. (goto-char (point-max))
  5803. (outline-previous-heading)
  5804. (outline-end-of-heading)
  5805. (when (and (looking-at "[ \t\n]+")
  5806. (= (match-end 0) (point-max)))
  5807. (org-flag-region (point) (match-end 0) nil 'outline))))
  5808. ;;;; Reveal point location
  5809. (defun org-show-context (&optional key)
  5810. "Make sure point and context are visible.
  5811. Optional argument KEY, when non-nil, is a symbol. See
  5812. `org-show-context-detail' for allowed values and how much is to
  5813. be shown."
  5814. (org-show-set-visibility
  5815. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5816. ((cdr (assq key org-show-context-detail)))
  5817. (t (cdr (assq 'default org-show-context-detail))))))
  5818. (defun org-show-set-visibility (detail)
  5819. "Set visibility around point according to DETAIL.
  5820. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5821. `tree', `canonical' or t. See `org-show-context-detail' for more
  5822. information."
  5823. ;; Show current heading and possibly its entry, following headline
  5824. ;; or all children.
  5825. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5826. (org-flag-heading nil)
  5827. (org-show-entry)
  5828. ;; If point is hidden within a drawer or a block, make sure to
  5829. ;; expose it.
  5830. (dolist (o (overlays-at (point)))
  5831. (when (memq (overlay-get o 'invisible)
  5832. '(org-hide-block org-hide-drawer outline))
  5833. (delete-overlay o)))
  5834. (unless (org-before-first-heading-p)
  5835. (org-with-limited-levels
  5836. (cl-case detail
  5837. ((tree canonical t) (org-show-children))
  5838. ((nil minimal ancestors))
  5839. (t (save-excursion
  5840. (outline-next-heading)
  5841. (org-flag-heading nil)))))))
  5842. ;; Show all siblings.
  5843. (when (eq detail 'lineage) (org-show-siblings))
  5844. ;; Show ancestors, possibly with their children.
  5845. (when (memq detail '(ancestors lineage tree canonical t))
  5846. (save-excursion
  5847. (while (org-up-heading-safe)
  5848. (org-flag-heading nil)
  5849. (when (memq detail '(canonical t)) (org-show-entry))
  5850. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5851. (defvar org-reveal-start-hook nil
  5852. "Hook run before revealing a location.")
  5853. (defun org-reveal (&optional siblings)
  5854. "Show current entry, hierarchy above it, and the following headline.
  5855. This can be used to show a consistent set of context around
  5856. locations exposed with `org-show-context'.
  5857. With optional argument SIBLINGS, on each level of the hierarchy all
  5858. siblings are shown. This repairs the tree structure to what it would
  5859. look like when opened with hierarchical calls to `org-cycle'.
  5860. With a \\[universal-argument] \\[universal-argument] prefix, \
  5861. go to the parent and show the entire tree."
  5862. (interactive "P")
  5863. (run-hooks 'org-reveal-start-hook)
  5864. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5865. ((equal siblings '(16))
  5866. (save-excursion
  5867. (when (org-up-heading-safe)
  5868. (org-show-subtree)
  5869. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5870. (t (org-show-set-visibility 'lineage))))
  5871. ;;; Indirect buffer display of subtrees
  5872. (defvar org-indirect-dedicated-frame nil
  5873. "This is the frame being used for indirect tree display.")
  5874. (defvar org-last-indirect-buffer nil)
  5875. (defun org-tree-to-indirect-buffer (&optional arg)
  5876. "Create indirect buffer and narrow it to current subtree.
  5877. With a numerical prefix ARG, go up to this level and then take that tree.
  5878. If ARG is negative, go up that many levels.
  5879. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5880. indirect buffer previously made with this command, to avoid proliferation of
  5881. indirect buffers. However, when you call the command with a \
  5882. `\\[universal-argument]' prefix, or
  5883. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5884. so that you can work with several indirect buffers at the same time. If
  5885. `org-indirect-buffer-display' is `dedicated-frame', the \
  5886. `\\[universal-argument]' prefix also
  5887. requests that a new frame be made for the new buffer, so that the dedicated
  5888. frame is not changed."
  5889. (interactive "P")
  5890. (let ((cbuf (current-buffer))
  5891. (cwin (selected-window))
  5892. (pos (point))
  5893. beg end level heading ibuf)
  5894. (save-excursion
  5895. (org-back-to-heading t)
  5896. (when (numberp arg)
  5897. (setq level (org-outline-level))
  5898. (when (< arg 0) (setq arg (+ level arg)))
  5899. (while (> (setq level (org-outline-level)) arg)
  5900. (org-up-heading-safe)))
  5901. (setq beg (point)
  5902. heading (org-get-heading 'no-tags))
  5903. (org-end-of-subtree t t)
  5904. (when (org-at-heading-p) (backward-char 1))
  5905. (setq end (point)))
  5906. (when (and (buffer-live-p org-last-indirect-buffer)
  5907. (not (eq org-indirect-buffer-display 'new-frame))
  5908. (not arg))
  5909. (kill-buffer org-last-indirect-buffer))
  5910. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5911. org-last-indirect-buffer ibuf)
  5912. (cond
  5913. ((or (eq org-indirect-buffer-display 'new-frame)
  5914. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5915. (select-frame (make-frame))
  5916. (delete-other-windows)
  5917. (pop-to-buffer-same-window ibuf)
  5918. (org-set-frame-title heading))
  5919. ((eq org-indirect-buffer-display 'dedicated-frame)
  5920. (raise-frame
  5921. (select-frame (or (and org-indirect-dedicated-frame
  5922. (frame-live-p org-indirect-dedicated-frame)
  5923. org-indirect-dedicated-frame)
  5924. (setq org-indirect-dedicated-frame (make-frame)))))
  5925. (delete-other-windows)
  5926. (pop-to-buffer-same-window ibuf)
  5927. (org-set-frame-title (concat "Indirect: " heading)))
  5928. ((eq org-indirect-buffer-display 'current-window)
  5929. (pop-to-buffer-same-window ibuf))
  5930. ((eq org-indirect-buffer-display 'other-window)
  5931. (pop-to-buffer ibuf))
  5932. (t (error "Invalid value")))
  5933. (narrow-to-region beg end)
  5934. (org-show-all '(headings blocks))
  5935. (goto-char pos)
  5936. (run-hook-with-args 'org-cycle-hook 'all)
  5937. (and (window-live-p cwin) (select-window cwin))))
  5938. (defun org-get-indirect-buffer (&optional buffer heading)
  5939. (setq buffer (or buffer (current-buffer)))
  5940. (let ((n 1) (base (buffer-name buffer)) bname)
  5941. (while (buffer-live-p
  5942. (get-buffer
  5943. (setq bname
  5944. (concat base "-"
  5945. (if heading (concat heading "-" (number-to-string n))
  5946. (number-to-string n))))))
  5947. (setq n (1+ n)))
  5948. (condition-case nil
  5949. (make-indirect-buffer buffer bname 'clone)
  5950. (error (make-indirect-buffer buffer bname)))))
  5951. (defun org-set-frame-title (title)
  5952. "Set the title of the current frame to the string TITLE."
  5953. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5954. ;;;; Structure editing
  5955. ;;; Inserting headlines
  5956. (defun org--line-empty-p (n)
  5957. "Is the Nth next line empty?
  5958. Counts the current line as N = 1 and the previous line as N = 0;
  5959. see `beginning-of-line'."
  5960. (save-excursion
  5961. (and (not (bobp))
  5962. (or (beginning-of-line n) t)
  5963. (save-match-data
  5964. (looking-at "[ \t]*$")))))
  5965. (defun org-previous-line-empty-p ()
  5966. "Is the previous line a blank line?
  5967. When NEXT is non-nil, check the next line instead."
  5968. (org--line-empty-p 0))
  5969. (defun org-next-line-empty-p ()
  5970. "Is the previous line a blank line?
  5971. When NEXT is non-nil, check the next line instead."
  5972. (org--line-empty-p 2))
  5973. (defun org--blank-before-heading-p (&optional parent)
  5974. "Non-nil when an empty line should precede a new heading here.
  5975. When optional argument PARENT is non-nil, consider parent
  5976. headline instead of current one."
  5977. (pcase (assq 'heading org-blank-before-new-entry)
  5978. (`(heading . auto)
  5979. (save-excursion
  5980. (org-with-limited-levels
  5981. (unless (and (org-before-first-heading-p)
  5982. (not (outline-next-heading)))
  5983. (org-back-to-heading t)
  5984. (when parent (org-up-heading-safe))
  5985. (cond ((not (bobp))
  5986. (org-previous-line-empty-p))
  5987. ((outline-next-heading)
  5988. (org-previous-line-empty-p))
  5989. ;; Ignore trailing spaces on last buffer line.
  5990. ((progn (skip-chars-backward " \t") (bolp))
  5991. (org-previous-line-empty-p))
  5992. (t nil))))))
  5993. (`(heading . ,value) value)
  5994. (_ nil)))
  5995. (defun org-insert-heading (&optional arg invisible-ok top)
  5996. "Insert a new heading or an item with the same depth at point.
  5997. If point is at the beginning of a heading, insert a new heading
  5998. or a new headline above the current one. When at the beginning
  5999. of a regular line of text, turn it into a heading.
  6000. If point is in the middle of a line, split it and create a new
  6001. headline with the text in the current line after point (see
  6002. `org-M-RET-may-split-line' on how to modify this behavior). As
  6003. a special case, on a headline, splitting can only happen on the
  6004. title itself. E.g., this excludes breaking stars or tags.
  6005. With a `\\[universal-argument]' prefix, set \
  6006. `org-insert-heading-respect-content' to
  6007. a non-nil value for the duration of the command. This forces the
  6008. insertion of a heading after the current subtree, independently
  6009. on the location of point.
  6010. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6011. insert the heading at the end of the tree
  6012. above the current heading. For example, if point is within a
  6013. 2nd-level heading, then it will insert a 2nd-level heading at
  6014. the end of the 1st-level parent subtree.
  6015. When INVISIBLE-OK is set, stop at invisible headlines when going
  6016. back. This is important for non-interactive uses of the
  6017. command.
  6018. When optional argument TOP is non-nil, insert a level 1 heading,
  6019. unconditionally."
  6020. (interactive "P")
  6021. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6022. (level (org-current-level))
  6023. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6024. (cond
  6025. ((or org-insert-heading-respect-content
  6026. (member arg '((4) (16)))
  6027. (and (not invisible-ok)
  6028. (invisible-p (max (1- (point)) (point-min)))))
  6029. ;; Position point at the location of insertion. Make sure we
  6030. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6031. (org-with-limited-levels
  6032. (if (not level) (outline-next-heading) ;before first headline
  6033. (org-back-to-heading invisible-ok)
  6034. (when (equal arg '(16)) (org-up-heading-safe))
  6035. (org-end-of-subtree)))
  6036. (unless (bolp) (insert "\n"))
  6037. (unless (and blank? (org-previous-line-empty-p))
  6038. (org-N-empty-lines-before-current (if blank? 1 0)))
  6039. (insert stars " ")
  6040. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6041. ;; is visible.
  6042. (unless invisible-ok
  6043. (pcase (get-char-property-and-overlay (point) 'invisible)
  6044. (`(outline . ,o)
  6045. (move-overlay o (overlay-start o) (line-end-position 0)))
  6046. (_ nil))))
  6047. ;; At a headline...
  6048. ((org-at-heading-p)
  6049. (cond ((bolp)
  6050. (when blank? (save-excursion (insert "\n")))
  6051. (save-excursion (insert stars " \n"))
  6052. (unless (and blank? (org-previous-line-empty-p))
  6053. (org-N-empty-lines-before-current (if blank? 1 0)))
  6054. (end-of-line))
  6055. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6056. (org-match-line org-complex-heading-regexp)
  6057. (org-pos-in-match-range (point) 4))
  6058. ;; Grab the text that should moved to the new headline.
  6059. ;; Preserve tags.
  6060. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6061. (if (looking-at "[ \t]*$") (replace-match "")
  6062. (org-align-tags))
  6063. (end-of-line)
  6064. (when blank? (insert "\n"))
  6065. (insert "\n" stars " ")
  6066. (when (org-string-nw-p split) (insert split))))
  6067. (t
  6068. (end-of-line)
  6069. (when blank? (insert "\n"))
  6070. (insert "\n" stars " "))))
  6071. ;; On regular text, turn line into a headline or split, if
  6072. ;; appropriate.
  6073. ((bolp)
  6074. (insert stars " ")
  6075. (unless (and blank? (org-previous-line-empty-p))
  6076. (org-N-empty-lines-before-current (if blank? 1 0))))
  6077. (t
  6078. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6079. (end-of-line))
  6080. (insert "\n" stars " ")
  6081. (unless (and blank? (org-previous-line-empty-p))
  6082. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6083. (run-hooks 'org-insert-heading-hook))
  6084. (defun org-N-empty-lines-before-current (n)
  6085. "Make the number of empty lines before current exactly N.
  6086. So this will delete or add empty lines."
  6087. (let ((column (current-column)))
  6088. (beginning-of-line)
  6089. (unless (bobp)
  6090. (let ((start (save-excursion
  6091. (skip-chars-backward " \r\t\n")
  6092. (line-end-position))))
  6093. (delete-region start (line-end-position 0))))
  6094. (insert (make-string n ?\n))
  6095. (move-to-column column)))
  6096. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6097. "Return the heading of the current entry, without the stars.
  6098. When NO-TAGS is non-nil, don't include tags.
  6099. When NO-TODO is non-nil, don't include TODO keywords.
  6100. When NO-PRIORITY is non-nil, don't include priority cookie.
  6101. When NO-COMMENT is non-nil, don't include COMMENT string.
  6102. Return nil before first heading."
  6103. (unless (org-before-first-heading-p)
  6104. (save-excursion
  6105. (org-back-to-heading t)
  6106. (let ((case-fold-search nil))
  6107. (looking-at org-complex-heading-regexp)
  6108. (let ((todo (and (not no-todo) (match-string 2)))
  6109. (priority (and (not no-priority) (match-string 3)))
  6110. (headline (pcase (match-string 4)
  6111. (`nil "")
  6112. ((and (guard no-comment) h)
  6113. (replace-regexp-in-string
  6114. (eval-when-compile
  6115. (format "\\`%s[ \t]+" org-comment-string))
  6116. "" h))
  6117. (h h)))
  6118. (tags (and (not no-tags) (match-string 5))))
  6119. (mapconcat #'identity
  6120. (delq nil (list todo priority headline tags))
  6121. " "))))))
  6122. (defun org-heading-components ()
  6123. "Return the components of the current heading.
  6124. This is a list with the following elements:
  6125. - the level as an integer
  6126. - the reduced level, different if `org-odd-levels-only' is set.
  6127. - the TODO keyword, or nil
  6128. - the priority character, like ?A, or nil if no priority is given
  6129. - the headline text itself, or the tags string if no headline text
  6130. - the tags string, or nil."
  6131. (save-excursion
  6132. (org-back-to-heading t)
  6133. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6134. (list (length (match-string 1))
  6135. (org-reduced-level (length (match-string 1)))
  6136. (match-string-no-properties 2)
  6137. (and (match-end 3) (aref (match-string 3) 2))
  6138. (match-string-no-properties 4)
  6139. (match-string-no-properties 5)))))
  6140. (defun org-get-entry ()
  6141. "Get the entry text, after heading, entire subtree."
  6142. (save-excursion
  6143. (org-back-to-heading t)
  6144. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6145. (defun org-edit-headline (&optional heading)
  6146. "Edit the current headline.
  6147. Set it to HEADING when provided."
  6148. (interactive)
  6149. (org-with-wide-buffer
  6150. (org-back-to-heading t)
  6151. (let ((case-fold-search nil))
  6152. (when (looking-at org-complex-heading-regexp)
  6153. (let* ((old (match-string-no-properties 4))
  6154. (new (save-match-data
  6155. (org-trim (or heading (read-string "Edit: " old))))))
  6156. (unless (equal old new)
  6157. (if old (replace-match new t t nil 4)
  6158. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6159. (insert " " new))
  6160. (org-align-tags)
  6161. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6162. (defun org-insert-heading-after-current ()
  6163. "Insert a new heading with same level as current, after current subtree."
  6164. (interactive)
  6165. (org-back-to-heading)
  6166. (org-insert-heading)
  6167. (org-move-subtree-down)
  6168. (end-of-line 1))
  6169. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6170. "Insert heading with `org-insert-heading-respect-content' set to t."
  6171. (interactive)
  6172. (org-insert-heading '(4) invisible-ok))
  6173. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6174. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6175. (interactive)
  6176. (org-insert-todo-heading force-state '(4)))
  6177. (defun org-insert-todo-heading (arg &optional force-heading)
  6178. "Insert a new heading with the same level and TODO state as current heading.
  6179. If the heading has no TODO state, or if the state is DONE, use
  6180. the first state (TODO by default). Also with one prefix arg,
  6181. force first state. With two prefix args, force inserting at the
  6182. end of the parent subtree.
  6183. When called at a plain list item, insert a new item with an
  6184. unchecked check box."
  6185. (interactive "P")
  6186. (when (or force-heading (not (org-insert-item 'checkbox)))
  6187. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6188. force-heading))
  6189. (save-excursion
  6190. (org-forward-heading-same-level -1)
  6191. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6192. (let* ((new-mark-x
  6193. (if (or (equal arg '(4))
  6194. (not (match-beginning 2))
  6195. (member (match-string 2) org-done-keywords))
  6196. (car org-todo-keywords-1)
  6197. (match-string 2)))
  6198. (new-mark
  6199. (or
  6200. (run-hook-with-args-until-success
  6201. 'org-todo-get-default-hook new-mark-x nil)
  6202. new-mark-x)))
  6203. (beginning-of-line 1)
  6204. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6205. (if org-treat-insert-todo-heading-as-state-change
  6206. (org-todo new-mark)
  6207. (insert new-mark " "))))
  6208. (when org-provide-todo-statistics
  6209. (org-update-parent-todo-statistics))))
  6210. (defun org-insert-subheading (arg)
  6211. "Insert a new subheading and demote it.
  6212. Works for outline headings and for plain lists alike."
  6213. (interactive "P")
  6214. (org-insert-heading arg)
  6215. (cond
  6216. ((org-at-heading-p) (org-do-demote))
  6217. ((org-at-item-p) (org-indent-item))))
  6218. (defun org-insert-todo-subheading (arg)
  6219. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6220. Works for outline headings and for plain lists alike."
  6221. (interactive "P")
  6222. (org-insert-todo-heading arg)
  6223. (cond
  6224. ((org-at-heading-p) (org-do-demote))
  6225. ((org-at-item-p) (org-indent-item))))
  6226. ;;; Promotion and Demotion
  6227. (defvar org-after-demote-entry-hook nil
  6228. "Hook run after an entry has been demoted.
  6229. The cursor will be at the beginning of the entry.
  6230. When a subtree is being demoted, the hook will be called for each node.")
  6231. (defvar org-after-promote-entry-hook nil
  6232. "Hook run after an entry has been promoted.
  6233. The cursor will be at the beginning of the entry.
  6234. When a subtree is being promoted, the hook will be called for each node.")
  6235. (defun org-promote-subtree ()
  6236. "Promote the entire subtree.
  6237. See also `org-promote'."
  6238. (interactive)
  6239. (save-excursion
  6240. (org-with-limited-levels (org-map-tree 'org-promote)))
  6241. (org-fix-position-after-promote))
  6242. (defun org-demote-subtree ()
  6243. "Demote the entire subtree.
  6244. See `org-demote' and `org-promote'."
  6245. (interactive)
  6246. (save-excursion
  6247. (org-with-limited-levels (org-map-tree 'org-demote)))
  6248. (org-fix-position-after-promote))
  6249. (defun org-do-promote ()
  6250. "Promote the current heading higher up the tree.
  6251. If the region is active in `transient-mark-mode', promote all
  6252. headings in the region."
  6253. (interactive)
  6254. (save-excursion
  6255. (if (org-region-active-p)
  6256. (org-map-region 'org-promote (region-beginning) (region-end))
  6257. (org-promote)))
  6258. (org-fix-position-after-promote))
  6259. (defun org-do-demote ()
  6260. "Demote the current heading lower down the tree.
  6261. If the region is active in `transient-mark-mode', demote all
  6262. headings in the region."
  6263. (interactive)
  6264. (save-excursion
  6265. (if (org-region-active-p)
  6266. (org-map-region 'org-demote (region-beginning) (region-end))
  6267. (org-demote)))
  6268. (org-fix-position-after-promote))
  6269. (defun org-fix-position-after-promote ()
  6270. "Fix cursor position and indentation after demoting/promoting."
  6271. (let ((pos (point)))
  6272. (when (save-excursion
  6273. (beginning-of-line)
  6274. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6275. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6276. (cond ((eobp) (insert " "))
  6277. ((eolp) (insert " "))
  6278. ((equal (char-after) ?\s) (forward-char 1))))))
  6279. (defun org-current-level ()
  6280. "Return the level of the current entry, or nil if before the first headline.
  6281. The level is the number of stars at the beginning of the
  6282. headline. Use `org-reduced-level' to remove the effect of
  6283. `org-odd-levels'. Unlike to `org-outline-level', this function
  6284. ignores inlinetasks."
  6285. (let ((level (org-with-limited-levels (org-outline-level))))
  6286. (and (> level 0) level)))
  6287. (defun org-get-previous-line-level ()
  6288. "Return the outline depth of the last headline before the current line.
  6289. Returns 0 for the first headline in the buffer, and nil if before the
  6290. first headline."
  6291. (and (org-current-level)
  6292. (or (and (/= (line-beginning-position) (point-min))
  6293. (save-excursion (beginning-of-line 0) (org-current-level)))
  6294. 0)))
  6295. (defun org-reduced-level (l)
  6296. "Compute the effective level of a heading.
  6297. This takes into account the setting of `org-odd-levels-only'."
  6298. (cond
  6299. ((zerop l) 0)
  6300. (org-odd-levels-only (1+ (floor (/ l 2))))
  6301. (t l)))
  6302. (defun org-level-increment ()
  6303. "Return the number of stars that will be added or removed at a
  6304. time to headlines when structure editing, based on the value of
  6305. `org-odd-levels-only'."
  6306. (if org-odd-levels-only 2 1))
  6307. (defun org-get-valid-level (level &optional change)
  6308. "Rectify a level change under the influence of `org-odd-levels-only'.
  6309. LEVEL is a current level, CHANGE is by how much the level should
  6310. be modified. Even if CHANGE is nil, LEVEL may be returned
  6311. modified because even level numbers will become the next higher
  6312. odd number. Returns values greater than 0."
  6313. (if org-odd-levels-only
  6314. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6315. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6316. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6317. (max 1 (+ level (or change 0)))))
  6318. (defun org-promote ()
  6319. "Promote the current heading higher up the tree."
  6320. (org-with-wide-buffer
  6321. (org-back-to-heading t)
  6322. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6323. after-change-functions))
  6324. (level (save-match-data (funcall outline-level)))
  6325. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6326. (diff (abs (- level (length up-head) -1))))
  6327. (cond
  6328. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6329. (replace-match "# " nil t))
  6330. ((= level 1)
  6331. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6332. (t (replace-match up-head nil t)))
  6333. (unless (= level 1)
  6334. (when org-auto-align-tags (org-align-tags))
  6335. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6336. (run-hooks 'org-after-promote-entry-hook))))
  6337. (defun org-demote ()
  6338. "Demote the current heading lower down the tree."
  6339. (org-with-wide-buffer
  6340. (org-back-to-heading t)
  6341. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6342. after-change-functions))
  6343. (level (save-match-data (funcall outline-level)))
  6344. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6345. (diff (abs (- level (length down-head) -1))))
  6346. (replace-match down-head nil t)
  6347. (when org-auto-align-tags (org-align-tags))
  6348. (when org-adapt-indentation (org-fixup-indentation diff))
  6349. (run-hooks 'org-after-demote-entry-hook))))
  6350. (defun org-cycle-level ()
  6351. "Cycle the level of an empty headline through possible states.
  6352. This goes first to child, then to parent, level, then up the hierarchy.
  6353. After top level, it switches back to sibling level."
  6354. (interactive)
  6355. (let ((org-adapt-indentation nil))
  6356. (when (org-point-at-end-of-empty-headline)
  6357. (setq this-command 'org-cycle-level) ; Only needed for caching
  6358. (let ((cur-level (org-current-level))
  6359. (prev-level (org-get-previous-line-level)))
  6360. (cond
  6361. ;; If first headline in file, promote to top-level.
  6362. ((= prev-level 0)
  6363. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6364. do (org-do-promote)))
  6365. ;; If same level as prev, demote one.
  6366. ((= prev-level cur-level)
  6367. (org-do-demote))
  6368. ;; If parent is top-level, promote to top level if not already.
  6369. ((= prev-level 1)
  6370. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6371. do (org-do-promote)))
  6372. ;; If top-level, return to prev-level.
  6373. ((= cur-level 1)
  6374. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6375. do (org-do-demote)))
  6376. ;; If less than prev-level, promote one.
  6377. ((< cur-level prev-level)
  6378. (org-do-promote))
  6379. ;; If deeper than prev-level, promote until higher than
  6380. ;; prev-level.
  6381. ((> cur-level prev-level)
  6382. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6383. do (org-do-promote))))
  6384. t))))
  6385. (defun org-map-tree (fun)
  6386. "Call FUN for every heading underneath the current one."
  6387. (org-back-to-heading t)
  6388. (let ((level (funcall outline-level)))
  6389. (save-excursion
  6390. (funcall fun)
  6391. (while (and (progn
  6392. (outline-next-heading)
  6393. (> (funcall outline-level) level))
  6394. (not (eobp)))
  6395. (funcall fun)))))
  6396. (defun org-map-region (fun beg end)
  6397. "Call FUN for every heading between BEG and END."
  6398. (let ((org-ignore-region t))
  6399. (save-excursion
  6400. (setq end (copy-marker end))
  6401. (goto-char beg)
  6402. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6403. (< (point) end))
  6404. (funcall fun))
  6405. (while (and (progn
  6406. (outline-next-heading)
  6407. (< (point) end))
  6408. (not (eobp)))
  6409. (funcall fun)))))
  6410. (defun org-fixup-indentation (diff)
  6411. "Change the indentation in the current entry by DIFF.
  6412. DIFF is an integer. Indentation is done according to the
  6413. following rules:
  6414. - Planning information and property drawers are always indented
  6415. according to the new level of the headline;
  6416. - Footnote definitions and their contents are ignored;
  6417. - Inlinetasks' boundaries are not shifted;
  6418. - Empty lines are ignored;
  6419. - Other lines' indentation are shifted by DIFF columns, unless
  6420. it would introduce a structural change in the document, in
  6421. which case no shifting is done at all.
  6422. Assume point is at a heading or an inlinetask beginning."
  6423. (org-with-wide-buffer
  6424. (narrow-to-region (line-beginning-position)
  6425. (save-excursion
  6426. (if (org-with-limited-levels (org-at-heading-p))
  6427. (org-with-limited-levels (outline-next-heading))
  6428. (org-inlinetask-goto-end))
  6429. (point)))
  6430. (forward-line)
  6431. ;; Indent properly planning info and property drawer.
  6432. (when (looking-at-p org-planning-line-re)
  6433. (org-indent-line)
  6434. (forward-line))
  6435. (when (looking-at org-property-drawer-re)
  6436. (goto-char (match-end 0))
  6437. (forward-line)
  6438. (org-indent-region (match-beginning 0) (match-end 0)))
  6439. (when (looking-at org-logbook-drawer-re)
  6440. (goto-char (match-end 0))
  6441. (forward-line)
  6442. (org-indent-region (match-beginning 0) (match-end 0)))
  6443. (catch 'no-shift
  6444. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6445. (throw 'no-shift nil))
  6446. ;; If DIFF is negative, first check if a shift is possible at all
  6447. ;; (e.g., it doesn't break structure). This can only happen if
  6448. ;; some contents are not properly indented.
  6449. (let ((case-fold-search t))
  6450. (when (< diff 0)
  6451. (let ((diff (- diff))
  6452. (forbidden-re (concat org-outline-regexp
  6453. "\\|"
  6454. (substring org-footnote-definition-re 1))))
  6455. (save-excursion
  6456. (while (not (eobp))
  6457. (cond
  6458. ((looking-at-p "[ \t]*$") (forward-line))
  6459. ((and (looking-at-p org-footnote-definition-re)
  6460. (let ((e (org-element-at-point)))
  6461. (and (eq (org-element-type e) 'footnote-definition)
  6462. (goto-char (org-element-property :end e))))))
  6463. ((looking-at-p org-outline-regexp) (forward-line))
  6464. ;; Give up if shifting would move before column 0 or
  6465. ;; if it would introduce a headline or a footnote
  6466. ;; definition.
  6467. (t
  6468. (skip-chars-forward " \t")
  6469. (let ((ind (current-column)))
  6470. (when (or (< ind diff)
  6471. (and (= ind diff) (looking-at-p forbidden-re)))
  6472. (throw 'no-shift nil)))
  6473. ;; Ignore contents of example blocks and source
  6474. ;; blocks if their indentation is meant to be
  6475. ;; preserved. Jump to block's closing line.
  6476. (beginning-of-line)
  6477. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6478. (let ((e (org-element-at-point)))
  6479. (and (memq (org-element-type e)
  6480. '(example-block src-block))
  6481. (or org-src-preserve-indentation
  6482. (org-element-property :preserve-indent e))
  6483. (goto-char (org-element-property :end e))
  6484. (progn (skip-chars-backward " \r\t\n")
  6485. (beginning-of-line)
  6486. t))))
  6487. (forward-line))))))))
  6488. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6489. ;; by DIFF. Also skip contents of source or example blocks
  6490. ;; when indentation is meant to be preserved.
  6491. (while (not (eobp))
  6492. (cond
  6493. ((and (looking-at-p org-footnote-definition-re)
  6494. (let ((e (org-element-at-point)))
  6495. (and (eq (org-element-type e) 'footnote-definition)
  6496. (goto-char (org-element-property :end e))))))
  6497. ((looking-at-p org-outline-regexp) (forward-line))
  6498. ((looking-at-p "[ \t]*$") (forward-line))
  6499. (t
  6500. (indent-line-to (+ (current-indentation) diff))
  6501. (beginning-of-line)
  6502. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6503. (let ((e (org-element-at-point)))
  6504. (and (memq (org-element-type e)
  6505. '(example-block src-block))
  6506. (or org-src-preserve-indentation
  6507. (org-element-property :preserve-indent e))
  6508. (goto-char (org-element-property :end e))
  6509. (progn (skip-chars-backward " \r\t\n")
  6510. (beginning-of-line)
  6511. t))))
  6512. (forward-line)))))))))
  6513. (defun org-convert-to-odd-levels ()
  6514. "Convert an Org file with all levels allowed to one with odd levels.
  6515. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6516. level 5 etc."
  6517. (interactive)
  6518. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6519. (let ((outline-level 'org-outline-level)
  6520. (org-odd-levels-only nil) n)
  6521. (save-excursion
  6522. (goto-char (point-min))
  6523. (while (re-search-forward "^\\*\\*+ " nil t)
  6524. (setq n (- (length (match-string 0)) 2))
  6525. (while (>= (setq n (1- n)) 0)
  6526. (org-demote))
  6527. (end-of-line 1))))))
  6528. (defun org-convert-to-oddeven-levels ()
  6529. "Convert an Org file with only odd levels to one with odd/even levels.
  6530. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6531. file contains a section with an even level, conversion would
  6532. destroy the structure of the file. An error is signaled in this
  6533. case."
  6534. (interactive)
  6535. (goto-char (point-min))
  6536. ;; First check if there are no even levels
  6537. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6538. (org-show-set-visibility 'canonical)
  6539. (error "Not all levels are odd in this file. Conversion not possible"))
  6540. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6541. (let ((outline-regexp org-outline-regexp)
  6542. (outline-level 'org-outline-level)
  6543. (org-odd-levels-only nil) n)
  6544. (save-excursion
  6545. (goto-char (point-min))
  6546. (while (re-search-forward "^\\*\\*+ " nil t)
  6547. (setq n (/ (1- (length (match-string 0))) 2))
  6548. (while (>= (setq n (1- n)) 0)
  6549. (org-promote))
  6550. (end-of-line 1))))))
  6551. (defun org-tr-level (n)
  6552. "Make N odd if required."
  6553. (if org-odd-levels-only (1+ (/ n 2)) n))
  6554. ;;; Vertical tree motion, cutting and pasting of subtrees
  6555. (defun org-move-subtree-up (&optional arg)
  6556. "Move the current subtree up past ARG headlines of the same level."
  6557. (interactive "p")
  6558. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6559. (defun org-move-subtree-down (&optional arg)
  6560. "Move the current subtree down past ARG headlines of the same level."
  6561. (interactive "p")
  6562. (setq arg (prefix-numeric-value arg))
  6563. (org-preserve-local-variables
  6564. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6565. 'org-get-last-sibling))
  6566. (ins-point (make-marker))
  6567. (cnt (abs arg))
  6568. (col (current-column))
  6569. beg end txt folded)
  6570. ;; Select the tree
  6571. (org-back-to-heading)
  6572. (setq beg (point))
  6573. (save-match-data
  6574. (save-excursion (outline-end-of-heading)
  6575. (setq folded (org-invisible-p)))
  6576. (progn (org-end-of-subtree nil t)
  6577. (unless (eobp) (backward-char))))
  6578. (outline-next-heading)
  6579. (setq end (point))
  6580. (goto-char beg)
  6581. ;; Find insertion point, with error handling
  6582. (while (> cnt 0)
  6583. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6584. (goto-char beg)
  6585. (user-error "Cannot move past superior level or buffer limit"))
  6586. (setq cnt (1- cnt)))
  6587. (when (> arg 0)
  6588. ;; Moving forward - still need to move over subtree
  6589. (org-end-of-subtree t t)
  6590. (save-excursion
  6591. (org-back-over-empty-lines)
  6592. (or (bolp) (newline))))
  6593. (move-marker ins-point (point))
  6594. (setq txt (buffer-substring beg end))
  6595. (org-save-markers-in-region beg end)
  6596. (delete-region beg end)
  6597. (org-remove-empty-overlays-at beg)
  6598. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6599. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6600. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6601. (let ((bbb (point)))
  6602. (insert-before-markers txt)
  6603. (org-reinstall-markers-in-region bbb)
  6604. (move-marker ins-point bbb))
  6605. (or (bolp) (insert "\n"))
  6606. (goto-char ins-point)
  6607. (org-skip-whitespace)
  6608. (move-marker ins-point nil)
  6609. (if folded
  6610. (org-flag-subtree t)
  6611. (org-show-entry)
  6612. (org-show-children))
  6613. (org-clean-visibility-after-subtree-move)
  6614. ;; move back to the initial column we were at
  6615. (move-to-column col))))
  6616. (defvar org-subtree-clip ""
  6617. "Clipboard for cut and paste of subtrees.
  6618. This is actually only a copy of the kill, because we use the normal kill
  6619. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6620. (defvar org-subtree-clip-folded nil
  6621. "Was the last copied subtree folded?
  6622. This is used to fold the tree back after pasting.")
  6623. (defun org-cut-subtree (&optional n)
  6624. "Cut the current subtree into the clipboard.
  6625. With prefix arg N, cut this many sequential subtrees.
  6626. This is a short-hand for marking the subtree and then cutting it."
  6627. (interactive "p")
  6628. (org-copy-subtree n 'cut))
  6629. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6630. "Copy the current subtree into the clipboard.
  6631. With prefix arg N, copy this many sequential subtrees.
  6632. This is a short-hand for marking the subtree and then copying it.
  6633. If CUT is non-nil, actually cut the subtree.
  6634. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6635. of some markers in the region, even if CUT is non-nil. This is
  6636. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6637. (interactive "p")
  6638. (org-preserve-local-variables
  6639. (let (beg end folded (beg0 (point)))
  6640. (if (called-interactively-p 'any)
  6641. (org-back-to-heading nil) ; take what looks like a subtree
  6642. (org-back-to-heading t)) ; take what is really there
  6643. (setq beg (point))
  6644. (skip-chars-forward " \t\r\n")
  6645. (save-match-data
  6646. (if nosubtrees
  6647. (outline-next-heading)
  6648. (save-excursion (outline-end-of-heading)
  6649. (setq folded (org-invisible-p)))
  6650. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6651. (org-end-of-subtree t t)))
  6652. ;; Include the end of an inlinetask
  6653. (when (and (featurep 'org-inlinetask)
  6654. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6655. "END[ \t]*$")))
  6656. (end-of-line))
  6657. (setq end (point))
  6658. (goto-char beg0)
  6659. (when (> end beg)
  6660. (setq org-subtree-clip-folded folded)
  6661. (when (or cut force-store-markers)
  6662. (org-save-markers-in-region beg end))
  6663. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6664. (setq org-subtree-clip (current-kill 0))
  6665. (message "%s: Subtree(s) with %d characters"
  6666. (if cut "Cut" "Copied")
  6667. (length org-subtree-clip))))))
  6668. (defun org-paste-subtree (&optional level tree for-yank remove)
  6669. "Paste the clipboard as a subtree, with modification of headline level.
  6670. The entire subtree is promoted or demoted in order to match a new headline
  6671. level.
  6672. If the cursor is at the beginning of a headline, the same level as
  6673. that headline is used to paste the tree.
  6674. If not, the new level is derived from the *visible* headings
  6675. before and after the insertion point, and taken to be the inferior headline
  6676. level of the two. So if the previous visible heading is level 3 and the
  6677. next is level 4 (or vice versa), level 4 will be used for insertion.
  6678. This makes sure that the subtree remains an independent subtree and does
  6679. not swallow low level entries.
  6680. You can also force a different level, either by using a numeric prefix
  6681. argument, or by inserting the heading marker by hand. For example, if the
  6682. cursor is after \"*****\", then the tree will be shifted to level 5.
  6683. If optional TREE is given, use this text instead of the kill ring.
  6684. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6685. move back over whitespace before inserting, and move point to the end of
  6686. the inserted text when done.
  6687. When REMOVE is non-nil, remove the subtree from the clipboard."
  6688. (interactive "P")
  6689. (setq tree (or tree (and kill-ring (current-kill 0))))
  6690. (unless (org-kill-is-subtree-p tree)
  6691. (user-error
  6692. (substitute-command-keys
  6693. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6694. (org-with-limited-levels
  6695. (let* ((visp (not (org-invisible-p)))
  6696. (txt tree)
  6697. (old-level (if (string-match org-outline-regexp-bol txt)
  6698. (- (match-end 0) (match-beginning 0) 1)
  6699. -1))
  6700. (force-level
  6701. (cond
  6702. (level (prefix-numeric-value level))
  6703. ;; When point is after the stars in an otherwise empty
  6704. ;; headline, use the number of stars as the forced level.
  6705. ((and (org-match-line "^\\*+[ \t]*$")
  6706. (not (eq ?* (char-after))))
  6707. (org-outline-level))
  6708. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6709. (previous-level
  6710. (save-excursion
  6711. (org-previous-visible-heading 1)
  6712. (if (org-at-heading-p) (org-outline-level) 1)))
  6713. (next-level
  6714. (save-excursion
  6715. (if (org-at-heading-p) (org-outline-level)
  6716. (org-next-visible-heading 1)
  6717. (if (org-at-heading-p) (org-outline-level) 1))))
  6718. (new-level (or force-level (max previous-level next-level)))
  6719. (shift (if (or (= old-level -1)
  6720. (= new-level -1)
  6721. (= old-level new-level))
  6722. 0
  6723. (- new-level old-level)))
  6724. (delta (if (> shift 0) -1 1))
  6725. (func (if (> shift 0) #'org-demote #'org-promote))
  6726. (org-odd-levels-only nil)
  6727. beg end newend)
  6728. ;; Remove the forced level indicator.
  6729. (when (and force-level (not level))
  6730. (delete-region (line-beginning-position) (point)))
  6731. ;; Paste before the next visible heading or at end of buffer,
  6732. ;; unless point is at the beginning of a headline.
  6733. (unless (and (bolp) (org-at-heading-p))
  6734. (org-next-visible-heading 1)
  6735. (unless (bolp) (insert "\n")))
  6736. (setq beg (point))
  6737. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6738. (insert-before-markers txt)
  6739. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6740. (setq newend (point))
  6741. (org-reinstall-markers-in-region beg)
  6742. (setq end (point))
  6743. (goto-char beg)
  6744. (skip-chars-forward " \t\n\r")
  6745. (setq beg (point))
  6746. (when (and (org-invisible-p) visp)
  6747. (save-excursion (outline-show-heading)))
  6748. ;; Shift if necessary.
  6749. (unless (= shift 0)
  6750. (save-restriction
  6751. (narrow-to-region beg end)
  6752. (while (not (= shift 0))
  6753. (org-map-region func (point-min) (point-max))
  6754. (setq shift (+ delta shift)))
  6755. (goto-char (point-min))
  6756. (setq newend (point-max))))
  6757. (when (or for-yank (called-interactively-p 'interactive))
  6758. (message "Clipboard pasted as level %d subtree" new-level))
  6759. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6760. kill-ring
  6761. (equal org-subtree-clip (current-kill 0))
  6762. org-subtree-clip-folded)
  6763. ;; The tree was folded before it was killed/copied
  6764. (org-flag-subtree t))
  6765. (when for-yank (goto-char newend))
  6766. (when remove (pop kill-ring)))))
  6767. (defun org-kill-is-subtree-p (&optional txt)
  6768. "Check if the current kill is an outline subtree, or a set of trees.
  6769. Returns nil if kill does not start with a headline, or if the first
  6770. headline level is not the largest headline level in the tree.
  6771. So this will actually accept several entries of equal levels as well,
  6772. which is OK for `org-paste-subtree'.
  6773. If optional TXT is given, check this string instead of the current kill."
  6774. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6775. (re (org-get-limited-outline-regexp))
  6776. (^re (concat "^" re))
  6777. (start-level (and kill
  6778. (string-match
  6779. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6780. kill)
  6781. (- (match-end 2) (match-beginning 2) 1)))
  6782. (start (1+ (or (match-beginning 2) -1))))
  6783. (if (not start-level)
  6784. (progn
  6785. nil) ;; does not even start with a heading
  6786. (catch 'exit
  6787. (while (setq start (string-match ^re kill (1+ start)))
  6788. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6789. (throw 'exit nil)))
  6790. t))))
  6791. (defvar org-markers-to-move nil
  6792. "Markers that should be moved with a cut-and-paste operation.
  6793. Those markers are stored together with their positions relative to
  6794. the start of the region.")
  6795. (defun org-save-markers-in-region (beg end)
  6796. "Check markers in region.
  6797. If these markers are between BEG and END, record their position relative
  6798. to BEG, so that after moving the block of text, we can put the markers back
  6799. into place.
  6800. This function gets called just before an entry or tree gets cut from the
  6801. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6802. called immediately, to move the markers with the entries."
  6803. (setq org-markers-to-move nil)
  6804. (when (featurep 'org-clock)
  6805. (org-clock-save-markers-for-cut-and-paste beg end))
  6806. (when (featurep 'org-agenda)
  6807. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6808. (defun org-check-and-save-marker (marker beg end)
  6809. "Check if MARKER is between BEG and END.
  6810. If yes, remember the marker and the distance to BEG."
  6811. (when (and (marker-buffer marker)
  6812. (equal (marker-buffer marker) (current-buffer))
  6813. (>= marker beg) (< marker end))
  6814. (push (cons marker (- marker beg)) org-markers-to-move)))
  6815. (defun org-reinstall-markers-in-region (beg)
  6816. "Move all remembered markers to their position relative to BEG."
  6817. (dolist (x org-markers-to-move)
  6818. (move-marker (car x) (+ beg (cdr x))))
  6819. (setq org-markers-to-move nil))
  6820. (defun org-narrow-to-subtree ()
  6821. "Narrow buffer to the current subtree."
  6822. (interactive)
  6823. (save-excursion
  6824. (save-match-data
  6825. (org-with-limited-levels
  6826. (narrow-to-region
  6827. (progn (org-back-to-heading t) (point))
  6828. (progn (org-end-of-subtree t t)
  6829. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6830. (point)))))))
  6831. (defun org-toggle-narrow-to-subtree ()
  6832. "Narrow to the subtree at point or widen a narrowed buffer."
  6833. (interactive)
  6834. (if (buffer-narrowed-p)
  6835. (progn (widen) (message "Buffer widen"))
  6836. (org-narrow-to-subtree)
  6837. (message "Buffer narrowed to current subtree")))
  6838. (defun org-narrow-to-block ()
  6839. "Narrow buffer to the current block."
  6840. (interactive)
  6841. (let* ((case-fold-search t)
  6842. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6843. "^[ \t]*#\\+end_.*")))
  6844. (if blockp
  6845. (narrow-to-region (car blockp) (cdr blockp))
  6846. (user-error "Not in a block"))))
  6847. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6848. "Clone the task (subtree) at point N times.
  6849. The clones will be inserted as siblings.
  6850. In interactive use, the user will be prompted for the number of
  6851. clones to be produced. If the entry has a timestamp, the user
  6852. will also be prompted for a time shift, which may be a repeater
  6853. as used in time stamps, for example `+3d'. To disable this,
  6854. you can call the function with a universal prefix argument.
  6855. When a valid repeater is given and the entry contains any time
  6856. stamps, the clones will become a sequence in time, with time
  6857. stamps in the subtree shifted for each clone produced. If SHIFT
  6858. is nil or the empty string, time stamps will be left alone. The
  6859. ID property of the original subtree is removed.
  6860. In each clone, all the CLOCK entries will be removed. This
  6861. prevents Org from considering that the clocked times overlap.
  6862. If the original subtree did contain time stamps with a repeater,
  6863. the following will happen:
  6864. - the repeater will be removed in each clone
  6865. - an additional clone will be produced, with the current, unshifted
  6866. date(s) in the entry.
  6867. - the original entry will be placed *after* all the clones, with
  6868. repeater intact.
  6869. - the start days in the repeater in the original entry will be shifted
  6870. to past the last clone.
  6871. In this way you can spell out a number of instances of a repeating task,
  6872. and still retain the repeater to cover future instances of the task.
  6873. As described above, N+1 clones are produced when the original
  6874. subtree has a repeater. Setting N to 0, then, can be used to
  6875. remove the repeater from a subtree and create a shifted clone
  6876. with the original repeater."
  6877. (interactive "nNumber of clones to produce: ")
  6878. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6879. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6880. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6881. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6882. (shift
  6883. (or shift
  6884. (if (and (not (equal current-prefix-arg '(4)))
  6885. (save-excursion
  6886. (goto-char beg)
  6887. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6888. (read-from-minibuffer
  6889. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6890. ""))) ;No time shift
  6891. (doshift
  6892. (and (org-string-nw-p shift)
  6893. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6894. shift)
  6895. (user-error "Invalid shift specification %s" shift)))))
  6896. (goto-char end-of-tree)
  6897. (unless (bolp) (insert "\n"))
  6898. (let* ((end (point))
  6899. (template (buffer-substring beg end))
  6900. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6901. (shift-what (pcase (and doshift (match-string 2 shift))
  6902. (`nil nil)
  6903. ("d" 'day)
  6904. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6905. ("m" 'month)
  6906. ("y" 'year)
  6907. (_ (error "Unsupported time unit"))))
  6908. (nmin 1)
  6909. (nmax n)
  6910. (n-no-remove -1)
  6911. (idprop (org-entry-get beg "ID")))
  6912. (when (and doshift
  6913. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6914. template))
  6915. (delete-region beg end)
  6916. (setq end beg)
  6917. (setq nmin 0)
  6918. (setq nmax (1+ nmax))
  6919. (setq n-no-remove nmax))
  6920. (goto-char end)
  6921. (cl-loop for n from nmin to nmax do
  6922. (insert
  6923. ;; Prepare clone.
  6924. (with-temp-buffer
  6925. (insert template)
  6926. (org-mode)
  6927. (goto-char (point-min))
  6928. (org-show-subtree)
  6929. (and idprop (if org-clone-delete-id
  6930. (org-entry-delete nil "ID")
  6931. (org-id-get-create t)))
  6932. (unless (= n 0)
  6933. (while (re-search-forward org-clock-line-re nil t)
  6934. (delete-region (line-beginning-position)
  6935. (line-beginning-position 2)))
  6936. (goto-char (point-min))
  6937. (while (re-search-forward org-drawer-regexp nil t)
  6938. (org-remove-empty-drawer-at (point))))
  6939. (goto-char (point-min))
  6940. (when doshift
  6941. (while (re-search-forward org-ts-regexp-both nil t)
  6942. (org-timestamp-change (* n shift-n) shift-what))
  6943. (unless (= n n-no-remove)
  6944. (goto-char (point-min))
  6945. (while (re-search-forward org-ts-regexp nil t)
  6946. (save-excursion
  6947. (goto-char (match-beginning 0))
  6948. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6949. (delete-region (match-beginning 1) (match-end 1)))))))
  6950. (buffer-string)))))
  6951. (goto-char beg)))
  6952. ;;; Outline Sorting
  6953. (defun org-sort (&optional with-case)
  6954. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6955. Optional argument WITH-CASE means sort case-sensitively."
  6956. (interactive "P")
  6957. (org-call-with-arg
  6958. (cond ((org-at-table-p) #'org-table-sort-lines)
  6959. ((org-at-item-p) #'org-sort-list)
  6960. (t #'org-sort-entries))
  6961. with-case))
  6962. (defun org-sort-remove-invisible (s)
  6963. "Remove invisible part of links and emphasis markers from string S."
  6964. (remove-text-properties 0 (length s) org-rm-props s)
  6965. (replace-regexp-in-string
  6966. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  6967. (replace-regexp-in-string
  6968. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  6969. (org-link-display-format s)
  6970. t t) t t))
  6971. (defvar org-after-sorting-entries-or-items-hook nil
  6972. "Hook that is run after a bunch of entries or items have been sorted.
  6973. When children are sorted, the cursor is in the parent line when this
  6974. hook gets called. When a region or a plain list is sorted, the cursor
  6975. will be in the first entry of the sorted region/list.")
  6976. (defun org-sort-entries
  6977. (&optional with-case sorting-type getkey-func compare-func property
  6978. interactive?)
  6979. "Sort entries on a certain level of an outline tree.
  6980. If there is an active region, the entries in the region are sorted.
  6981. Else, if the cursor is before the first entry, sort the top-level items.
  6982. Else, the children of the entry at point are sorted.
  6983. Sorting can be alphabetically, numerically, by date/time as given by
  6984. a time stamp, by a property, by priority order, or by a custom function.
  6985. The command prompts for the sorting type unless it has been given to the
  6986. function through the SORTING-TYPE argument, which needs to be a character,
  6987. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6988. the precise meaning of each character:
  6989. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6990. c By creation time, which is assumed to be the first inactive time stamp
  6991. at the beginning of a line.
  6992. d By deadline date/time.
  6993. k By clocking time.
  6994. n Numerically, by converting the beginning of the entry/item to a number.
  6995. o By order of TODO keywords.
  6996. p By priority according to the cookie.
  6997. r By the value of a property.
  6998. s By scheduled date/time.
  6999. t By date/time, either the first active time stamp in the entry, or, if
  7000. none exist, by the first inactive one.
  7001. Capital letters will reverse the sort order.
  7002. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7003. called with point at the beginning of the record. It must return a
  7004. value that is compatible with COMPARE-FUNC, the function used to
  7005. compare entries.
  7006. Comparing entries ignores case by default. However, with an optional argument
  7007. WITH-CASE, the sorting considers case as well.
  7008. Sorting is done against the visible part of the headlines, it ignores hidden
  7009. links.
  7010. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7011. A non-nil value for INTERACTIVE? is used to signal that this
  7012. function is being called interactively."
  7013. (interactive (list current-prefix-arg nil nil nil nil t))
  7014. (let ((case-func (if with-case 'identity 'downcase))
  7015. start beg end stars re re2
  7016. txt what tmp)
  7017. ;; Find beginning and end of region to sort
  7018. (cond
  7019. ((org-region-active-p)
  7020. ;; we will sort the region
  7021. (setq end (region-end)
  7022. what "region")
  7023. (goto-char (region-beginning))
  7024. (unless (org-at-heading-p) (outline-next-heading))
  7025. (setq start (point)))
  7026. ((or (org-at-heading-p)
  7027. (ignore-errors (progn (org-back-to-heading) t)))
  7028. ;; we will sort the children of the current headline
  7029. (org-back-to-heading)
  7030. (setq start (point)
  7031. end (progn (org-end-of-subtree t t)
  7032. (or (bolp) (insert "\n"))
  7033. (when (>= (org-back-over-empty-lines) 1)
  7034. (forward-line 1))
  7035. (point))
  7036. what "children")
  7037. (goto-char start)
  7038. (outline-show-subtree)
  7039. (outline-next-heading))
  7040. (t
  7041. ;; we will sort the top-level entries in this file
  7042. (goto-char (point-min))
  7043. (or (org-at-heading-p) (outline-next-heading))
  7044. (setq start (point))
  7045. (goto-char (point-max))
  7046. (beginning-of-line 1)
  7047. (when (looking-at ".*?\\S-")
  7048. ;; File ends in a non-white line
  7049. (end-of-line 1)
  7050. (insert "\n"))
  7051. (setq end (point-max))
  7052. (setq what "top-level")
  7053. (goto-char start)
  7054. (org-show-all '(headings blocks))))
  7055. (setq beg (point))
  7056. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7057. (looking-at "\\(\\*+\\)")
  7058. (setq stars (match-string 1)
  7059. re (concat "^" (regexp-quote stars) " +")
  7060. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7061. txt (buffer-substring beg end))
  7062. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7063. (when (and (not (equal stars "*")) (string-match re2 txt))
  7064. (user-error "Region to sort contains a level above the first entry"))
  7065. (unless sorting-type
  7066. (message
  7067. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7068. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7069. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7070. what)
  7071. (setq sorting-type (read-char-exclusive)))
  7072. (unless getkey-func
  7073. (and (= (downcase sorting-type) ?f)
  7074. (setq getkey-func
  7075. (or (and interactive?
  7076. (org-read-function
  7077. "Function for extracting keys: "))
  7078. (error "Missing key extractor")))))
  7079. (and (= (downcase sorting-type) ?r)
  7080. (not property)
  7081. (setq property
  7082. (completing-read "Property: "
  7083. (mapcar #'list (org-buffer-property-keys t))
  7084. nil t)))
  7085. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7086. (message "Sorting entries...")
  7087. (save-restriction
  7088. (narrow-to-region start end)
  7089. (let ((restore-clock?
  7090. ;; The clock marker is lost when using `sort-subr'; mark
  7091. ;; the clock with temporary `:org-clock-marker-backup'
  7092. ;; text property.
  7093. (when (and (eq (org-clock-is-active) (current-buffer))
  7094. (<= start (marker-position org-clock-marker))
  7095. (>= end (marker-position org-clock-marker)))
  7096. (with-silent-modifications
  7097. (put-text-property (1- org-clock-marker) org-clock-marker
  7098. :org-clock-marker-backup t))
  7099. t))
  7100. (dcst (downcase sorting-type))
  7101. (case-fold-search nil)
  7102. (now (current-time)))
  7103. (org-preserve-local-variables
  7104. (sort-subr
  7105. (/= dcst sorting-type)
  7106. ;; This function moves to the beginning character of the
  7107. ;; "record" to be sorted.
  7108. (lambda nil
  7109. (if (re-search-forward re nil t)
  7110. (goto-char (match-beginning 0))
  7111. (goto-char (point-max))))
  7112. ;; This function moves to the last character of the "record" being
  7113. ;; sorted.
  7114. (lambda nil
  7115. (save-match-data
  7116. (condition-case nil
  7117. (outline-forward-same-level 1)
  7118. (error
  7119. (goto-char (point-max))))))
  7120. ;; This function returns the value that gets sorted against.
  7121. (lambda ()
  7122. (cond
  7123. ((= dcst ?n)
  7124. (string-to-number
  7125. (org-sort-remove-invisible (org-get-heading t t t t))))
  7126. ((= dcst ?a)
  7127. (funcall case-func
  7128. (org-sort-remove-invisible (org-get-heading t t t t))))
  7129. ((= dcst ?k)
  7130. (or (get-text-property (point) :org-clock-minutes) 0))
  7131. ((= dcst ?t)
  7132. (let ((end (save-excursion (outline-next-heading) (point))))
  7133. (if (or (re-search-forward org-ts-regexp end t)
  7134. (re-search-forward org-ts-regexp-both end t))
  7135. (org-time-string-to-seconds (match-string 0))
  7136. (float-time now))))
  7137. ((= dcst ?c)
  7138. (let ((end (save-excursion (outline-next-heading) (point))))
  7139. (if (re-search-forward
  7140. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7141. end t)
  7142. (org-time-string-to-seconds (match-string 0))
  7143. (float-time now))))
  7144. ((= dcst ?s)
  7145. (let ((end (save-excursion (outline-next-heading) (point))))
  7146. (if (re-search-forward org-scheduled-time-regexp end t)
  7147. (org-time-string-to-seconds (match-string 1))
  7148. (float-time now))))
  7149. ((= dcst ?d)
  7150. (let ((end (save-excursion (outline-next-heading) (point))))
  7151. (if (re-search-forward org-deadline-time-regexp end t)
  7152. (org-time-string-to-seconds (match-string 1))
  7153. (float-time now))))
  7154. ((= dcst ?p)
  7155. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7156. (string-to-char (match-string 2))
  7157. org-priority-default))
  7158. ((= dcst ?r)
  7159. (or (org-entry-get nil property) ""))
  7160. ((= dcst ?o)
  7161. (when (looking-at org-complex-heading-regexp)
  7162. (let* ((m (match-string 2))
  7163. (s (if (member m org-done-keywords) '- '+)))
  7164. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7165. ((= dcst ?f)
  7166. (if getkey-func
  7167. (progn
  7168. (setq tmp (funcall getkey-func))
  7169. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7170. tmp)
  7171. (error "Invalid key function `%s'" getkey-func)))
  7172. (t (error "Invalid sorting type `%c'" sorting-type))))
  7173. nil
  7174. (cond
  7175. ((= dcst ?a) 'org-string-collate-lessp)
  7176. ((= dcst ?f)
  7177. (or compare-func
  7178. (and interactive?
  7179. (org-read-function
  7180. (concat "Function for comparing keys "
  7181. "(empty for default `sort-subr' predicate): ")
  7182. 'allow-empty))))
  7183. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7184. (org-cycle-hide-drawers 'all)
  7185. (when restore-clock?
  7186. (move-marker org-clock-marker
  7187. (1+ (next-single-property-change
  7188. start :org-clock-marker-backup)))
  7189. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7190. '(:org-clock-marker-backup t)))))
  7191. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7192. (message "Sorting entries...done")))
  7193. (defun org-contextualize-keys (alist contexts)
  7194. "Return valid elements in ALIST depending on CONTEXTS.
  7195. `org-agenda-custom-commands' or `org-capture-templates' are the
  7196. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7197. or `org-capture-templates-contexts' are the associated contexts
  7198. definitions."
  7199. (let ((contexts
  7200. ;; normalize contexts
  7201. (mapcar
  7202. (lambda(c) (cond ((listp (cadr c))
  7203. (list (car c) (car c) (nth 1 c)))
  7204. ((string= "" (cadr c))
  7205. (list (car c) (car c) (nth 2 c)))
  7206. (t c)))
  7207. contexts))
  7208. (a alist) r s)
  7209. ;; loop over all commands or templates
  7210. (dolist (c a)
  7211. (let (vrules repl)
  7212. (cond
  7213. ((not (assoc (car c) contexts))
  7214. (push c r))
  7215. ((and (assoc (car c) contexts)
  7216. (setq vrules (org-contextualize-validate-key
  7217. (car c) contexts)))
  7218. (mapc (lambda (vr)
  7219. (unless (equal (car vr) (cadr vr))
  7220. (setq repl vr)))
  7221. vrules)
  7222. (if (not repl) (push c r)
  7223. (push (cadr repl) s)
  7224. (push
  7225. (cons (car c)
  7226. (cdr (or (assoc (cadr repl) alist)
  7227. (error "Undefined key `%s' as contextual replacement for `%s'"
  7228. (cadr repl) (car c)))))
  7229. r))))))
  7230. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7231. (delq
  7232. nil
  7233. (delete-dups
  7234. (mapcar (lambda (x)
  7235. (let ((tpl (car x)))
  7236. (unless (delq
  7237. nil
  7238. (mapcar (lambda (y)
  7239. (equal y tpl))
  7240. s))
  7241. x)))
  7242. (reverse r))))))
  7243. (defun org-contextualize-validate-key (key contexts)
  7244. "Check CONTEXTS for agenda or capture KEY."
  7245. (let (res)
  7246. (dolist (r contexts)
  7247. (dolist (rr (car (last r)))
  7248. (when
  7249. (and (equal key (car r))
  7250. (if (functionp rr) (funcall rr)
  7251. (or (and (eq (car rr) 'in-file)
  7252. (buffer-file-name)
  7253. (string-match (cdr rr) (buffer-file-name)))
  7254. (and (eq (car rr) 'in-mode)
  7255. (string-match (cdr rr) (symbol-name major-mode)))
  7256. (and (eq (car rr) 'in-buffer)
  7257. (string-match (cdr rr) (buffer-name)))
  7258. (when (and (eq (car rr) 'not-in-file)
  7259. (buffer-file-name))
  7260. (not (string-match (cdr rr) (buffer-file-name))))
  7261. (when (eq (car rr) 'not-in-mode)
  7262. (not (string-match (cdr rr) (symbol-name major-mode))))
  7263. (when (eq (car rr) 'not-in-buffer)
  7264. (not (string-match (cdr rr) (buffer-name)))))))
  7265. (push r res))))
  7266. (delete-dups (delq nil res))))
  7267. ;; Defined to provide a value for defcustom, since there is no
  7268. ;; string-collate-greaterp in Emacs.
  7269. (defun org-string-collate-greaterp (s1 s2)
  7270. "Return non-nil if S1 is greater than S2 in collation order."
  7271. (not (org-string-collate-lessp s1 s2)))
  7272. ;;;###autoload
  7273. (defun org-run-like-in-org-mode (cmd)
  7274. "Run a command, pretending that the current buffer is in Org mode.
  7275. This will temporarily bind local variables that are typically bound in
  7276. Org mode to the values they have in Org mode, and then interactively
  7277. call CMD."
  7278. (org-load-modules-maybe)
  7279. (let (binds)
  7280. (dolist (var (org-get-local-variables))
  7281. (when (or (not (boundp (car var)))
  7282. (eq (symbol-value (car var))
  7283. (default-value (car var))))
  7284. (push (list (car var) `(quote ,(cadr var))) binds)))
  7285. (eval `(let ,binds
  7286. (call-interactively (quote ,cmd))))))
  7287. (defun org-get-category (&optional pos force-refresh)
  7288. "Get the category applying to position POS."
  7289. (save-match-data
  7290. (when force-refresh (org-refresh-category-properties))
  7291. (let ((pos (or pos (point))))
  7292. (or (get-text-property pos 'org-category)
  7293. (progn (org-refresh-category-properties)
  7294. (get-text-property pos 'org-category))))))
  7295. ;;; Refresh properties
  7296. (defun org-refresh-properties (dprop tprop)
  7297. "Refresh buffer text properties.
  7298. DPROP is the drawer property and TPROP is either the
  7299. corresponding text property to set, or an alist with each element
  7300. being a text property (as a symbol) and a function to apply to
  7301. the value of the drawer property."
  7302. (let* ((case-fold-search t)
  7303. (inhibit-read-only t)
  7304. (inherit? (org-property-inherit-p dprop))
  7305. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7306. (global-or-keyword (and inherit?
  7307. (org--property-global-or-keyword-value dprop nil))))
  7308. (with-silent-modifications
  7309. (org-with-point-at 1
  7310. ;; Set global and keyword based values to the whole buffer.
  7311. (when global-or-keyword
  7312. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7313. ;; Set values based on property-drawers throughout the document.
  7314. (while (re-search-forward property-re nil t)
  7315. (when (org-at-property-p)
  7316. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7317. (outline-next-heading))))))
  7318. (defun org-refresh-property (tprop p &optional inherit)
  7319. "Refresh the buffer text property TPROP from the drawer property P.
  7320. The refresh happens only for the current entry, or the whole
  7321. sub-tree if optional argument INHERIT is non-nil.
  7322. If point is before first headline, the function applies to the
  7323. part before the first headline. In that particular case, when
  7324. optional argument INHERIT is non-nil, it refreshes properties for
  7325. the whole buffer."
  7326. (save-excursion
  7327. (org-back-to-heading-or-point-min t)
  7328. (let ((start (point))
  7329. (end (save-excursion
  7330. (cond ((and inherit (org-before-first-heading-p))
  7331. (point-max))
  7332. (inherit
  7333. (org-end-of-subtree t t))
  7334. ((outline-next-heading))
  7335. ((point-max))))))
  7336. (if (symbolp tprop)
  7337. ;; TPROP is a text property symbol.
  7338. (put-text-property start end tprop p)
  7339. ;; TPROP is an alist with (property . function) elements.
  7340. (pcase-dolist (`(,prop . ,f) tprop)
  7341. (put-text-property start end prop (funcall f p)))))))
  7342. (defun org-refresh-category-properties ()
  7343. "Refresh category text properties in the buffer."
  7344. (let ((case-fold-search t)
  7345. (inhibit-read-only t)
  7346. (default-category
  7347. (cond ((null org-category)
  7348. (if buffer-file-name
  7349. (file-name-sans-extension
  7350. (file-name-nondirectory buffer-file-name))
  7351. "???"))
  7352. ((symbolp org-category) (symbol-name org-category))
  7353. (t org-category))))
  7354. (with-silent-modifications
  7355. (org-with-wide-buffer
  7356. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7357. ;; keyword. If none is found, fall-back to `org-category' or
  7358. ;; buffer file name, or set it by the document property drawer.
  7359. (put-text-property
  7360. (point-min) (point-max)
  7361. 'org-category
  7362. (catch 'buffer-category
  7363. (goto-char (point-max))
  7364. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7365. (let ((element (org-element-at-point)))
  7366. (when (eq (org-element-type element) 'keyword)
  7367. (throw 'buffer-category
  7368. (org-element-property :value element)))))
  7369. default-category))
  7370. ;; Set categories from the document property drawer or
  7371. ;; property drawers in the outline. If category is found in
  7372. ;; the property drawer for the whole buffer that value
  7373. ;; overrides the keyword-based value set above.
  7374. (goto-char (point-min))
  7375. (let ((regexp (org-re-property "CATEGORY")))
  7376. (while (re-search-forward regexp nil t)
  7377. (let ((value (match-string-no-properties 3)))
  7378. (when (org-at-property-p)
  7379. (put-text-property
  7380. (save-excursion (org-back-to-heading-or-point-min t))
  7381. (save-excursion (if (org-before-first-heading-p)
  7382. (point-max)
  7383. (org-end-of-subtree t t)))
  7384. 'org-category
  7385. value)))))))))
  7386. (defun org-refresh-stats-properties ()
  7387. "Refresh stats text properties in the buffer."
  7388. (with-silent-modifications
  7389. (org-with-point-at 1
  7390. (let ((regexp (concat org-outline-regexp-bol
  7391. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7392. (while (re-search-forward regexp nil t)
  7393. (let* ((numerator (string-to-number (match-string 1)))
  7394. (denominator (and (match-end 2)
  7395. (string-to-number (match-string 2))))
  7396. (stats (cond ((not denominator) numerator) ;percent
  7397. ((= denominator 0) 0)
  7398. (t (/ (* numerator 100) denominator)))))
  7399. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7400. 'org-stats stats)))))))
  7401. (defun org-refresh-effort-properties ()
  7402. "Refresh effort properties."
  7403. (org-refresh-properties
  7404. org-effort-property
  7405. '((effort . identity)
  7406. (effort-minutes . org-duration-to-minutes))))
  7407. (defun org-find-file-at-mouse (ev)
  7408. "Open file link or URL at mouse."
  7409. (interactive "e")
  7410. (mouse-set-point ev)
  7411. (org-open-at-point 'in-emacs))
  7412. (defun org-open-at-mouse (ev)
  7413. "Open file link or URL at mouse.
  7414. See the docstring of `org-open-file' for details."
  7415. (interactive "e")
  7416. (mouse-set-point ev)
  7417. (when (eq major-mode 'org-agenda-mode)
  7418. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7419. (org-open-at-point))
  7420. (defvar org-window-config-before-follow-link nil
  7421. "The window configuration before following a link.
  7422. This is saved in case the need arises to restore it.")
  7423. (defun org--file-default-apps ()
  7424. "Return the default applications for this operating system."
  7425. (pcase system-type
  7426. (`darwin org-file-apps-macos)
  7427. (`windows-nt org-file-apps-windowsnt)
  7428. (_ org-file-apps-gnu)))
  7429. (defun org--file-apps-entry-dlink-p (entry)
  7430. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7431. It assumes that is the case when the entry uses a regular
  7432. expression which has at least one grouping construct and the
  7433. action is either a Lisp form or a command string containing
  7434. \"%1\", i.e., using at least one subexpression match as
  7435. a parameter."
  7436. (pcase entry
  7437. (`(,selector . ,action)
  7438. (and (stringp selector)
  7439. (> (regexp-opt-depth selector) 0)
  7440. (or (and (stringp action)
  7441. (string-match "%[0-9]" action))
  7442. (consp action))))
  7443. (_ nil)))
  7444. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7445. "Convert extensions to regular expressions in the cars of LIST.
  7446. Also, weed out any non-string entries, because the return value
  7447. is used only for regexp matching.
  7448. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7449. point to the symbol `emacs', indicating that the file should be
  7450. opened in Emacs."
  7451. (append
  7452. (delq nil
  7453. (mapcar (lambda (x)
  7454. (unless (not (stringp (car x)))
  7455. (if (string-match "\\W" (car x))
  7456. x
  7457. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7458. list))
  7459. (when add-auto-mode
  7460. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7461. ;;;###autoload
  7462. (defun org-open-file (path &optional in-emacs line search)
  7463. "Open the file at PATH.
  7464. First, this expands any special file name abbreviations. Then the
  7465. configuration variable `org-file-apps' is checked if it contains an
  7466. entry for this file type, and if yes, the corresponding command is launched.
  7467. If no application is found, Emacs simply visits the file.
  7468. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7469. With a double \\[universal-argument] \\[universal-argument] \
  7470. prefix arg, Org tries to avoid opening in Emacs
  7471. and to use an external application to visit the file.
  7472. Optional LINE specifies a line to go to, optional SEARCH a string
  7473. to search for. If LINE or SEARCH is given, the file will be
  7474. opened in Emacs, unless an entry from `org-file-apps' that makes
  7475. use of groups in a regexp matches.
  7476. If you want to change the way frames are used when following a
  7477. link, please customize `org-link-frame-setup'.
  7478. If the file does not exist, throw an error."
  7479. (let* ((file (if (equal path "") buffer-file-name
  7480. (substitute-in-file-name (expand-file-name path))))
  7481. (file-apps (append org-file-apps (org--file-default-apps)))
  7482. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7483. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7484. file-apps))
  7485. (remp (and (assq 'remote apps) (file-remote-p file)))
  7486. (dirp (unless remp (file-directory-p file)))
  7487. (file (if (and dirp org-open-directory-means-index-dot-org)
  7488. (concat (file-name-as-directory file) "index.org")
  7489. file))
  7490. (a-m-a-p (assq 'auto-mode apps))
  7491. (dfile (downcase file))
  7492. ;; Reconstruct the original link from the PATH, LINE and
  7493. ;; SEARCH args.
  7494. (link (cond (line (concat file "::" (number-to-string line)))
  7495. (search (concat file "::" search))
  7496. (t file)))
  7497. (dlink (downcase link))
  7498. (ext
  7499. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7500. (match-string 1 dfile)))
  7501. (save-position-maybe
  7502. (let ((old-buffer (current-buffer))
  7503. (old-pos (point))
  7504. (old-mode major-mode))
  7505. (lambda ()
  7506. (and (derived-mode-p 'org-mode)
  7507. (eq old-mode 'org-mode)
  7508. (or (not (eq old-buffer (current-buffer)))
  7509. (not (eq old-pos (point))))
  7510. (org-mark-ring-push old-pos old-buffer)))))
  7511. cmd link-match-data)
  7512. (cond
  7513. ((member in-emacs '((16) system))
  7514. (setq cmd (cdr (assq 'system apps))))
  7515. (in-emacs (setq cmd 'emacs))
  7516. (t
  7517. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7518. (and dirp (cdr (assq 'directory apps)))
  7519. ;; First, try matching against apps-dlink if we
  7520. ;; get a match here, store the match data for
  7521. ;; later.
  7522. (let ((match (assoc-default dlink apps-dlink
  7523. 'string-match)))
  7524. (if match
  7525. (progn (setq link-match-data (match-data))
  7526. match)
  7527. (progn (setq in-emacs (or in-emacs line search))
  7528. nil))) ; if we have no match in apps-dlink,
  7529. ; always open the file in emacs if line or search
  7530. ; is given (for backwards compatibility)
  7531. (assoc-default dfile
  7532. (org--file-apps-regexp-alist apps a-m-a-p)
  7533. 'string-match)
  7534. (cdr (assoc ext apps))
  7535. (cdr (assq t apps))))))
  7536. (when (eq cmd 'system)
  7537. (setq cmd (cdr (assq 'system apps))))
  7538. (when (eq cmd 'default)
  7539. (setq cmd (cdr (assoc t apps))))
  7540. (when (eq cmd 'mailcap)
  7541. (require 'mailcap)
  7542. (mailcap-parse-mailcaps)
  7543. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7544. (command (mailcap-mime-info mime-type)))
  7545. (if (stringp command)
  7546. (setq cmd command)
  7547. (setq cmd 'emacs))))
  7548. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7549. (not (file-exists-p file))
  7550. (not org-open-non-existing-files))
  7551. (user-error "No such file: %s" file))
  7552. (cond
  7553. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7554. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7555. (while (string-match "['\"]%s['\"]" cmd)
  7556. (setq cmd (replace-match "%s" t t cmd)))
  7557. (setq cmd (replace-regexp-in-string
  7558. "%s"
  7559. (shell-quote-argument (convert-standard-filename file))
  7560. cmd
  7561. nil t))
  7562. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7563. (save-match-data
  7564. (let ((match-index 1)
  7565. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7566. (set-match-data link-match-data)
  7567. (while (<= match-index number-of-groups)
  7568. (let ((regex (concat "%" (number-to-string match-index)))
  7569. (replace-with (match-string match-index dlink)))
  7570. (while (string-match regex cmd)
  7571. (setq cmd (replace-match replace-with t t cmd))))
  7572. (setq match-index (+ match-index 1)))))
  7573. (save-window-excursion
  7574. (message "Running %s...done" cmd)
  7575. (start-process-shell-command cmd nil cmd)
  7576. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7577. ((or (stringp cmd)
  7578. (eq cmd 'emacs))
  7579. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7580. (widen)
  7581. (cond (line (org-goto-line line)
  7582. (when (derived-mode-p 'org-mode) (org-reveal)))
  7583. (search (condition-case err
  7584. (org-link-search search)
  7585. ;; Save position before error-ing out so user
  7586. ;; can easily move back to the original buffer.
  7587. (error (funcall save-position-maybe)
  7588. (error (nth 1 err)))))))
  7589. ((functionp cmd)
  7590. (save-match-data
  7591. (set-match-data link-match-data)
  7592. (condition-case nil
  7593. (funcall cmd file link)
  7594. ;; FIXME: Remove this check when most default installations
  7595. ;; of Emacs have at least Org 9.0.
  7596. ((debug wrong-number-of-arguments wrong-type-argument
  7597. invalid-function)
  7598. (user-error "Please see Org News for version 9.0 about \
  7599. `org-file-apps'--Lisp error: %S" cmd)))))
  7600. ((consp cmd)
  7601. ;; FIXME: Remove this check when most default installations of
  7602. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7603. ;; fall back to `org-link-frame-setup' for an old usage of
  7604. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7605. (user-error "Please see Org News for version 9.0 about \
  7606. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7607. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7608. (funcall save-position-maybe)))
  7609. ;;;###autoload
  7610. (defun org-open-at-point-global ()
  7611. "Follow a link or a time-stamp like Org mode does.
  7612. Also follow links and emails as seen by `thing-at-point'.
  7613. This command can be called in any mode to follow an external
  7614. link or a time-stamp that has Org mode syntax. Its behavior
  7615. is undefined when called on internal links like fuzzy links.
  7616. Raise a user error when there is nothing to follow."
  7617. (interactive)
  7618. (let ((tap-url (thing-at-point 'url))
  7619. (tap-email (thing-at-point 'email)))
  7620. (cond ((org-in-regexp org-link-any-re)
  7621. (org-link-open-from-string (match-string-no-properties 0)))
  7622. ((or (org-in-regexp org-ts-regexp-both nil t)
  7623. (org-in-regexp org-tsr-regexp-both nil t))
  7624. (org-follow-timestamp-link))
  7625. (tap-url (org-link-open-from-string tap-url))
  7626. (tap-email (org-link-open-from-string
  7627. (concat "mailto:" tap-email)))
  7628. (t (user-error "No link found")))))
  7629. (defvar org-open-at-point-functions nil
  7630. "Hook that is run when following a link at point.
  7631. Functions in this hook must return t if they identify and follow
  7632. a link at point. If they don't find anything interesting at point,
  7633. they must return nil.")
  7634. (defun org-open-at-point (&optional arg)
  7635. "Open link, timestamp, footnote or tags at point.
  7636. When point is on a link, follow it. Normally, files will be
  7637. opened by an appropriate application. If the optional prefix
  7638. argument ARG is non-nil, Emacs will visit the file. With
  7639. a double prefix argument, try to open outside of Emacs, in the
  7640. application the system uses for this file type.
  7641. When point is on a timestamp, open the agenda at the day
  7642. specified.
  7643. When point is a footnote definition, move to the first reference
  7644. found. If it is on a reference, move to the associated
  7645. definition.
  7646. When point is on a headline, display a list of every link in the
  7647. entry, so it is possible to pick one, or all, of them. If point
  7648. is on a tag, call `org-tags-view' instead.
  7649. On top of syntactically correct links, this function also tries
  7650. to open links and time-stamps in comments, node properties, and
  7651. keywords if point is on something looking like a timestamp or
  7652. a link."
  7653. (interactive "P")
  7654. (org-load-modules-maybe)
  7655. (setq org-window-config-before-follow-link (current-window-configuration))
  7656. (org-remove-occur-highlights nil nil t)
  7657. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7658. (let* ((context
  7659. ;; Only consider supported types, even if they are not the
  7660. ;; closest one.
  7661. (org-element-lineage
  7662. (org-element-context)
  7663. '(clock comment comment-block footnote-definition
  7664. footnote-reference headline inline-src-block inlinetask
  7665. keyword link node-property planning src-block timestamp)
  7666. t))
  7667. (type (org-element-type context))
  7668. (value (org-element-property :value context)))
  7669. (cond
  7670. ((not type) (user-error "No link found"))
  7671. ;; No valid link at point. For convenience, look if something
  7672. ;; looks like a link under point in some specific places.
  7673. ((memq type '(comment comment-block node-property keyword))
  7674. (call-interactively #'org-open-at-point-global))
  7675. ;; On a headline or an inlinetask, but not on a timestamp,
  7676. ;; a link, a footnote reference.
  7677. ((memq type '(headline inlinetask))
  7678. (org-match-line org-complex-heading-regexp)
  7679. (let ((tags-beg (match-beginning 5))
  7680. (tags-end (match-end 5)))
  7681. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7682. ;; On tags.
  7683. (org-tags-view
  7684. arg
  7685. (save-excursion
  7686. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7687. (end-tag (search-forward ":" tags-end nil 2)))
  7688. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7689. ;; Not on tags.
  7690. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7691. (`(nil . ,_)
  7692. (require 'org-attach)
  7693. (when (org-attach-dir)
  7694. (message "Opening attachment")
  7695. (if (equal arg '(4))
  7696. (org-attach-reveal-in-emacs)
  7697. (org-attach-reveal))))
  7698. (`(,links . ,links-end)
  7699. (dolist (link (if (stringp links) (list links) links))
  7700. (search-forward link nil links-end)
  7701. (goto-char (match-beginning 0))
  7702. (org-open-at-point arg)))))))
  7703. ;; On a footnote reference or at definition's label.
  7704. ((or (eq type 'footnote-reference)
  7705. (and (eq type 'footnote-definition)
  7706. (save-excursion
  7707. ;; Do not validate action when point is on the
  7708. ;; spaces right after the footnote label, in order
  7709. ;; to be on par with behavior on links.
  7710. (skip-chars-forward " \t")
  7711. (let ((begin
  7712. (org-element-property :contents-begin context)))
  7713. (if begin (< (point) begin)
  7714. (= (org-element-property :post-affiliated context)
  7715. (line-beginning-position)))))))
  7716. (org-footnote-action))
  7717. ;; On a planning line. Check if we are really on a timestamp.
  7718. ((and (eq type 'planning)
  7719. (org-in-regexp org-ts-regexp-both nil t))
  7720. (org-follow-timestamp-link))
  7721. ;; On a clock line, make sure point is on the timestamp
  7722. ;; before opening it.
  7723. ((and (eq type 'clock)
  7724. value
  7725. (>= (point) (org-element-property :begin value))
  7726. (<= (point) (org-element-property :end value)))
  7727. (org-follow-timestamp-link))
  7728. ((eq type 'src-block) (org-babel-open-src-block-result))
  7729. ;; Do nothing on white spaces after an object.
  7730. ((>= (point)
  7731. (save-excursion
  7732. (goto-char (org-element-property :end context))
  7733. (skip-chars-backward " \t")
  7734. (point)))
  7735. (user-error "No link found"))
  7736. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7737. ((eq type 'timestamp) (org-follow-timestamp-link))
  7738. ((eq type 'link) (org-link-open context arg))
  7739. (t (user-error "No link found")))))
  7740. (run-hook-with-args 'org-follow-link-hook))
  7741. ;;;###autoload
  7742. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7743. "Offer links in the current entry and return the selected link.
  7744. If there is only one link, return it.
  7745. If NTH is an integer, return the NTH link found.
  7746. If ZERO is a string, check also this string for a link, and if
  7747. there is one, return it."
  7748. (with-current-buffer buffer
  7749. (org-with-wide-buffer
  7750. (goto-char marker)
  7751. (let ((cnt ?0)
  7752. have-zero end links link c)
  7753. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7754. (push (match-string 0 zero) links)
  7755. (setq cnt (1- cnt) have-zero t))
  7756. (save-excursion
  7757. (org-back-to-heading t)
  7758. (setq end (save-excursion (outline-next-heading) (point)))
  7759. (while (re-search-forward org-link-any-re end t)
  7760. (push (match-string 0) links))
  7761. (setq links (org-uniquify (reverse links))))
  7762. (cond
  7763. ((null links)
  7764. (message "No links"))
  7765. ((equal (length links) 1)
  7766. (setq link (car links)))
  7767. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7768. (setq link (nth (if have-zero nth (1- nth)) links)))
  7769. (t ; we have to select a link
  7770. (save-excursion
  7771. (save-window-excursion
  7772. (delete-other-windows)
  7773. (with-output-to-temp-buffer "*Select Link*"
  7774. (dolist (l links)
  7775. (cond
  7776. ((not (string-match org-link-bracket-re l))
  7777. (princ (format "[%c] %s\n" (cl-incf cnt)
  7778. (org-unbracket-string "<" ">" l))))
  7779. ((match-end 2)
  7780. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7781. (match-string 2 l) (match-string 1 l))))
  7782. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7783. (match-string 1 l)))))))
  7784. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7785. (message "Select link to open, RET to open all:")
  7786. (setq c (read-char-exclusive))
  7787. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7788. (when (equal c ?q) (user-error "Abort"))
  7789. (if (equal c ?\C-m)
  7790. (setq link links)
  7791. (setq nth (- c ?0))
  7792. (when have-zero (setq nth (1+ nth)))
  7793. (unless (and (integerp nth) (>= (length links) nth))
  7794. (user-error "Invalid link selection"))
  7795. (setq link (nth (1- nth) links)))))
  7796. (cons link end)))))
  7797. ;;; File search
  7798. (defun org-do-occur (regexp &optional cleanup)
  7799. "Call the Emacs command `occur'.
  7800. If CLEANUP is non-nil, remove the printout of the regular expression
  7801. in the *Occur* buffer. This is useful if the regex is long and not useful
  7802. to read."
  7803. (occur regexp)
  7804. (when cleanup
  7805. (let ((cwin (selected-window)) win beg end)
  7806. (when (setq win (get-buffer-window "*Occur*"))
  7807. (select-window win))
  7808. (goto-char (point-min))
  7809. (when (re-search-forward "match[a-z]+" nil t)
  7810. (setq beg (match-end 0))
  7811. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7812. (setq end (1- (match-beginning 0)))))
  7813. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7814. (goto-char (point-min))
  7815. (select-window cwin))))
  7816. ;;; The Mark Ring
  7817. (defvar org-mark-ring nil
  7818. "Mark ring for positions before jumps in Org mode.")
  7819. (defvar org-mark-ring-last-goto nil
  7820. "Last position in the mark ring used to go back.")
  7821. ;; Fill and close the ring
  7822. (setq org-mark-ring nil)
  7823. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7824. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7825. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7826. org-mark-ring)
  7827. (defun org-mark-ring-push (&optional pos buffer)
  7828. "Put the current position into the mark ring and rotate it.
  7829. Also push position into the Emacs mark ring. If optional
  7830. argument POS and BUFFER are not nil, mark this location instead."
  7831. (interactive)
  7832. (let ((pos (or pos (point)))
  7833. (buffer (or buffer (current-buffer))))
  7834. (with-current-buffer buffer
  7835. (org-with-point-at pos (push-mark nil t)))
  7836. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7837. (move-marker (car org-mark-ring) pos buffer))
  7838. (message
  7839. (substitute-command-keys
  7840. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7841. (defun org-mark-ring-goto (&optional n)
  7842. "Jump to the previous position in the mark ring.
  7843. With prefix arg N, jump back that many stored positions. When
  7844. called several times in succession, walk through the entire ring.
  7845. Org mode commands jumping to a different position in the current file,
  7846. or to another Org file, automatically push the old position onto the ring."
  7847. (interactive "p")
  7848. (let (p m)
  7849. (if (eq last-command this-command)
  7850. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7851. (setq p org-mark-ring))
  7852. (setq org-mark-ring-last-goto p)
  7853. (setq m (car p))
  7854. (pop-to-buffer-same-window (marker-buffer m))
  7855. (goto-char m)
  7856. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7857. ;;; Following specific links
  7858. (defvar org-agenda-buffer-tmp-name)
  7859. (defvar org-agenda-start-on-weekday)
  7860. (defun org-follow-timestamp-link ()
  7861. "Open an agenda view for the time-stamp date/range at point."
  7862. (cond
  7863. ((org-at-date-range-p t)
  7864. (let ((org-agenda-start-on-weekday)
  7865. (t1 (match-string 1))
  7866. (t2 (match-string 2)) tt1 tt2)
  7867. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7868. tt2 (time-to-days (org-time-string-to-time t2)))
  7869. (let ((org-agenda-buffer-tmp-name
  7870. (format "*Org Agenda(a:%s)"
  7871. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7872. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7873. ((org-at-timestamp-p 'lax)
  7874. (let ((org-agenda-buffer-tmp-name
  7875. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7876. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7877. (substring (match-string 1) 0 10)))
  7878. 1)))
  7879. (t (error "This should not happen"))))
  7880. ;;; Following file links
  7881. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7882. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7883. (declare-function mailcap-mime-info
  7884. "mailcap" (string &optional request no-decode))
  7885. (defvar org-wait nil)
  7886. ;;;; Refiling
  7887. (defun org-get-org-file ()
  7888. "Read a filename, with default directory `org-directory'."
  7889. (let ((default (or org-default-notes-file remember-data-file)))
  7890. (read-file-name (format "File name [%s]: " default)
  7891. (file-name-as-directory org-directory)
  7892. default)))
  7893. (defun org-notes-order-reversed-p ()
  7894. "Check if the current file should receive notes in reversed order."
  7895. (cond
  7896. ((not org-reverse-note-order) nil)
  7897. ((eq t org-reverse-note-order) t)
  7898. ((not (listp org-reverse-note-order)) nil)
  7899. (t (catch 'exit
  7900. (dolist (entry org-reverse-note-order)
  7901. (when (string-match (car entry) buffer-file-name)
  7902. (throw 'exit (cdr entry))))))))
  7903. (defvar org-agenda-new-buffers nil
  7904. "Buffers created to visit agenda files.")
  7905. (declare-function org-string-nw-p "org-macs" (s))
  7906. ;;;; Dynamic blocks
  7907. (defun org-find-dblock (name)
  7908. "Find the first dynamic block with name NAME in the buffer.
  7909. If not found, stay at current position and return nil."
  7910. (let ((case-fold-search t) pos)
  7911. (save-excursion
  7912. (goto-char (point-min))
  7913. (setq pos (and (re-search-forward
  7914. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7915. (match-beginning 0))))
  7916. (when pos (goto-char pos))
  7917. pos))
  7918. (defun org-create-dblock (plist)
  7919. "Create a dynamic block section, with parameters taken from PLIST.
  7920. PLIST must contain a :name entry which is used as the name of the block."
  7921. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7922. (end-of-line 1)
  7923. (newline))
  7924. (let ((col (current-column))
  7925. (name (plist-get plist :name)))
  7926. (insert "#+BEGIN: " name)
  7927. (while plist
  7928. (if (eq (car plist) :name)
  7929. (setq plist (cddr plist))
  7930. (insert " " (prin1-to-string (pop plist)))))
  7931. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7932. (beginning-of-line -2)))
  7933. (defun org-prepare-dblock ()
  7934. "Prepare dynamic block for refresh.
  7935. This empties the block, puts the cursor at the insert position and returns
  7936. the property list including an extra property :name with the block name."
  7937. (unless (looking-at org-dblock-start-re)
  7938. (user-error "Not at a dynamic block"))
  7939. (let* ((begdel (1+ (match-end 0)))
  7940. (name (org-no-properties (match-string 1)))
  7941. (params (append (list :name name)
  7942. (read (concat "(" (match-string 3) ")")))))
  7943. (save-excursion
  7944. (beginning-of-line 1)
  7945. (skip-chars-forward " \t")
  7946. (setq params (plist-put params :indentation-column (current-column))))
  7947. (unless (re-search-forward org-dblock-end-re nil t)
  7948. (error "Dynamic block not terminated"))
  7949. (setq params
  7950. (append params
  7951. (list :content (buffer-substring
  7952. begdel (match-beginning 0)))))
  7953. (delete-region begdel (match-beginning 0))
  7954. (goto-char begdel)
  7955. (open-line 1)
  7956. params))
  7957. (defun org-map-dblocks (&optional command)
  7958. "Apply COMMAND to all dynamic blocks in the current buffer.
  7959. If COMMAND is not given, use `org-update-dblock'."
  7960. (let ((cmd (or command 'org-update-dblock)))
  7961. (save-excursion
  7962. (goto-char (point-min))
  7963. (while (re-search-forward org-dblock-start-re nil t)
  7964. (goto-char (match-beginning 0))
  7965. (save-excursion
  7966. (condition-case nil
  7967. (funcall cmd)
  7968. (error (message "Error during update of dynamic block"))))
  7969. (unless (re-search-forward org-dblock-end-re nil t)
  7970. (error "Dynamic block not terminated"))))))
  7971. (defvar org-dynamic-block-alist nil
  7972. "Alist defining all the Org dynamic blocks.
  7973. The key is the dynamic block type name, as a string. The value
  7974. is the function used to insert the dynamic block.
  7975. Use `org-dynamic-block-define' to populate it.")
  7976. (defun org-dynamic-block-function (type)
  7977. "Return function associated to a given dynamic block type.
  7978. TYPE is the dynamic block type, as a string."
  7979. (cdr (assoc type org-dynamic-block-alist)))
  7980. (defun org-dynamic-block-types ()
  7981. "List all defined dynamic block types."
  7982. (mapcar #'car org-dynamic-block-alist))
  7983. (defun org-dynamic-block-define (type func)
  7984. "Define dynamic block TYPE with FUNC.
  7985. TYPE is a string. FUNC is the function creating the dynamic
  7986. block of such type."
  7987. (pcase (assoc type org-dynamic-block-alist)
  7988. (`nil (push (cons type func) org-dynamic-block-alist))
  7989. (def (setcdr def func))))
  7990. (defun org-dynamic-block-insert-dblock (type)
  7991. "Insert a dynamic block of type TYPE.
  7992. When used interactively, select the dynamic block types among
  7993. defined types, per `org-dynamic-block-define'."
  7994. (interactive (list (completing-read "Dynamic block: "
  7995. (org-dynamic-block-types))))
  7996. (pcase (org-dynamic-block-function type)
  7997. (`nil (error "No such dynamic block: %S" type))
  7998. ((and f (pred functionp)) (funcall f))
  7999. (_ (error "Invalid function for dynamic block %S" type))))
  8000. (defun org-dblock-update (&optional arg)
  8001. "User command for updating dynamic blocks.
  8002. Update the dynamic block at point. With prefix ARG, update all dynamic
  8003. blocks in the buffer."
  8004. (interactive "P")
  8005. (if arg
  8006. (org-update-all-dblocks)
  8007. (or (looking-at org-dblock-start-re)
  8008. (org-beginning-of-dblock))
  8009. (org-update-dblock)))
  8010. (defun org-update-dblock ()
  8011. "Update the dynamic block at point.
  8012. This means to empty the block, parse for parameters and then call
  8013. the correct writing function."
  8014. (interactive)
  8015. (save-excursion
  8016. (let* ((win (selected-window))
  8017. (pos (point))
  8018. (line (org-current-line))
  8019. (params (org-prepare-dblock))
  8020. (name (plist-get params :name))
  8021. (indent (plist-get params :indentation-column))
  8022. (cmd (intern (concat "org-dblock-write:" name))))
  8023. (message "Updating dynamic block `%s' at line %d..." name line)
  8024. (funcall cmd params)
  8025. (message "Updating dynamic block `%s' at line %d...done" name line)
  8026. (goto-char pos)
  8027. (when (and indent (> indent 0))
  8028. (setq indent (make-string indent ?\ ))
  8029. (save-excursion
  8030. (select-window win)
  8031. (org-beginning-of-dblock)
  8032. (forward-line 1)
  8033. (while (not (looking-at org-dblock-end-re))
  8034. (insert indent)
  8035. (beginning-of-line 2))
  8036. (when (looking-at org-dblock-end-re)
  8037. (and (looking-at "[ \t]+")
  8038. (replace-match ""))
  8039. (insert indent)))))))
  8040. (defun org-beginning-of-dblock ()
  8041. "Find the beginning of the dynamic block at point.
  8042. Error if there is no such block at point."
  8043. (let ((pos (point))
  8044. beg)
  8045. (end-of-line 1)
  8046. (if (and (re-search-backward org-dblock-start-re nil t)
  8047. (setq beg (match-beginning 0))
  8048. (re-search-forward org-dblock-end-re nil t)
  8049. (> (match-end 0) pos))
  8050. (goto-char beg)
  8051. (goto-char pos)
  8052. (error "Not in a dynamic block"))))
  8053. (defun org-update-all-dblocks ()
  8054. "Update all dynamic blocks in the buffer.
  8055. This function can be used in a hook."
  8056. (interactive)
  8057. (when (derived-mode-p 'org-mode)
  8058. (org-map-dblocks 'org-update-dblock)))
  8059. ;;;; Completion
  8060. (declare-function org-export-backend-options "ox" (cl-x) t)
  8061. (defun org-get-export-keywords ()
  8062. "Return a list of all currently understood export keywords.
  8063. Export keywords include options, block names, attributes and
  8064. keywords relative to each registered export back-end."
  8065. (let (keywords)
  8066. (dolist (backend
  8067. (bound-and-true-p org-export-registered-backends)
  8068. (delq nil keywords))
  8069. ;; Back-end name (for keywords, like #+LATEX:)
  8070. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8071. (dolist (option-entry (org-export-backend-options backend))
  8072. ;; Back-end options.
  8073. (push (nth 1 option-entry) keywords)))))
  8074. (defconst org-options-keywords
  8075. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8076. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8077. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8078. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8079. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8080. (defcustom org-structure-template-alist
  8081. '(("a" . "export ascii")
  8082. ("c" . "center")
  8083. ("C" . "comment")
  8084. ("e" . "example")
  8085. ("E" . "export")
  8086. ("h" . "export html")
  8087. ("l" . "export latex")
  8088. ("q" . "quote")
  8089. ("s" . "src")
  8090. ("v" . "verse"))
  8091. "An alist of keys and block types.
  8092. `org-insert-structure-template' will display a menu with this
  8093. list of templates to choose from. The block type is inserted,
  8094. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8095. The menu keys are defined by the car of each entry in this alist.
  8096. If two entries have the keys \"a\" and \"aa\" respectively, the
  8097. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8098. latter will be inserted by typing \"aa\". If an entry with the
  8099. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8100. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8101. block can be inserted by pressing TAB after the string \"<KEY\"."
  8102. :group 'org-edit-structure
  8103. :type '(repeat
  8104. (cons (string :tag "Key")
  8105. (string :tag "Template")))
  8106. :package-version '(Org . "9.2"))
  8107. (defun org--check-org-structure-template-alist (&optional checklist)
  8108. "Check whether `org-structure-template-alist' is set up correctly.
  8109. In particular, check if the Org 9.2 format is used as opposed to
  8110. previous format.
  8111. "
  8112. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8113. (or (eval checklist)
  8114. org-structure-template-alist))))
  8115. (when elm
  8116. (org-display-warning
  8117. (format "
  8118. Please update the entries of `%s'.
  8119. In Org 9.2 the format was changed from something like
  8120. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8121. to something like
  8122. (\"s\" . \"src\")
  8123. Please refer to the documentation of `org-structure-template-alist'.
  8124. The following entries must be updated:
  8125. %s"
  8126. (or checklist 'org-structure-template-alist)
  8127. (pp-to-string elm))))))
  8128. (defun org--insert-structure-template-mks ()
  8129. "Present `org-structure-template-alist' with `org-mks'.
  8130. Menus are added if keys require more than one keystroke. Tabs
  8131. are added to single key entries when more than one stroke is
  8132. needed. Keys longer than two characters are reduced to two
  8133. characters."
  8134. (org--check-org-structure-template-alist)
  8135. (let* (case-fold-search
  8136. (templates (append org-structure-template-alist
  8137. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8138. (keys (mapcar #'car templates))
  8139. (start-letters
  8140. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8141. ;; Sort each element of `org-structure-template-alist' into
  8142. ;; sublists according to the first letter.
  8143. (superlist
  8144. (mapcar (lambda (letter)
  8145. (list letter
  8146. (cl-remove-if-not
  8147. (apply-partially #'string-match-p (concat "^" letter))
  8148. templates :key #'car)))
  8149. start-letters)))
  8150. (org-mks
  8151. (apply #'append
  8152. ;; Make an `org-mks' table. If only one element is
  8153. ;; present in a sublist, make it part of the top-menu,
  8154. ;; otherwise make a submenu according to the starting
  8155. ;; letter and populate it.
  8156. (mapcar (lambda (sublist)
  8157. (if (eq 1 (length (cadr sublist)))
  8158. (mapcar (lambda (elm)
  8159. (list (substring (car elm) 0 1)
  8160. (cdr elm) ""))
  8161. (cadr sublist))
  8162. ;; Create submenu.
  8163. (let* ((topkey (car sublist))
  8164. (elms (cadr sublist))
  8165. (keys (mapcar #'car elms))
  8166. (long (> (length elms) 3)))
  8167. (append
  8168. (list
  8169. ;; Make a description of the submenu.
  8170. (list topkey
  8171. (concat
  8172. (mapconcat #'cdr
  8173. (cl-subseq elms 0 (if long 3 (length elms)))
  8174. ", ")
  8175. (when long ", ..."))))
  8176. ;; List of entries in submenu.
  8177. (cl-mapcar #'list
  8178. (org--insert-structure-template-unique-keys keys)
  8179. (mapcar #'cdr elms)
  8180. (make-list (length elms) ""))))))
  8181. superlist))
  8182. "Select a key\n============"
  8183. "Key: ")))
  8184. (defun org--insert-structure-template-unique-keys (keys)
  8185. "Make a list of unique, two characters long elements from KEYS.
  8186. Elements of length one have a tab appended. Elements of length
  8187. two are kept as is. Longer elements are truncated to length two.
  8188. If an element cannot be made unique, an error is raised."
  8189. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8190. menu-keys)
  8191. (dolist (key ordered-keys)
  8192. (let ((potential-key
  8193. (cl-case (length key)
  8194. (1 (concat key "\t"))
  8195. (2 key)
  8196. (otherwise
  8197. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8198. (mapcar (apply-partially #'concat (substring key 0 1))
  8199. (split-string (substring key 1) "" t)))))))
  8200. (if (or (not potential-key) (assoc potential-key menu-keys))
  8201. (user-error "Could not make unique key for %s." key)
  8202. (push (cons potential-key key) menu-keys))))
  8203. (mapcar #'car
  8204. (cl-sort menu-keys #'<
  8205. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8206. (defun org-insert-structure-template (type)
  8207. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8208. Select a block from `org-structure-template-alist' then type
  8209. either RET, TAB or SPC to write the block type. With an active
  8210. region, wrap the region in the block. Otherwise, insert an empty
  8211. block."
  8212. (interactive
  8213. (list (pcase (org--insert-structure-template-mks)
  8214. (`("\t" . ,_) (read-string "Structure type: "))
  8215. (`(,_ ,choice . ,_) choice))))
  8216. (let* ((region? (use-region-p))
  8217. (region-start (and region? (region-beginning)))
  8218. (region-end (and region? (copy-marker (region-end))))
  8219. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8220. (verbatim? (string-match-p
  8221. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8222. type)))
  8223. (when region? (goto-char region-start))
  8224. (let ((column (current-indentation)))
  8225. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8226. (beginning-of-line)
  8227. (insert "\n"))
  8228. (save-excursion
  8229. (indent-to column)
  8230. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8231. (when region?
  8232. (when verbatim? (org-escape-code-in-region (point) region-end))
  8233. (goto-char region-end)
  8234. ;; Ignore empty lines at the end of the region.
  8235. (skip-chars-backward " \r\t\n")
  8236. (end-of-line))
  8237. (unless (bolp) (insert "\n"))
  8238. (indent-to column)
  8239. (insert (format "#+end_%s" (car (split-string type))))
  8240. (if (looking-at "[ \t]*$") (replace-match "")
  8241. (insert "\n"))
  8242. (when (and (eobp) (not (bolp))) (insert "\n")))
  8243. (if extended? (end-of-line)
  8244. (forward-line)
  8245. (skip-chars-forward " \t")))))
  8246. ;;;; TODO, DEADLINE, Comments
  8247. (defun org-toggle-comment ()
  8248. "Change the COMMENT state of an entry."
  8249. (interactive)
  8250. (save-excursion
  8251. (org-back-to-heading)
  8252. (let ((case-fold-search nil))
  8253. (looking-at org-complex-heading-regexp))
  8254. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8255. (skip-chars-forward " \t")
  8256. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8257. (if (org-in-commented-heading-p t)
  8258. (delete-region (point)
  8259. (progn (search-forward " " (line-end-position) 'move)
  8260. (skip-chars-forward " \t")
  8261. (point)))
  8262. (insert org-comment-string)
  8263. (unless (eolp) (insert " ")))))
  8264. (defvar org-last-todo-state-is-todo nil
  8265. "This is non-nil when the last TODO state change led to a TODO state.
  8266. If the last change removed the TODO tag or switched to DONE, then
  8267. this is nil.")
  8268. (defvar org-todo-setup-filter-hook nil
  8269. "Hook for functions that pre-filter todo specs.
  8270. Each function takes a todo spec and returns either nil or the spec
  8271. transformed into canonical form." )
  8272. (defvar org-todo-get-default-hook nil
  8273. "Hook for functions that get a default item for todo.
  8274. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8275. nil or a string to be used for the todo mark." )
  8276. (defvar org-agenda-headline-snapshot-before-repeat)
  8277. (defun org-current-effective-time ()
  8278. "Return current time adjusted for `org-extend-today-until' variable."
  8279. (let* ((ct (org-current-time))
  8280. (dct (decode-time ct))
  8281. (ct1
  8282. (cond
  8283. (org-use-last-clock-out-time-as-effective-time
  8284. (or (org-clock-get-last-clock-out-time) ct))
  8285. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8286. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8287. (t ct))))
  8288. ct1))
  8289. (defun org-todo-yesterday (&optional arg)
  8290. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8291. (interactive "P")
  8292. (if (eq major-mode 'org-agenda-mode)
  8293. (apply 'org-agenda-todo-yesterday arg)
  8294. (let* ((org-use-effective-time t)
  8295. (hour (nth 2 (decode-time (org-current-time))))
  8296. (org-extend-today-until (1+ hour)))
  8297. (org-todo arg))))
  8298. (defvar org-block-entry-blocking ""
  8299. "First entry preventing the TODO state change.")
  8300. (defun org-cancel-repeater ()
  8301. "Cancel a repeater by setting its numeric value to zero."
  8302. (interactive)
  8303. (save-excursion
  8304. (org-back-to-heading t)
  8305. (let ((bound1 (point))
  8306. (bound0 (save-excursion (outline-next-heading) (point))))
  8307. (when (and (re-search-forward
  8308. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8309. org-deadline-time-regexp "\\)\\|\\("
  8310. org-ts-regexp "\\)")
  8311. bound0 t)
  8312. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8313. bound1 t))
  8314. (replace-match "0" t nil nil 1)))))
  8315. (defvar org-state)
  8316. (defvar org-blocked-by-checkboxes)
  8317. (defun org-todo (&optional arg)
  8318. "Change the TODO state of an item.
  8319. The state of an item is given by a keyword at the start of the heading,
  8320. like
  8321. *** TODO Write paper
  8322. *** DONE Call mom
  8323. The different keywords are specified in the variable `org-todo-keywords'.
  8324. By default the available states are \"TODO\" and \"DONE\". So, for this
  8325. example: when the item starts with TODO, it is changed to DONE.
  8326. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8327. DONE are present, add TODO at the beginning of the heading.
  8328. You can set up single-character keys to fast-select the new state. See the
  8329. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8330. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8331. and take a
  8332. logging note.
  8333. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8334. next set of TODO \
  8335. keywords (nextset).
  8336. Another way to achieve this is `S-C-<right>'.
  8337. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8338. prefix, circumvent any state blocking.
  8339. With numeric prefix arg, switch to the Nth state.
  8340. With a numeric prefix arg of 0, inhibit note taking for the change.
  8341. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8342. When called through ELisp, arg is also interpreted in the following way:
  8343. `none' -> empty state
  8344. \"\" -> switch to empty state
  8345. `done' -> switch to DONE
  8346. `nextset' -> switch to the next set of keywords
  8347. `previousset' -> switch to the previous set of keywords
  8348. \"WAITING\" -> switch to the specified keyword, but only if it
  8349. really is a member of `org-todo-keywords'."
  8350. (interactive "P")
  8351. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8352. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8353. 'region-start-level 'region))
  8354. org-loop-over-headlines-in-active-region)
  8355. (org-map-entries
  8356. `(org-todo ,arg)
  8357. org-loop-over-headlines-in-active-region
  8358. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8359. (when (equal arg '(16)) (setq arg 'nextset))
  8360. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8361. (let ((org-blocker-hook org-blocker-hook)
  8362. commentp
  8363. case-fold-search)
  8364. (when (equal arg '(64))
  8365. (setq arg nil org-blocker-hook nil))
  8366. (when (and org-blocker-hook
  8367. (or org-inhibit-blocking
  8368. (org-entry-get nil "NOBLOCKING")))
  8369. (setq org-blocker-hook nil))
  8370. (save-excursion
  8371. (catch 'exit
  8372. (org-back-to-heading t)
  8373. (when (org-in-commented-heading-p t)
  8374. (org-toggle-comment)
  8375. (setq commentp t))
  8376. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8377. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8378. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8379. (let* ((match-data (match-data))
  8380. (startpos (copy-marker (line-beginning-position)))
  8381. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8382. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8383. (org-log-done org-log-done)
  8384. (org-log-repeat org-log-repeat)
  8385. (org-todo-log-states org-todo-log-states)
  8386. (org-inhibit-logging
  8387. (if (equal arg 0)
  8388. (progn (setq arg nil) 'note) org-inhibit-logging))
  8389. (this (match-string 1))
  8390. (hl-pos (match-beginning 0))
  8391. (head (org-get-todo-sequence-head this))
  8392. (ass (assoc head org-todo-kwd-alist))
  8393. (interpret (nth 1 ass))
  8394. (done-word (nth 3 ass))
  8395. (final-done-word (nth 4 ass))
  8396. (org-last-state (or this ""))
  8397. (completion-ignore-case t)
  8398. (member (member this org-todo-keywords-1))
  8399. (tail (cdr member))
  8400. (org-state (cond
  8401. ((eq arg 'right)
  8402. ;; Next state
  8403. (if this
  8404. (if tail (car tail) nil)
  8405. (car org-todo-keywords-1)))
  8406. ((eq arg 'left)
  8407. ;; Previous state
  8408. (unless (equal member org-todo-keywords-1)
  8409. (if this
  8410. (nth (- (length org-todo-keywords-1)
  8411. (length tail) 2)
  8412. org-todo-keywords-1)
  8413. (org-last org-todo-keywords-1))))
  8414. (arg
  8415. ;; User or caller requests a specific state.
  8416. (cond
  8417. ((equal arg "") nil)
  8418. ((eq arg 'none) nil)
  8419. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8420. ((eq arg 'nextset)
  8421. (or (car (cdr (member head org-todo-heads)))
  8422. (car org-todo-heads)))
  8423. ((eq arg 'previousset)
  8424. (let ((org-todo-heads (reverse org-todo-heads)))
  8425. (or (car (cdr (member head org-todo-heads)))
  8426. (car org-todo-heads))))
  8427. ((car (member arg org-todo-keywords-1)))
  8428. ((stringp arg)
  8429. (user-error "State `%s' not valid in this file" arg))
  8430. ((nth (1- (prefix-numeric-value arg))
  8431. org-todo-keywords-1))))
  8432. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8433. ;; Use fast selection.
  8434. (org-fast-todo-selection this))
  8435. ((null member) (or head (car org-todo-keywords-1)))
  8436. ((equal this final-done-word) nil) ;-> make empty
  8437. ((null tail) nil) ;-> first entry
  8438. ((memq interpret '(type priority))
  8439. (if (eq this-command last-command)
  8440. (car tail)
  8441. (if (> (length tail) 0)
  8442. (or done-word (car org-done-keywords))
  8443. nil)))
  8444. (t
  8445. (car tail))))
  8446. (org-state (or
  8447. (run-hook-with-args-until-success
  8448. 'org-todo-get-default-hook org-state org-last-state)
  8449. org-state))
  8450. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8451. (change-plist (list :type 'todo-state-change :from this :to org-state
  8452. :position startpos))
  8453. dolog now-done-p)
  8454. (when org-blocker-hook
  8455. (let (org-blocked-by-checkboxes block-reason)
  8456. (setq org-last-todo-state-is-todo
  8457. (not (member this org-done-keywords)))
  8458. (unless (save-excursion
  8459. (save-match-data
  8460. (org-with-wide-buffer
  8461. (run-hook-with-args-until-failure
  8462. 'org-blocker-hook change-plist))))
  8463. (setq block-reason (if org-blocked-by-checkboxes
  8464. "contained checkboxes"
  8465. (format "\"%s\"" org-block-entry-blocking)))
  8466. (if (called-interactively-p 'interactive)
  8467. (user-error "TODO state change from %s to %s blocked (by %s)"
  8468. this org-state block-reason)
  8469. ;; Fail silently.
  8470. (message "TODO state change from %s to %s blocked (by %s)"
  8471. this org-state block-reason)
  8472. (throw 'exit nil)))))
  8473. (store-match-data match-data)
  8474. (replace-match next t t)
  8475. (cond ((and org-state (equal this org-state))
  8476. (message "TODO state was already %s" (org-trim next)))
  8477. ((not (pos-visible-in-window-p hl-pos))
  8478. (message "TODO state changed to %s" (org-trim next))))
  8479. (unless head
  8480. (setq head (org-get-todo-sequence-head org-state)
  8481. ass (assoc head org-todo-kwd-alist)
  8482. interpret (nth 1 ass)
  8483. done-word (nth 3 ass)
  8484. final-done-word (nth 4 ass)))
  8485. (when (memq arg '(nextset previousset))
  8486. (message "Keyword-Set %d/%d: %s"
  8487. (- (length org-todo-sets) -1
  8488. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8489. (length org-todo-sets)
  8490. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8491. (setq org-last-todo-state-is-todo
  8492. (not (member org-state org-done-keywords)))
  8493. (setq now-done-p (and (member org-state org-done-keywords)
  8494. (not (member this org-done-keywords))))
  8495. (and logging (org-local-logging logging))
  8496. (when (or (and (or org-todo-log-states org-log-done)
  8497. (not (eq org-inhibit-logging t))
  8498. (not (memq arg '(nextset previousset))))
  8499. force-log)
  8500. ;; We need to look at recording a time and note.
  8501. (setq dolog (or (if force-log 'note)
  8502. (nth 1 (assoc org-state org-todo-log-states))
  8503. (nth 2 (assoc this org-todo-log-states))))
  8504. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8505. (setq dolog 'time))
  8506. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8507. (and org-state
  8508. (member org-state org-not-done-keywords)
  8509. (not (member this org-not-done-keywords))))
  8510. ;; This is now a todo state and was not one before
  8511. ;; If there was a CLOSED time stamp, get rid of it.
  8512. (org-add-planning-info nil nil 'closed))
  8513. (when (and now-done-p org-log-done)
  8514. ;; It is now done, and it was not done before.
  8515. (org-add-planning-info 'closed (org-current-effective-time))
  8516. (when (and (not dolog) (eq 'note org-log-done))
  8517. (org-add-log-setup 'done org-state this 'note)))
  8518. (when (and org-state dolog)
  8519. ;; This is a non-nil state, and we need to log it.
  8520. (org-add-log-setup 'state org-state this dolog)))
  8521. ;; Fixup tag positioning.
  8522. (org-todo-trigger-tag-changes org-state)
  8523. (when org-auto-align-tags (org-align-tags))
  8524. (when org-provide-todo-statistics
  8525. (org-update-parent-todo-statistics))
  8526. (when (bound-and-true-p org-clock-out-when-done)
  8527. (org-clock-out-if-current))
  8528. (run-hooks 'org-after-todo-state-change-hook)
  8529. (when (and arg (not (member org-state org-done-keywords)))
  8530. (setq head (org-get-todo-sequence-head org-state)))
  8531. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8532. ;; Do we need to trigger a repeat?
  8533. (when now-done-p
  8534. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8535. ;; This is for the agenda, take a snapshot of the headline.
  8536. (save-match-data
  8537. (setq org-agenda-headline-snapshot-before-repeat
  8538. (org-get-heading))))
  8539. (org-auto-repeat-maybe org-state))
  8540. ;; Fixup cursor location if close to the keyword.
  8541. (when (and (outline-on-heading-p)
  8542. (not (bolp))
  8543. (save-excursion (beginning-of-line 1)
  8544. (looking-at org-todo-line-regexp))
  8545. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8546. (goto-char (or (match-end 2) (match-end 1)))
  8547. (and (looking-at " ")
  8548. (not (looking-at " *:"))
  8549. (just-one-space)))
  8550. (when org-trigger-hook
  8551. (save-excursion
  8552. (run-hook-with-args 'org-trigger-hook change-plist)))
  8553. (when commentp (org-toggle-comment))))))))
  8554. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8555. "Block turning an entry into a TODO, using the hierarchy.
  8556. This checks whether the current task should be blocked from state
  8557. changes. Such blocking occurs when:
  8558. 1. The task has children which are not all in a completed state.
  8559. 2. A task has a parent with the property :ORDERED:, and there
  8560. are siblings prior to the current task with incomplete
  8561. status.
  8562. 3. The parent of the task is blocked because it has siblings that should
  8563. be done first, or is child of a block grandparent TODO entry."
  8564. (if (not org-enforce-todo-dependencies)
  8565. t ; if locally turned off don't block
  8566. (catch 'dont-block
  8567. ;; If this is not a todo state change, or if this entry is already DONE,
  8568. ;; do not block
  8569. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8570. (member (plist-get change-plist :from)
  8571. (cons 'done org-done-keywords))
  8572. (member (plist-get change-plist :to)
  8573. (cons 'todo org-not-done-keywords))
  8574. (not (plist-get change-plist :to)))
  8575. (throw 'dont-block t))
  8576. ;; If this task has children, and any are undone, it's blocked
  8577. (save-excursion
  8578. (org-back-to-heading t)
  8579. (let ((this-level (funcall outline-level)))
  8580. (outline-next-heading)
  8581. (let ((child-level (funcall outline-level)))
  8582. (while (and (not (eobp))
  8583. (> child-level this-level))
  8584. ;; this todo has children, check whether they are all
  8585. ;; completed
  8586. (when (and (not (org-entry-is-done-p))
  8587. (org-entry-is-todo-p))
  8588. (setq org-block-entry-blocking (org-get-heading))
  8589. (throw 'dont-block nil))
  8590. (outline-next-heading)
  8591. (setq child-level (funcall outline-level))))))
  8592. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8593. ;; any previous siblings are undone, it's blocked
  8594. (save-excursion
  8595. (org-back-to-heading t)
  8596. (let* ((pos (point))
  8597. (parent-pos (and (org-up-heading-safe) (point)))
  8598. (case-fold-search nil))
  8599. (unless parent-pos (throw 'dont-block t)) ; no parent
  8600. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8601. (forward-line 1)
  8602. (re-search-forward org-not-done-heading-regexp pos t))
  8603. (setq org-block-entry-blocking (match-string 0))
  8604. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8605. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8606. (while t
  8607. (goto-char parent-pos)
  8608. (unless (looking-at org-not-done-heading-regexp)
  8609. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8610. (setq pos (point))
  8611. (setq parent-pos (and (org-up-heading-safe) (point)))
  8612. (unless parent-pos (throw 'dont-block t)) ; no parent
  8613. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8614. (forward-line 1)
  8615. (re-search-forward org-not-done-heading-regexp pos t)
  8616. (setq org-block-entry-blocking (org-get-heading)))
  8617. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8618. (defcustom org-track-ordered-property-with-tag nil
  8619. "Should the ORDERED property also be shown as a tag?
  8620. The ORDERED property decides if an entry should require subtasks to be
  8621. completed in sequence. Since a property is not very visible, setting
  8622. this option means that toggling the ORDERED property with the command
  8623. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8624. not relevant for the behavior, but it makes things more visible.
  8625. Note that toggling the tag with tags commands will not change the property
  8626. and therefore not influence behavior!
  8627. This can be t, meaning the tag ORDERED should be used. It can also be a
  8628. string to select a different tag for this task."
  8629. :group 'org-todo
  8630. :type '(choice
  8631. (const :tag "No tracking" nil)
  8632. (const :tag "Track with ORDERED tag" t)
  8633. (string :tag "Use other tag")))
  8634. (defun org-toggle-ordered-property ()
  8635. "Toggle the ORDERED property of the current entry.
  8636. For better visibility, you can track the value of this property with a tag.
  8637. See variable `org-track-ordered-property-with-tag'."
  8638. (interactive)
  8639. (let* ((t1 org-track-ordered-property-with-tag)
  8640. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8641. (save-excursion
  8642. (org-back-to-heading)
  8643. (if (org-entry-get nil "ORDERED")
  8644. (progn
  8645. (org-delete-property "ORDERED")
  8646. (and tag (org-toggle-tag tag 'off))
  8647. (message "Subtasks can be completed in arbitrary order"))
  8648. (org-entry-put nil "ORDERED" "t")
  8649. (and tag (org-toggle-tag tag 'on))
  8650. (message "Subtasks must be completed in sequence")))))
  8651. (defun org-block-todo-from-checkboxes (change-plist)
  8652. "Block turning an entry into a TODO, using checkboxes.
  8653. This checks whether the current task should be blocked from state
  8654. changes because there are unchecked boxes in this entry."
  8655. (if (not org-enforce-todo-checkbox-dependencies)
  8656. t ; if locally turned off don't block
  8657. (catch 'dont-block
  8658. ;; If this is not a todo state change, or if this entry is already DONE,
  8659. ;; do not block
  8660. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8661. (member (plist-get change-plist :from)
  8662. (cons 'done org-done-keywords))
  8663. (member (plist-get change-plist :to)
  8664. (cons 'todo org-not-done-keywords))
  8665. (not (plist-get change-plist :to)))
  8666. (throw 'dont-block t))
  8667. ;; If this task has checkboxes that are not checked, it's blocked
  8668. (save-excursion
  8669. (org-back-to-heading t)
  8670. (let ((beg (point)) end)
  8671. (outline-next-heading)
  8672. (setq end (point))
  8673. (goto-char beg)
  8674. (when (org-list-search-forward
  8675. (concat (org-item-beginning-re)
  8676. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8677. "\\[[- ]\\]")
  8678. end t)
  8679. (when (boundp 'org-blocked-by-checkboxes)
  8680. (setq org-blocked-by-checkboxes t))
  8681. (throw 'dont-block nil))))
  8682. t))) ; do not block
  8683. (defun org-entry-blocked-p ()
  8684. "Non-nil if entry at point is blocked."
  8685. (and (not (org-entry-get nil "NOBLOCKING"))
  8686. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8687. (not (run-hook-with-args-until-failure
  8688. 'org-blocker-hook
  8689. (list :type 'todo-state-change
  8690. :position (point)
  8691. :from 'todo
  8692. :to 'done)))))
  8693. (defun org-update-statistics-cookies (all)
  8694. "Update the statistics cookie, either from TODO or from checkboxes.
  8695. This should be called with the cursor in a line with a statistics
  8696. cookie. When called with a \\[universal-argument] prefix, update
  8697. all statistics cookies in the buffer."
  8698. (interactive "P")
  8699. (if all
  8700. (progn
  8701. (org-update-checkbox-count 'all)
  8702. (org-map-entries 'org-update-parent-todo-statistics))
  8703. (if (not (org-at-heading-p))
  8704. (org-update-checkbox-count)
  8705. (let ((pos (point-marker))
  8706. end l1 l2)
  8707. (ignore-errors (org-back-to-heading t))
  8708. (if (not (org-at-heading-p))
  8709. (org-update-checkbox-count)
  8710. (setq l1 (org-outline-level))
  8711. (setq end (save-excursion
  8712. (outline-next-heading)
  8713. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8714. (point)))
  8715. (if (and (save-excursion
  8716. (re-search-forward
  8717. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8718. (not (save-excursion (re-search-forward
  8719. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8720. (org-update-checkbox-count)
  8721. (if (and l2 (> l2 l1))
  8722. (progn
  8723. (goto-char end)
  8724. (org-update-parent-todo-statistics))
  8725. (goto-char pos)
  8726. (beginning-of-line 1)
  8727. (while (re-search-forward
  8728. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8729. (point-at-eol) t)
  8730. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8731. (goto-char pos)
  8732. (move-marker pos nil)))))
  8733. (defvar org-entry-property-inherited-from) ;; defined below
  8734. (defun org-update-parent-todo-statistics ()
  8735. "Update any statistics cookie in the parent of the current headline.
  8736. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8737. the entire subtree and this will travel up the hierarchy and update
  8738. statistics everywhere."
  8739. (let* ((prop (save-excursion (org-up-heading-safe)
  8740. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8741. (recursive (or (not org-hierarchical-todo-statistics)
  8742. (and prop (string-match "\\<recursive\\>" prop))))
  8743. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8744. 0))
  8745. (first t)
  8746. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8747. level ltoggle l1 new ndel
  8748. (cnt-all 0) (cnt-done 0) is-percent kwd
  8749. checkbox-beg cookie-present)
  8750. (catch 'exit
  8751. (save-excursion
  8752. (beginning-of-line 1)
  8753. (setq ltoggle (funcall outline-level))
  8754. ;; Three situations are to consider:
  8755. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8756. ;; to the top-level ancestor on the headline;
  8757. ;; 2. If parent has "recursive" property, repeat up to the
  8758. ;; headline setting that property, taking inheritance into
  8759. ;; account;
  8760. ;; 3. Else, move up to direct parent and proceed only once.
  8761. (while (and (setq level (org-up-heading-safe))
  8762. (or recursive first)
  8763. (>= (point) lim))
  8764. (setq first nil cookie-present nil)
  8765. (unless (and level
  8766. (not (string-match
  8767. "\\<checkbox\\>"
  8768. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8769. "")))))
  8770. (throw 'exit nil))
  8771. (while (re-search-forward box-re (point-at-eol) t)
  8772. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8773. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8774. (save-match-data
  8775. (unless (outline-next-heading) (throw 'exit nil))
  8776. (while (and (looking-at org-complex-heading-regexp)
  8777. (> (setq l1 (length (match-string 1))) level))
  8778. (setq kwd (and (or recursive (= l1 ltoggle))
  8779. (match-string 2)))
  8780. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8781. (and (eq org-provide-todo-statistics t)
  8782. (or (member kwd org-done-keywords)))
  8783. (and (listp org-provide-todo-statistics)
  8784. (stringp (car org-provide-todo-statistics))
  8785. (or (member kwd org-provide-todo-statistics)
  8786. (member kwd org-done-keywords)))
  8787. (and (listp org-provide-todo-statistics)
  8788. (listp (car org-provide-todo-statistics))
  8789. (or (member kwd (car org-provide-todo-statistics))
  8790. (and (member kwd org-done-keywords)
  8791. (member kwd (cadr org-provide-todo-statistics))))))
  8792. (setq cnt-all (1+ cnt-all))
  8793. (and (eq org-provide-todo-statistics t)
  8794. kwd
  8795. (setq cnt-all (1+ cnt-all))))
  8796. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8797. (member kwd org-done-keywords))
  8798. (and (listp org-provide-todo-statistics)
  8799. (listp (car org-provide-todo-statistics))
  8800. (member kwd org-done-keywords)
  8801. (member kwd (cadr org-provide-todo-statistics)))
  8802. (and (listp org-provide-todo-statistics)
  8803. (stringp (car org-provide-todo-statistics))
  8804. (member kwd org-done-keywords)))
  8805. (setq cnt-done (1+ cnt-done)))
  8806. (outline-next-heading)))
  8807. (setq new
  8808. (if is-percent
  8809. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8810. (max 1 cnt-all)))
  8811. (format "[%d/%d]" cnt-done cnt-all))
  8812. ndel (- (match-end 0) checkbox-beg))
  8813. (goto-char checkbox-beg)
  8814. (insert new)
  8815. (delete-region (point) (+ (point) ndel))
  8816. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8817. (when cookie-present
  8818. (run-hook-with-args 'org-after-todo-statistics-hook
  8819. cnt-done (- cnt-all cnt-done))))))
  8820. (run-hooks 'org-todo-statistics-hook)))
  8821. (defvar org-after-todo-statistics-hook nil
  8822. "Hook that is called after a TODO statistics cookie has been updated.
  8823. Each function is called with two arguments: the number of not-done entries
  8824. and the number of done entries.
  8825. For example, the following function, when added to this hook, will switch
  8826. an entry to DONE when all children are done, and back to TODO when new
  8827. entries are set to a TODO status. Note that this hook is only called
  8828. when there is a statistics cookie in the headline!
  8829. (defun org-summary-todo (n-done n-not-done)
  8830. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8831. (let (org-log-done org-log-states) ; turn off logging
  8832. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  8833. ")
  8834. (defvar org-todo-statistics-hook nil
  8835. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8836. This hook runs even if there is no statistics cookie present, in which case
  8837. `org-after-todo-statistics-hook' would not run.")
  8838. (defun org-todo-trigger-tag-changes (state)
  8839. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8840. (let ((l org-todo-state-tags-triggers)
  8841. changes)
  8842. (when (or (not state) (equal state ""))
  8843. (setq changes (append changes (cdr (assoc "" l)))))
  8844. (when (and (stringp state) (> (length state) 0))
  8845. (setq changes (append changes (cdr (assoc state l)))))
  8846. (when (member state org-not-done-keywords)
  8847. (setq changes (append changes (cdr (assq 'todo l)))))
  8848. (when (member state org-done-keywords)
  8849. (setq changes (append changes (cdr (assq 'done l)))))
  8850. (dolist (c changes)
  8851. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8852. (defun org-local-logging (value)
  8853. "Get logging settings from a property VALUE."
  8854. ;; Directly set the variables, they are already local.
  8855. (setq org-log-done nil
  8856. org-log-repeat nil
  8857. org-todo-log-states nil)
  8858. (dolist (w (split-string value))
  8859. (let (a)
  8860. (cond
  8861. ((setq a (assoc w org-startup-options))
  8862. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8863. (set (nth 1 a) (nth 2 a))))
  8864. ((setq a (org-extract-log-state-settings w))
  8865. (and (member (car a) org-todo-keywords-1)
  8866. (push a org-todo-log-states)))))))
  8867. (defun org-get-todo-sequence-head (kwd)
  8868. "Return the head of the TODO sequence to which KWD belongs.
  8869. If KWD is not set, check if there is a text property remembering the
  8870. right sequence."
  8871. (let (p)
  8872. (cond
  8873. ((not kwd)
  8874. (or (get-text-property (point-at-bol) 'org-todo-head)
  8875. (progn
  8876. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8877. nil (point-at-eol)))
  8878. (get-text-property p 'org-todo-head))))
  8879. ((not (member kwd org-todo-keywords-1))
  8880. (car org-todo-keywords-1))
  8881. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8882. (defun org-fast-todo-selection (&optional current-state)
  8883. "Fast TODO keyword selection with single keys.
  8884. Returns the new TODO keyword, or nil if no state change should occur.
  8885. When CURRENT-STATE is given and selection letters are not unique globally,
  8886. prefer a state in the current sequence over on in another sequence."
  8887. (let* ((fulltable org-todo-key-alist)
  8888. (head (org-get-todo-sequence-head current-state))
  8889. (done-keywords org-done-keywords) ;; needed for the faces.
  8890. (maxlen (apply 'max (mapcar
  8891. (lambda (x)
  8892. (if (stringp (car x)) (string-width (car x)) 0))
  8893. fulltable)))
  8894. (expert (equal org-use-fast-todo-selection 'expert))
  8895. (prompt "")
  8896. (fwidth (+ maxlen 3 1 3))
  8897. (ncol (/ (- (window-width) 4) fwidth))
  8898. tg cnt e c tbl subtable
  8899. groups ingroup in-current-sequence)
  8900. (save-excursion
  8901. (save-window-excursion
  8902. (if expert
  8903. (set-buffer (get-buffer-create " *Org todo*"))
  8904. (delete-other-windows)
  8905. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8906. (org-switch-to-buffer-other-window " *Org todo*"))
  8907. (erase-buffer)
  8908. (setq-local org-done-keywords done-keywords)
  8909. (setq tbl fulltable cnt 0)
  8910. (while (setq e (pop tbl))
  8911. (cond
  8912. ((equal e '(:startgroup))
  8913. (push '() groups) (setq ingroup t)
  8914. (unless (= cnt 0)
  8915. (setq cnt 0)
  8916. (insert "\n"))
  8917. (setq prompt (concat prompt "{"))
  8918. (insert "{ "))
  8919. ((equal e '(:endgroup))
  8920. (setq ingroup nil cnt 0 in-current-sequence nil)
  8921. (setq prompt (concat prompt "}"))
  8922. (insert "}\n"))
  8923. ((equal e '(:newline))
  8924. (unless (= cnt 0)
  8925. (setq cnt 0)
  8926. (insert "\n")
  8927. (setq e (car tbl))
  8928. (while (equal (car tbl) '(:newline))
  8929. (insert "\n")
  8930. (setq tbl (cdr tbl)))))
  8931. (t
  8932. (setq tg (car e) c (cdr e))
  8933. (if (equal tg head) (setq in-current-sequence t))
  8934. (when ingroup (push tg (car groups)))
  8935. (when in-current-sequence (push e subtable))
  8936. (setq tg (org-add-props tg nil 'face
  8937. (org-get-todo-face tg)))
  8938. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8939. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8940. (insert "[" c "] " tg (make-string
  8941. (- fwidth 4 (length tg)) ?\ ))
  8942. (when (and (= (setq cnt (1+ cnt)) ncol)
  8943. ;; Avoid lines with just a closing delimiter.
  8944. (not (equal (car tbl) '(:endgroup))))
  8945. (insert "\n")
  8946. (when ingroup (insert " "))
  8947. (setq cnt 0)))))
  8948. (insert "\n")
  8949. (goto-char (point-min))
  8950. (unless expert (org-fit-window-to-buffer))
  8951. (message (concat "[a-z..]:Set [SPC]:clear"
  8952. (if expert (concat "\n" prompt) "")))
  8953. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8954. (setq subtable (nreverse subtable))
  8955. (cond
  8956. ((or (= c ?\C-g)
  8957. (and (= c ?q) (not (rassoc c fulltable))))
  8958. (setq quit-flag t))
  8959. ((= c ?\ ) nil)
  8960. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8961. tg (car e))
  8962. tg)
  8963. (t (setq quit-flag t)))))))
  8964. (defun org-entry-is-todo-p ()
  8965. (member (org-get-todo-state) org-not-done-keywords))
  8966. (defun org-entry-is-done-p ()
  8967. (member (org-get-todo-state) org-done-keywords))
  8968. (defun org-get-todo-state ()
  8969. "Return the TODO keyword of the current subtree."
  8970. (save-excursion
  8971. (org-back-to-heading t)
  8972. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  8973. (match-end 2)
  8974. (match-string 2))))
  8975. (defun org-at-date-range-p (&optional inactive-ok)
  8976. "Non-nil if point is inside a date range.
  8977. When optional argument INACTIVE-OK is non-nil, also consider
  8978. inactive time ranges.
  8979. When this function returns a non-nil value, match data is set
  8980. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8981. on INACTIVE-OK."
  8982. (interactive)
  8983. (save-excursion
  8984. (catch 'exit
  8985. (let ((pos (point)))
  8986. (skip-chars-backward "^[<\r\n")
  8987. (skip-chars-backward "<[")
  8988. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8989. (>= (match-end 0) pos)
  8990. (throw 'exit t))
  8991. (skip-chars-backward "^<[\r\n")
  8992. (skip-chars-backward "<[")
  8993. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8994. (>= (match-end 0) pos)
  8995. (throw 'exit t)))
  8996. nil)))
  8997. (defun org-get-repeat (&optional timestamp)
  8998. "Check if there is a time-stamp with repeater in this entry.
  8999. Return the repeater, as a string, or nil. Also return nil when
  9000. this function is called before first heading.
  9001. When optional argument TIMESTAMP is a string, extract the
  9002. repeater from there instead."
  9003. (save-match-data
  9004. (cond (timestamp
  9005. (and (string-match org-repeat-re timestamp)
  9006. (match-string-no-properties 1 timestamp)))
  9007. ((org-before-first-heading-p) nil)
  9008. (t
  9009. (save-excursion
  9010. (org-back-to-heading t)
  9011. (let ((end (org-entry-end-position)))
  9012. (catch :repeat
  9013. (while (re-search-forward org-repeat-re end t)
  9014. (when (save-match-data (org-at-timestamp-p 'agenda))
  9015. (throw :repeat (match-string-no-properties 1)))))))))))
  9016. (defvar org-last-changed-timestamp)
  9017. (defvar org-last-inserted-timestamp)
  9018. (defvar org-log-post-message)
  9019. (defvar org-log-note-purpose)
  9020. (defvar org-log-note-how nil)
  9021. (defvar org-log-note-extra)
  9022. (defun org-auto-repeat-maybe (done-word)
  9023. "Check if the current headline contains a repeated time-stamp.
  9024. If yes, set TODO state back to what it was and change the base date
  9025. of repeating deadline/scheduled time stamps to new date.
  9026. This function is run automatically after each state change to a DONE state."
  9027. (let* ((repeat (org-get-repeat))
  9028. (aa (assoc org-last-state org-todo-kwd-alist))
  9029. (interpret (nth 1 aa))
  9030. (head (nth 2 aa))
  9031. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9032. (msg "Entry repeats: ")
  9033. (org-log-done nil)
  9034. (org-todo-log-states nil)
  9035. (end (copy-marker (org-entry-end-position))))
  9036. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9037. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9038. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9039. (and (stringp org-todo-repeat-to-state)
  9040. org-todo-repeat-to-state)
  9041. (and org-todo-repeat-to-state org-last-state))))
  9042. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9043. to-state)
  9044. ((eq interpret 'type) org-last-state)
  9045. (head)
  9046. (t 'none))))
  9047. (org-back-to-heading t)
  9048. (org-add-planning-info nil nil 'closed)
  9049. ;; When `org-log-repeat' is non-nil or entry contains
  9050. ;; a clock, set LAST_REPEAT property.
  9051. (when (or org-log-repeat
  9052. (catch :clock
  9053. (save-excursion
  9054. (while (re-search-forward org-clock-line-re end t)
  9055. (when (org-at-clock-log-p) (throw :clock t))))))
  9056. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9057. (org-time-stamp-format t t))))
  9058. (when org-log-repeat
  9059. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9060. (memq 'org-add-log-note post-command-hook))
  9061. ;; We are already setup for some record.
  9062. (when (eq org-log-repeat 'note)
  9063. ;; Make sure we take a note, not only a time stamp.
  9064. (setq org-log-note-how 'note))
  9065. ;; Set up for taking a record.
  9066. (org-add-log-setup 'state
  9067. (or done-word (car org-done-keywords))
  9068. org-last-state
  9069. org-log-repeat)))
  9070. ;; Time-stamps without a repeater are usually skipped. However,
  9071. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9072. ;; longer relevant.
  9073. (save-excursion
  9074. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9075. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9076. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9077. ;; Update every time-stamp with a repeater in the entry.
  9078. (let ((planning-re (regexp-opt
  9079. (list org-scheduled-string org-deadline-string))))
  9080. (while (re-search-forward org-repeat-re end t)
  9081. (let* ((ts (match-string 0))
  9082. (type (if (not (org-at-planning-p)) "Plain:"
  9083. (save-excursion
  9084. (re-search-backward
  9085. planning-re (line-beginning-position) t)
  9086. (match-string 0)))))
  9087. (when (and (org-at-timestamp-p 'agenda)
  9088. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9089. (let ((n (string-to-number (match-string 2 ts)))
  9090. (what (match-string 3 ts)))
  9091. (when (equal what "w") (setq n (* n 7) what "d"))
  9092. (when (and (equal what "h")
  9093. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9094. ts)))
  9095. (user-error
  9096. "Cannot repeat in %d hour(s) because no hour has been set"
  9097. n))
  9098. ;; Preparation, see if we need to modify the start
  9099. ;; date for the change.
  9100. (when (match-end 1)
  9101. (let ((time (save-match-data (org-time-string-to-time ts)))
  9102. (repeater-type (match-string 1 ts)))
  9103. (cond
  9104. ((equal "." repeater-type)
  9105. ;; Shift starting date to today.
  9106. (org-timestamp-change (- (org-today) (time-to-days time))
  9107. 'day))
  9108. ((equal "+" repeater-type)
  9109. (let ((nshiftmax 10)
  9110. (nshift 0))
  9111. (while (or (= nshift 0)
  9112. (not (org-time-less-p nil time)))
  9113. (when (= nshiftmax (cl-incf nshift))
  9114. (or (y-or-n-p
  9115. (format "%d repeater intervals were not \
  9116. enough to shift date past today. Continue? "
  9117. nshift))
  9118. (user-error "Abort")))
  9119. (org-timestamp-change n (cdr (assoc what whata)))
  9120. (org-in-regexp org-ts-regexp3)
  9121. (setq ts (match-string 1))
  9122. (setq time
  9123. (save-match-data
  9124. (org-time-string-to-time ts)))))
  9125. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9126. ;; Rematch, so that we have everything in place
  9127. ;; for the real shift.
  9128. (org-in-regexp org-ts-regexp3)
  9129. (setq ts (match-string 1))
  9130. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9131. ts)))))
  9132. (save-excursion
  9133. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9134. (setq msg
  9135. (concat msg type " " org-last-changed-timestamp " ")))))))
  9136. (run-hooks 'org-todo-repeat-hook)
  9137. (setq org-log-post-message msg)
  9138. (message msg))))
  9139. (defun org-show-todo-tree (arg)
  9140. "Make a compact tree which shows all headlines marked with TODO.
  9141. The tree will show the lines where the regexp matches, and all higher
  9142. headlines above the match.
  9143. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9144. With a numeric prefix N, construct a sparse tree for the Nth element
  9145. of `org-todo-keywords-1'."
  9146. (interactive "P")
  9147. (let ((case-fold-search nil)
  9148. (kwd-re
  9149. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9150. ((equal arg '(4))
  9151. (let ((kwd
  9152. (completing-read "Keyword (or KWD1|KWD2|...): "
  9153. (mapcar #'list org-todo-keywords-1))))
  9154. (concat "\\("
  9155. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9156. "\\)\\>")))
  9157. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9158. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9159. org-todo-keywords-1)))
  9160. (t (user-error "Invalid prefix argument: %s" arg)))))
  9161. (message "%d TODO entries found"
  9162. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9163. (defun org--deadline-or-schedule (arg type time)
  9164. "Insert DEADLINE or SCHEDULE information in current entry.
  9165. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9166. `org-schedule' for information about ARG and TIME arguments."
  9167. (let* ((deadline? (eq type 'deadline))
  9168. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9169. (log (if deadline? org-log-redeadline org-log-reschedule))
  9170. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9171. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9172. ;; Save repeater cookie from either TIME or current scheduled
  9173. ;; time stamp. We are going to insert it back at the end of
  9174. ;; the process.
  9175. (repeater (or (and (org-string-nw-p time)
  9176. ;; We use `org-repeat-re' because we need
  9177. ;; to tell the difference between a real
  9178. ;; repeater and a time delta, e.g. "+2d".
  9179. (string-match org-repeat-re time)
  9180. (match-string 1 time))
  9181. (and (org-string-nw-p old-date)
  9182. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9183. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9184. old-date)
  9185. (match-string 1 old-date)))))
  9186. (pcase arg
  9187. (`(4)
  9188. (if (not old-date)
  9189. (message (if deadline? "Entry had no deadline to remove"
  9190. "Entry was not scheduled"))
  9191. (when (and old-date log)
  9192. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9193. nil old-date log))
  9194. (org-remove-timestamp-with-keyword keyword)
  9195. (message (if deadline? "Entry no longer has a deadline."
  9196. "Entry is no longer scheduled."))))
  9197. (`(16)
  9198. (save-excursion
  9199. (org-back-to-heading t)
  9200. (let ((regexp (if deadline? org-deadline-time-regexp
  9201. org-scheduled-time-regexp)))
  9202. (if (not (re-search-forward regexp (line-end-position 2) t))
  9203. (user-error (if deadline? "No deadline information to update"
  9204. "No scheduled information to update"))
  9205. (let* ((rpl0 (match-string 1))
  9206. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9207. (msg (if deadline? "Warn starting from" "Delay until")))
  9208. (replace-match
  9209. (concat keyword
  9210. " <" rpl
  9211. (format " -%dd"
  9212. (abs (- (time-to-days
  9213. (save-match-data
  9214. (org-read-date
  9215. nil t nil msg old-date-time)))
  9216. (time-to-days old-date-time))))
  9217. ">") t t))))))
  9218. (_
  9219. (org-add-planning-info type time 'closed)
  9220. (when (and old-date
  9221. log
  9222. (not (equal old-date org-last-inserted-timestamp)))
  9223. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9224. org-last-inserted-timestamp
  9225. old-date
  9226. log))
  9227. (when repeater
  9228. (save-excursion
  9229. (org-back-to-heading t)
  9230. (when (re-search-forward
  9231. (concat keyword " " org-last-inserted-timestamp)
  9232. (line-end-position 2)
  9233. t)
  9234. (goto-char (1- (match-end 0)))
  9235. (insert " " repeater)
  9236. (setq org-last-inserted-timestamp
  9237. (concat (substring org-last-inserted-timestamp 0 -1)
  9238. " " repeater
  9239. (substring org-last-inserted-timestamp -1))))))
  9240. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9241. org-last-inserted-timestamp)))))
  9242. (defun org-deadline (arg &optional time)
  9243. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9244. With one universal prefix argument, remove any deadline from the item.
  9245. With two universal prefix arguments, prompt for a warning delay.
  9246. With argument TIME, set the deadline at the corresponding date. TIME
  9247. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9248. (interactive "P")
  9249. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9250. (org-map-entries
  9251. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9252. nil
  9253. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9254. 'region-start-level
  9255. 'region)
  9256. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9257. (org--deadline-or-schedule arg 'deadline time)))
  9258. (defun org-schedule (arg &optional time)
  9259. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9260. With one universal prefix argument, remove any scheduling date from the item.
  9261. With two universal prefix arguments, prompt for a delay cookie.
  9262. With argument TIME, scheduled at the corresponding date. TIME can
  9263. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9264. (interactive "P")
  9265. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9266. (org-map-entries
  9267. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9268. nil
  9269. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9270. 'region-start-level
  9271. 'region)
  9272. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9273. (org--deadline-or-schedule arg 'scheduled time)))
  9274. (defun org-get-scheduled-time (pom &optional inherit)
  9275. "Get the scheduled time as a time tuple, of a format suitable
  9276. for calling org-schedule with, or if there is no scheduling,
  9277. returns nil."
  9278. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9279. (when time
  9280. (org-time-string-to-time time))))
  9281. (defun org-get-deadline-time (pom &optional inherit)
  9282. "Get the deadline as a time tuple, of a format suitable for
  9283. calling org-deadline with, or if there is no scheduling, returns
  9284. nil."
  9285. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9286. (when time
  9287. (org-time-string-to-time time))))
  9288. (defun org-remove-timestamp-with-keyword (keyword)
  9289. "Remove all time stamps with KEYWORD in the current entry."
  9290. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9291. beg)
  9292. (save-excursion
  9293. (org-back-to-heading t)
  9294. (setq beg (point))
  9295. (outline-next-heading)
  9296. (while (re-search-backward re beg t)
  9297. (replace-match "")
  9298. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9299. (equal (char-before) ?\ ))
  9300. (backward-delete-char 1)
  9301. (when (string-match "^[ \t]*$" (buffer-substring
  9302. (point-at-bol) (point-at-eol)))
  9303. (delete-region (point-at-bol)
  9304. (min (point-max) (1+ (point-at-eol))))))))))
  9305. (defvar org-time-was-given) ; dynamically scoped parameter
  9306. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9307. (defun org-at-planning-p ()
  9308. "Non-nil when point is on a planning info line."
  9309. ;; This is as accurate and faster than `org-element-at-point' since
  9310. ;; planning info location is fixed in the section.
  9311. (org-with-wide-buffer
  9312. (beginning-of-line)
  9313. (and (looking-at-p org-planning-line-re)
  9314. (eq (point)
  9315. (ignore-errors
  9316. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9317. (org-back-to-heading t)
  9318. (org-with-limited-levels (org-back-to-heading t)))
  9319. (line-beginning-position 2))))))
  9320. (defun org-add-planning-info (what &optional time &rest remove)
  9321. "Insert new timestamp with keyword in the planning line.
  9322. WHAT indicates what kind of time stamp to add. It is a symbol
  9323. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9324. the time to use. If none is given, the user is prompted for
  9325. a date. REMOVE indicates what kind of entries to remove. An old
  9326. WHAT entry will also be removed."
  9327. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9328. (catch 'exit
  9329. (when (and (memq what '(scheduled deadline))
  9330. (or (not time)
  9331. (and (stringp time)
  9332. (string-match "^[-+]+[0-9]" time))))
  9333. ;; Try to get a default date/time from existing timestamp
  9334. (save-excursion
  9335. (org-back-to-heading t)
  9336. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9337. (when (re-search-forward (if (eq what 'scheduled)
  9338. org-scheduled-time-regexp
  9339. org-deadline-time-regexp)
  9340. end t)
  9341. (setq ts (match-string 1)
  9342. default-time (org-time-string-to-time ts)
  9343. default-input (and ts (org-get-compact-tod ts)))))))
  9344. (when what
  9345. (setq time
  9346. (if (stringp time)
  9347. ;; This is a string (relative or absolute), set
  9348. ;; proper date.
  9349. (apply #'encode-time
  9350. (org-read-date-analyze
  9351. time default-time (decode-time default-time)))
  9352. ;; If necessary, get the time from the user
  9353. (or time (org-read-date nil 'to-time nil
  9354. (cl-case what
  9355. (deadline "DEADLINE")
  9356. (scheduled "SCHEDULED")
  9357. (otherwise nil))
  9358. default-time default-input)))))
  9359. (org-with-wide-buffer
  9360. (org-back-to-heading t)
  9361. (forward-line)
  9362. (unless (bolp) (insert "\n"))
  9363. (cond ((looking-at-p org-planning-line-re)
  9364. ;; Move to current indentation.
  9365. (skip-chars-forward " \t")
  9366. ;; Check if we have to remove something.
  9367. (dolist (type (if what (cons what remove) remove))
  9368. (save-excursion
  9369. (when (re-search-forward
  9370. (cl-case type
  9371. (closed org-closed-time-regexp)
  9372. (deadline org-deadline-time-regexp)
  9373. (scheduled org-scheduled-time-regexp)
  9374. (otherwise
  9375. (error "Invalid planning type: %s" type)))
  9376. (line-end-position) t)
  9377. ;; Delete until next keyword or end of line.
  9378. (delete-region
  9379. (match-beginning 0)
  9380. (if (re-search-forward org-keyword-time-not-clock-regexp
  9381. (line-end-position)
  9382. t)
  9383. (match-beginning 0)
  9384. (line-end-position))))))
  9385. ;; If there is nothing more to add and no more keyword
  9386. ;; is left, remove the line completely.
  9387. (if (and (looking-at-p "[ \t]*$") (not what))
  9388. (delete-region (line-beginning-position)
  9389. (line-beginning-position 2))
  9390. ;; If we removed last keyword, do not leave trailing
  9391. ;; white space at the end of line.
  9392. (let ((p (point)))
  9393. (save-excursion
  9394. (end-of-line)
  9395. (unless (= (skip-chars-backward " \t" p) 0)
  9396. (delete-region (point) (line-end-position)))))))
  9397. ((not what) (throw 'exit nil)) ; Nothing to do.
  9398. (t (insert-before-markers "\n")
  9399. (backward-char 1)
  9400. (when org-adapt-indentation
  9401. (indent-to-column (1+ (org-outline-level))))))
  9402. (when what
  9403. ;; Insert planning keyword.
  9404. (insert (cl-case what
  9405. (closed org-closed-string)
  9406. (deadline org-deadline-string)
  9407. (scheduled org-scheduled-string)
  9408. (otherwise (error "Invalid planning type: %s" what)))
  9409. " ")
  9410. ;; Insert associated timestamp.
  9411. (let ((ts (org-insert-time-stamp
  9412. time
  9413. (or org-time-was-given
  9414. (and (eq what 'closed) org-log-done-with-time))
  9415. (eq what 'closed)
  9416. nil nil (list org-end-time-was-given))))
  9417. (unless (eolp) (insert " "))
  9418. ts))))))
  9419. (defvar org-log-note-marker (make-marker)
  9420. "Marker pointing at the entry where the note is to be inserted.")
  9421. (defvar org-log-note-purpose nil)
  9422. (defvar org-log-note-state nil)
  9423. (defvar org-log-note-previous-state nil)
  9424. (defvar org-log-note-extra nil)
  9425. (defvar org-log-note-window-configuration nil)
  9426. (defvar org-log-note-return-to (make-marker))
  9427. (defvar org-log-note-effective-time nil
  9428. "Remembered current time so that dynamically scoped
  9429. `org-extend-today-until' affects timestamps in state change log")
  9430. (defvar org-log-post-message nil
  9431. "Message to be displayed after a log note has been stored.
  9432. The auto-repeater uses this.")
  9433. (defun org-add-note ()
  9434. "Add a note to the current entry.
  9435. This is done in the same way as adding a state change note."
  9436. (interactive)
  9437. (org-add-log-setup 'note))
  9438. (defun org-log-beginning (&optional create)
  9439. "Return expected start of log notes in current entry.
  9440. When optional argument CREATE is non-nil, the function creates
  9441. a drawer to store notes, if necessary. Returned position ignores
  9442. narrowing."
  9443. (org-with-wide-buffer
  9444. (let ((drawer (org-log-into-drawer)))
  9445. (cond
  9446. (drawer
  9447. (org-end-of-meta-data)
  9448. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9449. (end (if (org-at-heading-p) (point)
  9450. (save-excursion (outline-next-heading) (point))))
  9451. (case-fold-search t))
  9452. (catch 'exit
  9453. ;; Try to find existing drawer.
  9454. (while (re-search-forward regexp end t)
  9455. (let ((element (org-element-at-point)))
  9456. (when (eq (org-element-type element) 'drawer)
  9457. (let ((cend (org-element-property :contents-end element)))
  9458. (when (and (not org-log-states-order-reversed) cend)
  9459. (goto-char cend)))
  9460. (throw 'exit nil))))
  9461. ;; No drawer found. Create one, if permitted.
  9462. (when create
  9463. (unless (bolp) (insert "\n"))
  9464. (let ((beg (point)))
  9465. (insert ":" drawer ":\n:END:\n")
  9466. (org-indent-region beg (point))
  9467. (org-flag-region
  9468. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  9469. (end-of-line -1)))))
  9470. (t
  9471. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9472. (skip-chars-forward " \t\n")
  9473. (beginning-of-line)
  9474. (unless org-log-states-order-reversed
  9475. (org-skip-over-state-notes)
  9476. (skip-chars-backward " \t\n")
  9477. (forward-line)))))
  9478. (if (bolp) (point) (line-beginning-position 2))))
  9479. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9480. "Set up the post command hook to take a note.
  9481. If this is about to TODO state change, the new state is expected in STATE.
  9482. HOW is an indicator what kind of note should be created.
  9483. EXTRA is additional text that will be inserted into the notes buffer."
  9484. (move-marker org-log-note-marker (point))
  9485. (setq org-log-note-purpose purpose
  9486. org-log-note-state state
  9487. org-log-note-previous-state prev-state
  9488. org-log-note-how how
  9489. org-log-note-extra extra
  9490. org-log-note-effective-time (org-current-effective-time))
  9491. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9492. (defun org-skip-over-state-notes ()
  9493. "Skip past the list of State notes in an entry."
  9494. (when (ignore-errors (goto-char (org-in-item-p)))
  9495. (let* ((struct (org-list-struct))
  9496. (prevs (org-list-prevs-alist struct))
  9497. (regexp
  9498. (concat "[ \t]*- +"
  9499. (replace-regexp-in-string
  9500. " +" " +"
  9501. (org-replace-escapes
  9502. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9503. `(("%d" . ,org-ts-regexp-inactive)
  9504. ("%D" . ,org-ts-regexp)
  9505. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9506. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9507. ("%t" . ,org-ts-regexp-inactive)
  9508. ("%T" . ,org-ts-regexp)
  9509. ("%u" . ".*?")
  9510. ("%U" . ".*?")))))))
  9511. (while (looking-at-p regexp)
  9512. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9513. (org-list-get-item-end (point) struct)))))))
  9514. (defun org-add-log-note (&optional _purpose)
  9515. "Pop up a window for taking a note, and add this note later."
  9516. (remove-hook 'post-command-hook 'org-add-log-note)
  9517. (setq org-log-note-window-configuration (current-window-configuration))
  9518. (delete-other-windows)
  9519. (move-marker org-log-note-return-to (point))
  9520. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9521. (goto-char org-log-note-marker)
  9522. (org-switch-to-buffer-other-window "*Org Note*")
  9523. (erase-buffer)
  9524. (if (memq org-log-note-how '(time state))
  9525. (org-store-log-note)
  9526. (let ((org-inhibit-startup t)) (org-mode))
  9527. (insert (format "# Insert note for %s.
  9528. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9529. (cl-case org-log-note-purpose
  9530. (clock-out "stopped clock")
  9531. (done "closed todo item")
  9532. (reschedule "rescheduling")
  9533. (delschedule "no longer scheduled")
  9534. (redeadline "changing deadline")
  9535. (deldeadline "removing deadline")
  9536. (refile "refiling")
  9537. (note "this entry")
  9538. (state
  9539. (format "state change from \"%s\" to \"%s\""
  9540. (or org-log-note-previous-state "")
  9541. (or org-log-note-state "")))
  9542. (t (error "This should not happen")))))
  9543. (when org-log-note-extra (insert org-log-note-extra))
  9544. (setq-local org-finish-function 'org-store-log-note)
  9545. (run-hooks 'org-log-buffer-setup-hook)))
  9546. (defvar org-note-abort nil) ; dynamically scoped
  9547. (defun org-store-log-note ()
  9548. "Finish taking a log note, and insert it to where it belongs."
  9549. (let ((txt (prog1 (buffer-string)
  9550. (kill-buffer)))
  9551. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9552. lines)
  9553. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9554. (setq txt (replace-match "" t t txt)))
  9555. (when (string-match "\\s-+\\'" txt)
  9556. (setq txt (replace-match "" t t txt)))
  9557. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9558. (when (org-string-nw-p note)
  9559. (setq note
  9560. (org-replace-escapes
  9561. note
  9562. (list (cons "%u" (user-login-name))
  9563. (cons "%U" user-full-name)
  9564. (cons "%t" (format-time-string
  9565. (org-time-stamp-format 'long 'inactive)
  9566. org-log-note-effective-time))
  9567. (cons "%T" (format-time-string
  9568. (org-time-stamp-format 'long nil)
  9569. org-log-note-effective-time))
  9570. (cons "%d" (format-time-string
  9571. (org-time-stamp-format nil 'inactive)
  9572. org-log-note-effective-time))
  9573. (cons "%D" (format-time-string
  9574. (org-time-stamp-format nil nil)
  9575. org-log-note-effective-time))
  9576. (cons "%s" (cond
  9577. ((not org-log-note-state) "")
  9578. ((string-match-p org-ts-regexp
  9579. org-log-note-state)
  9580. (format "\"[%s]\""
  9581. (substring org-log-note-state 1 -1)))
  9582. (t (format "\"%s\"" org-log-note-state))))
  9583. (cons "%S"
  9584. (cond
  9585. ((not org-log-note-previous-state) "")
  9586. ((string-match-p org-ts-regexp
  9587. org-log-note-previous-state)
  9588. (format "\"[%s]\""
  9589. (substring
  9590. org-log-note-previous-state 1 -1)))
  9591. (t (format "\"%s\""
  9592. org-log-note-previous-state)))))))
  9593. (when lines (setq note (concat note " \\\\")))
  9594. (push note lines))
  9595. (when (and lines (not org-note-abort))
  9596. (with-current-buffer (marker-buffer org-log-note-marker)
  9597. (org-with-wide-buffer
  9598. ;; Find location for the new note.
  9599. (goto-char org-log-note-marker)
  9600. (set-marker org-log-note-marker nil)
  9601. ;; Note associated to a clock is to be located right after
  9602. ;; the clock. Do not move point.
  9603. (unless (eq org-log-note-purpose 'clock-out)
  9604. (goto-char (org-log-beginning t)))
  9605. ;; Make sure point is at the beginning of an empty line.
  9606. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9607. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9608. ;; In an existing list, add a new item at the top level.
  9609. ;; Otherwise, indent line like a regular one.
  9610. (let ((itemp (org-in-item-p)))
  9611. (if itemp
  9612. (indent-line-to
  9613. (let ((struct (save-excursion
  9614. (goto-char itemp) (org-list-struct))))
  9615. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9616. (org-indent-line)))
  9617. (insert (org-list-bullet-string "-") (pop lines))
  9618. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9619. (dolist (line lines)
  9620. (insert "\n")
  9621. (indent-line-to ind)
  9622. (insert line)))
  9623. (message "Note stored")
  9624. (org-back-to-heading t))
  9625. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9626. ;; from within `org-add-log-note' because `buffer-undo-list'
  9627. ;; is then modified outside of `org-with-remote-undo'.
  9628. (when (eq this-command 'org-agenda-todo)
  9629. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9630. ;; Don't add undo information when called from `org-agenda-todo'.
  9631. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9632. (set-window-configuration org-log-note-window-configuration)
  9633. (with-current-buffer (marker-buffer org-log-note-return-to)
  9634. (goto-char org-log-note-return-to))
  9635. (move-marker org-log-note-return-to nil)
  9636. (when org-log-post-message (message "%s" org-log-post-message))))
  9637. (defun org-remove-empty-drawer-at (pos)
  9638. "Remove an empty drawer at position POS.
  9639. POS may also be a marker."
  9640. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9641. (org-with-wide-buffer
  9642. (goto-char pos)
  9643. (let ((drawer (org-element-at-point)))
  9644. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9645. (not (org-element-property :contents-begin drawer)))
  9646. (delete-region (org-element-property :begin drawer)
  9647. (progn (goto-char (org-element-property :end drawer))
  9648. (skip-chars-backward " \r\t\n")
  9649. (forward-line)
  9650. (point))))))))
  9651. (defvar org-ts-type nil)
  9652. (defun org-sparse-tree (&optional arg type)
  9653. "Create a sparse tree, prompt for the details.
  9654. This command can create sparse trees. You first need to select the type
  9655. of match used to create the tree:
  9656. t Show all TODO entries.
  9657. T Show entries with a specific TODO keyword.
  9658. m Show entries selected by a tags/property match.
  9659. p Enter a property name and its value (both with completion on existing
  9660. names/values) and show entries with that property.
  9661. r Show entries matching a regular expression (`/' can be used as well).
  9662. b Show deadlines and scheduled items before a date.
  9663. a Show deadlines and scheduled items after a date.
  9664. d Show deadlines due within `org-deadline-warning-days'.
  9665. D Show deadlines and scheduled items between a date range."
  9666. (interactive "P")
  9667. (setq type (or type org-sparse-tree-default-date-type))
  9668. (setq org-ts-type type)
  9669. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9670. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  9671. \[c]ycle through date types: %s"
  9672. (cl-case type
  9673. (all "all timestamps")
  9674. (scheduled "only scheduled")
  9675. (deadline "only deadline")
  9676. (active "only active timestamps")
  9677. (inactive "only inactive timestamps")
  9678. (closed "with a closed time-stamp")
  9679. (otherwise "scheduled/deadline")))
  9680. (let ((answer (read-char-exclusive)))
  9681. (cl-case answer
  9682. (?c
  9683. (org-sparse-tree
  9684. arg
  9685. (cadr
  9686. (memq type '(nil all scheduled deadline active inactive closed)))))
  9687. (?d (call-interactively 'org-check-deadlines))
  9688. (?b (call-interactively 'org-check-before-date))
  9689. (?a (call-interactively 'org-check-after-date))
  9690. (?D (call-interactively 'org-check-dates-range))
  9691. (?t (call-interactively 'org-show-todo-tree))
  9692. (?T (org-show-todo-tree '(4)))
  9693. (?m (call-interactively 'org-match-sparse-tree))
  9694. ((?p ?P)
  9695. (let* ((kwd (completing-read
  9696. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9697. (value (completing-read
  9698. "Value: " (mapcar #'list (org-property-values kwd)))))
  9699. (unless (string-match "\\`{.*}\\'" value)
  9700. (setq value (concat "\"" value "\"")))
  9701. (org-match-sparse-tree arg (concat kwd "=" value))))
  9702. ((?r ?R ?/) (call-interactively 'org-occur))
  9703. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9704. (defvar-local org-occur-highlights nil
  9705. "List of overlays used for occur matches.")
  9706. (defvar-local org-occur-parameters nil
  9707. "Parameters of the active org-occur calls.
  9708. This is a list, each call to org-occur pushes as cons cell,
  9709. containing the regular expression and the callback, onto the list.
  9710. The list can contain several entries if `org-occur' has been called
  9711. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9712. will only contain one set of parameters. When the highlights are
  9713. removed (for example with `C-c C-c', or with the next edit (depending
  9714. on `org-remove-highlights-with-change'), this variable is emptied
  9715. as well.")
  9716. (defun org-occur (regexp &optional keep-previous callback)
  9717. "Make a compact tree which shows all matches of REGEXP.
  9718. The tree will show the lines where the regexp matches, and any other context
  9719. defined in `org-show-context-detail', which see.
  9720. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9721. done by a previous call to `org-occur' will be kept, to allow stacking of
  9722. calls to this command.
  9723. Optional argument CALLBACK can be a function of no argument. In this case,
  9724. it is called with point at the end of the match, match data being set
  9725. accordingly. Current match is shown only if the return value is non-nil.
  9726. The function must neither move point nor alter narrowing."
  9727. (interactive "sRegexp: \nP")
  9728. (when (equal regexp "")
  9729. (user-error "Regexp cannot be empty"))
  9730. (unless keep-previous
  9731. (org-remove-occur-highlights nil nil t))
  9732. (push (cons regexp callback) org-occur-parameters)
  9733. (let ((cnt 0))
  9734. (save-excursion
  9735. (goto-char (point-min))
  9736. (when (or (not keep-previous) ; do not want to keep
  9737. (not org-occur-highlights)) ; no previous matches
  9738. ;; hide everything
  9739. (org-overview))
  9740. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9741. (isearch-no-upper-case-p regexp t)
  9742. org-occur-case-fold-search)))
  9743. (while (re-search-forward regexp nil t)
  9744. (when (or (not callback)
  9745. (save-match-data (funcall callback)))
  9746. (setq cnt (1+ cnt))
  9747. (when org-highlight-sparse-tree-matches
  9748. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9749. (org-show-context 'occur-tree)))))
  9750. (when org-remove-highlights-with-change
  9751. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9752. nil 'local))
  9753. (unless org-sparse-tree-open-archived-trees
  9754. (org-hide-archived-subtrees (point-min) (point-max)))
  9755. (run-hooks 'org-occur-hook)
  9756. (when (called-interactively-p 'interactive)
  9757. (message "%d match(es) for regexp %s" cnt regexp))
  9758. cnt))
  9759. (defun org-occur-next-match (&optional n _reset)
  9760. "Function for `next-error-function' to find sparse tree matches.
  9761. N is the number of matches to move, when negative move backwards.
  9762. This function always goes back to the starting point when no
  9763. match is found."
  9764. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9765. (search-func (if (< n 0)
  9766. 'previous-single-char-property-change
  9767. 'next-single-char-property-change))
  9768. (n (abs n))
  9769. (pos (point))
  9770. p1)
  9771. (catch 'exit
  9772. (while (setq p1 (funcall search-func (point) 'org-type))
  9773. (when (equal p1 limit)
  9774. (goto-char pos)
  9775. (user-error "No more matches"))
  9776. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9777. (setq n (1- n))
  9778. (when (= n 0)
  9779. (goto-char p1)
  9780. (throw 'exit (point))))
  9781. (goto-char p1))
  9782. (goto-char p1)
  9783. (user-error "No more matches"))))
  9784. (defun org-highlight-new-match (beg end)
  9785. "Highlight from BEG to END and mark the highlight is an occur headline."
  9786. (let ((ov (make-overlay beg end)))
  9787. (overlay-put ov 'face 'secondary-selection)
  9788. (overlay-put ov 'org-type 'org-occur)
  9789. (push ov org-occur-highlights)))
  9790. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9791. "Remove the occur highlights from the buffer.
  9792. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9793. from the `before-change-functions' in the current buffer."
  9794. (interactive)
  9795. (unless org-inhibit-highlight-removal
  9796. (mapc #'delete-overlay org-occur-highlights)
  9797. (setq org-occur-highlights nil)
  9798. (setq org-occur-parameters nil)
  9799. (unless noremove
  9800. (remove-hook 'before-change-functions
  9801. 'org-remove-occur-highlights 'local))))
  9802. ;;;; Priorities
  9803. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9804. "Regular expression matching the priority indicator.
  9805. A priority indicator can be e.g. [#A] or [#1].
  9806. This regular expression matches these groups:
  9807. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9808. 1 : the priority cookie, e.g. \"[#A]\"
  9809. 2 : the value of the priority cookie, e.g. \"A\".")
  9810. (defun org-priority-up ()
  9811. "Increase the priority of the current item."
  9812. (interactive)
  9813. (org-priority 'up))
  9814. (defun org-priority-down ()
  9815. "Decrease the priority of the current item."
  9816. (interactive)
  9817. (org-priority 'down))
  9818. (defun org-priority (&optional action show)
  9819. "Change the priority of an item.
  9820. When called interactively with a `\\[universal-argument]' prefix,
  9821. show the priority in the minibuffer instead of changing it.
  9822. When called programmatically, ACTION can be `set', `up', `down',
  9823. or a character."
  9824. (interactive "P")
  9825. (when show
  9826. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9827. ;; passed the SHOW argument should be removed.
  9828. (warn "`org-priority' called with deprecated SHOW argument"))
  9829. (if (equal action '(4))
  9830. (org-priority-show)
  9831. (unless org-priority-enable-commands
  9832. (user-error "Priority commands are disabled"))
  9833. (setq action (or action 'set))
  9834. (let ((nump (< org-priority-lowest 65))
  9835. current new news have remove)
  9836. (save-excursion
  9837. (org-back-to-heading t)
  9838. (when (looking-at org-priority-regexp)
  9839. (let ((ms (match-string 2)))
  9840. (setq current (org-priority-to-value ms)
  9841. have t)))
  9842. (cond
  9843. ((eq action 'remove)
  9844. (setq remove t new ?\ ))
  9845. ((or (eq action 'set)
  9846. (integerp action))
  9847. (if (not (eq action 'set))
  9848. (setq new action)
  9849. (setq
  9850. new
  9851. (if nump
  9852. (string-to-number
  9853. (read-string (format "Priority %s-%s, SPC to remove: "
  9854. (number-to-string org-priority-highest)
  9855. (number-to-string org-priority-lowest))))
  9856. (progn (message "Priority %c-%c, SPC to remove: "
  9857. org-priority-highest org-priority-lowest)
  9858. (save-match-data
  9859. (setq new (read-char-exclusive)))))))
  9860. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9861. (= (upcase org-priority-lowest) org-priority-lowest))
  9862. (setq new (upcase new)))
  9863. (cond ((equal new ?\s) (setq remove t))
  9864. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9865. (user-error
  9866. (if nump
  9867. "Priority must be between `%s' and `%s'"
  9868. "Priority must be between `%c' and `%c'")
  9869. org-priority-highest org-priority-lowest))))
  9870. ((eq action 'up)
  9871. (setq new (if have
  9872. (1- current) ; normal cycling
  9873. ;; last priority was empty
  9874. (if (eq last-command this-command)
  9875. org-priority-lowest ; wrap around empty to lowest
  9876. ;; default
  9877. (if org-priority-start-cycle-with-default
  9878. org-priority-default
  9879. (1- org-priority-default))))))
  9880. ((eq action 'down)
  9881. (setq new (if have
  9882. (1+ current) ; normal cycling
  9883. ;; last priority was empty
  9884. (if (eq last-command this-command)
  9885. org-priority-highest ; wrap around empty to highest
  9886. ;; default
  9887. (if org-priority-start-cycle-with-default
  9888. org-priority-default
  9889. (1+ org-priority-default))))))
  9890. (t (user-error "Invalid action")))
  9891. (when (or (< (upcase new) org-priority-highest)
  9892. (> (upcase new) org-priority-lowest))
  9893. (if (and (memq action '(up down))
  9894. (not have) (not (eq last-command this-command)))
  9895. ;; `new' is from default priority
  9896. (error
  9897. "The default can not be set, see `org-priority-default' why")
  9898. ;; normal cycling: `new' is beyond highest/lowest priority
  9899. ;; and is wrapped around to the empty priority
  9900. (setq remove t)))
  9901. ;; Numerical priorities are limited to 64, beyond that number,
  9902. ;; assume the priority cookie is a character.
  9903. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9904. (if have
  9905. (if remove
  9906. (replace-match "" t t nil 1)
  9907. (replace-match news t t nil 2))
  9908. (if remove
  9909. (user-error "No priority cookie found in line")
  9910. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9911. (if (match-end 2)
  9912. (progn
  9913. (goto-char (match-end 2))
  9914. (insert " [#" news "]"))
  9915. (goto-char (match-beginning 3))
  9916. (insert "[#" news "] "))))
  9917. (org-align-tags))
  9918. (if remove
  9919. (message "Priority removed")
  9920. (message "Priority of current item set to %s" news)))))
  9921. (defalias 'org-show-priority 'org-priority-show)
  9922. (defun org-priority-show ()
  9923. "Show the priority of the current item.
  9924. This priority is composed of the main priority given with the [#A] cookies,
  9925. and by additional input from the age of a schedules or deadline entry."
  9926. (interactive)
  9927. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9928. (org-get-at-bol 'priority)
  9929. (save-excursion
  9930. (save-match-data
  9931. (beginning-of-line)
  9932. (and (looking-at org-heading-regexp)
  9933. (org-get-priority (match-string 0))))))))
  9934. (message "Priority is %d" (if pri pri -1000))))
  9935. (defun org-get-priority (s)
  9936. "Find priority cookie and return priority.
  9937. S is a string against which you can match `org-priority-regexp'.
  9938. If `org-priority-get-priority-function' is set to a custom
  9939. function, use it. Otherwise process S and output the priority
  9940. value, an integer."
  9941. (save-match-data
  9942. (if (functionp org-priority-get-priority-function)
  9943. (funcall org-priority-get-priority-function s)
  9944. (if (not (string-match org-priority-regexp s))
  9945. (* 1000 (- org-priority-lowest org-priority-default))
  9946. (* 1000 (- org-priority-lowest
  9947. (org-priority-to-value (match-string 2 s))))))))
  9948. ;;;; Tags
  9949. (defvar org-agenda-archives-mode)
  9950. (defvar org-map-continue-from nil
  9951. "Position from where mapping should continue.
  9952. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9953. (defvar org-scanner-tags nil
  9954. "The current tag list while the tags scanner is running.")
  9955. (defvar org-trust-scanner-tags nil
  9956. "Should `org-get-tags' use the tags for the scanner.
  9957. This is for internal dynamical scoping only.
  9958. When this is non-nil, the function `org-get-tags' will return the value
  9959. of `org-scanner-tags' instead of building the list by itself. This
  9960. can lead to large speed-ups when the tags scanner is used in a file with
  9961. many entries, and when the list of tags is retrieved, for example to
  9962. obtain a list of properties. Building the tags list for each entry in such
  9963. a file becomes an N^2 operation - but with this variable set, it scales
  9964. as N.")
  9965. (defvar org--matcher-tags-todo-only nil)
  9966. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9967. "Scan headline tags with inheritance and produce output ACTION.
  9968. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9969. or `agenda' to produce an entry list for an agenda view. It can also be
  9970. a Lisp form or a function that should be called at each matched headline, in
  9971. this case the return value is a list of all return values from these calls.
  9972. MATCHER is a function accepting three arguments, returning
  9973. a non-nil value whenever a given set of tags qualifies a headline
  9974. for inclusion. See `org-make-tags-matcher' for more information.
  9975. As a special case, it can also be set to t (respectively nil) in
  9976. order to match all (respectively none) headline.
  9977. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9978. included in the output.
  9979. START-LEVEL can be a string with asterisks, reducing the scope to
  9980. headlines matching this string."
  9981. (require 'org-agenda)
  9982. (let* ((re (concat "^"
  9983. (if start-level
  9984. ;; Get the correct level to match
  9985. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9986. org-outline-regexp)
  9987. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9988. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9989. (props (list 'face 'default
  9990. 'done-face 'org-agenda-done
  9991. 'undone-face 'default
  9992. 'mouse-face 'highlight
  9993. 'org-not-done-regexp org-not-done-regexp
  9994. 'org-todo-regexp org-todo-regexp
  9995. 'org-complex-heading-regexp org-complex-heading-regexp
  9996. 'help-echo
  9997. (format "mouse-2 or RET jump to Org file %S"
  9998. (abbreviate-file-name
  9999. (or (buffer-file-name (buffer-base-buffer))
  10000. (buffer-name (buffer-base-buffer)))))))
  10001. (org-map-continue-from nil)
  10002. lspos tags tags-list
  10003. (tags-alist (list (cons 0 org-file-tags)))
  10004. (llast 0) rtn rtn1 level category i txt
  10005. todo marker entry priority
  10006. ts-date ts-date-type ts-date-pair)
  10007. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10008. (setq action (list 'lambda nil action)))
  10009. (save-excursion
  10010. (goto-char (point-min))
  10011. (when (eq action 'sparse-tree)
  10012. (org-overview)
  10013. (org-remove-occur-highlights))
  10014. (while (let (case-fold-search)
  10015. (re-search-forward re nil t))
  10016. (setq org-map-continue-from nil)
  10017. (catch :skip
  10018. ;; Ignore closing parts of inline tasks.
  10019. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10020. (throw :skip t))
  10021. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10022. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10023. (goto-char (setq lspos (match-beginning 0)))
  10024. (setq level (org-reduced-level (org-outline-level))
  10025. category (org-get-category))
  10026. (when (eq action 'agenda)
  10027. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10028. ts-date (car ts-date-pair)
  10029. ts-date-type (cdr ts-date-pair)))
  10030. (setq i llast llast level)
  10031. ;; remove tag lists from same and sublevels
  10032. (while (>= i level)
  10033. (when (setq entry (assoc i tags-alist))
  10034. (setq tags-alist (delete entry tags-alist)))
  10035. (setq i (1- i)))
  10036. ;; add the next tags
  10037. (when tags
  10038. (setq tags (org-split-string tags ":")
  10039. tags-alist
  10040. (cons (cons level tags) tags-alist)))
  10041. ;; compile tags for current headline
  10042. (setq tags-list
  10043. (if org-use-tag-inheritance
  10044. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10045. tags)
  10046. org-scanner-tags tags-list)
  10047. (when org-use-tag-inheritance
  10048. (setcdr (car tags-alist)
  10049. (mapcar (lambda (x)
  10050. (setq x (copy-sequence x))
  10051. (org-add-prop-inherited x))
  10052. (cdar tags-alist))))
  10053. (when (and tags org-use-tag-inheritance
  10054. (or (not (eq t org-use-tag-inheritance))
  10055. org-tags-exclude-from-inheritance))
  10056. ;; Selective inheritance, remove uninherited ones.
  10057. (setcdr (car tags-alist)
  10058. (org-remove-uninherited-tags (cdar tags-alist))))
  10059. (when (and
  10060. ;; eval matcher only when the todo condition is OK
  10061. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10062. (if (functionp matcher)
  10063. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10064. (funcall matcher todo tags-list level))
  10065. matcher))
  10066. ;; Call the skipper, but return t if it does not
  10067. ;; skip, so that the `and' form continues evaluating.
  10068. (progn
  10069. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10070. t)
  10071. ;; Check if timestamps are deselecting this entry
  10072. (or (not todo-only)
  10073. (and (member todo org-todo-keywords-1)
  10074. (or (not org-agenda-tags-todo-honor-ignore-options)
  10075. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10076. ;; select this headline
  10077. (cond
  10078. ((eq action 'sparse-tree)
  10079. (and org-highlight-sparse-tree-matches
  10080. (org-get-heading) (match-end 0)
  10081. (org-highlight-new-match
  10082. (match-beginning 1) (match-end 1)))
  10083. (org-show-context 'tags-tree))
  10084. ((eq action 'agenda)
  10085. (setq txt (org-agenda-format-item
  10086. ""
  10087. (concat
  10088. (if (eq org-tags-match-list-sublevels 'indented)
  10089. (make-string (1- level) ?.) "")
  10090. (org-get-heading))
  10091. (make-string level ?\s)
  10092. category
  10093. tags-list)
  10094. priority (org-get-priority txt))
  10095. (goto-char lspos)
  10096. (setq marker (org-agenda-new-marker))
  10097. (org-add-props txt props
  10098. 'org-marker marker 'org-hd-marker marker 'org-category category
  10099. 'todo-state todo
  10100. 'ts-date ts-date
  10101. 'priority priority
  10102. 'type (concat "tagsmatch" ts-date-type))
  10103. (push txt rtn))
  10104. ((functionp action)
  10105. (setq org-map-continue-from nil)
  10106. (save-excursion
  10107. (setq rtn1 (funcall action))
  10108. (push rtn1 rtn)))
  10109. (t (user-error "Invalid action")))
  10110. ;; if we are to skip sublevels, jump to end of subtree
  10111. (unless org-tags-match-list-sublevels
  10112. (org-end-of-subtree t)
  10113. (backward-char 1))))
  10114. ;; Get the correct position from where to continue
  10115. (if org-map-continue-from
  10116. (goto-char org-map-continue-from)
  10117. (and (= (point) lspos) (end-of-line 1)))))
  10118. (when (and (eq action 'sparse-tree)
  10119. (not org-sparse-tree-open-archived-trees))
  10120. (org-hide-archived-subtrees (point-min) (point-max)))
  10121. (nreverse rtn)))
  10122. (defun org-remove-uninherited-tags (tags)
  10123. "Remove all tags that are not inherited from the list TAGS."
  10124. (cond
  10125. ((eq org-use-tag-inheritance t)
  10126. (if org-tags-exclude-from-inheritance
  10127. (org-delete-all org-tags-exclude-from-inheritance tags)
  10128. tags))
  10129. ((not org-use-tag-inheritance) nil)
  10130. ((stringp org-use-tag-inheritance)
  10131. (delq nil (mapcar
  10132. (lambda (x)
  10133. (if (and (string-match org-use-tag-inheritance x)
  10134. (not (member x org-tags-exclude-from-inheritance)))
  10135. x nil))
  10136. tags)))
  10137. ((listp org-use-tag-inheritance)
  10138. (delq nil (mapcar
  10139. (lambda (x)
  10140. (if (member x org-use-tag-inheritance) x nil))
  10141. tags)))))
  10142. (defun org-match-sparse-tree (&optional todo-only match)
  10143. "Create a sparse tree according to tags string MATCH.
  10144. MATCH is a string with match syntax. It can contain a selection
  10145. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10146. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10147. those. See the manual for details.
  10148. If optional argument TODO-ONLY is non-nil, only select lines that
  10149. are also TODO tasks."
  10150. (interactive "P")
  10151. (org-agenda-prepare-buffers (list (current-buffer)))
  10152. (let ((org--matcher-tags-todo-only todo-only))
  10153. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10154. org--matcher-tags-todo-only)))
  10155. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10156. (defvar org-cached-props nil)
  10157. (defun org-cached-entry-get (pom property)
  10158. (if (or (eq t org-use-property-inheritance)
  10159. (and (stringp org-use-property-inheritance)
  10160. (let ((case-fold-search t))
  10161. (string-match-p org-use-property-inheritance property)))
  10162. (and (listp org-use-property-inheritance)
  10163. (member-ignore-case property org-use-property-inheritance)))
  10164. ;; Caching is not possible, check it directly.
  10165. (org-entry-get pom property 'inherit)
  10166. ;; Get all properties, so we can do complicated checks easily.
  10167. (cdr (assoc-string property
  10168. (or org-cached-props
  10169. (setq org-cached-props (org-entry-properties pom)))
  10170. t))))
  10171. (defun org-global-tags-completion-table (&optional files)
  10172. "Return the list of all tags in all agenda buffer/files.
  10173. Optional FILES argument is a list of files which can be used
  10174. instead of the agenda files."
  10175. (save-excursion
  10176. (org-uniquify
  10177. (delq nil
  10178. (apply #'append
  10179. (mapcar
  10180. (lambda (file)
  10181. (set-buffer (find-file-noselect file))
  10182. (org--tag-add-to-alist
  10183. (org-get-buffer-tags)
  10184. (mapcar (lambda (x)
  10185. (and (stringp (car-safe x))
  10186. (list (car-safe x))))
  10187. org-current-tag-alist)))
  10188. (if (car-safe files) files
  10189. (org-agenda-files))))))))
  10190. (defun org-make-tags-matcher (match)
  10191. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10192. Returns a cons of the selection string MATCH and a function
  10193. implementing the matcher.
  10194. The matcher is to be called at an Org entry, with point on the
  10195. headline, and returns non-nil if the entry matches the selection
  10196. string MATCH. It must be called with three arguments: the TODO
  10197. keyword at the entry (or nil if none), the list of all tags at
  10198. the entry including inherited ones and the reduced level of the
  10199. headline. Additionally, the category of the entry, if any, must
  10200. be specified as the text property `org-category' on the headline.
  10201. This function sets the variable `org--matcher-tags-todo-only' to
  10202. a non-nil value if the matcher restricts matching to TODO
  10203. entries, otherwise it is not touched.
  10204. See also `org-scan-tags'."
  10205. (unless match
  10206. ;; Get a new match request, with completion against the global
  10207. ;; tags table and the local tags in current buffer.
  10208. (let ((org-last-tags-completion-table
  10209. (org--tag-add-to-alist
  10210. (org-get-buffer-tags)
  10211. (org-global-tags-completion-table))))
  10212. (setq match
  10213. (completing-read
  10214. "Match: "
  10215. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10216. (let ((match0 match)
  10217. (re (concat
  10218. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10219. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10220. "\\([<>=]\\{1,2\\}\\)"
  10221. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10222. "\\|" org-tag-re "\\)"))
  10223. (start 0)
  10224. tagsmatch todomatch tagsmatcher todomatcher)
  10225. ;; Expand group tags.
  10226. (setq match (org-tags-expand match))
  10227. ;; Check if there is a TODO part of this match, which would be the
  10228. ;; part after a "/". To make sure that this slash is not part of
  10229. ;; a property value to be matched against, we also check that
  10230. ;; there is no / after that slash. First, find the last slash.
  10231. (let ((s 0))
  10232. (while (string-match "/+" match s)
  10233. (setq start (match-beginning 0))
  10234. (setq s (match-end 0))))
  10235. (if (and (string-match "/+" match start)
  10236. (not (string-match-p "\"" match start)))
  10237. ;; Match contains also a TODO-matching request.
  10238. (progn
  10239. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10240. (setq todomatch (substring match (match-end 0)))
  10241. (when (string-prefix-p "!" todomatch)
  10242. (setq org--matcher-tags-todo-only t)
  10243. (setq todomatch (substring todomatch 1)))
  10244. (when (string-match "\\`\\s-*\\'" todomatch)
  10245. (setq todomatch nil)))
  10246. ;; Only matching tags.
  10247. (setq tagsmatch match)
  10248. (setq todomatch nil))
  10249. ;; Make the tags matcher.
  10250. (when (org-string-nw-p tagsmatch)
  10251. (let ((orlist nil)
  10252. (orterms (org-split-string tagsmatch "|"))
  10253. term)
  10254. (while (setq term (pop orterms))
  10255. (while (and (equal (substring term -1) "\\") orterms)
  10256. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10257. (while (string-match re term)
  10258. (let* ((rest (substring term (match-end 0)))
  10259. (minus (and (match-end 1)
  10260. (equal (match-string 1 term) "-")))
  10261. (tag (save-match-data
  10262. (replace-regexp-in-string
  10263. "\\\\-" "-" (match-string 2 term))))
  10264. (regexp (eq (string-to-char tag) ?{))
  10265. (levelp (match-end 4))
  10266. (propp (match-end 5))
  10267. (mm
  10268. (cond
  10269. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10270. (levelp
  10271. `(,(org-op-to-function (match-string 3 term))
  10272. level
  10273. ,(string-to-number (match-string 4 term))))
  10274. (propp
  10275. (let* ((gv (pcase (upcase (match-string 5 term))
  10276. ("CATEGORY"
  10277. '(get-text-property (point) 'org-category))
  10278. ("TODO" 'todo)
  10279. (p `(org-cached-entry-get nil ,p))))
  10280. (pv (match-string 7 term))
  10281. (regexp (eq (string-to-char pv) ?{))
  10282. (strp (eq (string-to-char pv) ?\"))
  10283. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10284. (po (org-op-to-function (match-string 6 term)
  10285. (if timep 'time strp))))
  10286. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10287. (when timep (setq pv (org-matcher-time pv)))
  10288. (cond ((and regexp (eq po '/=))
  10289. `(not (string-match ,pv (or ,gv ""))))
  10290. (regexp `(string-match ,pv (or ,gv "")))
  10291. (strp `(,po (or ,gv "") ,pv))
  10292. (t
  10293. `(,po
  10294. (string-to-number (or ,gv ""))
  10295. ,(string-to-number pv))))))
  10296. (t `(member ,tag tags-list)))))
  10297. (push (if minus `(not ,mm) mm) tagsmatcher)
  10298. (setq term rest)))
  10299. (push `(and ,@tagsmatcher) orlist)
  10300. (setq tagsmatcher nil))
  10301. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10302. ;; Make the TODO matcher.
  10303. (when (org-string-nw-p todomatch)
  10304. (let ((orlist nil))
  10305. (dolist (term (org-split-string todomatch "|"))
  10306. (while (string-match re term)
  10307. (let* ((minus (and (match-end 1)
  10308. (equal (match-string 1 term) "-")))
  10309. (kwd (match-string 2 term))
  10310. (regexp (eq (string-to-char kwd) ?{))
  10311. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10312. `(equal todo ,kwd))))
  10313. (push (if minus `(not ,mm) mm) todomatcher))
  10314. (setq term (substring term (match-end 0))))
  10315. (push (if (> (length todomatcher) 1)
  10316. (cons 'and todomatcher)
  10317. (car todomatcher))
  10318. orlist)
  10319. (setq todomatcher nil))
  10320. (setq todomatcher (cons 'or orlist))))
  10321. ;; Return the string and function of the matcher. If no
  10322. ;; tags-specific or todo-specific matcher exists, match
  10323. ;; everything.
  10324. (let ((matcher (if (and tagsmatcher todomatcher)
  10325. `(and ,tagsmatcher ,todomatcher)
  10326. (or tagsmatcher todomatcher t))))
  10327. (when org--matcher-tags-todo-only
  10328. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10329. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10330. (defun org--tags-expand-group (group tag-groups expanded)
  10331. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10332. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10333. an accumulator used in recursive calls."
  10334. (dolist (tag group)
  10335. (unless (member tag expanded)
  10336. (let ((group (assoc tag tag-groups)))
  10337. (push tag expanded)
  10338. (when group
  10339. (setq expanded
  10340. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10341. expanded)
  10342. (defun org-tags-expand (match &optional single-as-list downcased)
  10343. "Expand group tags in MATCH.
  10344. This replaces every group tag in MATCH with a regexp tag search.
  10345. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10346. will be replaced like this:
  10347. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10348. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10349. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10350. Replacing by a regexp preserves the structure of the match.
  10351. E.g., this expansion
  10352. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10353. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10354. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10355. A group tag in MATCH can contain regular expressions of its own.
  10356. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10357. will be replaced like this:
  10358. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10359. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10360. assumed to be a single group tag, and the function will return
  10361. the list of tags in this group.
  10362. When DOWNCASED is non-nil, expand downcased TAGS."
  10363. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10364. (let ((tag-groups
  10365. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10366. (if (not downcased) g
  10367. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10368. (cond
  10369. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10370. (org-group-tags
  10371. (let* ((case-fold-search t)
  10372. (tag-syntax org-mode-syntax-table)
  10373. (group-keys (mapcar #'car tag-groups))
  10374. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10375. (return-match (if downcased (downcase match) match)))
  10376. ;; Mark regexp-expressions in the match-expression so that we
  10377. ;; do not replace them later on.
  10378. (let ((s 0))
  10379. (while (string-match "{.+?}" return-match s)
  10380. (setq s (match-end 0))
  10381. (add-text-properties
  10382. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10383. ;; @ and _ are allowed as word-components in tags.
  10384. (modify-syntax-entry ?@ "w" tag-syntax)
  10385. (modify-syntax-entry ?_ "w" tag-syntax)
  10386. ;; For each tag token found in MATCH, compute a regexp and it
  10387. (with-syntax-table tag-syntax
  10388. (replace-regexp-in-string
  10389. key-regexp
  10390. (lambda (m)
  10391. (if (get-text-property (match-beginning 2) 'regexp m)
  10392. m ;regexp tag: ignore
  10393. (let* ((operator (match-string 1 m))
  10394. (tag-token (let ((tag (match-string 2 m)))
  10395. (list (if downcased (downcase tag) tag))))
  10396. regexp-tags regular-tags)
  10397. ;; Partition tags between regexp and regular tags.
  10398. ;; Remove curly bracket syntax from regexp tags.
  10399. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10400. (save-match-data
  10401. (if (string-match "{\\(.+?\\)}" tag)
  10402. (push (match-string 1 tag) regexp-tags)
  10403. (push tag regular-tags))))
  10404. ;; Replace tag token by the appropriate regexp.
  10405. ;; Regular tags need to be regexp-quoted, whereas
  10406. ;; regexp-tags are inserted as-is.
  10407. (let ((regular (regexp-opt regular-tags))
  10408. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10409. (concat operator
  10410. (cond
  10411. ((null regular-tags) (format "{%s}" regexp))
  10412. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10413. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10414. return-match
  10415. t t))))
  10416. (t match))))
  10417. (defun org-op-to-function (op &optional stringp)
  10418. "Turn an operator into the appropriate function."
  10419. (setq op
  10420. (cond
  10421. ((equal op "<" ) '(< org-string< org-time<))
  10422. ((equal op ">" ) '(> org-string> org-time>))
  10423. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10424. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10425. ((member op '("=" "==")) '(= string= org-time=))
  10426. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10427. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10428. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10429. (defvar org-tags-overlay (make-overlay 1 1))
  10430. (delete-overlay org-tags-overlay)
  10431. (defun org-add-prop-inherited (s)
  10432. (add-text-properties 0 (length s) '(inherited t) s)
  10433. s)
  10434. (defun org-toggle-tag (tag &optional onoff)
  10435. "Toggle the tag TAG for the current line.
  10436. If ONOFF is `on' or `off', don't toggle but set to this state."
  10437. (save-excursion
  10438. (org-back-to-heading t)
  10439. (let ((current
  10440. ;; Reverse the tags list so any new tag is appended to the
  10441. ;; current list of tags.
  10442. (nreverse (org-get-tags nil t)))
  10443. res)
  10444. (pcase onoff
  10445. (`off (setq current (delete tag current)))
  10446. ((or `on (guard (not (member tag current))))
  10447. (setq res t)
  10448. (cl-pushnew tag current :test #'equal))
  10449. (_ (setq current (delete tag current))))
  10450. (org-set-tags (nreverse current))
  10451. res)))
  10452. (defun org--align-tags-here (to-col)
  10453. "Align tags on the current headline to TO-COL.
  10454. Assume point is on a headline. Preserve point when aligning
  10455. tags."
  10456. (when (org-match-line org-tag-line-re)
  10457. (let* ((tags-start (match-beginning 1))
  10458. (blank-start (save-excursion
  10459. (goto-char tags-start)
  10460. (skip-chars-backward " \t")
  10461. (point)))
  10462. (new (max (if (>= to-col 0) to-col
  10463. (- (abs to-col) (string-width (match-string 1))))
  10464. ;; Introduce at least one space after the heading
  10465. ;; or the stars.
  10466. (save-excursion
  10467. (goto-char blank-start)
  10468. (1+ (current-column)))))
  10469. (current
  10470. (save-excursion (goto-char tags-start) (current-column)))
  10471. (origin (point-marker))
  10472. (column (current-column))
  10473. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10474. (when (/= new current)
  10475. (delete-region blank-start tags-start)
  10476. (goto-char blank-start)
  10477. (let ((indent-tabs-mode nil)) (indent-to new))
  10478. ;; Try to move back to original position. If point was in the
  10479. ;; blanks before the tags, ORIGIN marker is of no use because
  10480. ;; it now points to BLANK-START. Use COLUMN instead.
  10481. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10482. (defun org-set-tags-command (&optional arg)
  10483. "Set the tags for the current visible entry.
  10484. When called with `\\[universal-argument]' prefix argument ARG, \
  10485. realign all tags
  10486. in the current buffer.
  10487. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10488. unconditionally do not
  10489. offer the fast tag selection interface.
  10490. If a region is active, set tags in the region according to the
  10491. setting of `org-loop-over-headlines-in-active-region'.
  10492. This function is for interactive use only;
  10493. in Lisp code use `org-set-tags' instead."
  10494. (interactive "P")
  10495. (let ((org-use-fast-tag-selection
  10496. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10497. (cond
  10498. ((equal '(4) arg) (org-align-tags t))
  10499. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10500. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10501. (org-map-entries
  10502. #'org-set-tags-command
  10503. nil
  10504. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10505. 'region-start-level
  10506. 'region)
  10507. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10508. (t
  10509. (save-excursion
  10510. (org-back-to-heading)
  10511. (let* ((all-tags (org-get-tags))
  10512. (table (setq org-last-tags-completion-table
  10513. (org--tag-add-to-alist
  10514. (and org-complete-tags-always-offer-all-agenda-tags
  10515. (org-global-tags-completion-table
  10516. (org-agenda-files)))
  10517. (or org-current-tag-alist (org-get-buffer-tags)))))
  10518. (current-tags
  10519. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10520. all-tags))
  10521. (inherited-tags
  10522. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10523. all-tags))
  10524. (tags
  10525. (replace-regexp-in-string
  10526. ;; Ignore all forbidden characters in tags.
  10527. "[^[:alnum:]_@#%]+" ":"
  10528. (if (or (eq t org-use-fast-tag-selection)
  10529. (and org-use-fast-tag-selection
  10530. (delq nil (mapcar #'cdr table))))
  10531. (org-fast-tag-selection
  10532. current-tags
  10533. inherited-tags
  10534. table
  10535. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10536. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10537. (org-trim (completing-read
  10538. "Tags: "
  10539. #'org-tags-completion-function
  10540. nil nil (org-make-tag-string current-tags)
  10541. 'org-tags-history)))))))
  10542. (org-set-tags tags)))))))
  10543. (defun org-align-tags (&optional all)
  10544. "Align tags in current entry.
  10545. When optional argument ALL is non-nil, align all tags in the
  10546. visible part of the buffer."
  10547. (let ((get-indent-column
  10548. (lambda ()
  10549. (let ((offset (if (bound-and-true-p org-indent-mode)
  10550. (* (1- org-indent-indentation-per-level)
  10551. (1- (org-current-level)))
  10552. 0)))
  10553. (+ org-tags-column
  10554. (if (> org-tags-column 0) (- offset) offset))))))
  10555. (if (and (not all) (org-at-heading-p))
  10556. (org--align-tags-here (funcall get-indent-column))
  10557. (save-excursion
  10558. (if all
  10559. (progn
  10560. (goto-char (point-min))
  10561. (while (re-search-forward org-tag-line-re nil t)
  10562. (org--align-tags-here (funcall get-indent-column))))
  10563. (org-back-to-heading t)
  10564. (org--align-tags-here (funcall get-indent-column)))))))
  10565. (defun org-set-tags (tags)
  10566. "Set the tags of the current entry to TAGS, replacing current tags.
  10567. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10568. If TAGS is nil or the empty string, all tags are removed.
  10569. This function assumes point is on a headline."
  10570. (org-with-wide-buffer
  10571. (let ((tags (pcase tags
  10572. ((pred listp) tags)
  10573. ((pred stringp) (split-string (org-trim tags) ":" t))
  10574. (_ (error "Invalid tag specification: %S" tags))))
  10575. (old-tags (org-get-tags nil t))
  10576. (tags-change? nil))
  10577. (when (functionp org-tags-sort-function)
  10578. (setq tags (sort tags org-tags-sort-function)))
  10579. (setq tags-change? (not (equal tags old-tags)))
  10580. (when tags-change?
  10581. ;; Delete previous tags and any trailing white space.
  10582. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10583. (line-end-position)))
  10584. (skip-chars-backward " \t")
  10585. (delete-region (point) (line-end-position))
  10586. ;; Deleting white spaces may break an otherwise empty headline.
  10587. ;; Re-introduce one space in this case.
  10588. (unless (org-at-heading-p) (insert " "))
  10589. (when tags
  10590. (save-excursion (insert " " (org-make-tag-string tags)))
  10591. ;; When text is being inserted on an invisible region
  10592. ;; boundary, it can be inadvertently sucked into
  10593. ;; invisibility.
  10594. (unless (org-invisible-p (line-beginning-position))
  10595. (org-flag-region (point) (line-end-position) nil 'outline))))
  10596. ;; Align tags, if any.
  10597. (when tags (org-align-tags))
  10598. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10599. (defun org-change-tag-in-region (beg end tag off)
  10600. "Add or remove TAG for each entry in the region.
  10601. This works in the agenda, and also in an Org buffer."
  10602. (interactive
  10603. (list (region-beginning) (region-end)
  10604. (let ((org-last-tags-completion-table
  10605. (if (derived-mode-p 'org-mode)
  10606. (org--tag-add-to-alist
  10607. (org-get-buffer-tags)
  10608. (org-global-tags-completion-table))
  10609. (org-global-tags-completion-table))))
  10610. (completing-read
  10611. "Tag: " 'org-tags-completion-function nil nil nil
  10612. 'org-tags-history))
  10613. (progn
  10614. (message "[s]et or [r]emove? ")
  10615. (equal (read-char-exclusive) ?r))))
  10616. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10617. (let ((agendap (equal major-mode 'org-agenda-mode))
  10618. l1 l2 m buf pos newhead (cnt 0))
  10619. (goto-char end)
  10620. (setq l2 (1- (org-current-line)))
  10621. (goto-char beg)
  10622. (setq l1 (org-current-line))
  10623. (cl-loop for l from l1 to l2 do
  10624. (org-goto-line l)
  10625. (setq m (get-text-property (point) 'org-hd-marker))
  10626. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10627. (and agendap m))
  10628. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10629. pos (if agendap m (point)))
  10630. (with-current-buffer buf
  10631. (save-excursion
  10632. (save-restriction
  10633. (goto-char pos)
  10634. (setq cnt (1+ cnt))
  10635. (org-toggle-tag tag (if off 'off 'on))
  10636. (setq newhead (org-get-heading)))))
  10637. (and agendap (org-agenda-change-all-lines newhead m))))
  10638. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10639. (defun org-tags-completion-function (string _predicate &optional flag)
  10640. "Complete tag STRING.
  10641. FLAG specifies the type of completion operation to perform. This
  10642. function is passed as a collection function to `completing-read',
  10643. which see."
  10644. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10645. (confirm (lambda (x) (stringp (car x))))
  10646. (prefix ""))
  10647. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10648. (setq prefix (match-string 1 string))
  10649. (setq string (match-string 2 string)))
  10650. (pcase flag
  10651. (`t (all-completions string org-last-tags-completion-table confirm))
  10652. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10653. (`nil
  10654. (pcase (try-completion string org-last-tags-completion-table confirm)
  10655. ((and completion (pred stringp))
  10656. (concat prefix
  10657. completion
  10658. (if (and org-add-colon-after-tag-completion
  10659. (assoc completion org-last-tags-completion-table))
  10660. ":"
  10661. "")))
  10662. (completion completion)))
  10663. (_ nil))))
  10664. (defun org-fast-tag-insert (kwd tags face &optional end)
  10665. "Insert KWD, and the TAGS, the latter with face FACE.
  10666. Also insert END."
  10667. (insert (format "%-12s" (concat kwd ":"))
  10668. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10669. (or end "")))
  10670. (defun org-fast-tag-show-exit (flag)
  10671. (save-excursion
  10672. (org-goto-line 3)
  10673. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10674. (replace-match ""))
  10675. (when flag
  10676. (end-of-line 1)
  10677. (org-move-to-column (- (window-width) 19) t)
  10678. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10679. (defun org-set-current-tags-overlay (current prefix)
  10680. "Add an overlay to CURRENT tag with PREFIX."
  10681. (let ((s (org-make-tag-string current)))
  10682. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10683. (org-overlay-display org-tags-overlay (concat prefix s))))
  10684. (defvar org-last-tag-selection-key nil)
  10685. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10686. "Fast tag selection with single keys.
  10687. CURRENT is the current list of tags in the headline, INHERITED is the
  10688. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10689. possibly with grouping information. TODO-TABLE is a similar table with
  10690. TODO keywords, should these have keys assigned to them.
  10691. If the keys are nil, a-z are automatically assigned.
  10692. Returns the new tags string, or nil to not change the current settings."
  10693. (let* ((fulltable (append table todo-table))
  10694. (maxlen (if (null fulltable) 0
  10695. (apply #'max
  10696. (mapcar (lambda (x)
  10697. (if (stringp (car x)) (string-width (car x))
  10698. 0))
  10699. fulltable))))
  10700. (buf (current-buffer))
  10701. (expert (eq org-fast-tag-selection-single-key 'expert))
  10702. (buffer-tags nil)
  10703. (fwidth (+ maxlen 3 1 3))
  10704. (ncol (/ (- (window-width) 4) fwidth))
  10705. (i-face 'org-done)
  10706. (c-face 'org-todo)
  10707. tg cnt e c char c1 c2 ntable tbl rtn
  10708. ov-start ov-end ov-prefix
  10709. (exit-after-next org-fast-tag-selection-single-key)
  10710. (done-keywords org-done-keywords)
  10711. groups ingroup intaggroup)
  10712. (save-excursion
  10713. (beginning-of-line)
  10714. (if (looking-at org-tag-line-re)
  10715. (setq ov-start (match-beginning 1)
  10716. ov-end (match-end 1)
  10717. ov-prefix "")
  10718. (setq ov-start (1- (point-at-eol))
  10719. ov-end (1+ ov-start))
  10720. (skip-chars-forward "^\n\r")
  10721. (setq ov-prefix
  10722. (concat
  10723. (buffer-substring (1- (point)) (point))
  10724. (if (> (current-column) org-tags-column)
  10725. " "
  10726. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10727. (move-overlay org-tags-overlay ov-start ov-end)
  10728. (save-excursion
  10729. (save-window-excursion
  10730. (if expert
  10731. (set-buffer (get-buffer-create " *Org tags*"))
  10732. (delete-other-windows)
  10733. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10734. (org-switch-to-buffer-other-window " *Org tags*"))
  10735. (erase-buffer)
  10736. (setq-local org-done-keywords done-keywords)
  10737. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10738. (org-fast-tag-insert "Current" current c-face "\n\n")
  10739. (org-fast-tag-show-exit exit-after-next)
  10740. (org-set-current-tags-overlay current ov-prefix)
  10741. (setq tbl fulltable char ?a cnt 0)
  10742. (while (setq e (pop tbl))
  10743. (cond
  10744. ((eq (car e) :startgroup)
  10745. (push '() groups) (setq ingroup t)
  10746. (unless (zerop cnt)
  10747. (setq cnt 0)
  10748. (insert "\n"))
  10749. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10750. ((eq (car e) :endgroup)
  10751. (setq ingroup nil cnt 0)
  10752. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10753. ((eq (car e) :startgrouptag)
  10754. (setq intaggroup t)
  10755. (unless (zerop cnt)
  10756. (setq cnt 0)
  10757. (insert "\n"))
  10758. (insert "[ "))
  10759. ((eq (car e) :endgrouptag)
  10760. (setq intaggroup nil cnt 0)
  10761. (insert "]\n"))
  10762. ((equal e '(:newline))
  10763. (unless (zerop cnt)
  10764. (setq cnt 0)
  10765. (insert "\n")
  10766. (setq e (car tbl))
  10767. (while (equal (car tbl) '(:newline))
  10768. (insert "\n")
  10769. (setq tbl (cdr tbl)))))
  10770. ((equal e '(:grouptags)) (insert " : "))
  10771. (t
  10772. (setq tg (copy-sequence (car e)) c2 nil)
  10773. (if (cdr e)
  10774. (setq c (cdr e))
  10775. ;; automatically assign a character.
  10776. (setq c1 (string-to-char
  10777. (downcase (substring
  10778. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10779. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10780. (while (or (rassoc char ntable) (rassoc char table))
  10781. (setq char (1+ char)))
  10782. (setq c2 c1))
  10783. (setq c (or c2 char)))
  10784. (when ingroup (push tg (car groups)))
  10785. (setq tg (org-add-props tg nil 'face
  10786. (cond
  10787. ((not (assoc tg table))
  10788. (org-get-todo-face tg))
  10789. ((member tg current) c-face)
  10790. ((member tg inherited) i-face))))
  10791. (when (equal (caar tbl) :grouptags)
  10792. (org-add-props tg nil 'face 'org-tag-group))
  10793. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10794. (insert "[" c "] " tg (make-string
  10795. (- fwidth 4 (length tg)) ?\ ))
  10796. (push (cons tg c) ntable)
  10797. (when (= (cl-incf cnt) ncol)
  10798. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10799. (insert "\n")
  10800. (when (or ingroup intaggroup) (insert " ")))
  10801. (setq cnt 0)))))
  10802. (setq ntable (nreverse ntable))
  10803. (insert "\n")
  10804. (goto-char (point-min))
  10805. (unless expert (org-fit-window-to-buffer))
  10806. (setq rtn
  10807. (catch 'exit
  10808. (while t
  10809. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10810. (if (not groups) "no " "")
  10811. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10812. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10813. (setq org-last-tag-selection-key c)
  10814. (cond
  10815. ((= c ?\r) (throw 'exit t))
  10816. ((= c ?!)
  10817. (setq groups (not groups))
  10818. (goto-char (point-min))
  10819. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10820. ((= c ?\C-c)
  10821. (if (not expert)
  10822. (org-fast-tag-show-exit
  10823. (setq exit-after-next (not exit-after-next)))
  10824. (setq expert nil)
  10825. (delete-other-windows)
  10826. (set-window-buffer (split-window-vertically) " *Org tags*")
  10827. (org-switch-to-buffer-other-window " *Org tags*")
  10828. (org-fit-window-to-buffer)))
  10829. ((or (= c ?\C-g)
  10830. (and (= c ?q) (not (rassoc c ntable))))
  10831. (delete-overlay org-tags-overlay)
  10832. (setq quit-flag t))
  10833. ((= c ?\ )
  10834. (setq current nil)
  10835. (when exit-after-next (setq exit-after-next 'now)))
  10836. ((= c ?\t)
  10837. (condition-case nil
  10838. (setq tg (completing-read
  10839. "Tag: "
  10840. (or buffer-tags
  10841. (with-current-buffer buf
  10842. (setq buffer-tags
  10843. (org-get-buffer-tags))))))
  10844. (quit (setq tg "")))
  10845. (when (string-match "\\S-" tg)
  10846. (cl-pushnew (list tg) buffer-tags :test #'equal)
  10847. (if (member tg current)
  10848. (setq current (delete tg current))
  10849. (push tg current)))
  10850. (when exit-after-next (setq exit-after-next 'now)))
  10851. ((setq e (rassoc c todo-table) tg (car e))
  10852. (with-current-buffer buf
  10853. (save-excursion (org-todo tg)))
  10854. (when exit-after-next (setq exit-after-next 'now)))
  10855. ((setq e (rassoc c ntable) tg (car e))
  10856. (if (member tg current)
  10857. (setq current (delete tg current))
  10858. (cl-loop for g in groups do
  10859. (when (member tg g)
  10860. (dolist (x g) (setq current (delete x current)))))
  10861. (push tg current))
  10862. (when exit-after-next (setq exit-after-next 'now))))
  10863. ;; Create a sorted list
  10864. (setq current
  10865. (sort current
  10866. (lambda (a b)
  10867. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10868. (when (eq exit-after-next 'now) (throw 'exit t))
  10869. (goto-char (point-min))
  10870. (beginning-of-line 2)
  10871. (delete-region (point) (point-at-eol))
  10872. (org-fast-tag-insert "Current" current c-face)
  10873. (org-set-current-tags-overlay current ov-prefix)
  10874. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10875. (while (re-search-forward tag-re nil t)
  10876. (let ((tag (match-string 1)))
  10877. (add-text-properties
  10878. (match-beginning 1) (match-end 1)
  10879. (list 'face
  10880. (cond
  10881. ((member tag current) c-face)
  10882. ((member tag inherited) i-face)
  10883. (t (get-text-property (match-beginning 1) '
  10884. face))))))))
  10885. (goto-char (point-min)))))
  10886. (delete-overlay org-tags-overlay)
  10887. (if rtn
  10888. (mapconcat 'identity current ":")
  10889. nil)))))
  10890. (defun org-make-tag-string (tags)
  10891. "Return string associated to TAGS.
  10892. TAGS is a list of strings."
  10893. (if (null tags) ""
  10894. (format ":%s:" (mapconcat #'identity tags ":"))))
  10895. (defun org--get-local-tags ()
  10896. "Return list of tags for the current headline.
  10897. Assume point is at the beginning of the headline."
  10898. (and (looking-at org-tag-line-re)
  10899. (split-string (match-string-no-properties 2) ":" t)))
  10900. (defun org-get-tags (&optional pos local)
  10901. "Get the list of tags specified in the current headline.
  10902. When argument POS is non-nil, retrieve tags for headline at POS.
  10903. According to `org-use-tag-inheritance', tags may be inherited
  10904. from parent headlines, and from the whole document, through
  10905. `org-file-tags'. In this case, the returned list of tags
  10906. contains tags in this order: file tags, tags inherited from
  10907. parent headlines, local tags.
  10908. However, when optional argument LOCAL is non-nil, only return
  10909. tags specified at the headline.
  10910. Inherited tags have the `inherited' text property."
  10911. (if (and org-trust-scanner-tags
  10912. (or (not pos) (eq pos (point)))
  10913. (not local))
  10914. org-scanner-tags
  10915. (org-with-point-at (or pos (point))
  10916. (unless (org-before-first-heading-p)
  10917. (org-back-to-heading t)
  10918. (let ((ltags (org--get-local-tags)) itags)
  10919. (if (or local (not org-use-tag-inheritance)) ltags
  10920. (while (org-up-heading-safe)
  10921. (setq itags (append (mapcar #'org-add-prop-inherited
  10922. (org--get-local-tags))
  10923. itags)))
  10924. (setq itags (append org-file-tags itags))
  10925. (delete-dups
  10926. (append (org-remove-uninherited-tags itags) ltags))))))))
  10927. (defun org-get-buffer-tags ()
  10928. "Get a table of all tags used in the buffer, for completion."
  10929. (org-with-point-at 1
  10930. (let (tags)
  10931. (while (re-search-forward org-tag-line-re nil t)
  10932. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10933. tags)))
  10934. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  10935. ;;;; The mapping API
  10936. (defvar org-agenda-skip-comment-trees)
  10937. (defvar org-agenda-skip-function)
  10938. (defun org-map-entries (func &optional match scope &rest skip)
  10939. "Call FUNC at each headline selected by MATCH in SCOPE.
  10940. FUNC is a function or a lisp form. The function will be called without
  10941. arguments, with the cursor positioned at the beginning of the headline.
  10942. The return values of all calls to the function will be collected and
  10943. returned as a list.
  10944. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  10945. does not need to preserve point. After evaluation, the cursor will be
  10946. moved to the end of the line (presumably of the headline of the
  10947. processed entry) and search continues from there. Under some
  10948. circumstances, this may not produce the wanted results. For example,
  10949. if you have removed (e.g. archived) the current (sub)tree it could
  10950. mean that the next entry will be skipped entirely. In such cases, you
  10951. can specify the position from where search should continue by making
  10952. FUNC set the variable `org-map-continue-from' to the desired buffer
  10953. position.
  10954. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10955. Only headlines that are matched by this query will be considered during
  10956. the iteration. When MATCH is nil or t, all headlines will be
  10957. visited by the iteration.
  10958. SCOPE determines the scope of this command. It can be any of:
  10959. nil The current buffer, respecting the restriction if any
  10960. tree The subtree started with the entry at point
  10961. region The entries within the active region, if any
  10962. region-start-level
  10963. The entries within the active region, but only those at
  10964. the same level than the first one.
  10965. file The current buffer, without restriction
  10966. file-with-archives
  10967. The current buffer, and any archives associated with it
  10968. agenda All agenda files
  10969. agenda-with-archives
  10970. All agenda files with any archive files associated with them
  10971. \(file1 file2 ...)
  10972. If this is a list, all files in the list will be scanned
  10973. The remaining args are treated as settings for the skipping facilities of
  10974. the scanner. The following items can be given here:
  10975. archive skip trees with the archive tag
  10976. comment skip trees with the COMMENT keyword
  10977. function or Emacs Lisp form:
  10978. will be used as value for `org-agenda-skip-function', so
  10979. whenever the function returns a position, FUNC will not be
  10980. called for that entry and search will continue from the
  10981. position returned
  10982. If your function needs to retrieve the tags including inherited tags
  10983. at the *current* entry, you can use the value of the variable
  10984. `org-scanner-tags' which will be much faster than getting the value
  10985. with `org-get-tags'. If your function gets properties with
  10986. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10987. to t around the call to `org-entry-properties' to get the same speedup.
  10988. Note that if your function moves around to retrieve tags and properties at
  10989. a *different* entry, you cannot use these techniques."
  10990. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10991. (not (org-region-active-p)))
  10992. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10993. (org-agenda-skip-archived-trees (memq 'archive skip))
  10994. (org-agenda-skip-comment-trees (memq 'comment skip))
  10995. (org-agenda-skip-function
  10996. (car (org-delete-all '(comment archive) skip)))
  10997. (org-tags-match-list-sublevels t)
  10998. (start-level (eq scope 'region-start-level))
  10999. matcher res
  11000. org-todo-keywords-for-agenda
  11001. org-done-keywords-for-agenda
  11002. org-todo-keyword-alist-for-agenda
  11003. org-tag-alist-for-agenda
  11004. org--matcher-tags-todo-only)
  11005. (cond
  11006. ((eq match t) (setq matcher t))
  11007. ((eq match nil) (setq matcher t))
  11008. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11009. (save-excursion
  11010. (save-restriction
  11011. (cond ((eq scope 'tree)
  11012. (org-back-to-heading t)
  11013. (org-narrow-to-subtree)
  11014. (setq scope nil))
  11015. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11016. (org-region-active-p))
  11017. ;; If needed, set start-level to a string like "2"
  11018. (when start-level
  11019. (save-excursion
  11020. (goto-char (region-beginning))
  11021. (unless (org-at-heading-p) (outline-next-heading))
  11022. (setq start-level (org-current-level))))
  11023. (narrow-to-region (region-beginning)
  11024. (save-excursion
  11025. (goto-char (region-end))
  11026. (unless (and (bolp) (org-at-heading-p))
  11027. (outline-next-heading))
  11028. (point)))
  11029. (setq scope nil)))
  11030. (if (not scope)
  11031. (progn
  11032. (org-agenda-prepare-buffers
  11033. (and buffer-file-name (list buffer-file-name)))
  11034. (setq res
  11035. (org-scan-tags
  11036. func matcher org--matcher-tags-todo-only start-level)))
  11037. ;; Get the right scope
  11038. (cond
  11039. ((and scope (listp scope) (symbolp (car scope)))
  11040. (setq scope (eval scope)))
  11041. ((eq scope 'agenda)
  11042. (setq scope (org-agenda-files t)))
  11043. ((eq scope 'agenda-with-archives)
  11044. (setq scope (org-agenda-files t))
  11045. (setq scope (org-add-archive-files scope)))
  11046. ((eq scope 'file)
  11047. (setq scope (and buffer-file-name (list buffer-file-name))))
  11048. ((eq scope 'file-with-archives)
  11049. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11050. (org-agenda-prepare-buffers scope)
  11051. (dolist (file scope)
  11052. (with-current-buffer (org-find-base-buffer-visiting file)
  11053. (org-with-wide-buffer
  11054. (goto-char (point-min))
  11055. (setq res
  11056. (append
  11057. res
  11058. (org-scan-tags
  11059. func matcher org--matcher-tags-todo-only)))))))))
  11060. res)))
  11061. ;;; Properties API
  11062. (defconst org-special-properties
  11063. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11064. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11065. "The special properties valid in Org mode.
  11066. These are properties that are not defined in the property drawer,
  11067. but in some other way.")
  11068. (defconst org-default-properties
  11069. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11070. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11071. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11072. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11073. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11074. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11075. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11076. "Some properties that are used by Org mode for various purposes.
  11077. Being in this list makes sure that they are offered for completion.")
  11078. (defun org--valid-property-p (property)
  11079. "Non-nil when string PROPERTY is a valid property name."
  11080. (not
  11081. (or (equal property "")
  11082. (string-match-p "\\s-" property))))
  11083. (defun org--update-property-plist (key val props)
  11084. "Associate KEY to VAL in alist PROPS.
  11085. Modifications are made by side-effect. Return new alist."
  11086. (let* ((appending (string= (substring key -1) "+"))
  11087. (key (if appending (substring key 0 -1) key))
  11088. (old (assoc-string key props t)))
  11089. (if (not old) (cons (cons key val) props)
  11090. (setcdr old (if appending (concat (cdr old) " " val) val))
  11091. props)))
  11092. (defun org-get-property-block (&optional beg force)
  11093. "Return the (beg . end) range of the body of the property drawer.
  11094. BEG is the beginning of the current subtree or the beginning of
  11095. the document if before the first headline. If it is not given,
  11096. it will be found. If the drawer does not exist, create it if
  11097. FORCE is non-nil, or return nil."
  11098. (org-with-wide-buffer
  11099. (let ((beg (cond (beg (goto-char beg))
  11100. ((or (not (featurep 'org-inlinetask))
  11101. (org-inlinetask-in-task-p))
  11102. (org-back-to-heading-or-point-min t) (point))
  11103. (t (org-with-limited-levels
  11104. (org-back-to-heading-or-point-min t))
  11105. (point)))))
  11106. ;; Move point to its position according to its positional rules.
  11107. (cond ((org-before-first-heading-p)
  11108. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11109. (t (forward-line)
  11110. (when (looking-at-p org-planning-line-re) (forward-line))))
  11111. (cond ((looking-at org-property-drawer-re)
  11112. (forward-line)
  11113. (cons (point) (progn (goto-char (match-end 0))
  11114. (line-beginning-position))))
  11115. (force
  11116. (goto-char beg)
  11117. (org-insert-property-drawer)
  11118. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11119. (line-beginning-position))))
  11120. (cons pos pos)))))))
  11121. (defun org-at-property-block-p ()
  11122. "Return t when point is at the first line of a property drawer.
  11123. The property drawer is validated according to its positional
  11124. rules using `org-get-property-block'."
  11125. (save-excursion
  11126. (beginning-of-line)
  11127. (and (looking-at org-property-start-re)
  11128. (forward-line)
  11129. (let ((property-drawer (org-get-property-block)))
  11130. (and property-drawer
  11131. (= (point) (car property-drawer)))))))
  11132. (defun org-at-property-p ()
  11133. "Non-nil when point is inside a property drawer.
  11134. See `org-property-re' for match data, if applicable."
  11135. (save-excursion
  11136. (beginning-of-line)
  11137. (and (looking-at org-property-re)
  11138. (let ((property-drawer (save-match-data (org-get-property-block))))
  11139. (and property-drawer
  11140. (>= (point) (car property-drawer))
  11141. (< (point) (cdr property-drawer)))))))
  11142. (defun org-property-action ()
  11143. "Do an action on properties."
  11144. (interactive)
  11145. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11146. (let ((c (read-char-exclusive)))
  11147. (cl-case c
  11148. (?s (call-interactively #'org-set-property))
  11149. (?d (call-interactively #'org-delete-property))
  11150. (?D (call-interactively #'org-delete-property-globally))
  11151. (?c (call-interactively #'org-compute-property-at-point))
  11152. (otherwise (user-error "No such property action %c" c)))))
  11153. (defun org-inc-effort ()
  11154. "Increment the value of the effort property in the current entry."
  11155. (interactive)
  11156. (org-set-effort t))
  11157. (defvar org-clock-effort) ; Defined in org-clock.el.
  11158. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11159. (defun org-set-effort (&optional increment value)
  11160. "Set the effort property of the current entry.
  11161. If INCREMENT is non-nil, set the property to the next allowed
  11162. value. Otherwise, if optional argument VALUE is provided, use
  11163. it. Eventually, prompt for the new value if none of the previous
  11164. variables is set."
  11165. (interactive "P")
  11166. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11167. (current (org-entry-get nil org-effort-property))
  11168. (value
  11169. (cond
  11170. (increment
  11171. (unless allowed (user-error "Allowed effort values are not set"))
  11172. (or (cl-caadr (member (list current) allowed))
  11173. (user-error "Unknown value %S among allowed values" current)))
  11174. (value
  11175. (if (stringp value) value
  11176. (error "Invalid effort value: %S" value)))
  11177. (t
  11178. (let ((must-match
  11179. (and allowed
  11180. (not (get-text-property 0 'org-unrestricted
  11181. (caar allowed))))))
  11182. (completing-read "Effort: " allowed nil must-match))))))
  11183. ;; Test whether the value can be interpreted as a duration before
  11184. ;; inserting it in the buffer:
  11185. (org-duration-to-minutes value)
  11186. ;; Maybe update the effort value:
  11187. (unless (equal current value)
  11188. (org-entry-put nil org-effort-property value))
  11189. (org-refresh-property '((effort . identity)
  11190. (effort-minutes . org-duration-to-minutes))
  11191. value)
  11192. (when (equal (org-get-heading t t t t)
  11193. (bound-and-true-p org-clock-current-task))
  11194. (setq org-clock-effort value)
  11195. (org-clock-update-mode-line))
  11196. (message "%s is now %s" org-effort-property value)))
  11197. (defun org-entry-properties (&optional pom which)
  11198. "Get all properties of the current entry.
  11199. When POM is a buffer position, get all properties from the entry
  11200. there instead.
  11201. This includes the TODO keyword, the tags, time strings for
  11202. deadline, scheduled, and clocking, and any additional properties
  11203. defined in the entry.
  11204. If WHICH is nil or `all', get all properties. If WHICH is
  11205. `special' or `standard', only get that subclass. If WHICH is
  11206. a string, only get that property.
  11207. Return value is an alist. Keys are properties, as upcased
  11208. strings."
  11209. (org-with-point-at pom
  11210. (when (and (derived-mode-p 'org-mode)
  11211. (org-back-to-heading-or-point-min t))
  11212. (catch 'exit
  11213. (let* ((beg (point))
  11214. (specific (and (stringp which) (upcase which)))
  11215. (which (cond ((not specific) which)
  11216. ((member specific org-special-properties) 'special)
  11217. (t 'standard)))
  11218. props)
  11219. ;; Get the special properties, like TODO and TAGS.
  11220. (when (memq which '(nil all special))
  11221. (when (or (not specific) (string= specific "CLOCKSUM"))
  11222. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11223. (when clocksum
  11224. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11225. props)))
  11226. (when specific (throw 'exit props)))
  11227. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11228. (let ((clocksumt (get-text-property (point)
  11229. :org-clock-minutes-today)))
  11230. (when clocksumt
  11231. (push (cons "CLOCKSUM_T"
  11232. (org-duration-from-minutes clocksumt))
  11233. props)))
  11234. (when specific (throw 'exit props)))
  11235. (when (or (not specific) (string= specific "ITEM"))
  11236. (let ((case-fold-search nil))
  11237. (when (looking-at org-complex-heading-regexp)
  11238. (push (cons "ITEM"
  11239. (let ((title (match-string-no-properties 4)))
  11240. (if (org-string-nw-p title)
  11241. (org-remove-tabs title)
  11242. "")))
  11243. props)))
  11244. (when specific (throw 'exit props)))
  11245. (when (or (not specific) (string= specific "TODO"))
  11246. (let ((case-fold-search nil))
  11247. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11248. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11249. (when specific (throw 'exit props)))
  11250. (when (or (not specific) (string= specific "PRIORITY"))
  11251. (push (cons "PRIORITY"
  11252. (if (looking-at org-priority-regexp)
  11253. (match-string-no-properties 2)
  11254. (char-to-string org-priority-default)))
  11255. props)
  11256. (when specific (throw 'exit props)))
  11257. (when (or (not specific) (string= specific "FILE"))
  11258. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11259. props)
  11260. (when specific (throw 'exit props)))
  11261. (when (or (not specific) (string= specific "TAGS"))
  11262. (let ((tags (org-get-tags nil t)))
  11263. (when tags
  11264. (push (cons "TAGS" (org-make-tag-string tags))
  11265. props)))
  11266. (when specific (throw 'exit props)))
  11267. (when (or (not specific) (string= specific "ALLTAGS"))
  11268. (let ((tags (org-get-tags)))
  11269. (when tags
  11270. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11271. props)))
  11272. (when specific (throw 'exit props)))
  11273. (when (or (not specific) (string= specific "BLOCKED"))
  11274. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11275. (when specific (throw 'exit props)))
  11276. (when (or (not specific)
  11277. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11278. (forward-line)
  11279. (when (looking-at-p org-planning-line-re)
  11280. (end-of-line)
  11281. (let ((bol (line-beginning-position))
  11282. ;; Backward compatibility: time keywords used to
  11283. ;; be configurable (before 8.3). Make sure we
  11284. ;; get the correct keyword.
  11285. (key-assoc `(("CLOSED" . ,org-closed-string)
  11286. ("DEADLINE" . ,org-deadline-string)
  11287. ("SCHEDULED" . ,org-scheduled-string))))
  11288. (dolist (pair (if specific (list (assoc specific key-assoc))
  11289. key-assoc))
  11290. (save-excursion
  11291. (when (search-backward (cdr pair) bol t)
  11292. (goto-char (match-end 0))
  11293. (skip-chars-forward " \t")
  11294. (and (looking-at org-ts-regexp-both)
  11295. (push (cons (car pair)
  11296. (match-string-no-properties 0))
  11297. props)))))))
  11298. (when specific (throw 'exit props)))
  11299. (when (or (not specific)
  11300. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11301. (let ((find-ts
  11302. (lambda (end ts)
  11303. ;; Fix next time-stamp before END. TS is the
  11304. ;; list of time-stamps found so far.
  11305. (let ((ts ts)
  11306. (regexp (cond
  11307. ((string= specific "TIMESTAMP")
  11308. org-ts-regexp)
  11309. ((string= specific "TIMESTAMP_IA")
  11310. org-ts-regexp-inactive)
  11311. ((assoc "TIMESTAMP_IA" ts)
  11312. org-ts-regexp)
  11313. ((assoc "TIMESTAMP" ts)
  11314. org-ts-regexp-inactive)
  11315. (t org-ts-regexp-both))))
  11316. (catch 'next
  11317. (while (re-search-forward regexp end t)
  11318. (backward-char)
  11319. (let ((object (org-element-context)))
  11320. ;; Accept to match timestamps in node
  11321. ;; properties, too.
  11322. (when (memq (org-element-type object)
  11323. '(node-property timestamp))
  11324. (let ((type
  11325. (org-element-property :type object)))
  11326. (cond
  11327. ((and (memq type '(active active-range))
  11328. (not (equal specific "TIMESTAMP_IA")))
  11329. (unless (assoc "TIMESTAMP" ts)
  11330. (push (cons "TIMESTAMP"
  11331. (org-element-property
  11332. :raw-value object))
  11333. ts)
  11334. (when specific (throw 'exit ts))))
  11335. ((and (memq type '(inactive inactive-range))
  11336. (not (string= specific "TIMESTAMP")))
  11337. (unless (assoc "TIMESTAMP_IA" ts)
  11338. (push (cons "TIMESTAMP_IA"
  11339. (org-element-property
  11340. :raw-value object))
  11341. ts)
  11342. (when specific (throw 'exit ts))))))
  11343. ;; Both timestamp types are found,
  11344. ;; move to next part.
  11345. (when (= (length ts) 2) (throw 'next ts)))))
  11346. ts)))))
  11347. (goto-char beg)
  11348. ;; First look for timestamps within headline.
  11349. (let ((ts (funcall find-ts (line-end-position) nil)))
  11350. (if (= (length ts) 2) (setq props (nconc ts props))
  11351. ;; Then find timestamps in the section, skipping
  11352. ;; planning line.
  11353. (let ((end (save-excursion (outline-next-heading))))
  11354. (forward-line)
  11355. (when (looking-at-p org-planning-line-re) (forward-line))
  11356. (setq props (nconc (funcall find-ts end ts) props))))))))
  11357. ;; Get the standard properties, like :PROP:.
  11358. (when (memq which '(nil all standard))
  11359. ;; If we are looking after a specific property, delegate
  11360. ;; to `org-entry-get', which is faster. However, make an
  11361. ;; exception for "CATEGORY", since it can be also set
  11362. ;; through keywords (i.e. #+CATEGORY).
  11363. (if (and specific (not (equal specific "CATEGORY")))
  11364. (let ((value (org-entry-get beg specific nil t)))
  11365. (throw 'exit (and value (list (cons specific value)))))
  11366. (let ((range (org-get-property-block beg)))
  11367. (when range
  11368. (let ((end (cdr range)) seen-base)
  11369. (goto-char (car range))
  11370. ;; Unlike to `org--update-property-plist', we
  11371. ;; handle the case where base values is found
  11372. ;; after its extension. We also forbid standard
  11373. ;; properties to be named as special properties.
  11374. (while (re-search-forward org-property-re end t)
  11375. (let* ((key (upcase (match-string-no-properties 2)))
  11376. (extendp (string-match-p "\\+\\'" key))
  11377. (key-base (if extendp (substring key 0 -1) key))
  11378. (value (match-string-no-properties 3)))
  11379. (cond
  11380. ((member-ignore-case key-base org-special-properties))
  11381. (extendp
  11382. (setq props
  11383. (org--update-property-plist key value props)))
  11384. ((member key seen-base))
  11385. (t (push key seen-base)
  11386. (let ((p (assoc-string key props t)))
  11387. (if p (setcdr p (concat value " " (cdr p)))
  11388. (push (cons key value) props))))))))))))
  11389. (unless (assoc "CATEGORY" props)
  11390. (push (cons "CATEGORY" (org-get-category beg)) props)
  11391. (when (string= specific "CATEGORY") (throw 'exit props)))
  11392. ;; Return value.
  11393. props)))))
  11394. (defun org--property-local-values (property literal-nil)
  11395. "Return value for PROPERTY in current entry.
  11396. Value is a list whose car is the base value for PROPERTY and cdr
  11397. a list of accumulated values. Return nil if neither is found in
  11398. the entry. Also return nil when PROPERTY is set to \"nil\",
  11399. unless LITERAL-NIL is non-nil."
  11400. (let ((range (org-get-property-block)))
  11401. (when range
  11402. (goto-char (car range))
  11403. (let* ((case-fold-search t)
  11404. (end (cdr range))
  11405. (value
  11406. ;; Base value.
  11407. (save-excursion
  11408. (let ((v (and (re-search-forward
  11409. (org-re-property property nil t) end t)
  11410. (match-string-no-properties 3))))
  11411. (list (if literal-nil v (org-not-nil v)))))))
  11412. ;; Find additional values.
  11413. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11414. (while (re-search-forward property+ end t)
  11415. (push (match-string-no-properties 3) value)))
  11416. ;; Return final values.
  11417. (and (not (equal value '(nil))) (nreverse value))))))
  11418. (defun org--property-global-or-keyword-value (property literal-nil)
  11419. "Return value for PROPERTY as defined by global properties or by keyword.
  11420. Return value is a string. Return nil if property is not set
  11421. globally or by keyword. Also return nil when PROPERTY is set to
  11422. \"nil\", unless LITERAL-NIL is non-nil."
  11423. (let ((global
  11424. (cdr (or (assoc-string property org-keyword-properties t)
  11425. (assoc-string property org-global-properties t)
  11426. (assoc-string property org-global-properties-fixed t)))))
  11427. (if literal-nil global (org-not-nil global))))
  11428. (defun org-entry-get (pom property &optional inherit literal-nil)
  11429. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11430. If INHERIT is non-nil and the entry does not have the property,
  11431. then also check higher levels of the hierarchy. If INHERIT is
  11432. the symbol `selective', use inheritance only if the setting in
  11433. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11434. If the property is present but empty, the return value is the
  11435. empty string. If the property is not present at all, nil is
  11436. returned. In any other case, return the value as a string.
  11437. Search is case-insensitive.
  11438. If LITERAL-NIL is set, return the string value \"nil\" as
  11439. a string, do not interpret it as the list atom nil. This is used
  11440. for inheritance when a \"nil\" value can supersede a non-nil
  11441. value higher up the hierarchy."
  11442. (org-with-point-at pom
  11443. (cond
  11444. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11445. ;; We need a special property. Use `org-entry-properties' to
  11446. ;; retrieve it, but specify the wanted property.
  11447. (cdr (assoc-string property (org-entry-properties nil property))))
  11448. ((and inherit
  11449. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11450. (org-entry-get-with-inheritance property literal-nil))
  11451. (t
  11452. (let* ((local (org--property-local-values property literal-nil))
  11453. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11454. (if literal-nil value (org-not-nil value)))))))
  11455. (defun org-property-or-variable-value (var &optional inherit)
  11456. "Check if there is a property fixing the value of VAR.
  11457. If yes, return this value. If not, return the current value of the variable."
  11458. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11459. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11460. (read prop)
  11461. (symbol-value var))))
  11462. (defun org-entry-delete (pom property)
  11463. "Delete PROPERTY from entry at point-or-marker POM.
  11464. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11465. non-nil when a property was removed."
  11466. (org-with-point-at pom
  11467. (pcase (org-get-property-block)
  11468. (`(,begin . ,origin)
  11469. (let* ((end (copy-marker origin))
  11470. (re (org-re-property
  11471. (concat (regexp-quote property) "\\+?") t t)))
  11472. (goto-char begin)
  11473. (while (re-search-forward re end t)
  11474. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11475. ;; If drawer is empty, remove it altogether.
  11476. (when (= begin end)
  11477. (delete-region (line-beginning-position 0)
  11478. (line-beginning-position 2)))
  11479. ;; Return non-nil if some property was removed.
  11480. (prog1 (/= end origin) (set-marker end nil))))
  11481. (_ nil))))
  11482. ;; Multi-values properties are properties that contain multiple values
  11483. ;; These values are assumed to be single words, separated by whitespace.
  11484. (defun org-entry-add-to-multivalued-property (pom property value)
  11485. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11486. (let* ((old (org-entry-get pom property))
  11487. (values (and old (split-string old))))
  11488. (setq value (org-entry-protect-space value))
  11489. (unless (member value values)
  11490. (setq values (append values (list value)))
  11491. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11492. (defun org-entry-remove-from-multivalued-property (pom property value)
  11493. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11494. (let* ((old (org-entry-get pom property))
  11495. (values (and old (split-string old))))
  11496. (setq value (org-entry-protect-space value))
  11497. (when (member value values)
  11498. (setq values (delete value values))
  11499. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11500. (defun org-entry-member-in-multivalued-property (pom property value)
  11501. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11502. (let* ((old (org-entry-get pom property))
  11503. (values (and old (split-string old))))
  11504. (setq value (org-entry-protect-space value))
  11505. (member value values)))
  11506. (defun org-entry-get-multivalued-property (pom property)
  11507. "Return a list of values in a multivalued property."
  11508. (let* ((value (org-entry-get pom property))
  11509. (values (and value (split-string value))))
  11510. (mapcar #'org-entry-restore-space values)))
  11511. (defun org-entry-put-multivalued-property (pom property &rest values)
  11512. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11513. VALUES should be a list of strings. Spaces will be protected."
  11514. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11515. (let* ((value (org-entry-get pom property))
  11516. (values (and value (split-string value))))
  11517. (mapcar #'org-entry-restore-space values)))
  11518. (defun org-entry-protect-space (s)
  11519. "Protect spaces and newline in string S."
  11520. (while (string-match " " s)
  11521. (setq s (replace-match "%20" t t s)))
  11522. (while (string-match "\n" s)
  11523. (setq s (replace-match "%0A" t t s)))
  11524. s)
  11525. (defun org-entry-restore-space (s)
  11526. "Restore spaces and newline in string S."
  11527. (while (string-match "%20" s)
  11528. (setq s (replace-match " " t t s)))
  11529. (while (string-match "%0A" s)
  11530. (setq s (replace-match "\n" t t s)))
  11531. s)
  11532. (defvar org-entry-property-inherited-from (make-marker)
  11533. "Marker pointing to the entry from where a property was inherited.
  11534. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11535. location of the entry where the inheritance search matched. If there was
  11536. no match, the marker will point nowhere.
  11537. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11538. is set.")
  11539. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11540. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11541. The search will stop at the first ancestor which has the property defined.
  11542. If the value found is \"nil\", return nil to show that the property
  11543. should be considered as undefined (this is the meaning of nil here).
  11544. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11545. (move-marker org-entry-property-inherited-from nil)
  11546. (org-with-wide-buffer
  11547. (let (value)
  11548. (catch 'exit
  11549. (while t
  11550. (let ((v (org--property-local-values property literal-nil)))
  11551. (when v
  11552. (setq value
  11553. (concat (mapconcat #'identity (delq nil v) " ")
  11554. (and value " ")
  11555. value)))
  11556. (cond
  11557. ((car v)
  11558. (org-back-to-heading-or-point-min t)
  11559. (move-marker org-entry-property-inherited-from (point))
  11560. (throw 'exit nil))
  11561. ((org-up-heading-or-point-min))
  11562. (t
  11563. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11564. (cond ((not global))
  11565. (value (setq value (concat global " " value)))
  11566. (t (setq value global))))
  11567. (throw 'exit nil))))))
  11568. (if literal-nil value (org-not-nil value)))))
  11569. (defvar org-property-changed-functions nil
  11570. "Hook called when the value of a property has changed.
  11571. Each hook function should accept two arguments, the name of the property
  11572. and the new value.")
  11573. (defun org-entry-put (pom property value)
  11574. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11575. If the value is nil, it is converted to the empty string. If it
  11576. is not a string, an error is raised. Also raise an error on
  11577. invalid property names.
  11578. PROPERTY can be any regular property (see
  11579. `org-special-properties'). It can also be \"TODO\",
  11580. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11581. For the last two properties, VALUE may have any of the special
  11582. values \"earlier\" and \"later\". The function then increases or
  11583. decreases scheduled or deadline date by one day."
  11584. (cond ((null value) (setq value ""))
  11585. ((not (stringp value)) (error "Properties values should be strings"))
  11586. ((not (org--valid-property-p property))
  11587. (user-error "Invalid property name: \"%s\"" property)))
  11588. (org-with-point-at pom
  11589. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11590. (org-back-to-heading-or-point-min t)
  11591. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11592. (let ((beg (point)))
  11593. (cond
  11594. ((equal property "TODO")
  11595. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11596. ((not (member value org-todo-keywords-1))
  11597. (user-error "\"%s\" is not a valid TODO state" value)))
  11598. (org-todo value)
  11599. (org-align-tags))
  11600. ((equal property "PRIORITY")
  11601. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11602. (org-align-tags))
  11603. ((equal property "SCHEDULED")
  11604. (forward-line)
  11605. (if (and (looking-at-p org-planning-line-re)
  11606. (re-search-forward
  11607. org-scheduled-time-regexp (line-end-position) t))
  11608. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11609. ((string= value "later") (org-timestamp-change 1 'day))
  11610. ((string= value "") (org-schedule '(4)))
  11611. (t (org-schedule nil value)))
  11612. (if (member value '("earlier" "later" ""))
  11613. (call-interactively #'org-schedule)
  11614. (org-schedule nil value))))
  11615. ((equal property "DEADLINE")
  11616. (forward-line)
  11617. (if (and (looking-at-p org-planning-line-re)
  11618. (re-search-forward
  11619. org-deadline-time-regexp (line-end-position) t))
  11620. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11621. ((string= value "later") (org-timestamp-change 1 'day))
  11622. ((string= value "") (org-deadline '(4)))
  11623. (t (org-deadline nil value)))
  11624. (if (member value '("earlier" "later" ""))
  11625. (call-interactively #'org-deadline)
  11626. (org-deadline nil value))))
  11627. ((member property org-special-properties)
  11628. (error "The %s property cannot be set with `org-entry-put'" property))
  11629. (t
  11630. (let* ((range (org-get-property-block beg 'force))
  11631. (end (cdr range))
  11632. (case-fold-search t))
  11633. (goto-char (car range))
  11634. (if (re-search-forward (org-re-property property nil t) end t)
  11635. (progn (delete-region (match-beginning 0) (match-end 0))
  11636. (goto-char (match-beginning 0)))
  11637. (goto-char end)
  11638. (insert "\n")
  11639. (backward-char))
  11640. (insert ":" property ":")
  11641. (when value (insert " " value))
  11642. (org-indent-line)))))
  11643. (run-hook-with-args 'org-property-changed-functions property value)))
  11644. (defun org-buffer-property-keys (&optional specials defaults columns)
  11645. "Get all property keys in the current buffer.
  11646. When SPECIALS is non-nil, also list the special properties that
  11647. reflect things like tags and TODO state.
  11648. When DEFAULTS is non-nil, also include properties that has
  11649. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11650. DESCRIPTION, LOCATION, and LOGGING and others.
  11651. When COLUMNS in non-nil, also include property names given in
  11652. COLUMN formats in the current buffer."
  11653. (let ((case-fold-search t)
  11654. (props (append
  11655. (and specials org-special-properties)
  11656. (and defaults (cons org-effort-property org-default-properties))
  11657. nil)))
  11658. (org-with-wide-buffer
  11659. (goto-char (point-min))
  11660. (while (re-search-forward org-property-start-re nil t)
  11661. (catch :skip
  11662. (let ((range (org-get-property-block)))
  11663. (unless range (throw :skip nil))
  11664. (goto-char (car range))
  11665. (let ((begin (car range))
  11666. (end (cdr range)))
  11667. ;; Make sure that found property block is not located
  11668. ;; before current point, as it would generate an infloop.
  11669. ;; It can happen, for example, in the following
  11670. ;; situation:
  11671. ;;
  11672. ;; * Headline
  11673. ;; :PROPERTIES:
  11674. ;; ...
  11675. ;; :END:
  11676. ;; *************** Inlinetask
  11677. ;; #+BEGIN_EXAMPLE
  11678. ;; :PROPERTIES:
  11679. ;; #+END_EXAMPLE
  11680. ;;
  11681. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11682. (while (< (point) end)
  11683. (let ((p (progn (looking-at org-property-re)
  11684. (match-string-no-properties 2))))
  11685. ;; Only add true property name, not extension symbol.
  11686. (push (if (not (string-match-p "\\+\\'" p)) p
  11687. (substring p 0 -1))
  11688. props))
  11689. (forward-line))))
  11690. (outline-next-heading)))
  11691. (when columns
  11692. (goto-char (point-min))
  11693. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11694. (let ((element (org-element-at-point)))
  11695. (when (memq (org-element-type element) '(keyword node-property))
  11696. (let ((value (org-element-property :value element))
  11697. (start 0))
  11698. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11699. \\(?:{[^}]+}\\)?"
  11700. value start)
  11701. (setq start (match-end 0))
  11702. (let ((p (match-string-no-properties 1 value)))
  11703. (unless (member-ignore-case p org-special-properties)
  11704. (push p props))))))))))
  11705. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  11706. (defun org-property-values (key)
  11707. "List all non-nil values of property KEY in current buffer."
  11708. (org-with-wide-buffer
  11709. (goto-char (point-min))
  11710. (let ((case-fold-search t)
  11711. (re (org-re-property key))
  11712. values)
  11713. (while (re-search-forward re nil t)
  11714. (push (org-entry-get (point) key) values))
  11715. (delete-dups values))))
  11716. (defun org-insert-property-drawer ()
  11717. "Insert a property drawer into the current entry.
  11718. Do nothing if the drawer already exists. The newly created
  11719. drawer is immediately hidden."
  11720. (org-with-wide-buffer
  11721. ;; Set point to the position where the drawer should be inserted.
  11722. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11723. (org-back-to-heading-or-point-min t)
  11724. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11725. (if (org-before-first-heading-p)
  11726. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11727. (progn
  11728. (forward-line)
  11729. (when (looking-at-p org-planning-line-re) (forward-line))))
  11730. (unless (looking-at-p org-property-drawer-re)
  11731. ;; Make sure we start editing a line from current entry, not from
  11732. ;; next one. It prevents extending text properties or overlays
  11733. ;; belonging to the latter.
  11734. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11735. (let ((begin (if (bobp) (point) (1+ (point))))
  11736. (inhibit-read-only t))
  11737. (unless (bobp) (insert "\n"))
  11738. (insert ":PROPERTIES:\n:END:")
  11739. (org-flag-drawer t nil (line-end-position 0) (point))
  11740. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11741. (org-indent-region begin (point))))))
  11742. (defun org-insert-drawer (&optional arg drawer)
  11743. "Insert a drawer at point.
  11744. When optional argument ARG is non-nil, insert a property drawer.
  11745. Optional argument DRAWER, when non-nil, is a string representing
  11746. drawer's name. Otherwise, the user is prompted for a name.
  11747. If a region is active, insert the drawer around that region
  11748. instead.
  11749. Point is left between drawer's boundaries."
  11750. (interactive "P")
  11751. (let* ((drawer (if arg "PROPERTIES"
  11752. (or drawer (read-from-minibuffer "Drawer: ")))))
  11753. (cond
  11754. ;; With C-u, fall back on `org-insert-property-drawer'
  11755. (arg (org-insert-property-drawer))
  11756. ;; Check validity of suggested drawer's name.
  11757. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11758. (user-error "Invalid drawer name"))
  11759. ;; With an active region, insert a drawer at point.
  11760. ((not (org-region-active-p))
  11761. (progn
  11762. (unless (bolp) (insert "\n"))
  11763. (insert (format ":%s:\n\n:END:\n" drawer))
  11764. (forward-line -2)))
  11765. ;; Otherwise, insert the drawer at point
  11766. (t
  11767. (let ((rbeg (region-beginning))
  11768. (rend (copy-marker (region-end))))
  11769. (unwind-protect
  11770. (progn
  11771. (goto-char rbeg)
  11772. (beginning-of-line)
  11773. (when (save-excursion
  11774. (re-search-forward org-outline-regexp-bol rend t))
  11775. (user-error "Drawers cannot contain headlines"))
  11776. ;; Position point at the beginning of the first
  11777. ;; non-blank line in region. Insert drawer's opening
  11778. ;; there, then indent it.
  11779. (org-skip-whitespace)
  11780. (beginning-of-line)
  11781. (insert ":" drawer ":\n")
  11782. (forward-line -1)
  11783. (indent-for-tab-command)
  11784. ;; Move point to the beginning of the first blank line
  11785. ;; after the last non-blank line in region. Insert
  11786. ;; drawer's closing, then indent it.
  11787. (goto-char rend)
  11788. (skip-chars-backward " \r\t\n")
  11789. (insert "\n:END:")
  11790. (deactivate-mark t)
  11791. (indent-for-tab-command)
  11792. (unless (eolp) (insert "\n")))
  11793. ;; Clear marker, whatever the outcome of insertion is.
  11794. (set-marker rend nil)))))))
  11795. (defvar org-property-set-functions-alist nil
  11796. "Property set function alist.
  11797. Each entry should have the following format:
  11798. (PROPERTY . READ-FUNCTION)
  11799. The read function will be called with the same argument as
  11800. `org-completing-read'.")
  11801. (defun org-set-property-function (property)
  11802. "Get the function that should be used to set PROPERTY.
  11803. This is computed according to `org-property-set-functions-alist'."
  11804. (or (cdr (assoc property org-property-set-functions-alist))
  11805. 'org-completing-read))
  11806. (defun org-read-property-value (property &optional pom)
  11807. "Read value for PROPERTY, as a string.
  11808. When optional argument POM is non-nil, completion uses additional
  11809. information, i.e., allowed or existing values at point or marker
  11810. POM."
  11811. (let* ((completion-ignore-case t)
  11812. (allowed
  11813. (or (org-property-get-allowed-values nil property 'table)
  11814. (and pom (org-property-get-allowed-values pom property 'table))))
  11815. (current (org-entry-get nil property))
  11816. (prompt (format "%s value%s: "
  11817. property
  11818. (if (org-string-nw-p current)
  11819. (format " [%s]" current)
  11820. "")))
  11821. (set-function (org-set-property-function property)))
  11822. (org-trim
  11823. (if allowed
  11824. (funcall set-function
  11825. prompt allowed nil
  11826. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  11827. (let ((all (mapcar #'list
  11828. (append (org-property-values property)
  11829. (and pom
  11830. (org-with-point-at pom
  11831. (org-property-values property)))))))
  11832. (funcall set-function prompt all nil nil "" nil current))))))
  11833. (defvar org-last-set-property nil)
  11834. (defvar org-last-set-property-value nil)
  11835. (defun org-read-property-name ()
  11836. "Read a property name."
  11837. (let ((completion-ignore-case t)
  11838. (default-prop (or (and (org-at-property-p)
  11839. (match-string-no-properties 2))
  11840. org-last-set-property)))
  11841. (org-completing-read
  11842. (concat "Property"
  11843. (if default-prop (concat " [" default-prop "]") "")
  11844. ": ")
  11845. (mapcar #'list (org-buffer-property-keys nil t t))
  11846. nil nil nil nil default-prop)))
  11847. (defun org-set-property-and-value (use-last)
  11848. "Allow to set [PROPERTY]: [value] direction from prompt.
  11849. When use-default, don't even ask, just use the last
  11850. \"[PROPERTY]: [value]\" string from the history."
  11851. (interactive "P")
  11852. (let* ((completion-ignore-case t)
  11853. (pv (or (and use-last org-last-set-property-value)
  11854. (org-completing-read
  11855. "Enter a \"[Property]: [value]\" pair: "
  11856. nil nil nil nil nil
  11857. org-last-set-property-value)))
  11858. prop val)
  11859. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11860. (setq prop (match-string 1 pv)
  11861. val (match-string 2 pv))
  11862. (org-set-property prop val))))
  11863. (defun org-set-property (property value)
  11864. "In the current entry, set PROPERTY to VALUE.
  11865. When called interactively, this will prompt for a property name, offering
  11866. completion on existing and default properties. And then it will prompt
  11867. for a value, offering completion either on allowed values (via an inherited
  11868. xxx_ALL property) or on existing values in other instances of this property
  11869. in the current file.
  11870. Throw an error when trying to set a property with an invalid name."
  11871. (interactive (list nil nil))
  11872. (let ((property (or property (org-read-property-name))))
  11873. ;; `org-entry-put' also makes the following check, but this one
  11874. ;; avoids polluting `org-last-set-property' and
  11875. ;; `org-last-set-property-value' needlessly.
  11876. (unless (org--valid-property-p property)
  11877. (user-error "Invalid property name: \"%s\"" property))
  11878. (let ((value (or value (org-read-property-value property)))
  11879. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11880. (setq org-last-set-property property)
  11881. (setq org-last-set-property-value (concat property ": " value))
  11882. ;; Possibly postprocess the inserted value:
  11883. (when fn (setq value (funcall fn value)))
  11884. (unless (equal (org-entry-get nil property) value)
  11885. (org-entry-put nil property value)))))
  11886. (defun org-find-property (property &optional value)
  11887. "Find first entry in buffer that sets PROPERTY.
  11888. When optional argument VALUE is non-nil, only consider an entry
  11889. if it contains PROPERTY set to this value. If PROPERTY should be
  11890. explicitly set to nil, use string \"nil\" for VALUE.
  11891. Return position where the entry begins, or nil if there is no
  11892. such entry. If narrowing is in effect, only search the visible
  11893. part of the buffer."
  11894. (save-excursion
  11895. (goto-char (point-min))
  11896. (let ((case-fold-search t)
  11897. (re (org-re-property property nil (not value) value)))
  11898. (catch 'exit
  11899. (while (re-search-forward re nil t)
  11900. (when (if value (org-at-property-p)
  11901. (org-entry-get (point) property nil t))
  11902. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  11903. (defun org-delete-property (property)
  11904. "In the current entry, delete PROPERTY."
  11905. (interactive
  11906. (let* ((completion-ignore-case t)
  11907. (cat (org-entry-get (point) "CATEGORY"))
  11908. (props0 (org-entry-properties nil 'standard))
  11909. (props (if cat props0
  11910. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11911. (prop (if (< 1 (length props))
  11912. (completing-read "Property: " props nil t)
  11913. (caar props))))
  11914. (list prop)))
  11915. (if (not property)
  11916. (message "No property to delete in this entry")
  11917. (org-entry-delete nil property)
  11918. (message "Property \"%s\" deleted" property)))
  11919. (defun org-delete-property-globally (property)
  11920. "Remove PROPERTY globally, from all entries.
  11921. This function ignores narrowing, if any."
  11922. (interactive
  11923. (let* ((completion-ignore-case t)
  11924. (prop (completing-read
  11925. "Globally remove property: "
  11926. (mapcar #'list (org-buffer-property-keys)))))
  11927. (list prop)))
  11928. (org-with-wide-buffer
  11929. (goto-char (point-min))
  11930. (let ((count 0)
  11931. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11932. (while (re-search-forward re nil t)
  11933. (when (org-entry-delete (point) property) (cl-incf count)))
  11934. (message "Property \"%s\" removed from %d entries" property count))))
  11935. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11936. (defun org-compute-property-at-point ()
  11937. "Compute the property at point.
  11938. This looks for an enclosing column format, extracts the operator and
  11939. then applies it to the property in the column format's scope."
  11940. (interactive)
  11941. (unless (org-at-property-p)
  11942. (user-error "Not at a property"))
  11943. (let ((prop (match-string-no-properties 2)))
  11944. (org-columns-get-format-and-top-level)
  11945. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11946. (user-error "No operator defined for property %s" prop))
  11947. (org-columns-compute prop)))
  11948. (defvar org-property-allowed-value-functions nil
  11949. "Hook for functions supplying allowed values for a specific property.
  11950. The functions must take a single argument, the name of the property, and
  11951. return a flat list of allowed values. If \":ETC\" is one of
  11952. the values, this means that these values are intended as defaults for
  11953. completion, but that other values should be allowed too.
  11954. The functions must return nil if they are not responsible for this
  11955. property.")
  11956. (defun org-property-get-allowed-values (pom property &optional table)
  11957. "Get allowed values for the property PROPERTY.
  11958. When TABLE is non-nil, return an alist that can directly be used for
  11959. completion."
  11960. (let (vals)
  11961. (cond
  11962. ((equal property "TODO")
  11963. (setq vals (org-with-point-at pom
  11964. (append org-todo-keywords-1 '("")))))
  11965. ((equal property "PRIORITY")
  11966. (let ((n org-priority-lowest))
  11967. (while (>= n org-priority-highest)
  11968. (push (char-to-string n) vals)
  11969. (setq n (1- n)))))
  11970. ((equal property "CATEGORY"))
  11971. ((member property org-special-properties))
  11972. ((setq vals (run-hook-with-args-until-success
  11973. 'org-property-allowed-value-functions property)))
  11974. (t
  11975. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11976. (when (and vals (string-match "\\S-" vals))
  11977. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11978. (setq vals (mapcar (lambda (x)
  11979. (cond ((stringp x) x)
  11980. ((numberp x) (number-to-string x))
  11981. ((symbolp x) (symbol-name x))
  11982. (t "???")))
  11983. vals)))))
  11984. (when (member ":ETC" vals)
  11985. (setq vals (remove ":ETC" vals))
  11986. (org-add-props (car vals) '(org-unrestricted t)))
  11987. (if table (mapcar 'list vals) vals)))
  11988. (defun org-property-previous-allowed-value (&optional _previous)
  11989. "Switch to the next allowed value for this property."
  11990. (interactive)
  11991. (org-property-next-allowed-value t))
  11992. (defun org-property-next-allowed-value (&optional previous)
  11993. "Switch to the next allowed value for this property."
  11994. (interactive)
  11995. (unless (org-at-property-p)
  11996. (user-error "Not at a property"))
  11997. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11998. (key (match-string 2))
  11999. (value (match-string 3))
  12000. (allowed (or (org-property-get-allowed-values (point) key)
  12001. (and (member value '("[ ]" "[-]" "[X]"))
  12002. '("[ ]" "[X]"))))
  12003. (heading (save-match-data (nth 4 (org-heading-components))))
  12004. nval)
  12005. (unless allowed
  12006. (user-error "Allowed values for this property have not been defined"))
  12007. (when previous (setq allowed (reverse allowed)))
  12008. (when (member value allowed)
  12009. (setq nval (car (cdr (member value allowed)))))
  12010. (setq nval (or nval (car allowed)))
  12011. (when (equal nval value)
  12012. (user-error "Only one allowed value for this property"))
  12013. (org-at-property-p)
  12014. (replace-match (concat " :" key ": " nval) t t)
  12015. (org-indent-line)
  12016. (beginning-of-line 1)
  12017. (skip-chars-forward " \t")
  12018. (when (equal prop org-effort-property)
  12019. (org-refresh-property
  12020. '((effort . identity)
  12021. (effort-minutes . org-duration-to-minutes))
  12022. nval)
  12023. (when (string= org-clock-current-task heading)
  12024. (setq org-clock-effort nval)
  12025. (org-clock-update-mode-line)))
  12026. (run-hook-with-args 'org-property-changed-functions key nval)))
  12027. (defun org-find-olp (path &optional this-buffer)
  12028. "Return a marker pointing to the entry at outline path OLP.
  12029. If anything goes wrong, throw an error.
  12030. You can wrap this call to catch the error like this:
  12031. (condition-case msg
  12032. (org-mobile-locate-entry (match-string 4))
  12033. (error (nth 1 msg)))
  12034. The return value will then be either a string with the error message,
  12035. or a marker if everything is OK.
  12036. If THIS-BUFFER is set, the outline path does not contain a file,
  12037. only headings."
  12038. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12039. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12040. (level 1)
  12041. (lmin 1)
  12042. (lmax 1)
  12043. end found flevel)
  12044. (unless buffer (error "File not found :%s" file))
  12045. (with-current-buffer buffer
  12046. (unless (derived-mode-p 'org-mode)
  12047. (error "Buffer %s needs to be in Org mode" buffer))
  12048. (org-with-wide-buffer
  12049. (goto-char (point-min))
  12050. (dolist (heading path)
  12051. (let ((re (format org-complex-heading-regexp-format
  12052. (regexp-quote heading)))
  12053. (cnt 0))
  12054. (while (re-search-forward re end t)
  12055. (setq level (- (match-end 1) (match-beginning 1)))
  12056. (when (and (>= level lmin) (<= level lmax))
  12057. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12058. (when (= cnt 0)
  12059. (error "Heading not found on level %d: %s" lmax heading))
  12060. (when (> cnt 1)
  12061. (error "Heading not unique on level %d: %s" lmax heading))
  12062. (goto-char found)
  12063. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12064. (setq end (save-excursion (org-end-of-subtree t t)))))
  12065. (when (org-at-heading-p)
  12066. (point-marker))))))
  12067. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12068. "Find node HEADING in BUFFER.
  12069. Return a marker to the heading if it was found, or nil if not.
  12070. If POS-ONLY is set, return just the position instead of a marker.
  12071. The heading text must match exact, but it may have a TODO keyword,
  12072. a priority cookie and tags in the standard locations."
  12073. (with-current-buffer (or buffer (current-buffer))
  12074. (org-with-wide-buffer
  12075. (goto-char (point-min))
  12076. (let (case-fold-search)
  12077. (when (re-search-forward
  12078. (format org-complex-heading-regexp-format
  12079. (regexp-quote heading)) nil t)
  12080. (if pos-only
  12081. (match-beginning 0)
  12082. (move-marker (make-marker) (match-beginning 0))))))))
  12083. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12084. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12085. When the target headline is found, return a marker to this location."
  12086. (let ((files (directory-files (or dir default-directory)
  12087. t "\\`[^.#].*\\.org\\'"))
  12088. visiting m buffer)
  12089. (catch 'found
  12090. (dolist (file files)
  12091. (message "trying %s" file)
  12092. (setq visiting (org-find-base-buffer-visiting file))
  12093. (setq buffer (or visiting (find-file-noselect file)))
  12094. (setq m (org-find-exact-headline-in-buffer
  12095. heading buffer))
  12096. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12097. (and m (throw 'found m))))))
  12098. (defun org-find-entry-with-id (ident)
  12099. "Locate the entry that contains the ID property with exact value IDENT.
  12100. IDENT can be a string, a symbol or a number, this function will search for
  12101. the string representation of it.
  12102. Return the position where this entry starts, or nil if there is no such entry."
  12103. (interactive "sID: ")
  12104. (let ((id (cond
  12105. ((stringp ident) ident)
  12106. ((symbolp ident) (symbol-name ident))
  12107. ((numberp ident) (number-to-string ident))
  12108. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12109. (org-with-wide-buffer (org-find-property "ID" id))))
  12110. ;;;; Timestamps
  12111. (defvar org-last-changed-timestamp nil)
  12112. (defvar org-last-inserted-timestamp nil
  12113. "The last time stamp inserted with `org-insert-time-stamp'.")
  12114. (defun org-time-stamp (arg &optional inactive)
  12115. "Prompt for a date/time and insert a time stamp.
  12116. If the user specifies a time like HH:MM or if this command is
  12117. called with at least one prefix argument, the time stamp contains
  12118. the date and the time. Otherwise, only the date is included.
  12119. All parts of a date not specified by the user are filled in from
  12120. the timestamp at point, if any, or the current date/time
  12121. otherwise.
  12122. If there is already a timestamp at the cursor, it is replaced.
  12123. With two universal prefix arguments, insert an active timestamp
  12124. with the current time without prompting the user.
  12125. When called from lisp, the timestamp is inactive if INACTIVE is
  12126. non-nil."
  12127. (interactive "P")
  12128. (let* ((ts (cond
  12129. ((org-at-date-range-p t)
  12130. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12131. ((org-at-timestamp-p 'lax) (match-string 0))))
  12132. ;; Default time is either the timestamp at point or today.
  12133. ;; When entering a range, only the range start is considered.
  12134. (default-time (and ts (org-time-string-to-time ts)))
  12135. (default-input (and ts (org-get-compact-tod ts)))
  12136. (repeater (and ts
  12137. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12138. (match-string 0 ts)))
  12139. org-time-was-given
  12140. org-end-time-was-given
  12141. (time
  12142. (if (equal arg '(16)) (current-time)
  12143. ;; Preserve `this-command' and `last-command'.
  12144. (let ((this-command this-command)
  12145. (last-command last-command))
  12146. (org-read-date
  12147. arg 'totime nil nil default-time default-input
  12148. inactive)))))
  12149. (cond
  12150. ((and ts
  12151. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12152. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12153. (insert "--")
  12154. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12155. (ts
  12156. ;; Make sure we're on a timestamp. When in the middle of a date
  12157. ;; range, move arbitrarily to range end.
  12158. (unless (org-at-timestamp-p 'lax)
  12159. (skip-chars-forward "-")
  12160. (org-at-timestamp-p 'lax))
  12161. (replace-match "")
  12162. (setq org-last-changed-timestamp
  12163. (org-insert-time-stamp
  12164. time (or org-time-was-given arg)
  12165. inactive nil nil (list org-end-time-was-given)))
  12166. (when repeater
  12167. (backward-char)
  12168. (insert " " repeater)
  12169. (setq org-last-changed-timestamp
  12170. (concat (substring org-last-inserted-timestamp 0 -1)
  12171. " " repeater ">")))
  12172. (message "Timestamp updated"))
  12173. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12174. (t (org-insert-time-stamp
  12175. time (or org-time-was-given arg) inactive nil nil
  12176. (list org-end-time-was-given))))))
  12177. ;; FIXME: can we use this for something else, like computing time differences?
  12178. (defun org-get-compact-tod (s)
  12179. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12180. (let* ((t1 (match-string 1 s))
  12181. (h1 (string-to-number (match-string 2 s)))
  12182. (m1 (string-to-number (match-string 3 s)))
  12183. (t2 (and (match-end 4) (match-string 5 s)))
  12184. (h2 (and t2 (string-to-number (match-string 6 s))))
  12185. (m2 (and t2 (string-to-number (match-string 7 s))))
  12186. dh dm)
  12187. (if (not t2)
  12188. t1
  12189. (setq dh (- h2 h1) dm (- m2 m1))
  12190. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12191. (concat t1 "+" (number-to-string dh)
  12192. (and (/= 0 dm) (format ":%02d" dm)))))))
  12193. (defun org-time-stamp-inactive (&optional arg)
  12194. "Insert an inactive time stamp.
  12195. An inactive time stamp is enclosed in square brackets instead of angle
  12196. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12197. does not link to the calendar and cannot be changed with the S-cursor keys.
  12198. So these are more for recording a certain time/date.
  12199. If the user specifies a time like HH:MM or if this command is called with
  12200. at least one prefix argument, the time stamp contains the date and the time.
  12201. Otherwise, only the date is included.
  12202. When called with two universal prefix arguments, insert an active time stamp
  12203. with the current time without prompting the user."
  12204. (interactive "P")
  12205. (org-time-stamp arg 'inactive))
  12206. (defvar org-date-ovl (make-overlay 1 1))
  12207. (overlay-put org-date-ovl 'face 'org-date-selected)
  12208. (delete-overlay org-date-ovl)
  12209. (defvar org-ans1) ; dynamically scoped parameter
  12210. (defvar org-ans2) ; dynamically scoped parameter
  12211. (defvar org-plain-time-of-day-regexp) ; defined below
  12212. (defvar org-overriding-default-time nil) ; dynamically scoped
  12213. (defvar org-read-date-overlay nil)
  12214. (defvar org-read-date-history nil)
  12215. (defvar org-read-date-final-answer nil)
  12216. (defvar org-read-date-analyze-futurep nil)
  12217. (defvar org-read-date-analyze-forced-year nil)
  12218. (defvar org-read-date-inactive)
  12219. (defvar org-def)
  12220. (defvar org-defdecode)
  12221. (defvar org-with-time)
  12222. (defvar calendar-setup) ; Dynamically scoped.
  12223. (defun org-read-date (&optional with-time to-time from-string prompt
  12224. default-time default-input inactive)
  12225. "Read a date, possibly a time, and make things smooth for the user.
  12226. The prompt will suggest to enter an ISO date, but you can also enter anything
  12227. which will at least partially be understood by `parse-time-string'.
  12228. Unrecognized parts of the date will default to the current day, month, year,
  12229. hour and minute. If this command is called to replace a timestamp at point,
  12230. or to enter the second timestamp of a range, the default time is taken
  12231. from the existing stamp. Furthermore, the command prefers the future,
  12232. so if you are giving a date where the year is not given, and the day-month
  12233. combination is already past in the current year, it will assume you
  12234. mean next year. For details, see the manual. A few examples:
  12235. 3-2-5 --> 2003-02-05
  12236. feb 15 --> currentyear-02-15
  12237. 2/15 --> currentyear-02-15
  12238. sep 12 9 --> 2009-09-12
  12239. 12:45 --> today 12:45
  12240. 22 sept 0:34 --> currentyear-09-22 0:34
  12241. 12 --> currentyear-currentmonth-12
  12242. Fri --> nearest Friday after today
  12243. -Tue --> last Tuesday
  12244. etc.
  12245. Furthermore you can specify a relative date by giving, as the *first* thing
  12246. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12247. change in days weeks, months, years.
  12248. With a single plus or minus, the date is relative to today. With a double
  12249. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12250. +4d --> four days from today
  12251. +4 --> same as above
  12252. +2w --> two weeks from today
  12253. ++5 --> five days from default date
  12254. The function understands only English month and weekday abbreviations.
  12255. While prompting, a calendar is popped up - you can also select the
  12256. date with the mouse (button 1). The calendar shows a period of three
  12257. months. To scroll it to other months, use the keys `>' and `<'.
  12258. If you don't like the calendar, turn it off with
  12259. (setq org-read-date-popup-calendar nil)
  12260. With optional argument TO-TIME, the date will immediately be converted
  12261. to an internal time.
  12262. With an optional argument WITH-TIME, the prompt will suggest to
  12263. also insert a time. Note that when WITH-TIME is not set, you can
  12264. still enter a time, and this function will inform the calling routine
  12265. about this change. The calling routine may then choose to change the
  12266. format used to insert the time stamp into the buffer to include the time.
  12267. With optional argument FROM-STRING, read from this string instead from
  12268. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12269. the time/date that is used for everything that is not specified by the
  12270. user."
  12271. (require 'parse-time)
  12272. (let* ((org-with-time with-time)
  12273. (org-time-stamp-rounding-minutes
  12274. (if (equal org-with-time '(16))
  12275. '(0 0)
  12276. org-time-stamp-rounding-minutes))
  12277. (ct (org-current-time))
  12278. (org-def (or org-overriding-default-time default-time ct))
  12279. (org-defdecode (decode-time org-def))
  12280. (cur-frame (selected-frame))
  12281. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12282. (calendar-setup
  12283. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12284. (calendar-move-hook nil)
  12285. (calendar-view-diary-initially-flag nil)
  12286. (calendar-view-holidays-initially-flag nil)
  12287. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12288. ;; Rationalize `org-def' and `org-defdecode', if required.
  12289. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12290. (setf (nth 2 org-defdecode) -1)
  12291. (setf (nth 1 org-defdecode) 59)
  12292. (setq org-def (apply #'encode-time org-defdecode))
  12293. (setq org-defdecode (decode-time org-def)))
  12294. (let* ((timestr (format-time-string
  12295. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12296. org-def))
  12297. (prompt (concat (if prompt (concat prompt " ") "")
  12298. (format "Date+time [%s]: " timestr))))
  12299. (cond
  12300. (from-string (setq ans from-string))
  12301. (org-read-date-popup-calendar
  12302. (save-excursion
  12303. (save-window-excursion
  12304. (calendar)
  12305. (when (eq calendar-setup 'calendar-only)
  12306. (setq cal-frame
  12307. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12308. (select-frame cal-frame))
  12309. (org-eval-in-calendar '(setq cursor-type nil) t)
  12310. (unwind-protect
  12311. (progn
  12312. (calendar-forward-day (- (time-to-days org-def)
  12313. (calendar-absolute-from-gregorian
  12314. (calendar-current-date))))
  12315. (org-eval-in-calendar nil t)
  12316. (let* ((old-map (current-local-map))
  12317. (map (copy-keymap calendar-mode-map))
  12318. (minibuffer-local-map
  12319. (copy-keymap org-read-date-minibuffer-local-map)))
  12320. (org-defkey map (kbd "RET") 'org-calendar-select)
  12321. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12322. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12323. (unwind-protect
  12324. (progn
  12325. (use-local-map map)
  12326. (setq org-read-date-inactive inactive)
  12327. (add-hook 'post-command-hook 'org-read-date-display)
  12328. (setq org-ans0
  12329. (read-string prompt
  12330. default-input
  12331. 'org-read-date-history
  12332. nil))
  12333. ;; org-ans0: from prompt
  12334. ;; org-ans1: from mouse click
  12335. ;; org-ans2: from calendar motion
  12336. (setq ans
  12337. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12338. (remove-hook 'post-command-hook 'org-read-date-display)
  12339. (use-local-map old-map)
  12340. (when org-read-date-overlay
  12341. (delete-overlay org-read-date-overlay)
  12342. (setq org-read-date-overlay nil)))))
  12343. (bury-buffer "*Calendar*")
  12344. (when cal-frame
  12345. (delete-frame cal-frame)
  12346. (select-frame-set-input-focus cur-frame))))))
  12347. (t ; Naked prompt only
  12348. (unwind-protect
  12349. (setq ans (read-string prompt default-input
  12350. 'org-read-date-history timestr))
  12351. (when org-read-date-overlay
  12352. (delete-overlay org-read-date-overlay)
  12353. (setq org-read-date-overlay nil))))))
  12354. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12355. (when org-read-date-analyze-forced-year
  12356. (message "Year was forced into %s"
  12357. (if org-read-date-force-compatible-dates
  12358. "compatible range (1970-2037)"
  12359. "range representable on this machine"))
  12360. (ding))
  12361. (setq final (apply #'encode-time final))
  12362. (setq org-read-date-final-answer ans)
  12363. (if to-time
  12364. final
  12365. ;; This round-trip gets rid of 34th of August and stuff like that....
  12366. (setq final (decode-time final))
  12367. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12368. (format "%04d-%02d-%02d %02d:%02d"
  12369. (nth 5 final) (nth 4 final) (nth 3 final)
  12370. (nth 2 final) (nth 1 final))
  12371. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12372. (defun org-read-date-display ()
  12373. "Display the current date prompt interpretation in the minibuffer."
  12374. (when org-read-date-display-live
  12375. (when org-read-date-overlay
  12376. (delete-overlay org-read-date-overlay))
  12377. (when (minibufferp (current-buffer))
  12378. (save-excursion
  12379. (end-of-line 1)
  12380. (while (not (equal (buffer-substring
  12381. (max (point-min) (- (point) 4)) (point))
  12382. " "))
  12383. (insert " ")))
  12384. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12385. " " (or org-ans1 org-ans2)))
  12386. (org-end-time-was-given nil)
  12387. (f (org-read-date-analyze ans org-def org-defdecode))
  12388. (fmts (if org-display-custom-times
  12389. org-time-stamp-custom-formats
  12390. org-time-stamp-formats))
  12391. (fmt (if (or org-with-time
  12392. (and (boundp 'org-time-was-given) org-time-was-given))
  12393. (cdr fmts)
  12394. (car fmts)))
  12395. (txt (format-time-string fmt (apply #'encode-time f)))
  12396. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12397. (txt (concat "=> " txt)))
  12398. (when (and org-end-time-was-given
  12399. (string-match org-plain-time-of-day-regexp txt))
  12400. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12401. org-end-time-was-given
  12402. (substring txt (match-end 0)))))
  12403. (when org-read-date-analyze-futurep
  12404. (setq txt (concat txt " (=>F)")))
  12405. (setq org-read-date-overlay
  12406. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12407. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12408. (defun org-read-date-analyze (ans def defdecode)
  12409. "Analyze the combined answer of the date prompt."
  12410. ;; FIXME: cleanup and comment
  12411. (let ((org-def def)
  12412. (org-defdecode defdecode)
  12413. (nowdecode (decode-time))
  12414. delta deltan deltaw deltadef year month day
  12415. hour minute second wday pm h2 m2 tl wday1
  12416. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12417. (setq org-read-date-analyze-futurep nil
  12418. org-read-date-analyze-forced-year nil)
  12419. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12420. (setq ans "+0"))
  12421. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12422. (setq ans (replace-match "" t t ans)
  12423. deltan (car delta)
  12424. deltaw (nth 1 delta)
  12425. deltadef (nth 2 delta)))
  12426. ;; Check if there is an iso week date in there. If yes, store the
  12427. ;; info and postpone interpreting it until the rest of the parsing
  12428. ;; is done.
  12429. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12430. (setq iso-year (when (match-end 1)
  12431. (org-small-year-to-year
  12432. (string-to-number (match-string 1 ans))))
  12433. iso-weekday (when (match-end 3)
  12434. (string-to-number (match-string 3 ans)))
  12435. iso-week (string-to-number (match-string 2 ans)))
  12436. (setq ans (replace-match "" t t ans)))
  12437. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12438. (when (string-match
  12439. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12440. (setq year (if (match-end 2)
  12441. (string-to-number (match-string 2 ans))
  12442. (progn (setq kill-year t)
  12443. (string-to-number (format-time-string "%Y"))))
  12444. month (string-to-number (match-string 3 ans))
  12445. day (string-to-number (match-string 4 ans)))
  12446. (setq year (org-small-year-to-year year))
  12447. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12448. t nil ans)))
  12449. ;; Help matching dotted european dates
  12450. (when (string-match
  12451. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12452. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12453. (setq kill-year t)
  12454. (string-to-number (format-time-string "%Y")))
  12455. day (string-to-number (match-string 1 ans))
  12456. month (string-to-number (match-string 2 ans))
  12457. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12458. t nil ans)))
  12459. ;; Help matching american dates, like 5/30 or 5/30/7
  12460. (when (string-match
  12461. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12462. (setq year (if (match-end 4)
  12463. (string-to-number (match-string 4 ans))
  12464. (progn (setq kill-year t)
  12465. (string-to-number (format-time-string "%Y"))))
  12466. month (string-to-number (match-string 1 ans))
  12467. day (string-to-number (match-string 2 ans)))
  12468. (setq year (org-small-year-to-year year))
  12469. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12470. t nil ans)))
  12471. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12472. ;; If there is a time with am/pm, and *no* time without it, we convert
  12473. ;; so that matching will be successful.
  12474. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12475. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12476. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12477. (setq hour (string-to-number (match-string 1 ans))
  12478. minute (if (match-end 3)
  12479. (string-to-number (match-string 3 ans))
  12480. 0)
  12481. pm (equal ?p
  12482. (string-to-char (downcase (match-string 4 ans)))))
  12483. (if (and (= hour 12) (not pm))
  12484. (setq hour 0)
  12485. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12486. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12487. t t ans))))
  12488. ;; Check if a time range is given as a duration
  12489. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12490. (setq hour (string-to-number (match-string 1 ans))
  12491. h2 (+ hour (string-to-number (match-string 3 ans)))
  12492. minute (string-to-number (match-string 2 ans))
  12493. m2 (+ minute (if (match-end 5) (string-to-number
  12494. (match-string 5 ans))0)))
  12495. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12496. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12497. t t ans)))
  12498. ;; Check if there is a time range
  12499. (when (boundp 'org-end-time-was-given)
  12500. (setq org-time-was-given nil)
  12501. (when (and (string-match org-plain-time-of-day-regexp ans)
  12502. (match-end 8))
  12503. (setq org-end-time-was-given (match-string 8 ans))
  12504. (setq ans (concat (substring ans 0 (match-beginning 7))
  12505. (substring ans (match-end 7))))))
  12506. (setq tl (parse-time-string ans)
  12507. day (or (nth 3 tl) (nth 3 org-defdecode))
  12508. month
  12509. (cond ((nth 4 tl))
  12510. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12511. ;; Day was specified. Make sure DAY+MONTH
  12512. ;; combination happens in the future.
  12513. ((nth 3 tl)
  12514. (setq futurep t)
  12515. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12516. (nth 4 nowdecode)))
  12517. (t (nth 4 org-defdecode)))
  12518. year
  12519. (cond ((and (not kill-year) (nth 5 tl)))
  12520. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12521. ;; Month was guessed in the future and is at least
  12522. ;; equal to NOWDECODE's. Fix year accordingly.
  12523. (futurep
  12524. (if (or (> month (nth 4 nowdecode))
  12525. (>= day (nth 3 nowdecode)))
  12526. (nth 5 nowdecode)
  12527. (1+ (nth 5 nowdecode))))
  12528. ;; Month was specified. Make sure MONTH+YEAR
  12529. ;; combination happens in the future.
  12530. ((nth 4 tl)
  12531. (setq futurep t)
  12532. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12533. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12534. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12535. (t (nth 5 nowdecode))))
  12536. (t (nth 5 org-defdecode)))
  12537. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12538. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12539. second (or (nth 0 tl) 0)
  12540. wday (nth 6 tl))
  12541. (when (and (eq org-read-date-prefer-future 'time)
  12542. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12543. (equal day (nth 3 nowdecode))
  12544. (equal month (nth 4 nowdecode))
  12545. (equal year (nth 5 nowdecode))
  12546. (nth 2 tl)
  12547. (or (< (nth 2 tl) (nth 2 nowdecode))
  12548. (and (= (nth 2 tl) (nth 2 nowdecode))
  12549. (nth 1 tl)
  12550. (< (nth 1 tl) (nth 1 nowdecode)))))
  12551. (setq day (1+ day)
  12552. futurep t))
  12553. ;; Special date definitions below
  12554. (cond
  12555. (iso-week
  12556. ;; There was an iso week
  12557. (require 'cal-iso)
  12558. (setq futurep nil)
  12559. (setq year (or iso-year year)
  12560. day (or iso-weekday wday 1)
  12561. wday nil ; to make sure that the trigger below does not match
  12562. iso-date (calendar-gregorian-from-absolute
  12563. (calendar-iso-to-absolute
  12564. (list iso-week day year))))
  12565. ; FIXME: Should we also push ISO weeks into the future?
  12566. ; (when (and org-read-date-prefer-future
  12567. ; (not iso-year)
  12568. ; (< (calendar-absolute-from-gregorian iso-date)
  12569. ; (time-to-days nil)))
  12570. ; (setq year (1+ year)
  12571. ; iso-date (calendar-gregorian-from-absolute
  12572. ; (calendar-iso-to-absolute
  12573. ; (list iso-week day year)))))
  12574. (setq month (car iso-date)
  12575. year (nth 2 iso-date)
  12576. day (nth 1 iso-date)))
  12577. (deltan
  12578. (setq futurep nil)
  12579. (unless deltadef
  12580. (let ((now (decode-time)))
  12581. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12582. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12583. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12584. ((equal deltaw "m") (setq month (+ month deltan)))
  12585. ((equal deltaw "y") (setq year (+ year deltan)))))
  12586. ((and wday (not (nth 3 tl)))
  12587. ;; Weekday was given, but no day, so pick that day in the week
  12588. ;; on or after the derived date.
  12589. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12590. (unless (equal wday wday1)
  12591. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12592. (when (and (boundp 'org-time-was-given)
  12593. (nth 2 tl))
  12594. (setq org-time-was-given t))
  12595. (when (< year 100) (setq year (+ 2000 year)))
  12596. ;; Check of the date is representable
  12597. (if org-read-date-force-compatible-dates
  12598. (progn
  12599. (when (< year 1970)
  12600. (setq year 1970 org-read-date-analyze-forced-year t))
  12601. (when (> year 2037)
  12602. (setq year 2037 org-read-date-analyze-forced-year t)))
  12603. (condition-case nil
  12604. (ignore (encode-time second minute hour day month year))
  12605. (error
  12606. (setq year (nth 5 org-defdecode))
  12607. (setq org-read-date-analyze-forced-year t))))
  12608. (setq org-read-date-analyze-futurep futurep)
  12609. (list second minute hour day month year)))
  12610. (defvar parse-time-weekdays)
  12611. (defun org-read-date-get-relative (s today default)
  12612. "Check string S for special relative date string.
  12613. TODAY and DEFAULT are internal times, for today and for a default.
  12614. Return shift list (N what def-flag)
  12615. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12616. N is the number of WHATs to shift.
  12617. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12618. the DEFAULT date rather than TODAY."
  12619. (require 'parse-time)
  12620. (when (and
  12621. (string-match
  12622. (concat
  12623. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12624. "\\([0-9]+\\)?"
  12625. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12626. "\\([ \t]\\|$\\)") s)
  12627. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12628. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12629. (string-to-char (substring (match-string 1 s) -1))
  12630. ?+))
  12631. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12632. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12633. (what (if (match-end 3) (match-string 3 s) "d"))
  12634. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12635. (date (if rel default today))
  12636. (wday (nth 6 (decode-time date)))
  12637. delta)
  12638. (if wday1
  12639. (progn
  12640. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12641. (when (= delta 0) (setq delta 7))
  12642. (when (= dir ?-)
  12643. (setq delta (- delta 7))
  12644. (when (= delta 0) (setq delta -7)))
  12645. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12646. (list delta "d" rel))
  12647. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12648. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12649. "Turn a user-specified date into the internal representation.
  12650. The internal representation needed by the calendar is (month day year).
  12651. This is a wrapper to handle the brain-dead convention in calendar that
  12652. user function argument order change dependent on argument order."
  12653. (pcase calendar-date-style
  12654. (`american (list arg1 arg2 arg3))
  12655. (`european (list arg2 arg1 arg3))
  12656. (`iso (list arg2 arg3 arg1))))
  12657. (defun org-eval-in-calendar (form &optional keepdate)
  12658. "Eval FORM in the calendar window and return to current window.
  12659. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12660. (let ((sf (selected-frame))
  12661. (sw (selected-window)))
  12662. (select-window (get-buffer-window "*Calendar*" t))
  12663. (eval form)
  12664. (when (and (not keepdate) (calendar-cursor-to-date))
  12665. (let* ((date (calendar-cursor-to-date))
  12666. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12667. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12668. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12669. (select-window sw)
  12670. (select-frame-set-input-focus sf)))
  12671. (defun org-calendar-select ()
  12672. "Return to `org-read-date' with the date currently selected.
  12673. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12674. (interactive)
  12675. (when (calendar-cursor-to-date)
  12676. (let* ((date (calendar-cursor-to-date))
  12677. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12678. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12679. (when (active-minibuffer-window) (exit-minibuffer))))
  12680. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12681. "Insert a date stamp for the date given by the internal TIME.
  12682. See `format-time-string' for the format of TIME.
  12683. WITH-HM means use the stamp format that includes the time of the day.
  12684. INACTIVE means use square brackets instead of angular ones, so that the
  12685. stamp will not contribute to the agenda.
  12686. PRE and POST are optional strings to be inserted before and after the
  12687. stamp.
  12688. The command returns the inserted time stamp."
  12689. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12690. stamp)
  12691. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12692. (insert-before-markers (or pre ""))
  12693. (when (listp extra)
  12694. (setq extra (car extra))
  12695. (if (and (stringp extra)
  12696. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12697. (setq extra (format "-%02d:%02d"
  12698. (string-to-number (match-string 1 extra))
  12699. (string-to-number (match-string 2 extra))))
  12700. (setq extra nil)))
  12701. (when extra
  12702. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12703. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12704. (insert-before-markers (or post ""))
  12705. (setq org-last-inserted-timestamp stamp)))
  12706. (defun org-toggle-time-stamp-overlays ()
  12707. "Toggle the use of custom time stamp formats."
  12708. (interactive)
  12709. (setq org-display-custom-times (not org-display-custom-times))
  12710. (unless org-display-custom-times
  12711. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12712. (while (setq p (next-single-property-change p 'display))
  12713. (when (and (get-text-property p 'display)
  12714. (eq (get-text-property p 'face) 'org-date))
  12715. (remove-text-properties
  12716. p (setq p (next-single-property-change p 'display))
  12717. '(display t))))
  12718. (set-buffer-modified-p bmp)))
  12719. (org-restart-font-lock)
  12720. (setq org-table-may-need-update t)
  12721. (if org-display-custom-times
  12722. (message "Time stamps are overlaid with custom format")
  12723. (message "Time stamp overlays removed")))
  12724. (defun org-display-custom-time (beg end)
  12725. "Overlay modified time stamp format over timestamp between BEG and END."
  12726. (let* ((ts (buffer-substring beg end))
  12727. t1 with-hm tf time str (off 0))
  12728. (save-match-data
  12729. (setq t1 (org-parse-time-string ts t))
  12730. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12731. (setq off (- (match-end 0) (match-beginning 0)))))
  12732. (setq end (- end off))
  12733. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12734. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12735. time (org-fix-decoded-time t1)
  12736. str (org-add-props
  12737. (format-time-string
  12738. (substring tf 1 -1) (apply 'encode-time time))
  12739. nil 'mouse-face 'highlight))
  12740. (put-text-property beg end 'display str)))
  12741. (defun org-fix-decoded-time (time)
  12742. "Set 0 instead of nil for the first 6 elements of time.
  12743. Don't touch the rest."
  12744. (let ((n 0))
  12745. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12746. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12747. "Difference between TIMESTAMP-STRING and now in days.
  12748. If SECONDS is non-nil, return the difference in seconds."
  12749. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12750. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12751. (funcall fdiff nil))))
  12752. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12753. "Is the time in TIMESTAMP-STRING close to the current date?"
  12754. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12755. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12756. (not (org-entry-is-done-p))))
  12757. (defun org-get-wdays (ts &optional delay zero-delay)
  12758. "Get the deadline lead time appropriate for timestring TS.
  12759. When DELAY is non-nil, get the delay time for scheduled items
  12760. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12761. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12762. don't try to find the delay cookie in the scheduled timestamp."
  12763. (let ((tv (if delay org-scheduled-delay-days
  12764. org-deadline-warning-days)))
  12765. (cond
  12766. ((or (and delay (< tv 0))
  12767. (and delay zero-delay (<= tv 0))
  12768. (and (not delay) (<= tv 0)))
  12769. ;; Enforce this value no matter what
  12770. (- tv))
  12771. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12772. ;; lead time is specified.
  12773. (floor (* (string-to-number (match-string 1 ts))
  12774. (cdr (assoc (match-string 2 ts)
  12775. '(("d" . 1) ("w" . 7)
  12776. ("m" . 30.4) ("y" . 365.25)
  12777. ("h" . 0.041667)))))))
  12778. ;; go for the default.
  12779. (t tv))))
  12780. (defun org-calendar-select-mouse (ev)
  12781. "Return to `org-read-date' with the date currently selected.
  12782. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12783. (interactive "e")
  12784. (mouse-set-point ev)
  12785. (when (calendar-cursor-to-date)
  12786. (let* ((date (calendar-cursor-to-date))
  12787. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12788. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12789. (when (active-minibuffer-window) (exit-minibuffer))))
  12790. (defun org-check-deadlines (ndays)
  12791. "Check if there are any deadlines due or past due.
  12792. A deadline is considered due if it happens within `org-deadline-warning-days'
  12793. days from today's date. If the deadline appears in an entry marked DONE,
  12794. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12795. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12796. are shown."
  12797. (interactive "P")
  12798. (let* ((org-warn-days
  12799. (cond
  12800. ((equal ndays '(4)) 100000)
  12801. (ndays (prefix-numeric-value ndays))
  12802. (t (abs org-deadline-warning-days))))
  12803. (case-fold-search nil)
  12804. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12805. (callback
  12806. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12807. (message "%d deadlines past-due or due within %d days"
  12808. (org-occur regexp nil callback)
  12809. org-warn-days)))
  12810. (defsubst org-re-timestamp (type)
  12811. "Return a regexp for timestamp TYPE.
  12812. Allowed values for TYPE are:
  12813. all: all timestamps
  12814. active: only active timestamps (<...>)
  12815. inactive: only inactive timestamps ([...])
  12816. scheduled: only scheduled timestamps
  12817. deadline: only deadline timestamps
  12818. closed: only closed time-stamps
  12819. When TYPE is nil, fall back on returning a regexp that matches
  12820. both scheduled and deadline timestamps."
  12821. (cl-case type
  12822. (all org-ts-regexp-both)
  12823. (active org-ts-regexp)
  12824. (inactive org-ts-regexp-inactive)
  12825. (scheduled org-scheduled-time-regexp)
  12826. (deadline org-deadline-time-regexp)
  12827. (closed org-closed-time-regexp)
  12828. (otherwise
  12829. (concat "\\<"
  12830. (regexp-opt (list org-deadline-string org-scheduled-string))
  12831. " *<\\([^>]+\\)>"))))
  12832. (defun org-check-before-date (d)
  12833. "Check if there are deadlines or scheduled entries before date D."
  12834. (interactive (list (org-read-date)))
  12835. (let* ((case-fold-search nil)
  12836. (regexp (org-re-timestamp org-ts-type))
  12837. (ts-type org-ts-type)
  12838. (callback
  12839. (lambda ()
  12840. (let ((match (match-string 1)))
  12841. (and (if (memq ts-type '(active inactive all))
  12842. (eq (org-element-type (save-excursion
  12843. (backward-char)
  12844. (org-element-context)))
  12845. 'timestamp)
  12846. (org-at-planning-p))
  12847. (time-less-p
  12848. (org-time-string-to-time match)
  12849. (org-time-string-to-time d)))))))
  12850. (message "%d entries before %s"
  12851. (org-occur regexp nil callback)
  12852. d)))
  12853. (defun org-check-after-date (d)
  12854. "Check if there are deadlines or scheduled entries after date D."
  12855. (interactive (list (org-read-date)))
  12856. (let* ((case-fold-search nil)
  12857. (regexp (org-re-timestamp org-ts-type))
  12858. (ts-type org-ts-type)
  12859. (callback
  12860. (lambda ()
  12861. (let ((match (match-string 1)))
  12862. (and (if (memq ts-type '(active inactive all))
  12863. (eq (org-element-type (save-excursion
  12864. (backward-char)
  12865. (org-element-context)))
  12866. 'timestamp)
  12867. (org-at-planning-p))
  12868. (not (time-less-p
  12869. (org-time-string-to-time match)
  12870. (org-time-string-to-time d))))))))
  12871. (message "%d entries after %s"
  12872. (org-occur regexp nil callback)
  12873. d)))
  12874. (defun org-check-dates-range (start-date end-date)
  12875. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12876. (interactive (list (org-read-date nil nil nil "Range starts")
  12877. (org-read-date nil nil nil "Range end")))
  12878. (let ((case-fold-search nil)
  12879. (regexp (org-re-timestamp org-ts-type))
  12880. (callback
  12881. (let ((type org-ts-type))
  12882. (lambda ()
  12883. (let ((match (match-string 1)))
  12884. (and
  12885. (if (memq type '(active inactive all))
  12886. (eq (org-element-type (save-excursion
  12887. (backward-char)
  12888. (org-element-context)))
  12889. 'timestamp)
  12890. (org-at-planning-p))
  12891. (not (time-less-p
  12892. (org-time-string-to-time match)
  12893. (org-time-string-to-time start-date)))
  12894. (time-less-p
  12895. (org-time-string-to-time match)
  12896. (org-time-string-to-time end-date))))))))
  12897. (message "%d entries between %s and %s"
  12898. (org-occur regexp nil callback) start-date end-date)))
  12899. (defun org-evaluate-time-range (&optional to-buffer)
  12900. "Evaluate a time range by computing the difference between start and end.
  12901. Normally the result is just printed in the echo area, but with prefix arg
  12902. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12903. If the time range is actually in a table, the result is inserted into the
  12904. next column.
  12905. For time difference computation, a year is assumed to be exactly 365
  12906. days in order to avoid rounding problems."
  12907. (interactive "P")
  12908. (or
  12909. (org-clock-update-time-maybe)
  12910. (save-excursion
  12911. (unless (org-at-date-range-p t)
  12912. (goto-char (point-at-bol))
  12913. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12914. (unless (org-at-date-range-p t)
  12915. (user-error "Not at a time-stamp range, and none found in current line")))
  12916. (let* ((ts1 (match-string 1))
  12917. (ts2 (match-string 2))
  12918. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12919. (match-end (match-end 0))
  12920. (time1 (org-time-string-to-time ts1))
  12921. (time2 (org-time-string-to-time ts2))
  12922. (diff (abs (float-time (time-subtract time2 time1))))
  12923. (negative (time-less-p time2 time1))
  12924. ;; (ys (floor (* 365 24 60 60)))
  12925. (ds (* 24 60 60))
  12926. (hs (* 60 60))
  12927. (fy "%dy %dd %02d:%02d")
  12928. (fy1 "%dy %dd")
  12929. (fd "%dd %02d:%02d")
  12930. (fd1 "%dd")
  12931. (fh "%02d:%02d")
  12932. y d h m align)
  12933. (if havetime
  12934. (setq ; y (floor diff ys) diff (mod diff ys)
  12935. y 0
  12936. d (floor diff ds) diff (mod diff ds)
  12937. h (floor diff hs) diff (mod diff hs)
  12938. m (floor diff 60))
  12939. (setq ; y (floor diff ys) diff (mod diff ys)
  12940. y 0
  12941. d (round diff ds)
  12942. h 0 m 0))
  12943. (if (not to-buffer)
  12944. (message "%s" (org-make-tdiff-string y d h m))
  12945. (if (org-at-table-p)
  12946. (progn
  12947. (goto-char match-end)
  12948. (setq align t)
  12949. (and (looking-at " *|") (goto-char (match-end 0))))
  12950. (goto-char match-end))
  12951. (when (looking-at
  12952. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12953. (replace-match ""))
  12954. (when negative (insert " -"))
  12955. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12956. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12957. (insert " " (format fh h m))))
  12958. (when align (org-table-align))
  12959. (message "Time difference inserted")))))
  12960. (defun org-make-tdiff-string (y d h m)
  12961. (let ((fmt "")
  12962. (l nil))
  12963. (when (> y 0)
  12964. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12965. (push y l))
  12966. (when (> d 0)
  12967. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12968. (push d l))
  12969. (when (> h 0)
  12970. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12971. (push h l))
  12972. (when (> m 0)
  12973. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12974. (push m l))
  12975. (apply 'format fmt (nreverse l))))
  12976. (defun org-time-string-to-time (s)
  12977. "Convert timestamp string S into internal time."
  12978. (apply #'encode-time (org-parse-time-string s)))
  12979. (defun org-time-string-to-seconds (s)
  12980. "Convert a timestamp string S into a number of seconds."
  12981. (float-time (org-time-string-to-time s)))
  12982. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12983. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12984. "Convert time stamp S to an absolute day number.
  12985. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12986. stamp, get the closest date to DAYNR. If PREFER is
  12987. `past' (respectively `future') return a date past (respectively
  12988. after) or equal to DAYNR.
  12989. POS is the location of time stamp S, as a buffer position in
  12990. BUFFER.
  12991. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12992. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12993. signaled."
  12994. (cond
  12995. ((string-match "\\`%%\\((.*)\\)" s)
  12996. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  12997. ;; only able to match individual dates. If it fails, raise an
  12998. ;; error.
  12999. (if (and daynr
  13000. (org-diary-sexp-entry
  13001. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13002. daynr
  13003. (signal 'org-diary-sexp-no-match (list s))))
  13004. (daynr (org-closest-date s daynr prefer))
  13005. (t (time-to-days
  13006. (condition-case errdata
  13007. (org-time-string-to-time s)
  13008. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13009. s
  13010. (if (not (and buffer pos)) ""
  13011. (format-message " at %d in buffer `%s'" pos buffer))
  13012. (cdr errdata))))))))
  13013. (defun org-days-to-iso-week (days)
  13014. "Return the iso week number."
  13015. (require 'cal-iso)
  13016. (car (calendar-iso-from-absolute days)))
  13017. (defun org-small-year-to-year (year)
  13018. "Convert 2-digit years into 4-digit years.
  13019. YEAR is expanded into one of the 30 next years, if possible, or
  13020. into a past one. Any year larger than 99 is returned unchanged."
  13021. (if (>= year 100) year
  13022. (let* ((current (string-to-number (format-time-string "%Y")))
  13023. (century (/ current 100))
  13024. (offset (- year (% current 100))))
  13025. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13026. ((> offset -70) (+ (* century 100) year))
  13027. (t (+ (* (1+ century) 100) year))))))
  13028. (defun org-time-from-absolute (d)
  13029. "Return the time corresponding to date D.
  13030. D may be an absolute day number, or a calendar-type list (month day year)."
  13031. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13032. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13033. (defvar org-agenda-current-date)
  13034. (defun org-calendar-holiday ()
  13035. "List of holidays, for Diary display in Org mode."
  13036. (require 'holidays)
  13037. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13038. (and hl (mapconcat #'identity hl "; "))))
  13039. (defun org-diary-sexp-entry (sexp entry d)
  13040. "Process a SEXP diary ENTRY for date D."
  13041. (require 'diary-lib)
  13042. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13043. ;; dynamically.
  13044. (let* ((sexp `(let ((entry ,entry)
  13045. (date ',d))
  13046. ,(car (read-from-string sexp))))
  13047. (result (if calendar-debug-sexp (eval sexp)
  13048. (condition-case nil
  13049. (eval sexp)
  13050. (error
  13051. (beep)
  13052. (message "Bad sexp at line %d in %s: %s"
  13053. (org-current-line)
  13054. (buffer-file-name) sexp)
  13055. (sleep-for 2))))))
  13056. (cond ((stringp result) (split-string result "; "))
  13057. ((and (consp result)
  13058. (not (consp (cdr result)))
  13059. (stringp (cdr result))) (cdr result))
  13060. ((and (consp result)
  13061. (stringp (car result))) result)
  13062. (result entry))))
  13063. (defun org-diary-to-ical-string (frombuf)
  13064. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13065. This uses the icalendar.el library."
  13066. (let* ((tmpdir temporary-file-directory)
  13067. (tmpfile (make-temp-name
  13068. (expand-file-name "orgics" tmpdir)))
  13069. buf rtn b e)
  13070. (with-current-buffer frombuf
  13071. (icalendar-export-region (point-min) (point-max) tmpfile)
  13072. (setq buf (find-buffer-visiting tmpfile))
  13073. (set-buffer buf)
  13074. (goto-char (point-min))
  13075. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13076. (setq b (match-beginning 0)))
  13077. (goto-char (point-max))
  13078. (when (re-search-backward "^END:VEVENT" nil t)
  13079. (setq e (match-end 0)))
  13080. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13081. (kill-buffer buf)
  13082. (delete-file tmpfile)
  13083. rtn))
  13084. (defun org-closest-date (start current prefer)
  13085. "Return closest date to CURRENT starting from START.
  13086. CURRENT and START are both time stamps.
  13087. When PREFER is `past', return a date that is either CURRENT or
  13088. past. When PREFER is `future', return a date that is either
  13089. CURRENT or future.
  13090. Only time stamps with a repeater are modified. Any other time
  13091. stamp stay unchanged. In any case, return value is an absolute
  13092. day number."
  13093. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13094. ;; No repeater. Do not shift time stamp.
  13095. (time-to-days (org-time-string-to-time start))
  13096. (let ((value (string-to-number (match-string 1 start)))
  13097. (type (match-string 2 start)))
  13098. (if (= 0 value)
  13099. ;; Repeater with a 0-value is considered as void.
  13100. (time-to-days (org-time-string-to-time start))
  13101. (let* ((base (org-date-to-gregorian start))
  13102. (target (org-date-to-gregorian current))
  13103. (sday (calendar-absolute-from-gregorian base))
  13104. (cday (calendar-absolute-from-gregorian target))
  13105. n1 n2)
  13106. ;; If START is already past CURRENT, just return START.
  13107. (if (<= cday sday) sday
  13108. ;; Compute closest date before (N1) and closest date past
  13109. ;; (N2) CURRENT.
  13110. (pcase type
  13111. ("h"
  13112. (let ((missing-hours
  13113. (mod (+ (- (* 24 (- cday sday))
  13114. (nth 2 (org-parse-time-string start)))
  13115. org-extend-today-until)
  13116. value)))
  13117. (setf n1 (if (= missing-hours 0) cday
  13118. (- cday (1+ (/ missing-hours 24)))))
  13119. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13120. ((or "d" "w")
  13121. (let ((value (if (equal type "w") (* 7 value) value)))
  13122. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13123. (setf n2 (+ n1 value))))
  13124. ("m"
  13125. (let* ((add-months
  13126. (lambda (d n)
  13127. ;; Add N months to gregorian date D, i.e.,
  13128. ;; a list (MONTH DAY YEAR). Return a valid
  13129. ;; gregorian date.
  13130. (let ((m (+ (nth 0 d) n)))
  13131. (list (mod m 12)
  13132. (nth 1 d)
  13133. (+ (/ m 12) (nth 2 d))))))
  13134. (months ; Complete months to TARGET.
  13135. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13136. (- (nth 0 target) (nth 0 base))
  13137. ;; If START's day is greater than
  13138. ;; TARGET's, remove incomplete month.
  13139. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13140. value)
  13141. value))
  13142. (before (funcall add-months base months)))
  13143. (setf n1 (calendar-absolute-from-gregorian before))
  13144. (setf n2
  13145. (calendar-absolute-from-gregorian
  13146. (funcall add-months before value)))))
  13147. (_
  13148. (let* ((d (nth 1 base))
  13149. (m (nth 0 base))
  13150. (y (nth 2 base))
  13151. (years ; Complete years to TARGET.
  13152. (* (/ (- (nth 2 target)
  13153. y
  13154. ;; If START's month and day are
  13155. ;; greater than TARGET's, remove
  13156. ;; incomplete year.
  13157. (if (or (> (nth 0 target) m)
  13158. (and (= (nth 0 target) m)
  13159. (> (nth 1 target) d)))
  13160. 0
  13161. 1))
  13162. value)
  13163. value))
  13164. (before (list m d (+ y years))))
  13165. (setf n1 (calendar-absolute-from-gregorian before))
  13166. (setf n2 (calendar-absolute-from-gregorian
  13167. (list m d (+ (nth 2 before) value)))))))
  13168. ;; Handle PREFER parameter, if any.
  13169. (cond
  13170. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13171. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13172. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13173. (defun org-date-to-gregorian (d)
  13174. "Turn any specification of date D into a Gregorian date for the calendar."
  13175. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13176. ((and (listp d) (= (length d) 3)) d)
  13177. ((stringp d)
  13178. (let ((d (org-parse-time-string d)))
  13179. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13180. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13181. (defun org-timestamp-up (&optional arg)
  13182. "Increase the date item at the cursor by one.
  13183. If the cursor is on the year, change the year. If it is on the month,
  13184. the day or the time, change that. If the cursor is on the enclosing
  13185. bracket, change the timestamp type.
  13186. With prefix ARG, change by that many units."
  13187. (interactive "p")
  13188. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13189. (defun org-timestamp-down (&optional arg)
  13190. "Decrease the date item at the cursor by one.
  13191. If the cursor is on the year, change the year. If it is on the month,
  13192. the day or the time, change that. If the cursor is on the enclosing
  13193. bracket, change the timestamp type.
  13194. With prefix ARG, change by that many units."
  13195. (interactive "p")
  13196. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13197. (defun org-timestamp-up-day (&optional arg)
  13198. "Increase the date in the time stamp by one day.
  13199. With prefix ARG, change that many days."
  13200. (interactive "p")
  13201. (if (and (not (org-at-timestamp-p 'lax))
  13202. (org-at-heading-p))
  13203. (org-todo 'up)
  13204. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13205. (defun org-timestamp-down-day (&optional arg)
  13206. "Decrease the date in the time stamp by one day.
  13207. With prefix ARG, change that many days."
  13208. (interactive "p")
  13209. (if (and (not (org-at-timestamp-p 'lax))
  13210. (org-at-heading-p))
  13211. (org-todo 'down)
  13212. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13213. (defun org-at-timestamp-p (&optional extended)
  13214. "Non-nil if point is inside a timestamp.
  13215. By default, the function only consider syntactically valid active
  13216. timestamps. However, the caller may have a broader definition
  13217. for timestamps. As a consequence, optional argument EXTENDED can
  13218. be set to the following values
  13219. `inactive'
  13220. Include also syntactically valid inactive timestamps.
  13221. `agenda'
  13222. Include timestamps allowed in Agenda, i.e., those in
  13223. properties drawers, planning lines and clock lines.
  13224. `lax'
  13225. Ignore context. The function matches any part of the
  13226. document looking like a timestamp. This includes comments,
  13227. example blocks...
  13228. For backward-compatibility with Org 9.0, every other non-nil
  13229. value is equivalent to `inactive'.
  13230. When at a timestamp, return the position of the point as a symbol
  13231. among `bracket', `after', `year', `month', `hour', `minute',
  13232. `day' or a number of character from the last know part of the
  13233. time stamp.
  13234. When matching, the match groups are the following:
  13235. group 1: year
  13236. group 2: month
  13237. group 3: day number
  13238. group 4: day name
  13239. group 5: hours, if any
  13240. group 6: minutes, if any"
  13241. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13242. (pos (point))
  13243. (match?
  13244. (let ((boundaries (org-in-regexp regexp)))
  13245. (save-match-data
  13246. (cond ((null boundaries) nil)
  13247. ((eq extended 'lax) t)
  13248. (t
  13249. (or (and (eq extended 'agenda)
  13250. (or (org-at-planning-p)
  13251. (org-at-property-p)
  13252. (and (bound-and-true-p
  13253. org-agenda-include-inactive-timestamps)
  13254. (org-at-clock-log-p))))
  13255. (eq 'timestamp
  13256. (save-excursion
  13257. (when (= pos (cdr boundaries)) (forward-char -1))
  13258. (org-element-type (org-element-context)))))))))))
  13259. (cond
  13260. ((not match?) nil)
  13261. ((= pos (match-beginning 0)) 'bracket)
  13262. ;; Distinguish location right before the closing bracket from
  13263. ;; right after it.
  13264. ((= pos (1- (match-end 0))) 'bracket)
  13265. ((= pos (match-end 0)) 'after)
  13266. ((org-pos-in-match-range pos 2) 'year)
  13267. ((org-pos-in-match-range pos 3) 'month)
  13268. ((org-pos-in-match-range pos 7) 'hour)
  13269. ((org-pos-in-match-range pos 8) 'minute)
  13270. ((or (org-pos-in-match-range pos 4)
  13271. (org-pos-in-match-range pos 5)) 'day)
  13272. ((and (> pos (or (match-end 8) (match-end 5)))
  13273. (< pos (match-end 0)))
  13274. (- pos (or (match-end 8) (match-end 5))))
  13275. (t 'day))))
  13276. (defun org-toggle-timestamp-type ()
  13277. "Toggle the type (<active> or [inactive]) of a time stamp."
  13278. (interactive)
  13279. (when (org-at-timestamp-p 'lax)
  13280. (let ((beg (match-beginning 0)) (end (match-end 0))
  13281. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13282. (save-excursion
  13283. (goto-char beg)
  13284. (while (re-search-forward "[][<>]" end t)
  13285. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13286. t t)))
  13287. (message "Timestamp is now %sactive"
  13288. (if (equal (char-after beg) ?<) "" "in")))))
  13289. (defun org-at-clock-log-p ()
  13290. "Non-nil if point is on a clock log line."
  13291. (and (org-match-line org-clock-line-re)
  13292. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13293. (defvar org-clock-history) ; defined in org-clock.el
  13294. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13295. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13296. "Change the date in the time stamp at point.
  13297. The date is changed by N times WHAT. WHAT can be `day', `month',
  13298. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13299. position in the timestamp determines what is changed.
  13300. When optional argument UPDOWN is non-nil, minutes are rounded
  13301. according to `org-time-stamp-rounding-minutes'.
  13302. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13303. \"--2d\"."
  13304. (let ((origin (point))
  13305. (timestamp? (org-at-timestamp-p 'lax))
  13306. origin-cat
  13307. with-hm inactive
  13308. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13309. extra rem
  13310. ts time time0 fixnext clrgx)
  13311. (unless timestamp? (user-error "Not at a timestamp"))
  13312. (if (and (not what) (eq timestamp? 'bracket))
  13313. (org-toggle-timestamp-type)
  13314. ;; Point isn't on brackets. Remember the part of the time-stamp
  13315. ;; the point was in. Indeed, size of time-stamps may change,
  13316. ;; but point must be kept in the same category nonetheless.
  13317. (setq origin-cat timestamp?)
  13318. (when (and (not what) (not (eq timestamp? 'day))
  13319. org-display-custom-times
  13320. (get-text-property (point) 'display)
  13321. (not (get-text-property (1- (point)) 'display)))
  13322. (setq timestamp? 'day))
  13323. (setq timestamp? (or what timestamp?)
  13324. inactive (= (char-after (match-beginning 0)) ?\[)
  13325. ts (match-string 0))
  13326. (replace-match "")
  13327. (when (string-match
  13328. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13329. ts)
  13330. (setq extra (match-string 1 ts))
  13331. (when suppress-tmp-delay
  13332. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13333. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13334. (setq with-hm t))
  13335. (setq time0 (org-parse-time-string ts))
  13336. (when (and updown
  13337. (eq timestamp? 'minute)
  13338. (not current-prefix-arg))
  13339. ;; This looks like s-up and s-down. Change by one rounding step.
  13340. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13341. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13342. (setcar (cdr time0) (+ (nth 1 time0)
  13343. (if (> n 0) (- rem) (- dm rem))))))
  13344. (setq time
  13345. (apply #'encode-time
  13346. (or (car time0) 0)
  13347. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13348. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13349. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13350. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13351. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13352. (nthcdr 6 time0)))
  13353. (when (and (memq timestamp? '(hour minute))
  13354. extra
  13355. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13356. (setq extra (org-modify-ts-extra
  13357. extra
  13358. (if (eq timestamp? 'hour) 2 5)
  13359. n dm)))
  13360. (when (integerp timestamp?)
  13361. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13362. (when (eq what 'calendar)
  13363. (let ((cal-date (org-get-date-from-calendar)))
  13364. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13365. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13366. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13367. (setcar time0 (or (car time0) 0))
  13368. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13369. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13370. (setq time (apply 'encode-time time0))))
  13371. ;; Insert the new time-stamp, and ensure point stays in the same
  13372. ;; category as before (i.e. not after the last position in that
  13373. ;; category).
  13374. (let ((pos (point)))
  13375. ;; Stay before inserted string. `save-excursion' is of no use.
  13376. (setq org-last-changed-timestamp
  13377. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13378. (goto-char pos))
  13379. (save-match-data
  13380. (looking-at org-ts-regexp3)
  13381. (goto-char
  13382. (pcase origin-cat
  13383. ;; `day' category ends before `hour' if any, or at the end
  13384. ;; of the day name.
  13385. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13386. (`hour (min (match-end 7) origin))
  13387. (`minute (min (1- (match-end 8)) origin))
  13388. ((pred integerp) (min (1- (match-end 0)) origin))
  13389. ;; Point was right after the time-stamp. However, the
  13390. ;; time-stamp length might have changed, so refer to
  13391. ;; (match-end 0) instead.
  13392. (`after (match-end 0))
  13393. ;; `year' and `month' have both fixed size: point couldn't
  13394. ;; have moved into another part.
  13395. (_ origin))))
  13396. ;; Update clock if on a CLOCK line.
  13397. (org-clock-update-time-maybe)
  13398. ;; Maybe adjust the closest clock in `org-clock-history'
  13399. (when org-clock-adjust-closest
  13400. (if (not (and (org-at-clock-log-p)
  13401. (< 1 (length (delq nil (mapcar 'marker-position
  13402. org-clock-history))))))
  13403. (message "No clock to adjust")
  13404. (cond ((save-excursion ; fix previous clock?
  13405. (re-search-backward org-ts-regexp0 nil t)
  13406. (looking-back (concat org-clock-string " \\[")
  13407. (line-beginning-position)))
  13408. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13409. ((save-excursion ; fix next clock?
  13410. (re-search-backward org-ts-regexp0 nil t)
  13411. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13412. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13413. (save-window-excursion
  13414. ;; Find closest clock to point, adjust the previous/next one in history
  13415. (let* ((p (save-excursion (org-back-to-heading t)))
  13416. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13417. (clfixnth
  13418. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13419. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13420. (if (not clfixpos)
  13421. (message "No clock to adjust")
  13422. (save-excursion
  13423. (org-goto-marker-or-bmk clfixpos)
  13424. (org-show-subtree)
  13425. (when (re-search-forward clrgx nil t)
  13426. (goto-char (match-beginning 1))
  13427. (let (org-clock-adjust-closest)
  13428. (org-timestamp-change n timestamp? updown))
  13429. (message "Clock adjusted in %s for heading: %s"
  13430. (file-name-nondirectory (buffer-file-name))
  13431. (org-get-heading t t)))))))))
  13432. ;; Try to recenter the calendar window, if any.
  13433. (when (and org-calendar-follow-timestamp-change
  13434. (get-buffer-window "*Calendar*" t)
  13435. (memq timestamp? '(day month year)))
  13436. (org-recenter-calendar (time-to-days time))))))
  13437. (defun org-modify-ts-extra (s pos n dm)
  13438. "Change the different parts of the lead-time and repeat fields in timestamp."
  13439. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13440. ng h m new rem)
  13441. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13442. (cond
  13443. ((or (org-pos-in-match-range pos 2)
  13444. (org-pos-in-match-range pos 3))
  13445. (setq m (string-to-number (match-string 3 s))
  13446. h (string-to-number (match-string 2 s)))
  13447. (if (org-pos-in-match-range pos 2)
  13448. (setq h (+ h n))
  13449. (setq n (* dm (with-no-warnings (cl-signum n))))
  13450. (unless (= 0 (setq rem (% m dm)))
  13451. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13452. (setq m (+ m n)))
  13453. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13454. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13455. (setq h (mod h 24))
  13456. (setq ng 1 new (format "-%02d:%02d" h m)))
  13457. ((org-pos-in-match-range pos 6)
  13458. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13459. ((org-pos-in-match-range pos 5)
  13460. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13461. ((org-pos-in-match-range pos 9)
  13462. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13463. ((org-pos-in-match-range pos 8)
  13464. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13465. (when ng
  13466. (setq s (concat
  13467. (substring s 0 (match-beginning ng))
  13468. new
  13469. (substring s (match-end ng))))))
  13470. s))
  13471. (defun org-recenter-calendar (d)
  13472. "If the calendar is visible, recenter it to date D."
  13473. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13474. (when cwin
  13475. (let ((calendar-move-hook nil))
  13476. (with-selected-window cwin
  13477. (calendar-goto-date
  13478. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13479. (defun org-goto-calendar (&optional arg)
  13480. "Go to the Emacs calendar at the current date.
  13481. If there is a time stamp in the current line, go to that date.
  13482. A prefix ARG can be used to force the current date."
  13483. (interactive "P")
  13484. (let ((calendar-move-hook nil)
  13485. (calendar-view-holidays-initially-flag nil)
  13486. (calendar-view-diary-initially-flag nil)
  13487. diff)
  13488. (when (or (org-at-timestamp-p 'lax)
  13489. (org-match-line (concat ".*" org-ts-regexp)))
  13490. (let ((d1 (time-to-days nil))
  13491. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13492. (setq diff (- d2 d1))))
  13493. (calendar)
  13494. (calendar-goto-today)
  13495. (when (and diff (not arg)) (calendar-forward-day diff))))
  13496. (defun org-get-date-from-calendar ()
  13497. "Return a list (month day year) of date at point in calendar."
  13498. (with-current-buffer "*Calendar*"
  13499. (save-match-data
  13500. (calendar-cursor-to-date))))
  13501. (defun org-date-from-calendar ()
  13502. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13503. If there is already a time stamp at the cursor position, update it."
  13504. (interactive)
  13505. (if (org-at-timestamp-p 'lax)
  13506. (org-timestamp-change 0 'calendar)
  13507. (let ((cal-date (org-get-date-from-calendar)))
  13508. (org-insert-time-stamp
  13509. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13510. (defcustom org-image-actual-width t
  13511. "When non-nil, use the actual width of images when inlining them.
  13512. When set to a number, use imagemagick (when available) to set the
  13513. image's width to this value.
  13514. When set to a number in a list, try to get the width from any
  13515. #+ATTR.* keyword if it matches a width specification like
  13516. #+ATTR_HTML: :width 300px
  13517. and fall back on that number if none is found.
  13518. When set to nil, try to get the width from an #+ATTR.* keyword
  13519. and fall back on the original width if none is found.
  13520. When set to any other non-nil value, always use the image width.
  13521. This requires Emacs >= 24.1, built with imagemagick support."
  13522. :group 'org-appearance
  13523. :version "24.4"
  13524. :package-version '(Org . "8.0")
  13525. :type '(choice
  13526. (const :tag "Use the image width" t)
  13527. (integer :tag "Use a number of pixels")
  13528. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13529. (const :tag "Use #+ATTR* or don't resize" nil)))
  13530. (defcustom org-agenda-inhibit-startup nil
  13531. "Inhibit startup when preparing agenda buffers.
  13532. When this variable is t, the initialization of the Org agenda
  13533. buffers is inhibited: e.g. the visibility state is not set, the
  13534. tables are not re-aligned, etc."
  13535. :type 'boolean
  13536. :version "24.3"
  13537. :group 'org-agenda)
  13538. (defcustom org-agenda-ignore-properties nil
  13539. "Avoid updating text properties when building the agenda.
  13540. Properties are used to prepare buffers for effort estimates,
  13541. appointments, statistics and subtree-local categories.
  13542. If you don't use these in the agenda, you can add them to this
  13543. list and agenda building will be a bit faster.
  13544. The value is a list, with zero or more of the symbols `effort', `appt',
  13545. `stats' or `category'."
  13546. :type '(set :greedy t
  13547. (const effort)
  13548. (const appt)
  13549. (const stats)
  13550. (const category))
  13551. :version "26.1"
  13552. :package-version '(Org . "8.3")
  13553. :group 'org-agenda)
  13554. ;;;; Files
  13555. (defun org-save-all-org-buffers ()
  13556. "Save all Org buffers without user confirmation."
  13557. (interactive)
  13558. (message "Saving all Org buffers...")
  13559. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13560. (when (featurep 'org-id) (org-id-locations-save))
  13561. (message "Saving all Org buffers... done"))
  13562. (defun org-revert-all-org-buffers ()
  13563. "Revert all Org buffers.
  13564. Prompt for confirmation when there are unsaved changes.
  13565. Be sure you know what you are doing before letting this function
  13566. overwrite your changes.
  13567. This function is useful in a setup where one tracks Org files
  13568. with a version control system, to revert on one machine after pulling
  13569. changes from another. I believe the procedure must be like this:
  13570. 1. M-x org-save-all-org-buffers
  13571. 2. Pull changes from the other machine, resolve conflicts
  13572. 3. M-x org-revert-all-org-buffers"
  13573. (interactive)
  13574. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13575. (user-error "Abort"))
  13576. (save-excursion
  13577. (save-window-excursion
  13578. (dolist (b (buffer-list))
  13579. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13580. (with-current-buffer b buffer-file-name))
  13581. (pop-to-buffer-same-window b)
  13582. (revert-buffer t 'no-confirm)))
  13583. (when (and (featurep 'org-id) org-id-track-globally)
  13584. (org-id-locations-load)))))
  13585. ;;;; Agenda files
  13586. ;;;###autoload
  13587. (defun org-switchb (&optional arg)
  13588. "Switch between Org buffers.
  13589. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13590. With `\\[universal-argument] \\[universal-argument]' \
  13591. prefix, restrict available buffers to agenda files."
  13592. (interactive "P")
  13593. (let ((blist (org-buffer-list
  13594. (cond ((equal arg '(4)) 'files)
  13595. ((equal arg '(16)) 'agenda)))))
  13596. (pop-to-buffer-same-window
  13597. (completing-read "Org buffer: "
  13598. (mapcar #'list (mapcar #'buffer-name blist))
  13599. nil t))))
  13600. (defun org-buffer-list (&optional predicate exclude-tmp)
  13601. "Return a list of Org buffers.
  13602. PREDICATE can be `export', `files' or `agenda'.
  13603. export restrict the list to Export buffers.
  13604. files restrict the list to buffers visiting Org files.
  13605. agenda restrict the list to buffers visiting agenda files.
  13606. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13607. (let* ((bfn nil)
  13608. (agenda-files (and (eq predicate 'agenda)
  13609. (mapcar 'file-truename (org-agenda-files t))))
  13610. (filter
  13611. (cond
  13612. ((eq predicate 'files)
  13613. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13614. ((eq predicate 'export)
  13615. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13616. ((eq predicate 'agenda)
  13617. (lambda (b)
  13618. (with-current-buffer b
  13619. (and (derived-mode-p 'org-mode)
  13620. (setq bfn (buffer-file-name b))
  13621. (member (file-truename bfn) agenda-files)))))
  13622. (t (lambda (b) (with-current-buffer b
  13623. (or (derived-mode-p 'org-mode)
  13624. (string-match "\\*Org .*Export"
  13625. (buffer-name b)))))))))
  13626. (delq nil
  13627. (mapcar
  13628. (lambda(b)
  13629. (if (and (funcall filter b)
  13630. (or (not exclude-tmp)
  13631. (not (string-match "tmp" (buffer-name b)))))
  13632. b
  13633. nil))
  13634. (buffer-list)))))
  13635. (defun org-agenda-files (&optional unrestricted archives)
  13636. "Get the list of agenda files.
  13637. Optional UNRESTRICTED means return the full list even if a restriction
  13638. is currently in place.
  13639. When ARCHIVES is t, include all archive files that are really being
  13640. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13641. `org-agenda-archives-mode' is t."
  13642. (let ((files
  13643. (cond
  13644. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13645. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13646. ((listp org-agenda-files) org-agenda-files)
  13647. (t (error "Invalid value of `org-agenda-files'")))))
  13648. (setq files (apply 'append
  13649. (mapcar (lambda (f)
  13650. (if (file-directory-p f)
  13651. (directory-files
  13652. f t org-agenda-file-regexp)
  13653. (list f)))
  13654. files)))
  13655. (when org-agenda-skip-unavailable-files
  13656. (setq files (delq nil
  13657. (mapcar (function
  13658. (lambda (file)
  13659. (and (file-readable-p file) file)))
  13660. files))))
  13661. (when (or (eq archives t)
  13662. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13663. (setq files (org-add-archive-files files)))
  13664. files))
  13665. (defun org-agenda-file-p (&optional file)
  13666. "Return non-nil, if FILE is an agenda file.
  13667. If FILE is omitted, use the file associated with the current
  13668. buffer."
  13669. (let ((fname (or file (buffer-file-name))))
  13670. (and fname
  13671. (member (file-truename fname)
  13672. (mapcar #'file-truename (org-agenda-files t))))))
  13673. (defun org-edit-agenda-file-list ()
  13674. "Edit the list of agenda files.
  13675. Depending on setup, this either uses customize to edit the variable
  13676. `org-agenda-files', or it visits the file that is holding the list. In the
  13677. latter case, the buffer is set up in a way that saving it automatically kills
  13678. the buffer and restores the previous window configuration."
  13679. (interactive)
  13680. (if (stringp org-agenda-files)
  13681. (let ((cw (current-window-configuration)))
  13682. (find-file org-agenda-files)
  13683. (setq-local org-window-configuration cw)
  13684. (add-hook 'after-save-hook
  13685. (lambda ()
  13686. (set-window-configuration
  13687. (prog1 org-window-configuration
  13688. (kill-buffer (current-buffer))))
  13689. (org-install-agenda-files-menu)
  13690. (message "New agenda file list installed"))
  13691. nil 'local)
  13692. (message "%s" (substitute-command-keys
  13693. "Edit list and finish with \\[save-buffer]")))
  13694. (customize-variable 'org-agenda-files)))
  13695. (defun org-store-new-agenda-file-list (list)
  13696. "Set new value for the agenda file list and save it correctly."
  13697. (if (stringp org-agenda-files)
  13698. (let ((fe (org-read-agenda-file-list t)) b u)
  13699. (while (setq b (find-buffer-visiting org-agenda-files))
  13700. (kill-buffer b))
  13701. (with-temp-file org-agenda-files
  13702. (insert
  13703. (mapconcat
  13704. (lambda (f) ;; Keep un-expanded entries.
  13705. (if (setq u (assoc f fe))
  13706. (cdr u)
  13707. f))
  13708. list "\n")
  13709. "\n")))
  13710. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13711. (org-insert-mode-line-in-empty-file nil))
  13712. (setq org-agenda-files list)
  13713. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13714. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13715. "Read the list of agenda files from a file.
  13716. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13717. filenames, used by `org-store-new-agenda-file-list' to write back
  13718. un-expanded file names."
  13719. (when (file-directory-p org-agenda-files)
  13720. (error "`org-agenda-files' cannot be a single directory"))
  13721. (when (stringp org-agenda-files)
  13722. (with-temp-buffer
  13723. (insert-file-contents org-agenda-files)
  13724. (mapcar
  13725. (lambda (f)
  13726. (let ((e (expand-file-name (substitute-in-file-name f)
  13727. org-directory)))
  13728. (if pair-with-expansion
  13729. (cons e f)
  13730. e)))
  13731. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13732. ;;;###autoload
  13733. (defun org-cycle-agenda-files ()
  13734. "Cycle through the files in `org-agenda-files'.
  13735. If the current buffer visits an agenda file, find the next one in the list.
  13736. If the current buffer does not, find the first agenda file."
  13737. (interactive)
  13738. (let* ((fs (or (org-agenda-files t)
  13739. (user-error "No agenda files")))
  13740. (files (copy-sequence fs))
  13741. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13742. file)
  13743. (when tcf
  13744. (while (and (setq file (pop files))
  13745. (not (equal (file-truename file) tcf)))))
  13746. (find-file (car (or files fs)))
  13747. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13748. (defun org-agenda-file-to-front (&optional to-end)
  13749. "Move/add the current file to the top of the agenda file list.
  13750. If the file is not present in the list, it is added to the front. If it is
  13751. present, it is moved there. With optional argument TO-END, add/move to the
  13752. end of the list."
  13753. (interactive "P")
  13754. (let ((org-agenda-skip-unavailable-files nil)
  13755. (file-alist (mapcar (lambda (x)
  13756. (cons (file-truename x) x))
  13757. (org-agenda-files t)))
  13758. (ctf (file-truename
  13759. (or buffer-file-name
  13760. (user-error "Please save the current buffer to a file"))))
  13761. x had)
  13762. (setq x (assoc ctf file-alist) had x)
  13763. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13764. (if to-end
  13765. (setq file-alist (append (delq x file-alist) (list x)))
  13766. (setq file-alist (cons x (delq x file-alist))))
  13767. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13768. (org-install-agenda-files-menu)
  13769. (message "File %s to %s of agenda file list"
  13770. (if had "moved" "added") (if to-end "end" "front"))))
  13771. (defun org-remove-file (&optional file)
  13772. "Remove current file from the list of files in variable `org-agenda-files'.
  13773. These are the files which are being checked for agenda entries.
  13774. Optional argument FILE means use this file instead of the current."
  13775. (interactive)
  13776. (let* ((org-agenda-skip-unavailable-files nil)
  13777. (file (or file buffer-file-name
  13778. (user-error "Current buffer does not visit a file")))
  13779. (true-file (file-truename file))
  13780. (afile (abbreviate-file-name file))
  13781. (files (delq nil (mapcar
  13782. (lambda (x)
  13783. (unless (equal true-file
  13784. (file-truename x))
  13785. x))
  13786. (org-agenda-files t)))))
  13787. (if (not (= (length files) (length (org-agenda-files t))))
  13788. (progn
  13789. (org-store-new-agenda-file-list files)
  13790. (org-install-agenda-files-menu)
  13791. (message "Removed from Org Agenda list: %s" afile))
  13792. (message "File was not in list: %s (not removed)" afile))))
  13793. (defun org-file-menu-entry (file)
  13794. (vector file (list 'find-file file) t))
  13795. (defun org-check-agenda-file (file)
  13796. "Make sure FILE exists. If not, ask user what to do."
  13797. (unless (file-exists-p file)
  13798. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13799. (abbreviate-file-name file))
  13800. (let ((r (downcase (read-char-exclusive))))
  13801. (cond
  13802. ((equal r ?r)
  13803. (org-remove-file file)
  13804. (throw 'nextfile t))
  13805. (t (user-error "Abort"))))))
  13806. (defun org-get-agenda-file-buffer (file)
  13807. "Get an agenda buffer visiting FILE.
  13808. If the buffer needs to be created, add it to the list of buffers
  13809. which might be released later."
  13810. (let ((buf (org-find-base-buffer-visiting file)))
  13811. (if buf
  13812. buf ; just return it
  13813. ;; Make a new buffer and remember it
  13814. (setq buf (find-file-noselect file))
  13815. (when buf (push buf org-agenda-new-buffers))
  13816. buf)))
  13817. (defun org-release-buffers (blist)
  13818. "Release all buffers in list, asking the user for confirmation when needed.
  13819. When a buffer is unmodified, it is just killed. When modified, it is saved
  13820. \(if the user agrees) and then killed."
  13821. (let (file)
  13822. (dolist (buf blist)
  13823. (setq file (buffer-file-name buf))
  13824. (when (and (buffer-modified-p buf)
  13825. file
  13826. (y-or-n-p (format "Save file %s? " file)))
  13827. (with-current-buffer buf (save-buffer)))
  13828. (kill-buffer buf))))
  13829. (defun org-agenda-prepare-buffers (files)
  13830. "Create buffers for all agenda files, protect archived trees and comments."
  13831. (interactive)
  13832. (let ((pa '(:org-archived t))
  13833. (pc '(:org-comment t))
  13834. (pall '(:org-archived t :org-comment t))
  13835. (inhibit-read-only t)
  13836. (org-inhibit-startup org-agenda-inhibit-startup)
  13837. (rea (org-make-tag-string (list org-archive-tag)))
  13838. re pos)
  13839. (setq org-tag-alist-for-agenda nil
  13840. org-tag-groups-alist-for-agenda nil)
  13841. (save-excursion
  13842. (save-restriction
  13843. (dolist (file files)
  13844. (catch 'nextfile
  13845. (if (bufferp file)
  13846. (set-buffer file)
  13847. (org-check-agenda-file file)
  13848. (set-buffer (org-get-agenda-file-buffer file)))
  13849. (widen)
  13850. (org-set-regexps-and-options 'tags-only)
  13851. (setq pos (point))
  13852. (or (memq 'category org-agenda-ignore-properties)
  13853. (org-refresh-category-properties))
  13854. (or (memq 'stats org-agenda-ignore-properties)
  13855. (org-refresh-stats-properties))
  13856. (or (memq 'effort org-agenda-ignore-properties)
  13857. (org-refresh-effort-properties))
  13858. (or (memq 'appt org-agenda-ignore-properties)
  13859. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13860. (setq org-todo-keywords-for-agenda
  13861. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13862. (setq org-done-keywords-for-agenda
  13863. (append org-done-keywords-for-agenda org-done-keywords))
  13864. (setq org-todo-keyword-alist-for-agenda
  13865. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13866. (setq org-tag-alist-for-agenda
  13867. (org--tag-add-to-alist
  13868. org-tag-alist-for-agenda
  13869. org-current-tag-alist))
  13870. ;; Merge current file's tag groups into global
  13871. ;; `org-tag-groups-alist-for-agenda'.
  13872. (when org-group-tags
  13873. (dolist (alist org-tag-groups-alist)
  13874. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13875. (if old
  13876. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13877. (push alist org-tag-groups-alist-for-agenda)))))
  13878. (with-silent-modifications
  13879. (save-excursion
  13880. (remove-text-properties (point-min) (point-max) pall)
  13881. (when org-agenda-skip-archived-trees
  13882. (goto-char (point-min))
  13883. (while (re-search-forward rea nil t)
  13884. (when (org-at-heading-p t)
  13885. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  13886. (goto-char (point-min))
  13887. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  13888. (while (re-search-forward re nil t)
  13889. (when (save-match-data (org-in-commented-heading-p t))
  13890. (add-text-properties
  13891. (match-beginning 0) (org-end-of-subtree t) pc)))))
  13892. (goto-char pos)))))
  13893. (setq org-todo-keywords-for-agenda
  13894. (org-uniquify org-todo-keywords-for-agenda))
  13895. (setq org-todo-keyword-alist-for-agenda
  13896. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13897. ;;;; CDLaTeX minor mode
  13898. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13899. "Keymap for the minor `org-cdlatex-mode'.")
  13900. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13901. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13902. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13903. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13904. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13905. (defvar org-cdlatex-texmathp-advice-is-done nil
  13906. "Flag remembering if we have applied the advice to texmathp already.")
  13907. (define-minor-mode org-cdlatex-mode
  13908. "Toggle the minor `org-cdlatex-mode'.
  13909. This mode supports entering LaTeX environment and math in LaTeX fragments
  13910. in Org mode.
  13911. \\{org-cdlatex-mode-map}"
  13912. nil " OCDL" nil
  13913. (when org-cdlatex-mode
  13914. (require 'cdlatex)
  13915. (run-hooks 'cdlatex-mode-hook)
  13916. (cdlatex-compute-tables))
  13917. (unless org-cdlatex-texmathp-advice-is-done
  13918. (setq org-cdlatex-texmathp-advice-is-done t)
  13919. (defadvice texmathp (around org-math-always-on activate)
  13920. "Always return t in Org buffers.
  13921. This is because we want to insert math symbols without dollars even outside
  13922. the LaTeX math segments. If Org mode thinks that point is actually inside
  13923. an embedded LaTeX fragment, let `texmathp' do its job.
  13924. `\\[org-cdlatex-mode-map]'"
  13925. (interactive)
  13926. (let (p)
  13927. (cond
  13928. ((not (derived-mode-p 'org-mode)) ad-do-it)
  13929. ((eq this-command 'cdlatex-math-symbol)
  13930. (setq ad-return-value t
  13931. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  13932. (t
  13933. (let ((p (org-inside-LaTeX-fragment-p)))
  13934. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  13935. (setq ad-return-value t
  13936. texmathp-why '("Org mode embedded math" . 0))
  13937. (when p ad-do-it)))))))))
  13938. (defun turn-on-org-cdlatex ()
  13939. "Unconditionally turn on `org-cdlatex-mode'."
  13940. (org-cdlatex-mode 1))
  13941. (defun org-try-cdlatex-tab ()
  13942. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13943. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13944. - inside a LaTeX fragment, or
  13945. - after the first word in a line, where an abbreviation expansion could
  13946. insert a LaTeX environment."
  13947. (when org-cdlatex-mode
  13948. (cond
  13949. ;; Before any word on the line: No expansion possible.
  13950. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13951. ;; Just after first word on the line: Expand it. Make sure it
  13952. ;; cannot happen on headlines, though.
  13953. ((save-excursion
  13954. (skip-chars-backward "a-zA-Z0-9*")
  13955. (skip-chars-backward " \t")
  13956. (and (bolp) (not (org-at-heading-p))))
  13957. (cdlatex-tab) t)
  13958. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13959. (defun org-cdlatex-underscore-caret (&optional _arg)
  13960. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13961. Revert to the normal definition outside of these fragments."
  13962. (interactive "P")
  13963. (if (org-inside-LaTeX-fragment-p)
  13964. (call-interactively 'cdlatex-sub-superscript)
  13965. (let (org-cdlatex-mode)
  13966. (call-interactively (key-binding (vector last-input-event))))))
  13967. (defun org-cdlatex-math-modify (&optional _arg)
  13968. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13969. Revert to the normal definition outside of these fragments."
  13970. (interactive "P")
  13971. (if (org-inside-LaTeX-fragment-p)
  13972. (call-interactively 'cdlatex-math-modify)
  13973. (let (org-cdlatex-mode)
  13974. (call-interactively (key-binding (vector last-input-event))))))
  13975. (defun org-cdlatex-environment-indent (&optional environment item)
  13976. "Execute `cdlatex-environment' and indent the inserted environment.
  13977. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13978. The inserted environment is indented to current indentation
  13979. unless point is at the beginning of the line, in which the
  13980. environment remains unintended."
  13981. (interactive)
  13982. ;; cdlatex-environment always return nil. Therefore, capture output
  13983. ;; first and determine if an environment was selected.
  13984. (let* ((beg (point-marker))
  13985. (end (copy-marker (point) t))
  13986. (inserted (progn
  13987. (ignore-errors (cdlatex-environment environment item))
  13988. (< beg end)))
  13989. ;; Figure out how many lines to move forward after the
  13990. ;; environment has been inserted.
  13991. (lines (when inserted
  13992. (save-excursion
  13993. (- (cl-loop while (< beg (point))
  13994. with x = 0
  13995. do (forward-line -1)
  13996. (cl-incf x)
  13997. finally return x)
  13998. (if (progn (goto-char beg)
  13999. (and (progn (skip-chars-forward " \t") (eolp))
  14000. (progn (skip-chars-backward " \t") (bolp))))
  14001. 1 0)))))
  14002. (env (org-trim (delete-and-extract-region beg end))))
  14003. (when inserted
  14004. ;; Get indentation of next line unless at column 0.
  14005. (let ((ind (if (bolp) 0
  14006. (save-excursion
  14007. (org-return-indent)
  14008. (prog1 (current-indentation)
  14009. (when (progn (skip-chars-forward " \t") (eolp))
  14010. (delete-region beg (point)))))))
  14011. (bol (progn (skip-chars-backward " \t") (bolp))))
  14012. ;; Insert a newline before environment unless at column zero
  14013. ;; to "escape" the current line. Insert a newline if
  14014. ;; something is one the same line as \end{ENVIRONMENT}.
  14015. (insert
  14016. (concat (unless bol "\n") env
  14017. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14018. (unless (zerop ind)
  14019. (save-excursion
  14020. (goto-char beg)
  14021. (while (< (point) end)
  14022. (unless (eolp) (indent-line-to ind))
  14023. (forward-line))))
  14024. (goto-char beg)
  14025. (forward-line lines)
  14026. (indent-line-to ind)))
  14027. (set-marker beg nil)
  14028. (set-marker end nil)))
  14029. ;;;; LaTeX fragments
  14030. (defun org-inside-LaTeX-fragment-p ()
  14031. "Test if point is inside a LaTeX fragment.
  14032. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14033. sequence appearing also before point.
  14034. Even though the matchers for math are configurable, this function assumes
  14035. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14036. delimiters are skipped when they have been removed by customization.
  14037. The return value is nil, or a cons cell with the delimiter and the
  14038. position of this delimiter.
  14039. This function does a reasonably good job, but can locally be fooled by
  14040. for example currency specifications. For example it will assume being in
  14041. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14042. fragments that are properly closed, but during editing, we have to live
  14043. with the uncertainty caused by missing closing delimiters. This function
  14044. looks only before point, not after."
  14045. (catch 'exit
  14046. (let ((pos (point))
  14047. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14048. (lim (save-excursion (org-backward-paragraph) (point)))
  14049. dd-on str (start 0) m re)
  14050. (goto-char pos)
  14051. (when dodollar
  14052. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14053. re (nth 1 (assoc "$" org-latex-regexps)))
  14054. (while (string-match re str start)
  14055. (cond
  14056. ((= (match-end 0) (length str))
  14057. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14058. ((= (match-end 0) (- (length str) 5))
  14059. (throw 'exit nil))
  14060. (t (setq start (match-end 0))))))
  14061. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14062. (goto-char pos)
  14063. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14064. (and (match-beginning 2) (throw 'exit nil))
  14065. ;; count $$
  14066. (while (re-search-backward "\\$\\$" lim t)
  14067. (setq dd-on (not dd-on)))
  14068. (goto-char pos)
  14069. (when dd-on (cons "$$" m))))))
  14070. (defun org-inside-latex-macro-p ()
  14071. "Is point inside a LaTeX macro or its arguments?"
  14072. (save-match-data
  14073. (org-in-regexp
  14074. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14075. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14076. "Build an overlay between BEG and END using IMAGE file.
  14077. Argument IMAGETYPE is the extension of the displayed image,
  14078. as a string. It defaults to \"png\"."
  14079. (let ((ov (make-overlay beg end))
  14080. (imagetype (or (intern imagetype) 'png)))
  14081. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14082. (overlay-put ov 'evaporate t)
  14083. (overlay-put ov
  14084. 'modification-hooks
  14085. (list (lambda (o _flag _beg _end &optional _l)
  14086. (delete-overlay o))))
  14087. (overlay-put ov
  14088. 'display
  14089. (list 'image :type imagetype :file image :ascent 'center))))
  14090. (defun org-clear-latex-preview (&optional beg end)
  14091. "Remove all overlays with LaTeX fragment images in current buffer.
  14092. When optional arguments BEG and END are non-nil, remove all
  14093. overlays between them instead. Return a non-nil value when some
  14094. overlays were removed, nil otherwise."
  14095. (let ((overlays
  14096. (cl-remove-if-not
  14097. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14098. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14099. (mapc #'delete-overlay overlays)
  14100. overlays))
  14101. (defun org--latex-preview-region (beg end)
  14102. "Preview LaTeX fragments between BEG and END.
  14103. BEG and END are buffer positions."
  14104. (let ((file (buffer-file-name (buffer-base-buffer))))
  14105. (save-excursion
  14106. (org-format-latex
  14107. (concat org-preview-latex-image-directory "org-ltximg")
  14108. beg end
  14109. ;; Emacs cannot overlay images from remote hosts. Create it in
  14110. ;; `temporary-file-directory' instead.
  14111. (if (or (not file) (file-remote-p file))
  14112. temporary-file-directory
  14113. default-directory)
  14114. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14115. (defun org-latex-preview (&optional arg)
  14116. "Toggle preview of the LaTeX fragment at point.
  14117. If the cursor is on a LaTeX fragment, create the image and
  14118. overlay it over the source code, if there is none. Remove it
  14119. otherwise. If there is no fragment at point, display images for
  14120. all fragments in the current section.
  14121. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14122. for all fragments
  14123. in the current section.
  14124. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14125. argument ARG, display image for all
  14126. fragments in the buffer.
  14127. With a `\\[universal-argument] \\[universal-argument] \
  14128. \\[universal-argument]' prefix argument ARG, clear image for all
  14129. fragments in the buffer."
  14130. (interactive "P")
  14131. (cond
  14132. ((not (display-graphic-p)) nil)
  14133. ;; Clear whole buffer.
  14134. ((equal arg '(64))
  14135. (org-clear-latex-preview (point-min) (point-max))
  14136. (message "LaTeX previews removed from buffer"))
  14137. ;; Preview whole buffer.
  14138. ((equal arg '(16))
  14139. (message "Creating LaTeX previews in buffer...")
  14140. (org--latex-preview-region (point-min) (point-max))
  14141. (message "Creating LaTeX previews in buffer... done."))
  14142. ;; Clear current section.
  14143. ((equal arg '(4))
  14144. (org-clear-latex-preview
  14145. (if (org-before-first-heading-p) (point-min)
  14146. (save-excursion
  14147. (org-with-limited-levels (org-back-to-heading t) (point))))
  14148. (org-with-limited-levels (org-entry-end-position))))
  14149. ;; Toggle preview on LaTeX code at point.
  14150. ((let ((datum (org-element-context)))
  14151. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14152. (let ((beg (org-element-property :begin datum))
  14153. (end (org-element-property :end datum)))
  14154. (if (org-clear-latex-preview beg end)
  14155. (message "LaTeX preview removed")
  14156. (message "Creating LaTeX preview...")
  14157. (org--latex-preview-region beg end)
  14158. (message "Creating LaTeX preview... done."))
  14159. t))))
  14160. ;; Preview current section.
  14161. (t
  14162. (let ((beg (if (org-before-first-heading-p) (point-min)
  14163. (save-excursion
  14164. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14165. (end (org-with-limited-levels (org-entry-end-position))))
  14166. (message "Creating LaTeX previews in section...")
  14167. (org--latex-preview-region beg end)
  14168. (message "Creating LaTeX previews in section... done.")))))
  14169. (defun org-format-latex
  14170. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14171. "Replace LaTeX fragments with links to an image.
  14172. The function takes care of creating the replacement image.
  14173. Only consider fragments between BEG and END when those are
  14174. provided.
  14175. When optional argument OVERLAYS is non-nil, display the image on
  14176. top of the fragment instead of replacing it.
  14177. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14178. Some of the options can be changed using the variable
  14179. `org-format-latex-options', which see."
  14180. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14181. (unless (eq processing-type 'verbatim)
  14182. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14183. (cnt 0)
  14184. checkdir-flag)
  14185. (goto-char (or beg (point-min)))
  14186. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14187. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14188. (overlay-recenter (or end (point-max))))
  14189. (while (re-search-forward math-regexp end t)
  14190. (unless (and overlays
  14191. (eq (get-char-property (point) 'org-overlay-type)
  14192. 'org-latex-overlay))
  14193. (let* ((context (org-element-context))
  14194. (type (org-element-type context)))
  14195. (when (memq type '(latex-environment latex-fragment))
  14196. (let ((block-type (eq type 'latex-environment))
  14197. (value (org-element-property :value context))
  14198. (beg (org-element-property :begin context))
  14199. (end (save-excursion
  14200. (goto-char (org-element-property :end context))
  14201. (skip-chars-backward " \r\t\n")
  14202. (point))))
  14203. (cond
  14204. ((eq processing-type 'mathjax)
  14205. ;; Prepare for MathJax processing.
  14206. (if (not (string-match "\\`\\$\\$?" value))
  14207. (goto-char end)
  14208. (delete-region beg end)
  14209. (if (string= (match-string 0 value) "$$")
  14210. (insert "\\[" (substring value 2 -2) "\\]")
  14211. (insert "\\(" (substring value 1 -1) "\\)"))))
  14212. ((assq processing-type org-preview-latex-process-alist)
  14213. ;; Process to an image.
  14214. (cl-incf cnt)
  14215. (goto-char beg)
  14216. (let* ((processing-info
  14217. (cdr (assq processing-type org-preview-latex-process-alist)))
  14218. (face (face-at-point))
  14219. ;; Get the colors from the face at point.
  14220. (fg
  14221. (let ((color (plist-get org-format-latex-options
  14222. :foreground)))
  14223. (if (and forbuffer (eq color 'auto))
  14224. (face-attribute face :foreground nil 'default)
  14225. color)))
  14226. (bg
  14227. (let ((color (plist-get org-format-latex-options
  14228. :background)))
  14229. (if (and forbuffer (eq color 'auto))
  14230. (face-attribute face :background nil 'default)
  14231. color)))
  14232. (hash (sha1 (prin1-to-string
  14233. (list org-format-latex-header
  14234. org-latex-default-packages-alist
  14235. org-latex-packages-alist
  14236. org-format-latex-options
  14237. forbuffer value fg bg))))
  14238. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14239. (absprefix (expand-file-name prefix dir))
  14240. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14241. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14242. (sep (and block-type "\n\n"))
  14243. (link (concat sep "[[file:" linkfile "]]" sep))
  14244. (options
  14245. (org-combine-plists
  14246. org-format-latex-options
  14247. `(:foreground ,fg :background ,bg))))
  14248. (when msg (message msg cnt))
  14249. (unless checkdir-flag ; Ensure the directory exists.
  14250. (setq checkdir-flag t)
  14251. (let ((todir (file-name-directory absprefix)))
  14252. (unless (file-directory-p todir)
  14253. (make-directory todir t))))
  14254. (unless (file-exists-p movefile)
  14255. (org-create-formula-image
  14256. value movefile options forbuffer processing-type))
  14257. (if overlays
  14258. (progn
  14259. (dolist (o (overlays-in beg end))
  14260. (when (eq (overlay-get o 'org-overlay-type)
  14261. 'org-latex-overlay)
  14262. (delete-overlay o)))
  14263. (org--make-preview-overlay beg end movefile imagetype)
  14264. (goto-char end))
  14265. (delete-region beg end)
  14266. (insert
  14267. (org-add-props link
  14268. (list 'org-latex-src
  14269. (replace-regexp-in-string "\"" "" value)
  14270. 'org-latex-src-embed-type
  14271. (if block-type 'paragraph 'character)))))))
  14272. ((eq processing-type 'mathml)
  14273. ;; Process to MathML.
  14274. (unless (org-format-latex-mathml-available-p)
  14275. (user-error "LaTeX to MathML converter not configured"))
  14276. (cl-incf cnt)
  14277. (when msg (message msg cnt))
  14278. (goto-char beg)
  14279. (delete-region beg end)
  14280. (insert (org-format-latex-as-mathml
  14281. value block-type prefix dir)))
  14282. (t
  14283. (error "Unknown conversion process %s for LaTeX fragments"
  14284. processing-type)))))))))))
  14285. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14286. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14287. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14288. successful, return the portion between \"<math...> </math>\"
  14289. elements otherwise return nil. When MATHML-FILE is specified,
  14290. write the results in to that file. When invoked as an
  14291. interactive command, prompt for LATEX-FRAG, with initial value
  14292. set to the current active region and echo the results for user
  14293. inspection."
  14294. (interactive (list (let ((frag (when (org-region-active-p)
  14295. (buffer-substring-no-properties
  14296. (region-beginning) (region-end)))))
  14297. (read-string "LaTeX Fragment: " frag nil frag))))
  14298. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14299. (let* ((tmp-in-file
  14300. (let ((file (file-relative-name
  14301. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14302. (write-region latex-frag nil file)
  14303. file))
  14304. (tmp-out-file (file-relative-name
  14305. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14306. (cmd (format-spec
  14307. org-latex-to-mathml-convert-command
  14308. `((?j . ,(and org-latex-to-mathml-jar-file
  14309. (shell-quote-argument
  14310. (expand-file-name
  14311. org-latex-to-mathml-jar-file))))
  14312. (?I . ,(shell-quote-argument tmp-in-file))
  14313. (?i . ,latex-frag)
  14314. (?o . ,(shell-quote-argument tmp-out-file)))))
  14315. mathml shell-command-output)
  14316. (when (called-interactively-p 'any)
  14317. (unless (org-format-latex-mathml-available-p)
  14318. (user-error "LaTeX to MathML converter not configured")))
  14319. (message "Running %s" cmd)
  14320. (setq shell-command-output (shell-command-to-string cmd))
  14321. (setq mathml
  14322. (when (file-readable-p tmp-out-file)
  14323. (with-current-buffer (find-file-noselect tmp-out-file t)
  14324. (goto-char (point-min))
  14325. (when (re-search-forward
  14326. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14327. (regexp-quote
  14328. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14329. nil t)
  14330. (prog1 (match-string 0) (kill-buffer))))))
  14331. (cond
  14332. (mathml
  14333. (setq mathml
  14334. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14335. (when mathml-file
  14336. (write-region mathml nil mathml-file))
  14337. (when (called-interactively-p 'any)
  14338. (message mathml)))
  14339. ((message "LaTeX to MathML conversion failed")
  14340. (message shell-command-output)))
  14341. (delete-file tmp-in-file)
  14342. (when (file-exists-p tmp-out-file)
  14343. (delete-file tmp-out-file))
  14344. mathml))
  14345. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14346. prefix &optional dir)
  14347. "Use `org-create-math-formula' but check local cache first."
  14348. (let* ((absprefix (expand-file-name prefix dir))
  14349. (print-length nil) (print-level nil)
  14350. (formula-id (concat
  14351. "formula-"
  14352. (sha1
  14353. (prin1-to-string
  14354. (list latex-frag
  14355. org-latex-to-mathml-convert-command)))))
  14356. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14357. (formula-cache-dir (file-name-directory formula-cache)))
  14358. (unless (file-directory-p formula-cache-dir)
  14359. (make-directory formula-cache-dir t))
  14360. (unless (file-exists-p formula-cache)
  14361. (org-create-math-formula latex-frag formula-cache))
  14362. (if (file-exists-p formula-cache)
  14363. ;; Successful conversion. Return the link to MathML file.
  14364. (org-add-props
  14365. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14366. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14367. 'org-latex-src-embed-type (if latex-frag-type
  14368. 'paragraph 'character)))
  14369. ;; Failed conversion. Return the LaTeX fragment verbatim
  14370. latex-frag)))
  14371. (defun org--get-display-dpi ()
  14372. "Get the DPI of the display.
  14373. The function assumes that the display has the same pixel width in
  14374. the horizontal and vertical directions."
  14375. (if (display-graphic-p)
  14376. (round (/ (display-pixel-height)
  14377. (/ (display-mm-height) 25.4)))
  14378. (error "Attempt to calculate the dpi of a non-graphic display")))
  14379. (defun org-create-formula-image
  14380. (string tofile options buffer &optional processing-type)
  14381. "Create an image from LaTeX source using external processes.
  14382. The LaTeX STRING is saved to a temporary LaTeX file, then
  14383. converted to an image file by process PROCESSING-TYPE defined in
  14384. `org-preview-latex-process-alist'. A nil value defaults to
  14385. `org-preview-latex-default-process'.
  14386. The generated image file is eventually moved to TOFILE.
  14387. The OPTIONS argument controls the size, foreground color and
  14388. background color of the generated image.
  14389. When BUFFER non-nil, this function is used for LaTeX previewing.
  14390. Otherwise, it is used to deal with LaTeX snippets showed in
  14391. a HTML file."
  14392. (let* ((processing-type (or processing-type
  14393. org-preview-latex-default-process))
  14394. (processing-info
  14395. (cdr (assq processing-type org-preview-latex-process-alist)))
  14396. (programs (plist-get processing-info :programs))
  14397. (error-message (or (plist-get processing-info :message) ""))
  14398. (image-input-type (plist-get processing-info :image-input-type))
  14399. (image-output-type (plist-get processing-info :image-output-type))
  14400. (post-clean (or (plist-get processing-info :post-clean)
  14401. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14402. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14403. (latex-header
  14404. (or (plist-get processing-info :latex-header)
  14405. (org-latex-make-preamble
  14406. (org-export-get-environment (org-export-get-backend 'latex))
  14407. org-format-latex-header
  14408. 'snippet)))
  14409. (latex-compiler (plist-get processing-info :latex-compiler))
  14410. (image-converter (plist-get processing-info :image-converter))
  14411. (tmpdir temporary-file-directory)
  14412. (texfilebase (make-temp-name
  14413. (expand-file-name "orgtex" tmpdir)))
  14414. (texfile (concat texfilebase ".tex"))
  14415. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14416. '(1.0 . 1.0)))
  14417. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14418. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14419. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14420. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14421. "Black"))
  14422. (bg (or (plist-get options (if buffer :background :html-background))
  14423. "Transparent"))
  14424. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14425. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14426. (dolist (program programs)
  14427. (org-check-external-command program error-message))
  14428. (if (eq fg 'default)
  14429. (setq fg (org-latex-color :foreground))
  14430. (setq fg (org-latex-color-format fg)))
  14431. (if (eq bg 'default)
  14432. (setq bg (org-latex-color :background))
  14433. (setq bg (org-latex-color-format
  14434. (if (string= bg "Transparent") "white" bg))))
  14435. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14436. (if (string-suffix-p string "\n")
  14437. (aset string (1- (length string)) ?%)
  14438. (setq string (concat string "%")))
  14439. (with-temp-file texfile
  14440. (insert latex-header)
  14441. (insert "\n\\begin{document}\n"
  14442. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14443. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14444. "\n\\pagecolor{bg}%\n"
  14445. "\n{\\color{fg}\n"
  14446. string
  14447. "\n}\n"
  14448. "\n\\end{document}\n"))
  14449. (let* ((err-msg (format "Please adjust `%s' part of \
  14450. `org-preview-latex-process-alist'."
  14451. processing-type))
  14452. (image-input-file
  14453. (org-compile-file
  14454. texfile latex-compiler image-input-type err-msg log-buf))
  14455. (image-output-file
  14456. (org-compile-file
  14457. image-input-file image-converter image-output-type err-msg log-buf
  14458. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14459. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14460. (copy-file image-output-file tofile 'replace)
  14461. (dolist (e post-clean)
  14462. (when (file-exists-p (concat texfilebase e))
  14463. (delete-file (concat texfilebase e))))
  14464. image-output-file)))
  14465. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14466. "Fill a LaTeX header template TPL.
  14467. In the template, the following place holders will be recognized:
  14468. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14469. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14470. [PACKAGES] \\usepackage statements for PKG
  14471. [NO-PACKAGES] do not include PKG
  14472. [EXTRA] the string EXTRA
  14473. [NO-EXTRA] do not include EXTRA
  14474. For backward compatibility, if both the positive and the negative place
  14475. holder is missing, the positive one (without the \"NO-\") will be
  14476. assumed to be present at the end of the template.
  14477. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14478. EXTRA is a string.
  14479. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14480. (let (rpl (end ""))
  14481. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14482. (setq rpl (if (or (match-end 1) (not def-pkg))
  14483. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14484. tpl (replace-match rpl t t tpl))
  14485. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14486. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14487. (setq rpl (if (or (match-end 1) (not pkg))
  14488. "" (org-latex-packages-to-string pkg snippets-p t))
  14489. tpl (replace-match rpl t t tpl))
  14490. (when pkg (setq end
  14491. (concat end "\n"
  14492. (org-latex-packages-to-string pkg snippets-p)))))
  14493. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14494. (setq rpl (if (or (match-end 1) (not extra))
  14495. "" (concat extra "\n"))
  14496. tpl (replace-match rpl t t tpl))
  14497. (when (and extra (string-match "\\S-" extra))
  14498. (setq end (concat end "\n" extra))))
  14499. (if (string-match "\\S-" end)
  14500. (concat tpl "\n" end)
  14501. tpl)))
  14502. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14503. "Turn an alist of packages into a string with the \\usepackage macros."
  14504. (setq pkg (mapconcat (lambda(p)
  14505. (cond
  14506. ((stringp p) p)
  14507. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14508. (format "%% Package %s omitted" (cadr p)))
  14509. ((equal "" (car p))
  14510. (format "\\usepackage{%s}" (cadr p)))
  14511. (t
  14512. (format "\\usepackage[%s]{%s}"
  14513. (car p) (cadr p)))))
  14514. pkg
  14515. "\n"))
  14516. (if newline (concat pkg "\n") pkg))
  14517. (defun org-dvipng-color (attr)
  14518. "Return a RGB color specification for dvipng."
  14519. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14520. (defun org-dvipng-color-format (color-name)
  14521. "Convert COLOR-NAME to a RGB color value for dvipng."
  14522. (apply #'format "rgb %s %s %s"
  14523. (mapcar 'org-normalize-color
  14524. (color-values color-name))))
  14525. (defun org-latex-color (attr)
  14526. "Return a RGB color for the LaTeX color package."
  14527. (org-latex-color-format (face-attribute 'default attr nil)))
  14528. (defun org-latex-color-format (color-name)
  14529. "Convert COLOR-NAME to a RGB color value."
  14530. (apply #'format "%s,%s,%s"
  14531. (mapcar 'org-normalize-color
  14532. (color-values color-name))))
  14533. (defun org-normalize-color (value)
  14534. "Return string to be used as color value for an RGB component."
  14535. (format "%g" (/ value 65535.0)))
  14536. ;; Image display
  14537. (defvar-local org-inline-image-overlays nil)
  14538. (defun org-toggle-inline-images (&optional include-linked)
  14539. "Toggle the display of inline images.
  14540. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14541. (interactive "P")
  14542. (if org-inline-image-overlays
  14543. (progn
  14544. (org-remove-inline-images)
  14545. (when (called-interactively-p 'interactive)
  14546. (message "Inline image display turned off")))
  14547. (org-display-inline-images include-linked)
  14548. (when (called-interactively-p 'interactive)
  14549. (message (if org-inline-image-overlays
  14550. (format "%d images displayed inline"
  14551. (length org-inline-image-overlays))
  14552. "No images to display inline")))))
  14553. (defun org-redisplay-inline-images ()
  14554. "Assure display of inline images and refresh them."
  14555. (interactive)
  14556. (org-toggle-inline-images)
  14557. (unless org-inline-image-overlays
  14558. (org-toggle-inline-images)))
  14559. ;; For without-x builds.
  14560. (declare-function image-refresh "image" (spec &optional frame))
  14561. (defcustom org-display-remote-inline-images 'skip
  14562. "How to display remote inline images.
  14563. Possible values of this option are:
  14564. skip Don't display remote images.
  14565. download Always download and display remote images.
  14566. cache Display remote images, and open them in separate buffers
  14567. for cacheing. Silently update the image buffer when a file
  14568. change is detected."
  14569. :group 'org-appearance
  14570. :package-version '(Org . "9.4")
  14571. :type '(choice
  14572. (const :tag "Ignore remote images" skip)
  14573. (const :tag "Always display remote images" download)
  14574. (const :tag "Display and silently update remote images" cache))
  14575. :safe #'symbolp)
  14576. (defun org--create-inline-image (file width)
  14577. "Create image located at FILE, or return nil.
  14578. WIDTH is the width of the image. The image may not be created
  14579. according to the value of `org-display-remote-inline-images'."
  14580. (let* ((remote? (file-remote-p file))
  14581. (file-or-data
  14582. (pcase org-display-remote-inline-images
  14583. ((guard (not remote?)) file)
  14584. (`download (with-temp-buffer
  14585. (set-buffer-multibyte nil)
  14586. (insert-file-contents-literally file)
  14587. (buffer-string)))
  14588. (`cache (let ((revert-without-query '(".")))
  14589. (with-current-buffer (find-file-noselect file)
  14590. (buffer-string))))
  14591. (`skip nil)
  14592. (other
  14593. (message "Invalid value of `org-display-remote-inline-images': %S"
  14594. other)
  14595. nil))))
  14596. (when file-or-data
  14597. (create-image file-or-data
  14598. (and (image-type-available-p 'imagemagick)
  14599. width
  14600. 'imagemagick)
  14601. remote?
  14602. :width width))))
  14603. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14604. "Display inline images.
  14605. An inline image is a link which follows either of these
  14606. conventions:
  14607. 1. Its path is a file with an extension matching return value
  14608. from `image-file-name-regexp' and it has no contents.
  14609. 2. Its description consists in a single link of the previous
  14610. type. In this case, that link must be a well-formed plain
  14611. or angle link, i.e., it must have an explicit \"file\" type.
  14612. Equip each image with the key-map `image-map'.
  14613. When optional argument INCLUDE-LINKED is non-nil, also links with
  14614. a text description part will be inlined. This can be nice for
  14615. a quick look at those images, but it does not reflect what
  14616. exported files will look like.
  14617. When optional argument REFRESH is non-nil, refresh existing
  14618. images between BEG and END. This will create new image displays
  14619. only if necessary.
  14620. BEG and END define the considered part. They default to the
  14621. buffer boundaries with possible narrowing."
  14622. (interactive "P")
  14623. (when (display-graphic-p)
  14624. (unless refresh
  14625. (org-remove-inline-images)
  14626. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14627. (let ((end (or end (point-max))))
  14628. (org-with-point-at (or beg (point-min))
  14629. (let* ((case-fold-search t)
  14630. (file-extension-re (image-file-name-regexp))
  14631. (link-abbrevs (mapcar #'car
  14632. (append org-link-abbrev-alist-local
  14633. org-link-abbrev-alist)))
  14634. ;; Check absolute, relative file names and explicit
  14635. ;; "file:" links. Also check link abbreviations since
  14636. ;; some might expand to "file" links.
  14637. (file-types-re
  14638. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14639. (if (not link-abbrevs) ""
  14640. (concat "\\|" (regexp-opt link-abbrevs))))))
  14641. (while (re-search-forward file-types-re end t)
  14642. (let* ((link (org-element-lineage
  14643. (save-match-data (org-element-context))
  14644. '(link) t))
  14645. (linktype (org-element-property :type link))
  14646. (inner-start (match-beginning 1))
  14647. (path
  14648. (cond
  14649. ;; No link at point; no inline image.
  14650. ((not link) nil)
  14651. ;; File link without a description. Also handle
  14652. ;; INCLUDE-LINKED here since it should have
  14653. ;; precedence over the next case. I.e., if link
  14654. ;; contains filenames in both the path and the
  14655. ;; description, prioritize the path only when
  14656. ;; INCLUDE-LINKED is non-nil.
  14657. ((or (not (org-element-property :contents-begin link))
  14658. include-linked)
  14659. (and (or (equal "file" linktype)
  14660. (equal "attachment" linktype))
  14661. (org-element-property :path link)))
  14662. ;; Link with a description. Check if description
  14663. ;; is a filename. Even if Org doesn't have syntax
  14664. ;; for those -- clickable image -- constructs, fake
  14665. ;; them, as in `org-export-insert-image-links'.
  14666. ((not inner-start) nil)
  14667. (t
  14668. (org-with-point-at inner-start
  14669. (and (looking-at
  14670. (if (char-equal ?< (char-after inner-start))
  14671. org-link-angle-re
  14672. org-link-plain-re))
  14673. ;; File name must fill the whole
  14674. ;; description.
  14675. (= (org-element-property :contents-end link)
  14676. (match-end 0))
  14677. (match-string 2)))))))
  14678. (when (and path (string-match-p file-extension-re path))
  14679. (let ((file (if (equal "attachment" linktype)
  14680. (progn
  14681. (require 'org-attach)
  14682. (ignore-errors (org-attach-expand path)))
  14683. (expand-file-name path))))
  14684. (when (and file (file-exists-p file))
  14685. (let ((width
  14686. ;; Apply `org-image-actual-width' specifications.
  14687. (cond
  14688. ((eq org-image-actual-width t) nil)
  14689. ((listp org-image-actual-width)
  14690. (or
  14691. ;; First try to find a width among
  14692. ;; attributes associated to the paragraph
  14693. ;; containing link.
  14694. (pcase (org-element-lineage link '(paragraph))
  14695. (`nil nil)
  14696. (p
  14697. (let* ((case-fold-search t)
  14698. (end (org-element-property :post-affiliated p))
  14699. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14700. (when (org-with-point-at
  14701. (org-element-property :begin p)
  14702. (re-search-forward re end t))
  14703. (string-to-number (match-string 1))))))
  14704. ;; Otherwise, fall-back to provided number.
  14705. (car org-image-actual-width)))
  14706. ((numberp org-image-actual-width)
  14707. org-image-actual-width)
  14708. (t nil)))
  14709. (old (get-char-property-and-overlay
  14710. (org-element-property :begin link)
  14711. 'org-image-overlay)))
  14712. (if (and (car-safe old) refresh)
  14713. (image-refresh (overlay-get (cdr old) 'display))
  14714. (let ((image (org--create-inline-image file width)))
  14715. (when image
  14716. (let ((ov (make-overlay
  14717. (org-element-property :begin link)
  14718. (progn
  14719. (goto-char
  14720. (org-element-property :end link))
  14721. (skip-chars-backward " \t")
  14722. (point)))))
  14723. (overlay-put ov 'display image)
  14724. (overlay-put ov 'face 'default)
  14725. (overlay-put ov 'org-image-overlay t)
  14726. (overlay-put
  14727. ov 'modification-hooks
  14728. (list 'org-display-inline-remove-overlay))
  14729. (when (<= 26 emacs-major-version)
  14730. (cl-assert (boundp 'image-map))
  14731. (overlay-put ov 'keymap image-map))
  14732. (push ov org-inline-image-overlays))))))))))))))))
  14733. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14734. "Remove inline-display overlay if a corresponding region is modified."
  14735. (let ((inhibit-modification-hooks t))
  14736. (when (and ov after)
  14737. (delete ov org-inline-image-overlays)
  14738. (delete-overlay ov))))
  14739. (defun org-remove-inline-images ()
  14740. "Remove inline display of images."
  14741. (interactive)
  14742. (mapc #'delete-overlay org-inline-image-overlays)
  14743. (setq org-inline-image-overlays nil))
  14744. (defvar org-self-insert-command-undo-counter 0)
  14745. (defvar org-speed-command nil)
  14746. (defun org-self-insert-command (N)
  14747. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14748. If the cursor is in a table looking at whitespace, the whitespace is
  14749. overwritten, and the table is not marked as requiring realignment."
  14750. (interactive "p")
  14751. (org-check-before-invisible-edit 'insert)
  14752. (cond
  14753. ((and org-use-speed-commands
  14754. (let ((kv (this-command-keys-vector)))
  14755. (setq org-speed-command
  14756. (run-hook-with-args-until-success
  14757. 'org-speed-command-hook
  14758. (make-string 1 (aref kv (1- (length kv))))))))
  14759. (cond
  14760. ((commandp org-speed-command)
  14761. (setq this-command org-speed-command)
  14762. (call-interactively org-speed-command))
  14763. ((functionp org-speed-command)
  14764. (funcall org-speed-command))
  14765. ((and org-speed-command (listp org-speed-command))
  14766. (eval org-speed-command))
  14767. (t (let (org-use-speed-commands)
  14768. (call-interactively 'org-self-insert-command)))))
  14769. ((and
  14770. (= N 1)
  14771. (not (org-region-active-p))
  14772. (org-at-table-p)
  14773. (progn
  14774. ;; Check if we blank the field, and if that triggers align.
  14775. (and (featurep 'org-table)
  14776. org-table-auto-blank-field
  14777. (memq last-command
  14778. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14779. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14780. ;; Got extra space, this field does not determine
  14781. ;; column width.
  14782. (let (org-table-may-need-update) (org-table-blank-field))
  14783. ;; No extra space, this field may determine column
  14784. ;; width.
  14785. (org-table-blank-field)))
  14786. t)
  14787. (looking-at "[^|\n]* |"))
  14788. ;; There is room for insertion without re-aligning the table.
  14789. (self-insert-command N)
  14790. (org-table-with-shrunk-field
  14791. (save-excursion
  14792. (skip-chars-forward "^|")
  14793. ;; Do not delete last space, which is
  14794. ;; `org-table-separator-space', but the regular space before
  14795. ;; it.
  14796. (delete-region (- (point) 2) (1- (point))))))
  14797. (t
  14798. (setq org-table-may-need-update t)
  14799. (self-insert-command N)
  14800. (org-fix-tags-on-the-fly)
  14801. (when org-self-insert-cluster-for-undo
  14802. (if (not (eq last-command 'org-self-insert-command))
  14803. (setq org-self-insert-command-undo-counter 1)
  14804. (if (>= org-self-insert-command-undo-counter 20)
  14805. (setq org-self-insert-command-undo-counter 1)
  14806. (and (> org-self-insert-command-undo-counter 0)
  14807. buffer-undo-list (listp buffer-undo-list)
  14808. (not (cadr buffer-undo-list)) ; remove nil entry
  14809. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14810. (setq org-self-insert-command-undo-counter
  14811. (1+ org-self-insert-command-undo-counter))))))))
  14812. (defun org-check-before-invisible-edit (kind)
  14813. "Check is editing if kind KIND would be dangerous with invisible text around.
  14814. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  14815. ;; First, try to get out of here as quickly as possible, to reduce overhead
  14816. (when (and org-catch-invisible-edits
  14817. (or (not (boundp 'visible-mode)) (not visible-mode))
  14818. (or (get-char-property (point) 'invisible)
  14819. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  14820. ;; OK, we need to take a closer look. Do not consider
  14821. ;; invisibility obtained through text properties (e.g., link
  14822. ;; fontification), as it cannot be toggled.
  14823. (let* ((invisible-at-point
  14824. (pcase (get-char-property-and-overlay (point) 'invisible)
  14825. (`(,_ . ,(and (pred overlayp) o)) o)))
  14826. ;; Assume that point cannot land in the middle of an
  14827. ;; overlay, or between two overlays.
  14828. (invisible-before-point
  14829. (and (not invisible-at-point)
  14830. (not (bobp))
  14831. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  14832. (`(,_ . ,(and (pred overlayp) o)) o))))
  14833. (border-and-ok-direction
  14834. (or
  14835. ;; Check if we are acting predictably before invisible
  14836. ;; text.
  14837. (and invisible-at-point
  14838. (memq kind '(insert delete-backward)))
  14839. ;; Check if we are acting predictably after invisible text
  14840. ;; This works not well, and I have turned it off. It seems
  14841. ;; better to always show and stop after invisible text.
  14842. ;; (and (not invisible-at-point) invisible-before-point
  14843. ;; (memq kind '(insert delete)))
  14844. )))
  14845. (when (or invisible-at-point invisible-before-point)
  14846. (when (eq org-catch-invisible-edits 'error)
  14847. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  14848. (if (and org-custom-properties-overlays
  14849. (y-or-n-p "Display invisible properties in this buffer? "))
  14850. (org-toggle-custom-properties-visibility)
  14851. ;; Make the area visible
  14852. (save-excursion
  14853. (when invisible-before-point
  14854. (goto-char
  14855. (previous-single-char-property-change (point) 'invisible)))
  14856. ;; Remove whatever overlay is currently making yet-to-be
  14857. ;; edited text invisible. Also remove nested invisibility
  14858. ;; related overlays.
  14859. (delete-overlay (or invisible-at-point invisible-before-point))
  14860. (let ((origin (if invisible-at-point (point) (1- (point)))))
  14861. (while (pcase (get-char-property-and-overlay origin 'invisible)
  14862. (`(,_ . ,(and (pred overlayp) o))
  14863. (delete-overlay o)
  14864. t)))))
  14865. (cond
  14866. ((eq org-catch-invisible-edits 'show)
  14867. ;; That's it, we do the edit after showing
  14868. (message
  14869. "Unfolding invisible region around point before editing")
  14870. (sit-for 1))
  14871. ((and (eq org-catch-invisible-edits 'smart)
  14872. border-and-ok-direction)
  14873. (message "Unfolding invisible region around point before editing"))
  14874. (t
  14875. ;; Don't do the edit, make the user repeat it in full visibility
  14876. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  14877. (defun org-fix-tags-on-the-fly ()
  14878. "Align tags in headline at point.
  14879. Unlike `org-align-tags', this function does nothing if point is
  14880. either not currently on a tagged headline or on a tag."
  14881. (when (and (org-match-line org-tag-line-re)
  14882. (< (point) (match-beginning 1)))
  14883. (org-align-tags)))
  14884. (defun org-delete-backward-char (N)
  14885. "Like `delete-backward-char', insert whitespace at field end in tables.
  14886. When deleting backwards, in tables this function will insert whitespace in
  14887. front of the next \"|\" separator, to keep the table aligned. The table will
  14888. still be marked for re-alignment if the field did fill the entire column,
  14889. because, in this case the deletion might narrow the column."
  14890. (interactive "p")
  14891. (save-match-data
  14892. (org-check-before-invisible-edit 'delete-backward)
  14893. (if (and (= N 1)
  14894. (not overwrite-mode)
  14895. (not (org-region-active-p))
  14896. (not (eq (char-before) ?|))
  14897. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14898. (looking-at-p ".*?|")
  14899. (org-at-table-p))
  14900. (progn (forward-char -1) (org-delete-char 1))
  14901. (backward-delete-char N)
  14902. (org-fix-tags-on-the-fly))))
  14903. (defun org-delete-char (N)
  14904. "Like `delete-char', but insert whitespace at field end in tables.
  14905. When deleting characters, in tables this function will insert whitespace in
  14906. front of the next \"|\" separator, to keep the table aligned. The table will
  14907. still be marked for re-alignment if the field did fill the entire column,
  14908. because, in this case the deletion might narrow the column."
  14909. (interactive "p")
  14910. (save-match-data
  14911. (org-check-before-invisible-edit 'delete)
  14912. (cond
  14913. ((or (/= N 1)
  14914. (eq (char-after) ?|)
  14915. (save-excursion (skip-chars-backward " \t") (bolp))
  14916. (not (org-at-table-p)))
  14917. (delete-char N)
  14918. (org-fix-tags-on-the-fly))
  14919. ((looking-at ".\\(.*?\\)|")
  14920. (let* ((update? org-table-may-need-update)
  14921. (noalign (looking-at-p ".*? |")))
  14922. (delete-char 1)
  14923. (org-table-with-shrunk-field
  14924. (save-excursion
  14925. ;; Last space is `org-table-separator-space', so insert
  14926. ;; a regular one before it instead.
  14927. (goto-char (- (match-end 0) 2))
  14928. (insert " ")))
  14929. ;; If there were two spaces at the end, this field does not
  14930. ;; determine the width of the column.
  14931. (when noalign (setq org-table-may-need-update update?))))
  14932. (t
  14933. (delete-char N)))))
  14934. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14935. (put 'org-self-insert-command 'delete-selection
  14936. (lambda ()
  14937. (not (run-hook-with-args-until-success
  14938. 'self-insert-uses-region-functions))))
  14939. (put 'orgtbl-self-insert-command 'delete-selection
  14940. (lambda ()
  14941. (not (run-hook-with-args-until-success
  14942. 'self-insert-uses-region-functions))))
  14943. (put 'org-delete-char 'delete-selection 'supersede)
  14944. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14945. (put 'org-yank 'delete-selection 'yank)
  14946. ;; Make `flyspell-mode' delay after some commands
  14947. (put 'org-self-insert-command 'flyspell-delayed t)
  14948. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14949. (put 'org-delete-char 'flyspell-delayed t)
  14950. (put 'org-delete-backward-char 'flyspell-delayed t)
  14951. ;; Make pabbrev-mode expand after Org mode commands
  14952. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14953. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14954. (defun org-transpose-words ()
  14955. "Transpose words for Org.
  14956. This uses the `org-mode-transpose-word-syntax-table' syntax
  14957. table, which interprets characters in `org-emphasis-alist' as
  14958. word constituents."
  14959. (interactive)
  14960. (with-syntax-table org-mode-transpose-word-syntax-table
  14961. (call-interactively 'transpose-words)))
  14962. (defvar org-ctrl-c-ctrl-c-hook nil
  14963. "Hook for functions attaching themselves to `C-c C-c'.
  14964. This can be used to add additional functionality to the C-c C-c
  14965. key which executes context-dependent commands. This hook is run
  14966. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14967. run after the last test.
  14968. Each function will be called with no arguments. The function
  14969. must check if the context is appropriate for it to act. If yes,
  14970. it should do its thing and then return a non-nil value. If the
  14971. context is wrong, just do nothing and return nil.")
  14972. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14973. "Hook for functions attaching themselves to `C-c C-c'.
  14974. This can be used to add additional functionality to the C-c C-c
  14975. key which executes context-dependent commands. This hook is run
  14976. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14977. before the first test.
  14978. Each function will be called with no arguments. The function
  14979. must check if the context is appropriate for it to act. If yes,
  14980. it should do its thing and then return a non-nil value. If the
  14981. context is wrong, just do nothing and return nil.")
  14982. (defvar org-tab-first-hook nil
  14983. "Hook for functions to attach themselves to TAB.
  14984. See `org-ctrl-c-ctrl-c-hook' for more information.
  14985. This hook runs as the first action when TAB is pressed, even before
  14986. `org-cycle' messes around with the `outline-regexp' to cater for
  14987. inline tasks and plain list item folding.
  14988. If any function in this hook returns t, any other actions that
  14989. would have been caused by TAB (such as table field motion or visibility
  14990. cycling) will not occur.")
  14991. (defvar org-tab-after-check-for-table-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 it has been established that the cursor is not in a
  14995. table, but before checking if the cursor is in a headline or if global cycling
  14996. should be done.
  14997. If any function in this hook returns t, not other actions like visibility
  14998. cycling will be done.")
  14999. (defvar org-tab-after-check-for-cycling-hook nil
  15000. "Hook for functions to attach themselves to TAB.
  15001. See `org-ctrl-c-ctrl-c-hook' for more information.
  15002. This hook runs after it has been established that not table field motion and
  15003. not visibility should be done because of current context. This is probably
  15004. the place where a package like yasnippets can hook in.")
  15005. (defvar org-tab-before-tab-emulation-hook nil
  15006. "Hook for functions to attach themselves to TAB.
  15007. See `org-ctrl-c-ctrl-c-hook' for more information.
  15008. This hook runs after every other options for TAB have been exhausted, but
  15009. before indentation and \t insertion takes place.")
  15010. (defvar org-metaleft-hook nil
  15011. "Hook for functions attaching themselves to `M-left'.
  15012. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15013. (defvar org-metaright-hook nil
  15014. "Hook for functions attaching themselves to `M-right'.
  15015. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15016. (defvar org-metaup-hook nil
  15017. "Hook for functions attaching themselves to `M-up'.
  15018. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15019. (defvar org-metadown-hook nil
  15020. "Hook for functions attaching themselves to `M-down'.
  15021. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15022. (defvar org-shiftmetaleft-hook nil
  15023. "Hook for functions attaching themselves to `M-S-left'.
  15024. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15025. (defvar org-shiftmetaright-hook nil
  15026. "Hook for functions attaching themselves to `M-S-right'.
  15027. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15028. (defvar org-shiftmetaup-hook nil
  15029. "Hook for functions attaching themselves to `M-S-up'.
  15030. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15031. (defvar org-shiftmetadown-hook nil
  15032. "Hook for functions attaching themselves to `M-S-down'.
  15033. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15034. (defvar org-metareturn-hook nil
  15035. "Hook for functions attaching themselves to `M-RET'.
  15036. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15037. (defvar org-shiftup-hook nil
  15038. "Hook for functions attaching themselves to `S-up'.
  15039. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15040. (defvar org-shiftup-final-hook nil
  15041. "Hook for functions attaching themselves to `S-up'.
  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-shiftdown-hook nil
  15045. "Hook for functions attaching themselves to `S-down'.
  15046. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15047. (defvar org-shiftdown-final-hook nil
  15048. "Hook for functions attaching themselves to `S-down'.
  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. (defvar org-shiftleft-hook nil
  15052. "Hook for functions attaching themselves to `S-left'.
  15053. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15054. (defvar org-shiftleft-final-hook nil
  15055. "Hook for functions attaching themselves to `S-left'.
  15056. This one runs after all other options except shift-select have been excluded.
  15057. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15058. (defvar org-shiftright-hook nil
  15059. "Hook for functions attaching themselves to `S-right'.
  15060. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15061. (defvar org-shiftright-final-hook nil
  15062. "Hook for functions attaching themselves to `S-right'.
  15063. This one runs after all other options except shift-select have been excluded.
  15064. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15065. (defun org-modifier-cursor-error ()
  15066. "Throw an error, a modified cursor command was applied in wrong context."
  15067. (user-error "This command is active in special context like tables, headlines or items"))
  15068. (defun org-shiftselect-error ()
  15069. "Throw an error because Shift-Cursor command was applied in wrong context."
  15070. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15071. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15072. (user-error "This command works only in special context like headlines or timestamps")))
  15073. (defun org-call-for-shift-select (cmd)
  15074. (let ((this-command-keys-shift-translated t))
  15075. (call-interactively cmd)))
  15076. (defun org-shifttab (&optional arg)
  15077. "Global visibility cycling or move to previous table field.
  15078. Call `org-table-previous-field' within a table.
  15079. When ARG is nil, cycle globally through visibility states.
  15080. When ARG is a numeric prefix, show contents of this level."
  15081. (interactive "P")
  15082. (cond
  15083. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15084. ((integerp arg)
  15085. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15086. (message "Content view to level: %d" arg)
  15087. (org-content (prefix-numeric-value arg2))
  15088. (org-cycle-show-empty-lines t)
  15089. (setq org-cycle-global-status 'overview)))
  15090. (t (call-interactively 'org-global-cycle))))
  15091. (defun org-shiftmetaleft ()
  15092. "Promote subtree or delete table column.
  15093. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15094. `org-table-delete-column', depending on context. See the
  15095. individual commands for more information."
  15096. (interactive)
  15097. (cond
  15098. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15099. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15100. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15101. ((if (not (org-region-active-p)) (org-at-item-p)
  15102. (save-excursion (goto-char (region-beginning))
  15103. (org-at-item-p)))
  15104. (call-interactively 'org-outdent-item-tree))
  15105. (t (org-modifier-cursor-error))))
  15106. (defun org-shiftmetaright ()
  15107. "Demote subtree or insert table column.
  15108. Calls `org-demote-subtree', `org-indent-item-tree', or
  15109. `org-table-insert-column', depending on context. See the
  15110. individual commands for more information."
  15111. (interactive)
  15112. (cond
  15113. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15114. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15115. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15116. ((if (not (org-region-active-p)) (org-at-item-p)
  15117. (save-excursion (goto-char (region-beginning))
  15118. (org-at-item-p)))
  15119. (call-interactively 'org-indent-item-tree))
  15120. (t (org-modifier-cursor-error))))
  15121. (defun org-shiftmetaup (&optional _arg)
  15122. "Drag the line at point up.
  15123. In a table, kill the current row.
  15124. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15125. but also adjust the previous clocked item in the clock history.
  15126. Everywhere else, drag the line at point up."
  15127. (interactive "P")
  15128. (cond
  15129. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15130. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15131. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15132. (call-interactively 'org-timestamp-up)))
  15133. (t (call-interactively 'org-drag-line-backward))))
  15134. (defun org-shiftmetadown (&optional _arg)
  15135. "Drag the line at point down.
  15136. In a table, insert an empty row at the current line.
  15137. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15138. but also adjust the previous clocked item in the clock history.
  15139. Everywhere else, drag the line at point down."
  15140. (interactive "P")
  15141. (cond
  15142. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15143. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15144. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15145. (call-interactively 'org-timestamp-down)))
  15146. (t (call-interactively 'org-drag-line-forward))))
  15147. (defsubst org-hidden-tree-error ()
  15148. (user-error
  15149. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15150. (defun org-metaleft (&optional _arg)
  15151. "Promote heading, list item at point or move table column left.
  15152. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15153. depending on context. With no specific context, calls the Emacs
  15154. default `backward-word'. See the individual commands for more
  15155. information.
  15156. This function runs the hook `org-metaleft-hook' as a first step,
  15157. and returns at first non-nil value."
  15158. (interactive "P")
  15159. (cond
  15160. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15161. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15162. ((org-with-limited-levels
  15163. (or (org-at-heading-p)
  15164. (and (org-region-active-p)
  15165. (save-excursion
  15166. (goto-char (region-beginning))
  15167. (org-at-heading-p)))))
  15168. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15169. (call-interactively 'org-do-promote))
  15170. ;; At an inline task.
  15171. ((org-at-heading-p)
  15172. (call-interactively 'org-inlinetask-promote))
  15173. ((or (org-at-item-p)
  15174. (and (org-region-active-p)
  15175. (save-excursion
  15176. (goto-char (region-beginning))
  15177. (org-at-item-p))))
  15178. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15179. (call-interactively 'org-outdent-item))
  15180. (t (call-interactively 'backward-word))))
  15181. (defun org-metaright (&optional _arg)
  15182. "Demote heading, list item at point or move table column right.
  15183. In front of a drawer or a block keyword, indent it correctly.
  15184. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15185. `org-indent-drawer' or `org-indent-block' depending on context.
  15186. With no specific context, calls the Emacs default `forward-word'.
  15187. See the individual commands for more information.
  15188. This function runs the hook `org-metaright-hook' as a first step,
  15189. and returns at first non-nil value."
  15190. (interactive "P")
  15191. (cond
  15192. ((run-hook-with-args-until-success 'org-metaright-hook))
  15193. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15194. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15195. ((org-at-block-p) (call-interactively 'org-indent-block))
  15196. ((org-with-limited-levels
  15197. (or (org-at-heading-p)
  15198. (and (org-region-active-p)
  15199. (save-excursion
  15200. (goto-char (region-beginning))
  15201. (org-at-heading-p)))))
  15202. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15203. (call-interactively 'org-do-demote))
  15204. ;; At an inline task.
  15205. ((org-at-heading-p)
  15206. (call-interactively 'org-inlinetask-demote))
  15207. ((or (org-at-item-p)
  15208. (and (org-region-active-p)
  15209. (save-excursion
  15210. (goto-char (region-beginning))
  15211. (org-at-item-p))))
  15212. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15213. (call-interactively 'org-indent-item))
  15214. (t (call-interactively 'forward-word))))
  15215. (defun org-check-for-hidden (what)
  15216. "Check if there are hidden headlines/items in the current visual line.
  15217. WHAT can be either `headlines' or `items'. If the current line is
  15218. an outline or item heading and it has a folded subtree below it,
  15219. this function returns t, nil otherwise."
  15220. (let ((re (cond
  15221. ((eq what 'headlines) org-outline-regexp-bol)
  15222. ((eq what 'items) (org-item-beginning-re))
  15223. (t (error "This should not happen"))))
  15224. beg end)
  15225. (save-excursion
  15226. (catch 'exit
  15227. (unless (org-region-active-p)
  15228. (setq beg (point-at-bol))
  15229. (beginning-of-line 2)
  15230. (while (and (not (eobp)) ;; this is like `next-line'
  15231. (get-char-property (1- (point)) 'invisible))
  15232. (beginning-of-line 2))
  15233. (setq end (point))
  15234. (goto-char beg)
  15235. (goto-char (point-at-eol))
  15236. (setq end (max end (point)))
  15237. (while (re-search-forward re end t)
  15238. (when (get-char-property (match-beginning 0) 'invisible)
  15239. (throw 'exit t))))
  15240. nil))))
  15241. (defun org-metaup (&optional _arg)
  15242. "Move subtree up or move table row up.
  15243. Calls `org-move-subtree-up' or `org-table-move-row' or
  15244. `org-move-item-up', depending on context. See the individual commands
  15245. for more information."
  15246. (interactive "P")
  15247. (cond
  15248. ((run-hook-with-args-until-success 'org-metaup-hook))
  15249. ((org-region-active-p)
  15250. (let* ((a (save-excursion
  15251. (goto-char (min (region-beginning) (region-end)))
  15252. (line-beginning-position)))
  15253. (b (save-excursion
  15254. (goto-char (max (region-beginning) (region-end)))
  15255. (if (bolp) (1- (point)) (line-end-position))))
  15256. (c (save-excursion
  15257. (goto-char a)
  15258. (move-beginning-of-line 0)
  15259. (point)))
  15260. (d (save-excursion
  15261. (goto-char a)
  15262. (move-end-of-line 0)
  15263. (point))))
  15264. (transpose-regions a b c d)
  15265. (goto-char c)))
  15266. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15267. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15268. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15269. (t (org-drag-element-backward))))
  15270. (defun org-metadown (&optional _arg)
  15271. "Move subtree down or move table row down.
  15272. Calls `org-move-subtree-down' or `org-table-move-row' or
  15273. `org-move-item-down', depending on context. See the individual
  15274. commands for more information."
  15275. (interactive "P")
  15276. (cond
  15277. ((run-hook-with-args-until-success 'org-metadown-hook))
  15278. ((org-region-active-p)
  15279. (let* ((a (save-excursion
  15280. (goto-char (min (region-beginning) (region-end)))
  15281. (line-beginning-position)))
  15282. (b (save-excursion
  15283. (goto-char (max (region-beginning) (region-end)))
  15284. (if (bolp) (1- (point)) (line-end-position))))
  15285. (c (save-excursion
  15286. (goto-char b)
  15287. (move-beginning-of-line (if (bolp) 1 2))
  15288. (point)))
  15289. (d (save-excursion
  15290. (goto-char b)
  15291. (move-end-of-line (if (bolp) 1 2))
  15292. (point))))
  15293. (transpose-regions a b c d)
  15294. (goto-char d)))
  15295. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15296. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15297. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15298. (t (org-drag-element-forward))))
  15299. (defun org-shiftup (&optional arg)
  15300. "Act on current element according to context.
  15301. Call `org-timestamp-up' or `org-priority-up', or
  15302. `org-previous-item', or `org-table-move-cell-up'. See the
  15303. individual commands for more information."
  15304. (interactive "P")
  15305. (cond
  15306. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15307. ((and org-support-shift-select (org-region-active-p))
  15308. (org-call-for-shift-select 'previous-line))
  15309. ((org-at-timestamp-p 'lax)
  15310. (call-interactively (if org-edit-timestamp-down-means-later
  15311. 'org-timestamp-down 'org-timestamp-up)))
  15312. ((and (not (eq org-support-shift-select 'always))
  15313. org-priority-enable-commands
  15314. (org-at-heading-p))
  15315. (call-interactively 'org-priority-up))
  15316. ((and (not org-support-shift-select) (org-at-item-p))
  15317. (call-interactively 'org-previous-item))
  15318. ((org-clocktable-try-shift 'up arg))
  15319. ((org-at-table-p) (org-table-move-cell-up))
  15320. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15321. (org-support-shift-select
  15322. (org-call-for-shift-select 'previous-line))
  15323. (t (org-shiftselect-error))))
  15324. (defun org-shiftdown (&optional arg)
  15325. "Act on current element according to context.
  15326. Call `org-timestamp-down' or `org-priority-down', or
  15327. `org-next-item', or `org-table-move-cell-down'. See the
  15328. individual commands for more information."
  15329. (interactive "P")
  15330. (cond
  15331. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15332. ((and org-support-shift-select (org-region-active-p))
  15333. (org-call-for-shift-select 'next-line))
  15334. ((org-at-timestamp-p 'lax)
  15335. (call-interactively (if org-edit-timestamp-down-means-later
  15336. 'org-timestamp-up 'org-timestamp-down)))
  15337. ((and (not (eq org-support-shift-select 'always))
  15338. org-priority-enable-commands
  15339. (org-at-heading-p))
  15340. (call-interactively 'org-priority-down))
  15341. ((and (not org-support-shift-select) (org-at-item-p))
  15342. (call-interactively 'org-next-item))
  15343. ((org-clocktable-try-shift 'down arg))
  15344. ((org-at-table-p) (org-table-move-cell-down))
  15345. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15346. (org-support-shift-select
  15347. (org-call-for-shift-select 'next-line))
  15348. (t (org-shiftselect-error))))
  15349. (defun org-shiftright (&optional arg)
  15350. "Act on the current element according to context.
  15351. This does one of the following:
  15352. - switch a timestamp at point one day into the future
  15353. - on a headline, switch to the next TODO keyword
  15354. - on an item, switch entire list to the next bullet type
  15355. - on a property line, switch to the next allowed value
  15356. - on a clocktable definition line, move time block into the future
  15357. - in a table, move a single cell right"
  15358. (interactive "P")
  15359. (cond
  15360. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15361. ((and org-support-shift-select (org-region-active-p))
  15362. (org-call-for-shift-select 'forward-char))
  15363. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15364. ((and (not (eq org-support-shift-select 'always))
  15365. (org-at-heading-p))
  15366. (let ((org-inhibit-logging
  15367. (not org-treat-S-cursor-todo-selection-as-state-change))
  15368. (org-inhibit-blocking
  15369. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15370. (org-call-with-arg 'org-todo 'right)))
  15371. ((or (and org-support-shift-select
  15372. (not (eq org-support-shift-select 'always))
  15373. (org-at-item-bullet-p))
  15374. (and (not org-support-shift-select) (org-at-item-p)))
  15375. (org-call-with-arg 'org-cycle-list-bullet nil))
  15376. ((and (not (eq org-support-shift-select 'always))
  15377. (org-at-property-p))
  15378. (call-interactively 'org-property-next-allowed-value))
  15379. ((org-clocktable-try-shift 'right arg))
  15380. ((org-at-table-p) (org-table-move-cell-right))
  15381. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15382. (org-support-shift-select
  15383. (org-call-for-shift-select 'forward-char))
  15384. (t (org-shiftselect-error))))
  15385. (defun org-shiftleft (&optional arg)
  15386. "Act on current element according to context.
  15387. This does one of the following:
  15388. - switch a timestamp at point one day into the past
  15389. - on a headline, switch to the previous TODO keyword.
  15390. - on an item, switch entire list to the previous bullet type
  15391. - on a property line, switch to the previous allowed value
  15392. - on a clocktable definition line, move time block into the past
  15393. - in a table, move a single cell left"
  15394. (interactive "P")
  15395. (cond
  15396. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15397. ((and org-support-shift-select (org-region-active-p))
  15398. (org-call-for-shift-select 'backward-char))
  15399. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15400. ((and (not (eq org-support-shift-select 'always))
  15401. (org-at-heading-p))
  15402. (let ((org-inhibit-logging
  15403. (not org-treat-S-cursor-todo-selection-as-state-change))
  15404. (org-inhibit-blocking
  15405. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15406. (org-call-with-arg 'org-todo 'left)))
  15407. ((or (and org-support-shift-select
  15408. (not (eq org-support-shift-select 'always))
  15409. (org-at-item-bullet-p))
  15410. (and (not org-support-shift-select) (org-at-item-p)))
  15411. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15412. ((and (not (eq org-support-shift-select 'always))
  15413. (org-at-property-p))
  15414. (call-interactively 'org-property-previous-allowed-value))
  15415. ((org-clocktable-try-shift 'left arg))
  15416. ((org-at-table-p) (org-table-move-cell-left))
  15417. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15418. (org-support-shift-select
  15419. (org-call-for-shift-select 'backward-char))
  15420. (t (org-shiftselect-error))))
  15421. (defun org-shiftcontrolright ()
  15422. "Switch to next TODO set."
  15423. (interactive)
  15424. (cond
  15425. ((and org-support-shift-select (org-region-active-p))
  15426. (org-call-for-shift-select 'forward-word))
  15427. ((and (not (eq org-support-shift-select 'always))
  15428. (org-at-heading-p))
  15429. (org-call-with-arg 'org-todo 'nextset))
  15430. (org-support-shift-select
  15431. (org-call-for-shift-select 'forward-word))
  15432. (t (org-shiftselect-error))))
  15433. (defun org-shiftcontrolleft ()
  15434. "Switch to previous TODO set."
  15435. (interactive)
  15436. (cond
  15437. ((and org-support-shift-select (org-region-active-p))
  15438. (org-call-for-shift-select 'backward-word))
  15439. ((and (not (eq org-support-shift-select 'always))
  15440. (org-at-heading-p))
  15441. (org-call-with-arg 'org-todo 'previousset))
  15442. (org-support-shift-select
  15443. (org-call-for-shift-select 'backward-word))
  15444. (t (org-shiftselect-error))))
  15445. (defun org-shiftcontrolup (&optional n)
  15446. "Change timestamps synchronously up in CLOCK log lines.
  15447. Optional argument N tells to change by that many units."
  15448. (interactive "P")
  15449. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15450. (let (org-support-shift-select)
  15451. (org-clock-timestamps-up n))
  15452. (user-error "Not at a clock log")))
  15453. (defun org-shiftcontroldown (&optional n)
  15454. "Change timestamps synchronously down in CLOCK log lines.
  15455. Optional argument N tells to change by that many units."
  15456. (interactive "P")
  15457. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15458. (let (org-support-shift-select)
  15459. (org-clock-timestamps-down n))
  15460. (user-error "Not at a clock log")))
  15461. (defun org-increase-number-at-point (&optional inc)
  15462. "Increment the number at point.
  15463. With an optional prefix numeric argument INC, increment using
  15464. this numeric value."
  15465. (interactive "p")
  15466. (if (not (number-at-point))
  15467. (user-error "Not on a number")
  15468. (unless inc (setq inc 1))
  15469. (let ((pos (point))
  15470. (beg (skip-chars-backward "-+^/*0-9eE."))
  15471. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15472. (setq nap (buffer-substring-no-properties
  15473. (+ pos beg) (+ pos beg end)))
  15474. (delete-region (+ pos beg) (+ pos beg end))
  15475. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15476. (when (org-at-table-p)
  15477. (org-table-align)
  15478. (org-table-end-of-field 1))))
  15479. (defun org-decrease-number-at-point (&optional inc)
  15480. "Decrement the number at point.
  15481. With an optional prefix numeric argument INC, decrement using
  15482. this numeric value."
  15483. (interactive "p")
  15484. (org-increase-number-at-point (- (or inc 1))))
  15485. (defun org-ctrl-c-ret ()
  15486. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  15487. (interactive)
  15488. (cond
  15489. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15490. (t (call-interactively 'org-insert-heading))))
  15491. (defun org-copy-visible (beg end)
  15492. "Copy the visible parts of the region."
  15493. (interactive "r")
  15494. (let ((result ""))
  15495. (while (/= beg end)
  15496. (when (get-char-property beg 'invisible)
  15497. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15498. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15499. (setq result (concat result (buffer-substring beg next)))
  15500. (setq beg next)))
  15501. (setq deactivate-mark t)
  15502. (kill-new result)
  15503. (message "Visible strings have been copied to the kill ring.")))
  15504. (defun org-copy-special ()
  15505. "Copy region in table or copy current subtree.
  15506. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15507. context. See the individual commands for more information."
  15508. (interactive)
  15509. (call-interactively
  15510. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15511. (defun org-cut-special ()
  15512. "Cut region in table or cut current subtree.
  15513. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15514. context. See the individual commands for more information."
  15515. (interactive)
  15516. (call-interactively
  15517. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15518. (defun org-paste-special (arg)
  15519. "Paste rectangular region into table, or past subtree relative to level.
  15520. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15521. See the individual commands for more information."
  15522. (interactive "P")
  15523. (if (org-at-table-p)
  15524. (org-table-paste-rectangle)
  15525. (org-paste-subtree arg)))
  15526. (defun org-edit-special (&optional arg)
  15527. "Call a special editor for the element at point.
  15528. When at a table, call the formula editor with `org-table-edit-formulas'.
  15529. When in a source code block, call `org-edit-src-code'.
  15530. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15531. When in an export block, call `org-edit-export-block'.
  15532. When in a LaTeX environment, call `org-edit-latex-environment'.
  15533. When at an #+INCLUDE keyword, visit the included file.
  15534. When at a footnote reference, call `org-edit-footnote-reference'.
  15535. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15536. When at an active timestamp, call `org-time-stamp'.
  15537. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15538. On a link, call `ffap' to visit the link at point.
  15539. Otherwise, return a user error."
  15540. (interactive "P")
  15541. (let ((element (org-element-at-point)))
  15542. (barf-if-buffer-read-only)
  15543. (pcase (org-element-type element)
  15544. (`src-block
  15545. (if (not arg) (org-edit-src-code)
  15546. (let* ((info (org-babel-get-src-block-info))
  15547. (lang (nth 0 info))
  15548. (params (nth 2 info))
  15549. (session (cdr (assq :session params))))
  15550. (if (not session) (org-edit-src-code)
  15551. ;; At a source block with a session and function called
  15552. ;; with an ARG: switch to the buffer related to the
  15553. ;; inferior process.
  15554. (switch-to-buffer
  15555. (funcall (intern (concat "org-babel-prep-session:" lang))
  15556. session params))))))
  15557. (`keyword
  15558. (unless (member (org-element-property :key element)
  15559. '("INCLUDE" "SETUPFILE"))
  15560. (user-error "No special environment to edit here"))
  15561. (let ((value (org-element-property :value element)))
  15562. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15563. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15564. (or (match-string 1 value)
  15565. (match-string 0 value)))))
  15566. (when (org-file-url-p file)
  15567. (user-error "Files located with a URL cannot be edited"))
  15568. (org-link-open-from-string
  15569. (format "[[%s]]" (expand-file-name file))))))
  15570. (`table
  15571. (if (eq (org-element-property :type element) 'table.el)
  15572. (org-edit-table.el)
  15573. (call-interactively 'org-table-edit-formulas)))
  15574. ;; Only Org tables contain `table-row' type elements.
  15575. (`table-row (call-interactively 'org-table-edit-formulas))
  15576. (`example-block (org-edit-src-code))
  15577. (`export-block (org-edit-export-block))
  15578. (`fixed-width (org-edit-fixed-width-region))
  15579. (`latex-environment (org-edit-latex-environment))
  15580. (`planning
  15581. (let ((proplist (cadr element)))
  15582. (mapc #'call-interactively
  15583. (remq nil
  15584. (list
  15585. (when (plist-get proplist :deadline) #'org-deadline)
  15586. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15587. (_
  15588. ;; No notable element at point. Though, we may be at a link or
  15589. ;; a footnote reference, which are objects. Thus, scan deeper.
  15590. (let ((context (org-element-context element)))
  15591. (pcase (org-element-type context)
  15592. (`footnote-reference (org-edit-footnote-reference))
  15593. (`inline-src-block (org-edit-inline-src-code))
  15594. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15595. (call-interactively #'org-time-stamp-inactive)
  15596. (call-interactively #'org-time-stamp)))
  15597. (`link (call-interactively #'ffap))
  15598. (_ (user-error "No special environment to edit here"))))))))
  15599. (defun org-ctrl-c-ctrl-c (&optional arg)
  15600. "Set tags in headline, or update according to changed information at point.
  15601. This command does many different things, depending on context:
  15602. - If column view is active, in agenda or org buffers, quit it.
  15603. - If there are highlights, remove them.
  15604. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15605. this is what we do.
  15606. - If the cursor is on a statistics cookie, update it.
  15607. - If the cursor is in a headline, in an agenda or an org buffer,
  15608. prompt for tags and insert them into the current line, aligned
  15609. to `org-tags-column'. When called with prefix arg, realign all
  15610. tags in the current buffer.
  15611. - If the cursor is in one of the special #+KEYWORD lines, this
  15612. triggers scanning the buffer for these lines and updating the
  15613. information.
  15614. - If the cursor is inside a table, realign the table. This command
  15615. works even if the automatic table editor has been turned off.
  15616. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15617. the entire table.
  15618. - If the cursor is at a footnote reference or definition, jump to
  15619. the corresponding definition or references, respectively.
  15620. - If the cursor is a the beginning of a dynamic block, update it.
  15621. - If the current buffer is a capture buffer, close note and file it.
  15622. - If the cursor is on a <<<target>>>, update radio targets and
  15623. corresponding links in this buffer.
  15624. - If the cursor is on a numbered item in a plain list, renumber the
  15625. ordered list.
  15626. - If the cursor is on a checkbox, toggle it.
  15627. - If the cursor is on a code block, evaluate it. The variable
  15628. `org-confirm-babel-evaluate' can be used to control prompting
  15629. before code block evaluation, by default every code block
  15630. evaluation requires confirmation. Code block evaluation can be
  15631. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15632. (interactive "P")
  15633. (cond
  15634. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15635. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15636. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15637. (org-remove-occur-highlights)
  15638. (message "Temporary highlights/overlays removed from current buffer"))
  15639. ((and (local-variable-p 'org-finish-function)
  15640. (fboundp org-finish-function))
  15641. (funcall org-finish-function))
  15642. ((org-babel-hash-at-point))
  15643. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15644. (t
  15645. (let* ((context
  15646. (org-element-lineage
  15647. (org-element-context)
  15648. ;; Limit to supported contexts.
  15649. '(babel-call clock dynamic-block footnote-definition
  15650. footnote-reference inline-babel-call inline-src-block
  15651. inlinetask item keyword node-property paragraph
  15652. plain-list planning property-drawer radio-target
  15653. src-block statistics-cookie table table-cell table-row
  15654. timestamp)
  15655. t))
  15656. (radio-list-p (org-at-radio-list-p))
  15657. (type (org-element-type context)))
  15658. ;; For convenience: at the first line of a paragraph on the same
  15659. ;; line as an item, apply function on that item instead.
  15660. (when (eq type 'paragraph)
  15661. (let ((parent (org-element-property :parent context)))
  15662. (when (and (eq (org-element-type parent) 'item)
  15663. (= (line-beginning-position)
  15664. (org-element-property :begin parent)))
  15665. (setq context parent)
  15666. (setq type 'item))))
  15667. ;; Act according to type of element or object at point.
  15668. ;;
  15669. ;; Do nothing on a blank line, except if it is contained in
  15670. ;; a source block. Hence, we first check if point is in such
  15671. ;; a block and then if it is at a blank line.
  15672. (pcase type
  15673. ((or `inline-src-block `src-block)
  15674. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15675. (org-babel-eval-wipe-error-buffer)
  15676. (org-babel-execute-src-block
  15677. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15678. ((guard (org-match-line "[ \t]*$"))
  15679. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15680. (user-error
  15681. (substitute-command-keys
  15682. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15683. ((or `babel-call `inline-babel-call)
  15684. (let ((info (org-babel-lob-get-info context)))
  15685. (when info (org-babel-execute-src-block nil info))))
  15686. (`clock (org-clock-update-time-maybe))
  15687. (`dynamic-block
  15688. (save-excursion
  15689. (goto-char (org-element-property :post-affiliated context))
  15690. (org-update-dblock)))
  15691. (`footnote-definition
  15692. (goto-char (org-element-property :post-affiliated context))
  15693. (call-interactively 'org-footnote-action))
  15694. (`footnote-reference (call-interactively #'org-footnote-action))
  15695. ((or `headline `inlinetask)
  15696. (save-excursion (goto-char (org-element-property :begin context))
  15697. (call-interactively #'org-set-tags-command)))
  15698. (`item
  15699. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15700. ;; unconditionally, whereas `C-u' will toggle its presence.
  15701. ;; Without a universal argument, if the item has a checkbox,
  15702. ;; toggle it. Otherwise repair the list.
  15703. (if (or radio-list-p
  15704. (and (boundp org-list-checkbox-radio-mode)
  15705. org-list-checkbox-radio-mode))
  15706. (org-toggle-radio-button arg)
  15707. (let* ((box (org-element-property :checkbox context))
  15708. (struct (org-element-property :structure context))
  15709. (old-struct (copy-tree struct))
  15710. (parents (org-list-parents-alist struct))
  15711. (prevs (org-list-prevs-alist struct))
  15712. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15713. (org-list-set-checkbox
  15714. (org-element-property :begin context) struct
  15715. (cond ((equal arg '(16)) "[-]")
  15716. ((and (not box) (equal arg '(4))) "[ ]")
  15717. ((or (not box) (equal arg '(4))) nil)
  15718. ((eq box 'on) "[ ]")
  15719. (t "[X]")))
  15720. ;; Mimic `org-list-write-struct' but with grabbing a return
  15721. ;; value from `org-list-struct-fix-box'.
  15722. (org-list-struct-fix-ind struct parents 2)
  15723. (org-list-struct-fix-item-end struct)
  15724. (org-list-struct-fix-bul struct prevs)
  15725. (org-list-struct-fix-ind struct parents)
  15726. (let ((block-item
  15727. (org-list-struct-fix-box struct parents prevs orderedp)))
  15728. (if (and box (equal struct old-struct))
  15729. (if (equal arg '(16))
  15730. (message "Checkboxes already reset")
  15731. (user-error "Cannot toggle this checkbox: %s"
  15732. (if (eq box 'on)
  15733. "all subitems checked"
  15734. "unchecked subitems")))
  15735. (org-list-struct-apply-struct struct old-struct)
  15736. (org-update-checkbox-count-maybe))
  15737. (when block-item
  15738. (message "Checkboxes were removed due to empty box at line %d"
  15739. (org-current-line block-item)))))))
  15740. (`plain-list
  15741. ;; At a plain list, with a double C-u argument, set
  15742. ;; checkboxes of each item to "[-]", whereas a single one
  15743. ;; will toggle their presence according to the state of the
  15744. ;; first item in the list. Without an argument, repair the
  15745. ;; list.
  15746. (if (or radio-list-p
  15747. (and (boundp org-list-checkbox-radio-mode)
  15748. org-list-checkbox-radio-mode))
  15749. (org-toggle-radio-button arg)
  15750. (let* ((begin (org-element-property :contents-begin context))
  15751. (struct (org-element-property :structure context))
  15752. (old-struct (copy-tree struct))
  15753. (first-box (save-excursion
  15754. (goto-char begin)
  15755. (looking-at org-list-full-item-re)
  15756. (match-string-no-properties 3)))
  15757. (new-box (cond ((equal arg '(16)) "[-]")
  15758. ((equal arg '(4)) (unless first-box "[ ]"))
  15759. ((equal first-box "[X]") "[ ]")
  15760. (t "[X]"))))
  15761. (cond
  15762. (arg
  15763. (dolist (pos
  15764. (org-list-get-all-items
  15765. begin struct (org-list-prevs-alist struct)))
  15766. (org-list-set-checkbox pos struct new-box)))
  15767. ((and first-box (eq (point) begin))
  15768. ;; For convenience, when point is at bol on the first
  15769. ;; item of the list and no argument is provided, simply
  15770. ;; toggle checkbox of that item, if any.
  15771. (org-list-set-checkbox begin struct new-box)))
  15772. (when (equal
  15773. (org-list-write-struct
  15774. struct (org-list-parents-alist struct) old-struct)
  15775. old-struct)
  15776. (message "Cannot update this checkbox"))
  15777. (org-update-checkbox-count-maybe))))
  15778. (`keyword
  15779. (let ((org-inhibit-startup-visibility-stuff t)
  15780. (org-startup-align-all-tables nil))
  15781. (when (boundp 'org-table-coordinate-overlays)
  15782. (mapc #'delete-overlay org-table-coordinate-overlays)
  15783. (setq org-table-coordinate-overlays nil))
  15784. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15785. (message "Local setup has been refreshed"))
  15786. ((or `property-drawer `node-property)
  15787. (call-interactively #'org-property-action))
  15788. (`radio-target
  15789. (call-interactively #'org-update-radio-target-regexp))
  15790. (`statistics-cookie
  15791. (call-interactively #'org-update-statistics-cookies))
  15792. ((or `table `table-cell `table-row)
  15793. ;; At a table, recalculate every field and align it. Also
  15794. ;; send the table if necessary. If the table has
  15795. ;; a `table.el' type, just give up. At a table row or cell,
  15796. ;; maybe recalculate line but always align table.
  15797. (if (eq (org-element-property :type context) 'table.el)
  15798. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15799. Use `\\[org-edit-special]' to edit table.el tables"))
  15800. (if (or (eq type 'table)
  15801. ;; Check if point is at a TBLFM line.
  15802. (and (eq type 'table-row)
  15803. (= (point) (org-element-property :end context))))
  15804. (save-excursion
  15805. (if (org-at-TBLFM-p)
  15806. (progn (require 'org-table)
  15807. (org-table-calc-current-TBLFM))
  15808. (goto-char (org-element-property :contents-begin context))
  15809. (org-call-with-arg 'org-table-recalculate (or arg t))
  15810. (orgtbl-send-table 'maybe)))
  15811. (org-table-maybe-eval-formula)
  15812. (cond (arg (call-interactively #'org-table-recalculate))
  15813. ((org-table-maybe-recalculate-line))
  15814. (t (org-table-align))))))
  15815. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15816. (org-timestamp-change 0 'day))
  15817. ((and `nil (guard (org-at-heading-p)))
  15818. ;; When point is on an unsupported object type, we can miss
  15819. ;; the fact that it also is at a heading. Handle it here.
  15820. (call-interactively #'org-set-tags-command))
  15821. ((guard
  15822. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15823. (_
  15824. (user-error
  15825. (substitute-command-keys
  15826. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15827. (defun org-mode-restart ()
  15828. (interactive)
  15829. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15830. (funcall major-mode)
  15831. (hack-local-variables)
  15832. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15833. (org-indent-mode -1))
  15834. (org-reset-file-cache))
  15835. (message "%s restarted" major-mode))
  15836. (defun org-flag-above-first-heading (&optional arg)
  15837. "Hide from bob up to the first heading.
  15838. Move point to the beginning of first heading or end of buffer."
  15839. (goto-char (point-min))
  15840. (unless (org-at-heading-p)
  15841. (outline-next-heading))
  15842. (unless (bobp)
  15843. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  15844. (defun org-show-branches-buffer ()
  15845. "Show all branches in the buffer."
  15846. (org-flag-above-first-heading)
  15847. (outline-hide-sublevels 1)
  15848. (unless (eobp)
  15849. (outline-show-branches)
  15850. (while (outline-get-next-sibling)
  15851. (outline-show-branches)))
  15852. (goto-char (point-min)))
  15853. (defun org-kill-note-or-show-branches ()
  15854. "Abort storing current note, or show just branches."
  15855. (interactive)
  15856. (cond (org-finish-function
  15857. (let ((org-note-abort t)) (funcall org-finish-function)))
  15858. ((org-before-first-heading-p)
  15859. (org-show-branches-buffer)
  15860. (org-hide-archived-subtrees (point-min) (point-max)))
  15861. (t
  15862. (let ((beg (progn (org-back-to-heading) (point)))
  15863. (end (save-excursion (org-end-of-subtree t t) (point))))
  15864. (outline-hide-subtree)
  15865. (outline-show-branches)
  15866. (org-hide-archived-subtrees beg end)))))
  15867. (defun org-delete-indentation (&optional arg)
  15868. "Join current line to previous and fix whitespace at join.
  15869. If previous line is a headline add to headline title. Otherwise
  15870. the function calls `delete-indentation'.
  15871. With a non-nil optional argument, join it to the following one."
  15872. (interactive "*P")
  15873. (if (save-excursion
  15874. (beginning-of-line (if arg 1 0))
  15875. (let ((case-fold-search nil))
  15876. (looking-at org-complex-heading-regexp)))
  15877. ;; At headline.
  15878. (let ((tags-column (when (match-beginning 5)
  15879. (save-excursion (goto-char (match-beginning 5))
  15880. (current-column))))
  15881. (string (concat " " (progn (when arg (forward-line 1))
  15882. (org-trim (delete-and-extract-region
  15883. (line-beginning-position)
  15884. (line-end-position)))))))
  15885. (unless (bobp) (delete-region (point) (1- (point))))
  15886. (goto-char (or (match-end 4)
  15887. (match-beginning 5)
  15888. (match-end 0)))
  15889. (skip-chars-backward " \t")
  15890. (save-excursion (insert string))
  15891. ;; Adjust alignment of tags.
  15892. (cond
  15893. ((not tags-column)) ;no tags
  15894. (org-auto-align-tags (org-align-tags))
  15895. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15896. (delete-indentation arg)))
  15897. (defun org-open-line (n)
  15898. "Insert a new row in tables, call `open-line' elsewhere.
  15899. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15900. As a special case, when a document starts with a table, allow to
  15901. call `open-line' on the very first character."
  15902. (interactive "*p")
  15903. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15904. (org-table-insert-row)
  15905. (open-line n)))
  15906. (defun org-return (&optional indent)
  15907. "Goto next table row or insert a newline.
  15908. Calls `org-table-next-row' or `newline', depending on context.
  15909. When optional INDENT argument is non-nil, call
  15910. `newline-and-indent' instead of `newline'.
  15911. When `org-return-follows-link' is non-nil and point is on
  15912. a timestamp or a link, call `org-open-at-point'. However, it
  15913. will not happen if point is in a table or on a \"dead\"
  15914. object (e.g., within a comment). In these case, you need to use
  15915. `org-open-at-point' directly."
  15916. (interactive)
  15917. (let ((context (if org-return-follows-link (org-element-context)
  15918. (org-element-at-point))))
  15919. (cond
  15920. ;; In a table, call `org-table-next-row'. However, before first
  15921. ;; column or after last one, split the table.
  15922. ((or (and (eq 'table (org-element-type context))
  15923. (not (eq 'table.el (org-element-property :type context)))
  15924. (>= (point) (org-element-property :contents-begin context))
  15925. (< (point) (org-element-property :contents-end context)))
  15926. (org-element-lineage context '(table-row table-cell) t))
  15927. (if (or (looking-at-p "[ \t]*$")
  15928. (save-excursion (skip-chars-backward " \t") (bolp)))
  15929. (insert "\n")
  15930. (org-table-justify-field-maybe)
  15931. (call-interactively #'org-table-next-row)))
  15932. ;; On a link or a timestamp, call `org-open-at-point' if
  15933. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15934. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15935. ((and org-return-follows-link
  15936. (or (and (eq 'link (org-element-type context))
  15937. ;; Ensure point is not on the white spaces after
  15938. ;; the link.
  15939. (let ((origin (point)))
  15940. (org-with-point-at (org-element-property :end context)
  15941. (skip-chars-backward " \t")
  15942. (> (point) origin))))
  15943. (org-in-regexp org-ts-regexp-both nil t)
  15944. (org-in-regexp org-tsr-regexp-both nil t)
  15945. (org-in-regexp org-link-any-re nil t)))
  15946. (call-interactively #'org-open-at-point))
  15947. ;; Insert newline in heading, but preserve tags.
  15948. ((and (not (bolp))
  15949. (let ((case-fold-search nil))
  15950. (org-match-line org-complex-heading-regexp)))
  15951. ;; At headline. Split line. However, if point is on keyword,
  15952. ;; priority cookie or tags, do not break any of them: add
  15953. ;; a newline after the headline instead.
  15954. (let ((tags-column (and (match-beginning 5)
  15955. (save-excursion (goto-char (match-beginning 5))
  15956. (current-column))))
  15957. (string
  15958. (when (and (match-end 4) (org-point-in-group (point) 4))
  15959. (delete-and-extract-region (point) (match-end 4)))))
  15960. ;; Adjust tag alignment.
  15961. (cond
  15962. ((not (and tags-column string)))
  15963. (org-auto-align-tags (org-align-tags))
  15964. (t (org--align-tags-here tags-column))) ;preserve tags column
  15965. (end-of-line)
  15966. (org-show-entry)
  15967. (if indent (newline-and-indent) (newline))
  15968. (when string (save-excursion (insert (org-trim string))))))
  15969. ;; In a list, make sure indenting keeps trailing text within.
  15970. ((and indent
  15971. (not (eolp))
  15972. (org-element-lineage context '(item)))
  15973. (let ((trailing-data
  15974. (delete-and-extract-region (point) (line-end-position))))
  15975. (newline-and-indent)
  15976. (save-excursion (insert trailing-data))))
  15977. (t
  15978. ;; Do not auto-fill when point is in an Org property drawer.
  15979. (let ((auto-fill-function (and (not (org-at-property-p))
  15980. auto-fill-function)))
  15981. (if indent
  15982. (newline-and-indent)
  15983. (newline)))))))
  15984. (defun org-return-indent ()
  15985. "Goto next table row or insert a newline and indent.
  15986. Calls `org-table-next-row' or `newline-and-indent', depending on
  15987. context. See the individual commands for more information."
  15988. (interactive)
  15989. (org-return t))
  15990. (defun org-ctrl-c-tab (&optional arg)
  15991. "Toggle columns width in a table, or show children.
  15992. Call `org-table-toggle-column-width' if point is in a table.
  15993. Otherwise, call `org-show-children'. ARG is the level to hide."
  15994. (interactive "p")
  15995. (if (org-at-table-p)
  15996. (call-interactively #'org-table-toggle-column-width)
  15997. (if (org-before-first-heading-p)
  15998. (progn
  15999. (org-flag-above-first-heading)
  16000. (outline-hide-sublevels (or arg 1))
  16001. (goto-char (point-min)))
  16002. (outline-hide-subtree)
  16003. (org-show-children arg))))
  16004. (defun org-ctrl-c-star ()
  16005. "Compute table, or change heading status of lines.
  16006. Calls `org-table-recalculate' or `org-toggle-heading',
  16007. depending on context."
  16008. (interactive)
  16009. (cond
  16010. ((org-at-table-p)
  16011. (call-interactively 'org-table-recalculate))
  16012. (t
  16013. ;; Convert all lines in region to list items
  16014. (call-interactively 'org-toggle-heading))))
  16015. (defun org-ctrl-c-minus ()
  16016. "Insert separator line in table or modify bullet status of line.
  16017. Also turns a plain line or a region of lines into list items.
  16018. Calls `org-table-insert-hline', `org-toggle-item', or
  16019. `org-cycle-list-bullet', depending on context."
  16020. (interactive)
  16021. (cond
  16022. ((org-at-table-p)
  16023. (call-interactively 'org-table-insert-hline))
  16024. ((org-region-active-p)
  16025. (call-interactively 'org-toggle-item))
  16026. ((org-in-item-p)
  16027. (call-interactively 'org-cycle-list-bullet))
  16028. (t
  16029. (call-interactively 'org-toggle-item))))
  16030. (defun org-toggle-heading (&optional nstars)
  16031. "Convert headings to normal text, or items or text to headings.
  16032. If there is no active region, only convert the current line.
  16033. With a `\\[universal-argument]' prefix, convert the whole list at
  16034. point into heading.
  16035. In a region:
  16036. - If the first non blank line is a headline, remove the stars
  16037. from all headlines in the region.
  16038. - If it is a normal line, turn each and every normal line (i.e.,
  16039. not an heading or an item) in the region into headings. If you
  16040. want to convert only the first line of this region, use one
  16041. universal prefix argument.
  16042. - If it is a plain list item, turn all plain list items into headings.
  16043. When converting a line into a heading, the number of stars is chosen
  16044. such that the lines become children of the current entry. However,
  16045. when a numeric prefix argument is given, its value determines the
  16046. number of stars to add."
  16047. (interactive "P")
  16048. (let ((skip-blanks
  16049. (function
  16050. ;; Return beginning of first non-blank line, starting from
  16051. ;; line at POS.
  16052. (lambda (pos)
  16053. (save-excursion
  16054. (goto-char pos)
  16055. (while (org-at-comment-p) (forward-line))
  16056. (skip-chars-forward " \r\t\n")
  16057. (point-at-bol)))))
  16058. beg end toggled)
  16059. ;; Determine boundaries of changes. If a universal prefix has
  16060. ;; been given, put the list in a region. If region ends at a bol,
  16061. ;; do not consider the last line to be in the region.
  16062. (when (and current-prefix-arg (org-at-item-p))
  16063. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16064. (org-mark-element))
  16065. (if (org-region-active-p)
  16066. (setq beg (funcall skip-blanks (region-beginning))
  16067. end (copy-marker (save-excursion
  16068. (goto-char (region-end))
  16069. (if (bolp) (point) (point-at-eol)))))
  16070. (setq beg (funcall skip-blanks (point-at-bol))
  16071. end (copy-marker (point-at-eol))))
  16072. ;; Ensure inline tasks don't count as headings.
  16073. (org-with-limited-levels
  16074. (save-excursion
  16075. (goto-char beg)
  16076. (cond
  16077. ;; Case 1. Started at an heading: de-star headings.
  16078. ((org-at-heading-p)
  16079. (while (< (point) end)
  16080. (when (org-at-heading-p t)
  16081. (looking-at org-outline-regexp) (replace-match "")
  16082. (setq toggled t))
  16083. (forward-line)))
  16084. ;; Case 2. Started at an item: change items into headlines.
  16085. ;; One star will be added by `org-list-to-subtree'.
  16086. ((org-at-item-p)
  16087. (while (< (point) end)
  16088. (when (org-at-item-p)
  16089. ;; Pay attention to cases when region ends before list.
  16090. (let* ((struct (org-list-struct))
  16091. (list-end
  16092. (min (org-list-get-bottom-point struct) (1+ end))))
  16093. (save-restriction
  16094. (narrow-to-region (point) list-end)
  16095. (insert (org-list-to-subtree
  16096. (org-list-to-lisp t)
  16097. (pcase (org-current-level)
  16098. (`nil 1)
  16099. (l (1+ (org-reduced-level l)))))
  16100. "\n")))
  16101. (setq toggled t))
  16102. (forward-line)))
  16103. ;; Case 3. Started at normal text: make every line an heading,
  16104. ;; skipping headlines and items.
  16105. (t (let* ((stars
  16106. (make-string
  16107. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16108. (add-stars
  16109. (cond (nstars "") ; stars from prefix only
  16110. ((equal stars "") "*") ; before first heading
  16111. (org-odd-levels-only "**") ; inside heading, odd
  16112. (t "*"))) ; inside heading, oddeven
  16113. (rpl (concat stars add-stars " "))
  16114. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16115. (while (< (point) (if (equal nstars '(4)) lend end))
  16116. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16117. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16118. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16119. (forward-line)))))))
  16120. (unless toggled (message "Cannot toggle heading from here"))))
  16121. (defun org-meta-return (&optional arg)
  16122. "Insert a new heading or wrap a region in a table.
  16123. Calls `org-insert-heading', `org-insert-item' or
  16124. `org-table-wrap-region', depending on context. When called with
  16125. an argument, unconditionally call `org-insert-heading'."
  16126. (interactive "P")
  16127. (org-check-before-invisible-edit 'insert)
  16128. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16129. (call-interactively (cond (arg #'org-insert-heading)
  16130. ((org-at-table-p) #'org-table-wrap-region)
  16131. ((org-in-item-p) #'org-insert-item)
  16132. (t #'org-insert-heading)))))
  16133. ;;; Menu entries
  16134. (defsubst org-in-subtree-not-table-p ()
  16135. "Are we in a subtree and not in a table?"
  16136. (and (not (org-before-first-heading-p))
  16137. (not (org-at-table-p))))
  16138. ;; Define the Org mode menus
  16139. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16140. `("Org"
  16141. ("Show/Hide"
  16142. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16143. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16144. ["Sparse Tree..." org-sparse-tree t]
  16145. ["Reveal Context" org-reveal t]
  16146. ["Show All" org-show-all t]
  16147. "--"
  16148. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16149. "--"
  16150. ["New Heading" org-insert-heading t]
  16151. ("Navigate Headings"
  16152. ["Up" outline-up-heading t]
  16153. ["Next" outline-next-visible-heading t]
  16154. ["Previous" outline-previous-visible-heading t]
  16155. ["Next Same Level" outline-forward-same-level t]
  16156. ["Previous Same Level" outline-backward-same-level t]
  16157. "--"
  16158. ["Jump" org-goto t])
  16159. ("Edit Structure"
  16160. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16161. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16162. "--"
  16163. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16164. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16165. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16166. "--"
  16167. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16168. "--"
  16169. ["Copy visible text" org-copy-visible t]
  16170. "--"
  16171. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16172. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16173. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16174. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16175. "--"
  16176. ["Sort Region/Children" org-sort t]
  16177. "--"
  16178. ["Convert to odd levels" org-convert-to-odd-levels t]
  16179. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16180. ("Editing"
  16181. ["Emphasis..." org-emphasize t]
  16182. ["Edit Source Example" org-edit-special t]
  16183. "--"
  16184. ["Footnote new/jump" org-footnote-action t]
  16185. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16186. ("Archive"
  16187. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16188. "--"
  16189. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16190. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16191. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16192. "--"
  16193. ("Hyperlinks"
  16194. ["Store Link (Global)" org-store-link t]
  16195. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16196. ["Insert Link" org-insert-link t]
  16197. ["Follow Link" org-open-at-point t]
  16198. "--"
  16199. ["Next link" org-next-link t]
  16200. ["Previous link" org-previous-link t]
  16201. "--"
  16202. ["Descriptive Links"
  16203. org-toggle-link-display
  16204. :style radio
  16205. :selected org-descriptive-links
  16206. ]
  16207. ["Literal Links"
  16208. org-toggle-link-display
  16209. :style radio
  16210. :selected (not org-descriptive-links)])
  16211. "--"
  16212. ("TODO Lists"
  16213. ["TODO/DONE/-" org-todo t]
  16214. ("Select keyword"
  16215. ["Next keyword" org-shiftright (org-at-heading-p)]
  16216. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16217. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16218. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16219. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16220. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16221. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16222. "--"
  16223. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16224. :selected org-enforce-todo-dependencies :style toggle :active t]
  16225. "Settings for tree at point"
  16226. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16227. :selected (org-entry-get nil "ORDERED")
  16228. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16229. ["Do Children parallel" org-toggle-ordered-property :style radio
  16230. :selected (not (org-entry-get nil "ORDERED"))
  16231. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16232. "--"
  16233. ["Set Priority" org-priority t]
  16234. ["Priority Up" org-shiftup t]
  16235. ["Priority Down" org-shiftdown t]
  16236. "--"
  16237. ["Get news from all feeds" org-feed-update-all t]
  16238. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16239. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16240. ("TAGS and Properties"
  16241. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16242. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16243. "--"
  16244. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16245. ["Column view of properties" org-columns t]
  16246. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16247. ("Dates and Scheduling"
  16248. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16249. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16250. ("Change Date"
  16251. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16252. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16253. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16254. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16255. ["Compute Time Range" org-evaluate-time-range t]
  16256. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16257. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16258. "--"
  16259. ["Custom time format" org-toggle-time-stamp-overlays
  16260. :style radio :selected org-display-custom-times]
  16261. "--"
  16262. ["Goto Calendar" org-goto-calendar t]
  16263. ["Date from Calendar" org-date-from-calendar t]
  16264. "--"
  16265. ["Start/Restart Timer" org-timer-start t]
  16266. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16267. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16268. ["Insert Timer String" org-timer t]
  16269. ["Insert Timer Item" org-timer-item t])
  16270. ("Logging work"
  16271. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16272. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16273. ["Clock out" org-clock-out t]
  16274. ["Clock cancel" org-clock-cancel t]
  16275. "--"
  16276. ["Mark as default task" org-clock-mark-default-task t]
  16277. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16278. ["Goto running clock" org-clock-goto t]
  16279. "--"
  16280. ["Display times" org-clock-display t]
  16281. ["Create clock table" org-clock-report t]
  16282. "--"
  16283. ["Record DONE time"
  16284. (progn (setq org-log-done (not org-log-done))
  16285. (message "Switching to %s will %s record a timestamp"
  16286. (car org-done-keywords)
  16287. (if org-log-done "automatically" "not")))
  16288. :style toggle :selected org-log-done])
  16289. "--"
  16290. ["Agenda Command..." org-agenda t]
  16291. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16292. ("File List for Agenda")
  16293. ("Special views current file"
  16294. ["TODO Tree" org-show-todo-tree t]
  16295. ["Check Deadlines" org-check-deadlines t]
  16296. ["Tags/Property tree" org-match-sparse-tree t])
  16297. "--"
  16298. ["Export/Publish..." org-export-dispatch t]
  16299. ("LaTeX"
  16300. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16301. :style toggle :selected org-cdlatex-mode]
  16302. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16303. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16304. ["Modify math symbol" org-cdlatex-math-modify
  16305. (org-inside-LaTeX-fragment-p)]
  16306. ["Insert citation" org-reftex-citation t])
  16307. "--"
  16308. ("Documentation"
  16309. ["Show Version" org-version t]
  16310. ["Info Documentation" org-info t]
  16311. ["Browse Org News" org-browse-news t])
  16312. ("Customize"
  16313. ["Browse Org Group" org-customize t]
  16314. "--"
  16315. ["Expand This Menu" org-create-customize-menu
  16316. (fboundp 'customize-menu-create)])
  16317. ["Send bug report" org-submit-bug-report t]
  16318. "--"
  16319. ("Refresh/Reload"
  16320. ["Refresh setup current buffer" org-mode-restart t]
  16321. ["Reload Org (after update)" org-reload t]
  16322. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16323. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16324. '("Table"
  16325. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16326. ["Next Field" org-cycle (org-at-table-p)]
  16327. ["Previous Field" org-shifttab (org-at-table-p)]
  16328. ["Next Row" org-return (org-at-table-p)]
  16329. "--"
  16330. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16331. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16332. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16333. "--"
  16334. ("Column"
  16335. ["Move Column Left" org-metaleft (org-at-table-p)]
  16336. ["Move Column Right" org-metaright (org-at-table-p)]
  16337. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16338. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16339. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16340. ("Row"
  16341. ["Move Row Up" org-metaup (org-at-table-p)]
  16342. ["Move Row Down" org-metadown (org-at-table-p)]
  16343. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16344. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16345. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16346. "--"
  16347. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16348. ("Rectangle"
  16349. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16350. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16351. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16352. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16353. "--"
  16354. ("Calculate"
  16355. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16356. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16357. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16358. "--"
  16359. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16360. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16361. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16362. "--"
  16363. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16364. "--"
  16365. ["Sum Column/Rectangle" org-table-sum
  16366. (or (org-at-table-p) (org-region-active-p))]
  16367. ["Which Column?" org-table-current-column (org-at-table-p)])
  16368. ["Debug Formulas"
  16369. org-table-toggle-formula-debugger
  16370. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16371. ["Show Col/Row Numbers"
  16372. org-table-toggle-coordinate-overlays
  16373. :style toggle
  16374. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16375. "--"
  16376. ["Create" org-table-create (not (org-at-table-p))]
  16377. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16378. ["Import from File" org-table-import (not (org-at-table-p))]
  16379. ["Export to File" org-table-export (org-at-table-p)]
  16380. "--"
  16381. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16382. "--"
  16383. ("Plot"
  16384. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16385. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16386. (defun org-info (&optional node)
  16387. "Read documentation for Org in the info system.
  16388. With optional NODE, go directly to that node."
  16389. (interactive)
  16390. (info (format "(org)%s" (or node ""))))
  16391. (defun org-browse-news ()
  16392. "Browse the news for the latest major release."
  16393. (interactive)
  16394. (browse-url "https://orgmode.org/Changes.html"))
  16395. ;;;###autoload
  16396. (defun org-submit-bug-report ()
  16397. "Submit a bug report on Org via mail.
  16398. Don't hesitate to report any problems or inaccurate documentation.
  16399. If you don't have setup sending mail from (X)Emacs, please copy the
  16400. output buffer into your mail program, as it gives us important
  16401. information about your Org version and configuration."
  16402. (interactive)
  16403. (require 'reporter)
  16404. (defvar reporter-prompt-for-summary-p)
  16405. (org-load-modules-maybe)
  16406. (org-require-autoloaded-modules)
  16407. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16408. (reporter-submit-bug-report
  16409. "emacs-orgmode@gnu.org"
  16410. (org-version nil 'full)
  16411. (let (list)
  16412. (save-window-excursion
  16413. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16414. (delete-other-windows)
  16415. (erase-buffer)
  16416. (insert "You are about to submit a bug report to the Org mailing list.
  16417. If your report is about Org installation, please read this section:
  16418. https://orgmode.org/org.html#Installation
  16419. Please read https://orgmode.org/org.html#Feedback on how to make
  16420. a good report, it will help Org contributors fixing your problem.
  16421. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16422. if the issue you are about to raise has already been dealt with.
  16423. We also would like to add your full Org and Outline configuration
  16424. to the bug report. It will help us debugging the issue.
  16425. *HOWEVER*, some variables you have customized may contain private
  16426. information. The names of customers, colleagues, or friends, might
  16427. appear in the form of file names, tags, todo states or search strings.
  16428. If you answer \"yes\" to the prompt, you might want to check and remove
  16429. such private information before sending the email.")
  16430. (add-text-properties (point-min) (point-max) '(face org-warning))
  16431. (when (yes-or-no-p "Include your Org configuration ")
  16432. (mapatoms
  16433. (lambda (v)
  16434. (and (boundp v)
  16435. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16436. (or (and (symbol-value v)
  16437. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16438. (and
  16439. (get v 'custom-type) (get v 'standard-value)
  16440. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16441. (push v list)))))
  16442. (kill-buffer (get-buffer "*Warn about privacy*"))
  16443. list))
  16444. nil nil
  16445. "Remember to cover the basics, that is, what you expected to happen and
  16446. what in fact did happen. You don't know how to make a good report? See
  16447. https://orgmode.org/manual/Feedback.html#Feedback
  16448. Your bug report will be posted to the Org mailing list.
  16449. ------------------------------------------------------------------------")
  16450. (save-excursion
  16451. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16452. (replace-match "\\1Bug: \\3 [\\2]")))))
  16453. (defun org-install-agenda-files-menu ()
  16454. (let ((bl (buffer-list)))
  16455. (save-excursion
  16456. (while bl
  16457. (set-buffer (pop bl))
  16458. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16459. (when (derived-mode-p 'org-mode)
  16460. (easy-menu-change
  16461. '("Org") "File List for Agenda"
  16462. (append
  16463. (list
  16464. ["Edit File List" (org-edit-agenda-file-list) t]
  16465. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16466. ["Remove Current File from List" org-remove-file t]
  16467. ["Cycle through agenda files" org-cycle-agenda-files t]
  16468. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16469. "--")
  16470. (mapcar 'org-file-menu-entry
  16471. ;; Prevent initialization from failing.
  16472. (ignore-errors (org-agenda-files t)))))))))
  16473. ;;;; Documentation
  16474. (defun org-require-autoloaded-modules ()
  16475. (interactive)
  16476. (mapc #'require
  16477. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16478. org-table org-timer)))
  16479. ;;;###autoload
  16480. (defun org-reload (&optional uncompiled)
  16481. "Reload all Org Lisp files.
  16482. With prefix arg UNCOMPILED, load the uncompiled versions."
  16483. (interactive "P")
  16484. (require 'loadhist)
  16485. (let* ((org-dir (org-find-library-dir "org"))
  16486. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16487. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16488. (remove-re (format "\\`%s\\'"
  16489. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16490. (feats (delete-dups
  16491. (mapcar 'file-name-sans-extension
  16492. (mapcar 'file-name-nondirectory
  16493. (delq nil
  16494. (mapcar 'feature-file
  16495. features))))))
  16496. (lfeat (append
  16497. (sort
  16498. (setq feats
  16499. (delq nil (mapcar
  16500. (lambda (f)
  16501. (if (and (string-match feature-re f)
  16502. (not (string-match remove-re f)))
  16503. f nil))
  16504. feats)))
  16505. 'string-lessp)
  16506. (list "org-version" "org")))
  16507. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16508. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16509. load-uncore load-misses)
  16510. (setq load-misses
  16511. (delq 't
  16512. (mapcar (lambda (f)
  16513. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16514. (and (string= org-dir contrib-dir)
  16515. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16516. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16517. (push f load-uncore)
  16518. 't)
  16519. f))
  16520. lfeat)))
  16521. (when load-uncore
  16522. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16523. (if (> (length load-uncore) 1) "s were" " was")
  16524. (reverse load-uncore)))
  16525. (if load-misses
  16526. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16527. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16528. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16529. ;;;###autoload
  16530. (defun org-customize ()
  16531. "Call the customize function with org as argument."
  16532. (interactive)
  16533. (org-load-modules-maybe)
  16534. (org-require-autoloaded-modules)
  16535. (customize-browse 'org))
  16536. (defun org-create-customize-menu ()
  16537. "Create a full customization menu for Org mode, insert it into the menu."
  16538. (interactive)
  16539. (org-load-modules-maybe)
  16540. (org-require-autoloaded-modules)
  16541. (if (fboundp 'customize-menu-create)
  16542. (progn
  16543. (easy-menu-change
  16544. '("Org") "Customize"
  16545. `(["Browse Org group" org-customize t]
  16546. "--"
  16547. ,(customize-menu-create 'org)
  16548. ["Set" Custom-set t]
  16549. ["Save" Custom-save t]
  16550. ["Reset to Current" Custom-reset-current t]
  16551. ["Reset to Saved" Custom-reset-saved t]
  16552. ["Reset to Standard Settings" Custom-reset-standard t]))
  16553. (message "\"Org\"-menu now contains full customization menu"))
  16554. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  16555. ;;;; Miscellaneous stuff
  16556. ;;; Generally useful functions
  16557. (defun org-in-clocktable-p ()
  16558. "Check if the cursor is in a clocktable."
  16559. (let ((pos (point)) start)
  16560. (save-excursion
  16561. (end-of-line 1)
  16562. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16563. (setq start (match-beginning 0))
  16564. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16565. (>= (match-end 0) pos)
  16566. start))))
  16567. (defun org-in-verbatim-emphasis ()
  16568. (save-match-data
  16569. (and (org-in-regexp org-verbatim-re 2)
  16570. (>= (point) (match-beginning 3))
  16571. (<= (point) (match-end 4)))))
  16572. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16573. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16574. (if (and marker (marker-buffer marker)
  16575. (buffer-live-p (marker-buffer marker)))
  16576. (progn
  16577. (pop-to-buffer-same-window (marker-buffer marker))
  16578. (when (or (> marker (point-max)) (< marker (point-min)))
  16579. (widen))
  16580. (goto-char marker)
  16581. (org-show-context 'org-goto))
  16582. (if bookmark
  16583. (bookmark-jump bookmark)
  16584. (error "Cannot find location"))))
  16585. (defun org-quote-csv-field (s)
  16586. "Quote field for inclusion in CSV material."
  16587. (if (string-match "[\",]" s)
  16588. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16589. s))
  16590. (defun org-force-self-insert (N)
  16591. "Needed to enforce self-insert under remapping."
  16592. (interactive "p")
  16593. (self-insert-command N))
  16594. (defun org-quote-vert (s)
  16595. "Replace \"|\" with \"\\vert\"."
  16596. (while (string-match "|" s)
  16597. (setq s (replace-match "\\vert" t t s)))
  16598. s)
  16599. (defun org-uuidgen-p (s)
  16600. "Is S an ID created by UUIDGEN?"
  16601. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16602. (defun org-in-src-block-p (&optional inside)
  16603. "Whether point is in a code source block.
  16604. When INSIDE is non-nil, don't consider we are within a source
  16605. block when point is at #+BEGIN_SRC or #+END_SRC."
  16606. (let ((case-fold-search t))
  16607. (or (and (eq (get-char-property (point) 'src-block) t))
  16608. (and (not inside)
  16609. (save-match-data
  16610. (save-excursion
  16611. (beginning-of-line)
  16612. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16613. (defun org-context ()
  16614. "Return a list of contexts of the current cursor position.
  16615. If several contexts apply, all are returned.
  16616. Each context entry is a list with a symbol naming the context, and
  16617. two positions indicating start and end of the context. Possible
  16618. contexts are:
  16619. :headline anywhere in a headline
  16620. :headline-stars on the leading stars in a headline
  16621. :todo-keyword on a TODO keyword (including DONE) in a headline
  16622. :tags on the TAGS in a headline
  16623. :priority on the priority cookie in a headline
  16624. :item on the first line of a plain list item
  16625. :item-bullet on the bullet/number of a plain list item
  16626. :checkbox on the checkbox in a plain list item
  16627. :table in an Org table
  16628. :table-special on a special filed in a table
  16629. :table-table in a table.el table
  16630. :clocktable in a clocktable
  16631. :src-block in a source block
  16632. :link on a hyperlink
  16633. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16634. :latex-fragment on a LaTeX fragment
  16635. :latex-preview on a LaTeX fragment with overlaid preview image
  16636. This function expects the position to be visible because it uses font-lock
  16637. faces as a help to recognize the following contexts: :table-special, :link,
  16638. and :keyword."
  16639. (let* ((f (get-text-property (point) 'face))
  16640. (faces (if (listp f) f (list f)))
  16641. (case-fold-search t)
  16642. (p (point)) clist o)
  16643. ;; First the large context
  16644. (cond
  16645. ((org-at-heading-p t)
  16646. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16647. (when (progn
  16648. (beginning-of-line 1)
  16649. (looking-at org-todo-line-tags-regexp))
  16650. (push (org-point-in-group p 1 :headline-stars) clist)
  16651. (push (org-point-in-group p 2 :todo-keyword) clist)
  16652. (push (org-point-in-group p 4 :tags) clist))
  16653. (goto-char p)
  16654. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16655. (when (looking-at "\\[#[A-Z0-9]\\]")
  16656. (push (org-point-in-group p 0 :priority) clist)))
  16657. ((org-at-item-p)
  16658. (push (org-point-in-group p 2 :item-bullet) clist)
  16659. (push (list :item (point-at-bol)
  16660. (save-excursion (org-end-of-item) (point)))
  16661. clist)
  16662. (and (org-at-item-checkbox-p)
  16663. (push (org-point-in-group p 0 :checkbox) clist)))
  16664. ((org-at-table-p)
  16665. (push (list :table (org-table-begin) (org-table-end)) clist)
  16666. (when (memq 'org-formula faces)
  16667. (push (list :table-special
  16668. (previous-single-property-change p 'face)
  16669. (next-single-property-change p 'face))
  16670. clist)))
  16671. ((org-at-table-p 'any)
  16672. (push (list :table-table) clist)))
  16673. (goto-char p)
  16674. (let ((case-fold-search t))
  16675. ;; New the "medium" contexts: clocktables, source blocks
  16676. (cond ((org-in-clocktable-p)
  16677. (push (list :clocktable
  16678. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16679. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16680. (match-beginning 1))
  16681. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16682. (match-end 0)))
  16683. clist))
  16684. ((org-in-src-block-p)
  16685. (push (list :src-block
  16686. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16687. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16688. (match-beginning 1))
  16689. (and (search-forward "#+END_SRC" nil t)
  16690. (match-beginning 0)))
  16691. clist))))
  16692. (goto-char p)
  16693. ;; Now the small context
  16694. (cond
  16695. ((org-at-timestamp-p)
  16696. (push (org-point-in-group p 0 :timestamp) clist))
  16697. ((memq 'org-link faces)
  16698. (push (list :link
  16699. (previous-single-property-change p 'face)
  16700. (next-single-property-change p 'face))
  16701. clist))
  16702. ((memq 'org-special-keyword faces)
  16703. (push (list :keyword
  16704. (previous-single-property-change p 'face)
  16705. (next-single-property-change p 'face))
  16706. clist))
  16707. ((setq o (cl-some
  16708. (lambda (o)
  16709. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16710. o))
  16711. (overlays-at (point))))
  16712. (push (list :latex-fragment
  16713. (overlay-start o) (overlay-end o))
  16714. clist)
  16715. (push (list :latex-preview
  16716. (overlay-start o) (overlay-end o))
  16717. clist))
  16718. ((org-inside-LaTeX-fragment-p)
  16719. ;; FIXME: positions wrong.
  16720. (push (list :latex-fragment (point) (point)) clist)))
  16721. (setq clist (nreverse (delq nil clist)))
  16722. clist))
  16723. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16724. "Non-nil when point is between matches of START-RE and END-RE.
  16725. Also return a non-nil value when point is on one of the matches.
  16726. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16727. buffer positions. Default values are the positions of headlines
  16728. surrounding the point.
  16729. The functions returns a cons cell whose car (resp. cdr) is the
  16730. position before START-RE (resp. after END-RE)."
  16731. (save-match-data
  16732. (let ((pos (point))
  16733. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16734. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16735. beg end)
  16736. (save-excursion
  16737. ;; Point is on a block when on START-RE or if START-RE can be
  16738. ;; found before it...
  16739. (and (or (org-in-regexp start-re)
  16740. (re-search-backward start-re limit-up t))
  16741. (setq beg (match-beginning 0))
  16742. ;; ... and END-RE after it...
  16743. (goto-char (match-end 0))
  16744. (re-search-forward end-re limit-down t)
  16745. (> (setq end (match-end 0)) pos)
  16746. ;; ... without another START-RE in-between.
  16747. (goto-char (match-beginning 0))
  16748. (not (re-search-backward start-re (1+ beg) t))
  16749. ;; Return value.
  16750. (cons beg end))))))
  16751. (defun org-in-block-p (names)
  16752. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16753. NAMES is a list of strings containing names of blocks.
  16754. Return first block name matched, or nil. Beware that in case of
  16755. nested blocks, the returned name may not belong to the closest
  16756. block from point."
  16757. (save-match-data
  16758. (catch 'exit
  16759. (let ((case-fold-search t)
  16760. (lim-up (save-excursion (outline-previous-heading)))
  16761. (lim-down (save-excursion (outline-next-heading))))
  16762. (dolist (name names)
  16763. (let ((n (regexp-quote name)))
  16764. (when (org-between-regexps-p
  16765. (concat "^[ \t]*#\\+begin_" n)
  16766. (concat "^[ \t]*#\\+end_" n)
  16767. lim-up lim-down)
  16768. (throw 'exit n)))))
  16769. nil)))
  16770. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16771. "Call `multi-occur' with buffers for all agenda files."
  16772. (interactive "sOrg-files matching: ")
  16773. (let* ((files (org-agenda-files))
  16774. (tnames (mapcar #'file-truename files))
  16775. (extra org-agenda-text-search-extra-files))
  16776. (when (eq (car extra) 'agenda-archives)
  16777. (setq extra (cdr extra))
  16778. (setq files (org-add-archive-files files)))
  16779. (dolist (f extra)
  16780. (unless (member (file-truename f) tnames)
  16781. (unless (member f files) (setq files (append files (list f))))
  16782. (setq tnames (append tnames (list (file-truename f))))))
  16783. (multi-occur
  16784. (mapcar (lambda (x)
  16785. (with-current-buffer
  16786. ;; FIXME: Why not just (find-file-noselect x)?
  16787. ;; Is it to avoid the "revert buffer" prompt?
  16788. (or (get-file-buffer x) (find-file-noselect x))
  16789. (widen)
  16790. (current-buffer)))
  16791. files)
  16792. regexp)))
  16793. (add-hook 'occur-mode-find-occurrence-hook
  16794. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  16795. (defun org-occur-link-in-agenda-files ()
  16796. "Create a link and search for it in the agendas.
  16797. The link is not stored in `org-stored-links', it is just created
  16798. for the search purpose."
  16799. (interactive)
  16800. (let ((link (condition-case nil
  16801. (org-store-link nil)
  16802. (error "Unable to create a link to here"))))
  16803. (org-occur-in-agenda-files (regexp-quote link))))
  16804. (defun org-back-over-empty-lines ()
  16805. "Move backwards over whitespace, to the beginning of the first empty line.
  16806. Returns the number of empty lines passed."
  16807. (let ((pos (point)))
  16808. (if (cdr (assq 'heading org-blank-before-new-entry))
  16809. (skip-chars-backward " \t\n\r")
  16810. (unless (eobp)
  16811. (forward-line -1)))
  16812. (beginning-of-line 2)
  16813. (goto-char (min (point) pos))
  16814. (count-lines (point) pos)))
  16815. ;;; TODO: Only called once, from ox-odt which should probably use
  16816. ;;; org-export-inline-image-p or something.
  16817. (defun org-file-image-p (file)
  16818. "Return non-nil if FILE is an image."
  16819. (save-match-data
  16820. (string-match (image-file-name-regexp) file)))
  16821. (defun org-get-cursor-date (&optional with-time)
  16822. "Return the date at cursor in as a time.
  16823. This works in the calendar and in the agenda, anywhere else it just
  16824. returns the current time.
  16825. If WITH-TIME is non-nil, returns the time of the event at point (in
  16826. the agenda) or the current time of the day; otherwise returns the
  16827. earliest time on the cursor date that Org treats as that date
  16828. (bearing in mind `org-extend-today-until')."
  16829. (let (date day defd tp hod mod)
  16830. (when with-time
  16831. (setq tp (get-text-property (point) 'time))
  16832. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  16833. (setq hod (string-to-number (match-string 1 tp))
  16834. mod (string-to-number (match-string 2 tp))))
  16835. (or tp (let ((now (decode-time)))
  16836. (setq hod (nth 2 now)
  16837. mod (nth 1 now)))))
  16838. (cond
  16839. ((eq major-mode 'calendar-mode)
  16840. (setq date (calendar-cursor-to-date)
  16841. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16842. (nth 1 date) (nth 0 date) (nth 2 date))))
  16843. ((eq major-mode 'org-agenda-mode)
  16844. (setq day (get-text-property (point) 'day))
  16845. (when day
  16846. (setq date (calendar-gregorian-from-absolute day)
  16847. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16848. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16849. (or defd (current-time))))
  16850. (defun org-mark-subtree (&optional up)
  16851. "Mark the current subtree.
  16852. This puts point at the start of the current subtree, and mark at
  16853. the end. If a numeric prefix UP is given, move up into the
  16854. hierarchy of headlines by UP levels before marking the subtree."
  16855. (interactive "P")
  16856. (org-with-limited-levels
  16857. (cond ((org-at-heading-p) (beginning-of-line))
  16858. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16859. (t (outline-previous-visible-heading 1))))
  16860. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16861. (if (called-interactively-p 'any)
  16862. (call-interactively 'org-mark-element)
  16863. (org-mark-element)))
  16864. ;;; Indentation
  16865. (defvar org-element-greater-elements)
  16866. (defun org--get-expected-indentation (element contentsp)
  16867. "Expected indentation column for current line, according to ELEMENT.
  16868. ELEMENT is an element containing point. CONTENTSP is non-nil
  16869. when indentation is to be computed according to contents of
  16870. ELEMENT."
  16871. (let ((type (org-element-type element))
  16872. (start (org-element-property :begin element))
  16873. (post-affiliated (org-element-property :post-affiliated element)))
  16874. (org-with-wide-buffer
  16875. (cond
  16876. (contentsp
  16877. (cl-case type
  16878. ((diary-sexp footnote-definition) 0)
  16879. ((headline inlinetask nil)
  16880. (if (not org-adapt-indentation) 0
  16881. (let ((level (org-current-level)))
  16882. (if level (1+ level) 0))))
  16883. ((item plain-list) (org-list-item-body-column post-affiliated))
  16884. (t
  16885. (goto-char start)
  16886. (current-indentation))))
  16887. ((and
  16888. (eq org-adapt-indentation 'headline-data)
  16889. (memq type '(planning clock node-property property-drawer drawer)))
  16890. (org--get-expected-indentation
  16891. (org-element-property :parent element) t))
  16892. ((memq type '(headline inlinetask nil))
  16893. (if (org-match-line "[ \t]*$")
  16894. (org--get-expected-indentation element t)
  16895. 0))
  16896. ((memq type '(diary-sexp footnote-definition)) 0)
  16897. ;; First paragraph of a footnote definition or an item.
  16898. ;; Indent like parent.
  16899. ((< (line-beginning-position) start)
  16900. (org--get-expected-indentation
  16901. (org-element-property :parent element) t))
  16902. ;; At first line: indent according to previous sibling, if any,
  16903. ;; ignoring footnote definitions and inline tasks, or parent's
  16904. ;; contents.
  16905. ((and ( = (line-beginning-position) start)
  16906. (eq org-adapt-indentation t))
  16907. (catch 'exit
  16908. (while t
  16909. (if (= (point-min) start) (throw 'exit 0)
  16910. (goto-char (1- start))
  16911. (let* ((previous (org-element-at-point))
  16912. (parent previous))
  16913. (while (and parent (<= (org-element-property :end parent) start))
  16914. (setq previous parent
  16915. parent (org-element-property :parent parent)))
  16916. (cond
  16917. ((not previous) (throw 'exit 0))
  16918. ((> (org-element-property :end previous) start)
  16919. (throw 'exit (org--get-expected-indentation previous t)))
  16920. ((memq (org-element-type previous)
  16921. '(footnote-definition inlinetask))
  16922. (setq start (org-element-property :begin previous)))
  16923. (t (goto-char (org-element-property :begin previous))
  16924. (throw 'exit
  16925. (if (bolp) (current-indentation)
  16926. ;; At first paragraph in an item or
  16927. ;; a footnote definition.
  16928. (org--get-expected-indentation
  16929. (org-element-property :parent previous) t))))))))))
  16930. ;; Otherwise, move to the first non-blank line above.
  16931. ((not (eq org-adapt-indentation 'headline-data))
  16932. (beginning-of-line)
  16933. (let ((pos (point)))
  16934. (skip-chars-backward " \r\t\n")
  16935. (cond
  16936. ;; Two blank lines end a footnote definition or a plain
  16937. ;; list. When we indent an empty line after them, the
  16938. ;; containing list or footnote definition is over, so it
  16939. ;; qualifies as a previous sibling. Therefore, we indent
  16940. ;; like its first line.
  16941. ((and (memq type '(footnote-definition plain-list))
  16942. (> (count-lines (point) pos) 2))
  16943. (goto-char start)
  16944. (current-indentation))
  16945. ;; Line above is the first one of a paragraph at the
  16946. ;; beginning of an item or a footnote definition. Indent
  16947. ;; like parent.
  16948. ((< (line-beginning-position) start)
  16949. (org--get-expected-indentation
  16950. (org-element-property :parent element) t))
  16951. ;; Line above is the beginning of an element, i.e., point
  16952. ;; was originally on the blank lines between element's start
  16953. ;; and contents.
  16954. ((= (line-beginning-position) post-affiliated)
  16955. (org--get-expected-indentation element t))
  16956. ;; POS is after contents in a greater element. Indent like
  16957. ;; the beginning of the element.
  16958. ((and (memq type org-element-greater-elements)
  16959. (let ((cend (org-element-property :contents-end element)))
  16960. (and cend (<= cend pos))))
  16961. ;; As a special case, if point is at the end of a footnote
  16962. ;; definition or an item, indent like the very last element
  16963. ;; within. If that last element is an item, indent like
  16964. ;; its contents.
  16965. (if (memq type '(footnote-definition item plain-list))
  16966. (let ((last (org-element-at-point)))
  16967. (goto-char pos)
  16968. (org--get-expected-indentation
  16969. last (eq (org-element-type last) 'item)))
  16970. (goto-char start)
  16971. (current-indentation)))
  16972. ;; In any other case, indent like the current line.
  16973. (t (current-indentation)))))
  16974. ;; Finally, no indentation is needed, fall back to 0.
  16975. (t (current-indentation))))))
  16976. (defun org--align-node-property ()
  16977. "Align node property at point.
  16978. Alignment is done according to `org-property-format', which see."
  16979. (when (save-excursion
  16980. (beginning-of-line)
  16981. (looking-at org-property-re))
  16982. (replace-match
  16983. (concat (match-string 4)
  16984. (org-trim
  16985. (format org-property-format (match-string 1) (match-string 3))))
  16986. t t)))
  16987. (defun org-indent-line ()
  16988. "Indent line depending on context.
  16989. Indentation is done according to the following rules:
  16990. - Footnote definitions, diary sexps, headlines and inline tasks
  16991. have to start at column 0.
  16992. - On the very first line of an element, consider, in order, the
  16993. next rules until one matches:
  16994. 1. If there's a sibling element before, ignoring footnote
  16995. definitions and inline tasks, indent like its first line.
  16996. 2. If element has a parent, indent like its contents. More
  16997. precisely, if parent is an item, indent after the bullet.
  16998. Else, indent like parent's first line.
  16999. 3. Otherwise, indent relatively to current level, if
  17000. `org-adapt-indentation' is non-nil, or to left margin.
  17001. - On a blank line at the end of an element, indent according to
  17002. the type of the element. More precisely
  17003. 1. If element is a plain list, an item, or a footnote
  17004. definition, indent like the very last element within.
  17005. 2. If element is a paragraph, indent like its last non blank
  17006. line.
  17007. 3. Otherwise, indent like its very first line.
  17008. - In the code part of a source block, use language major mode
  17009. to indent current line if `org-src-tab-acts-natively' is
  17010. non-nil. If it is nil, do nothing.
  17011. - Otherwise, indent like the first non-blank line above.
  17012. The function doesn't indent an item as it could break the whole
  17013. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17014. `\\[org-shiftmetaright]'.
  17015. Also align node properties according to `org-property-format'."
  17016. (interactive)
  17017. (if (org-at-heading-p) 'noindent
  17018. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17019. (type (org-element-type element)))
  17020. (cond ((and (memq type '(plain-list item))
  17021. (= (line-beginning-position)
  17022. (org-element-property :post-affiliated element)))
  17023. 'noindent)
  17024. ((and (eq type 'latex-environment)
  17025. (>= (point) (org-element-property :post-affiliated element))
  17026. (< (point) (org-with-wide-buffer
  17027. (goto-char (org-element-property :end element))
  17028. (skip-chars-backward " \r\t\n")
  17029. (line-beginning-position 2))))
  17030. 'noindent)
  17031. ((and (eq type 'src-block)
  17032. org-src-tab-acts-natively
  17033. (> (line-beginning-position)
  17034. (org-element-property :post-affiliated element))
  17035. (< (line-beginning-position)
  17036. (org-with-wide-buffer
  17037. (goto-char (org-element-property :end element))
  17038. (skip-chars-backward " \r\t\n")
  17039. (line-beginning-position))))
  17040. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17041. (t
  17042. (let ((column (org--get-expected-indentation element nil)))
  17043. ;; Preserve current column.
  17044. (if (<= (current-column) (current-indentation))
  17045. (indent-line-to column)
  17046. (save-excursion (indent-line-to column))))
  17047. ;; Align node property. Also preserve current column.
  17048. (when (eq type 'node-property)
  17049. (let ((column (current-column)))
  17050. (org--align-node-property)
  17051. (org-move-to-column column))))))))
  17052. (defun org-indent-region (start end)
  17053. "Indent each non-blank line in the region.
  17054. Called from a program, START and END specify the region to
  17055. indent. The function will not indent contents of example blocks,
  17056. verse blocks and export blocks as leading white spaces are
  17057. assumed to be significant there."
  17058. (interactive "r")
  17059. (save-excursion
  17060. (goto-char start)
  17061. (skip-chars-forward " \r\t\n")
  17062. (unless (eobp) (beginning-of-line))
  17063. (let ((indent-to
  17064. (lambda (ind pos)
  17065. ;; Set IND as indentation for all lines between point and
  17066. ;; POS. Blank lines are ignored. Leave point after POS
  17067. ;; once done.
  17068. (let ((limit (copy-marker pos)))
  17069. (while (< (point) limit)
  17070. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17071. (forward-line))
  17072. (set-marker limit nil))))
  17073. (end (copy-marker end)))
  17074. (while (< (point) end)
  17075. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17076. (let* ((element (org-element-at-point))
  17077. (type (org-element-type element))
  17078. (element-end (copy-marker (org-element-property :end element)))
  17079. (ind (org--get-expected-indentation element nil)))
  17080. (cond
  17081. ;; Element indented as a single block. Example blocks
  17082. ;; preserving indentation are a special case since the
  17083. ;; "contents" must not be indented whereas the block
  17084. ;; boundaries can.
  17085. ((or (memq type '(export-block latex-environment))
  17086. (and (eq type 'example-block)
  17087. (not
  17088. (or org-src-preserve-indentation
  17089. (org-element-property :preserve-indent element)))))
  17090. (let ((offset (- ind (current-indentation))))
  17091. (unless (zerop offset)
  17092. (indent-rigidly (org-element-property :begin element)
  17093. (org-element-property :end element)
  17094. offset)))
  17095. (goto-char element-end))
  17096. ;; Elements indented line wise. Be sure to exclude
  17097. ;; example blocks (preserving indentation) and source
  17098. ;; blocks from this category as they are treated
  17099. ;; specially later.
  17100. ((or (memq type '(paragraph table table-row))
  17101. (not (or (org-element-property :contents-begin element)
  17102. (memq type '(example-block src-block)))))
  17103. (when (eq type 'node-property)
  17104. (org--align-node-property)
  17105. (beginning-of-line))
  17106. (funcall indent-to ind (min element-end end)))
  17107. ;; Elements consisting of three parts: before the
  17108. ;; contents, the contents, and after the contents. The
  17109. ;; contents are treated specially, according to the
  17110. ;; element type, or not indented at all. Other parts are
  17111. ;; indented as a single block.
  17112. (t
  17113. (let* ((post (copy-marker
  17114. (org-element-property :post-affiliated element)))
  17115. (cbeg
  17116. (copy-marker
  17117. (cond
  17118. ((not (org-element-property :contents-begin element))
  17119. ;; Fake contents for source blocks.
  17120. (org-with-wide-buffer
  17121. (goto-char post)
  17122. (line-beginning-position 2)))
  17123. ((memq type '(footnote-definition item plain-list))
  17124. ;; Contents in these elements could start on
  17125. ;; the same line as the beginning of the
  17126. ;; element. Make sure we start indenting
  17127. ;; from the second line.
  17128. (org-with-wide-buffer
  17129. (goto-char post)
  17130. (end-of-line)
  17131. (skip-chars-forward " \r\t\n")
  17132. (if (eobp) (point) (line-beginning-position))))
  17133. (t (org-element-property :contents-begin element)))))
  17134. (cend (copy-marker
  17135. (or (org-element-property :contents-end element)
  17136. ;; Fake contents for source blocks.
  17137. (org-with-wide-buffer
  17138. (goto-char element-end)
  17139. (skip-chars-backward " \r\t\n")
  17140. (line-beginning-position)))
  17141. t)))
  17142. ;; Do not change items indentation individually as it
  17143. ;; might break the list as a whole. On the other
  17144. ;; hand, when at a plain list, indent it as a whole.
  17145. (cond ((eq type 'plain-list)
  17146. (let ((offset (- ind (current-indentation))))
  17147. (unless (zerop offset)
  17148. (indent-rigidly (org-element-property :begin element)
  17149. (org-element-property :end element)
  17150. offset))
  17151. (goto-char cbeg)))
  17152. ((eq type 'item) (goto-char cbeg))
  17153. (t (funcall indent-to ind (min cbeg end))))
  17154. (when (< (point) end)
  17155. (cl-case type
  17156. ((example-block verse-block))
  17157. (src-block
  17158. ;; In a source block, indent source code
  17159. ;; according to language major mode, but only if
  17160. ;; `org-src-tab-acts-natively' is non-nil.
  17161. (when (and (< (point) end) org-src-tab-acts-natively)
  17162. (ignore-errors
  17163. (org-babel-do-in-edit-buffer
  17164. (indent-region (point-min) (point-max))))))
  17165. (t (org-indent-region (point) (min cend end))))
  17166. (goto-char (min cend end))
  17167. (when (< (point) end)
  17168. (funcall indent-to ind (min element-end end))))
  17169. (set-marker post nil)
  17170. (set-marker cbeg nil)
  17171. (set-marker cend nil))))
  17172. (set-marker element-end nil))))
  17173. (set-marker end nil))))
  17174. (defun org-indent-drawer ()
  17175. "Indent the drawer at point."
  17176. (interactive)
  17177. (unless (save-excursion
  17178. (beginning-of-line)
  17179. (looking-at-p org-drawer-regexp))
  17180. (user-error "Not at a drawer"))
  17181. (let ((element (org-element-at-point)))
  17182. (unless (memq (org-element-type element) '(drawer property-drawer))
  17183. (user-error "Not at a drawer"))
  17184. (org-with-wide-buffer
  17185. (org-indent-region (org-element-property :begin element)
  17186. (org-element-property :end element))))
  17187. (message "Drawer at point indented"))
  17188. (defun org-indent-block ()
  17189. "Indent the block at point."
  17190. (interactive)
  17191. (unless (save-excursion
  17192. (beginning-of-line)
  17193. (let ((case-fold-search t))
  17194. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17195. (user-error "Not at a block"))
  17196. (let ((element (org-element-at-point)))
  17197. (unless (memq (org-element-type element)
  17198. '(comment-block center-block dynamic-block example-block
  17199. export-block quote-block special-block
  17200. src-block verse-block))
  17201. (user-error "Not at a block"))
  17202. (org-with-wide-buffer
  17203. (org-indent-region (org-element-property :begin element)
  17204. (org-element-property :end element))))
  17205. (message "Block at point indented"))
  17206. ;;; Filling
  17207. ;; We use our own fill-paragraph and auto-fill functions.
  17208. ;; `org-fill-paragraph' relies on adaptive filling and context
  17209. ;; checking. Appropriate `fill-prefix' is computed with
  17210. ;; `org-adaptive-fill-function'.
  17211. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17212. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17213. ;; `org-adaptive-fill-function' value. Internally,
  17214. ;; `org-comment-line-break-function' breaks the line.
  17215. ;; `org-setup-filling' installs filling and auto-filling related
  17216. ;; variables during `org-mode' initialization.
  17217. (defun org-setup-filling ()
  17218. (require 'org-element)
  17219. ;; Prevent auto-fill from inserting unwanted new items.
  17220. (when (boundp 'fill-nobreak-predicate)
  17221. (setq-local
  17222. fill-nobreak-predicate
  17223. (org-uniquify
  17224. (append fill-nobreak-predicate
  17225. '(org-fill-line-break-nobreak-p
  17226. org-fill-n-macro-as-item-nobreak-p
  17227. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17228. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17229. (setq-local paragraph-start paragraph-ending)
  17230. (setq-local paragraph-separate paragraph-ending))
  17231. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17232. (setq-local auto-fill-inhibit-regexp nil)
  17233. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17234. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17235. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17236. (defun org-fill-line-break-nobreak-p ()
  17237. "Non-nil when a new line at point would create an Org line break."
  17238. (save-excursion
  17239. (skip-chars-backward " \t")
  17240. (skip-chars-backward "\\\\")
  17241. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17242. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17243. "Non-nil when a new line at point would split a timestamp."
  17244. (and (org-at-timestamp-p 'lax)
  17245. (not (looking-at org-ts-regexp-both))))
  17246. (defun org-fill-n-macro-as-item-nobreak-p ()
  17247. "Non-nil when a new line at point would create a new list."
  17248. ;; During export, a "n" macro followed by a dot or a closing
  17249. ;; parenthesis can end up being parsed as a new list item.
  17250. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17251. (defun org-adaptive-fill-function ()
  17252. "Compute a fill prefix for the current line.
  17253. Return fill prefix, as a string, or nil if current line isn't
  17254. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17255. matches in paragraphs or comments, use it."
  17256. (org-with-wide-buffer
  17257. (unless (org-at-heading-p)
  17258. (let* ((p (line-beginning-position))
  17259. (element (save-excursion
  17260. (beginning-of-line)
  17261. (org-element-at-point)))
  17262. (type (org-element-type element))
  17263. (post-affiliated (org-element-property :post-affiliated element)))
  17264. (unless (< p post-affiliated)
  17265. (cl-case type
  17266. (comment
  17267. (save-excursion
  17268. (beginning-of-line)
  17269. (looking-at "[ \t]*")
  17270. (concat (match-string 0) "# ")))
  17271. (footnote-definition "")
  17272. ((item plain-list)
  17273. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17274. (paragraph
  17275. ;; Fill prefix is usually the same as the current line,
  17276. ;; unless the paragraph is at the beginning of an item.
  17277. (let ((parent (org-element-property :parent element)))
  17278. (save-excursion
  17279. (beginning-of-line)
  17280. (cond ((eq (org-element-type parent) 'item)
  17281. (make-string (org-list-item-body-column
  17282. (org-element-property :begin parent))
  17283. ?\s))
  17284. ((and adaptive-fill-regexp
  17285. ;; Locally disable
  17286. ;; `adaptive-fill-function' to let
  17287. ;; `fill-context-prefix' handle
  17288. ;; `adaptive-fill-regexp' variable.
  17289. (let (adaptive-fill-function)
  17290. (fill-context-prefix
  17291. post-affiliated
  17292. (org-element-property :end element)))))
  17293. ((looking-at "[ \t]+") (match-string 0))
  17294. (t "")))))
  17295. (comment-block
  17296. ;; Only fill contents if P is within block boundaries.
  17297. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17298. (forward-line)
  17299. (point)))
  17300. (cend (save-excursion
  17301. (goto-char (org-element-property :end element))
  17302. (skip-chars-backward " \r\t\n")
  17303. (line-beginning-position))))
  17304. (when (and (>= p cbeg) (< p cend))
  17305. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17306. (match-string 0)
  17307. ""))))))))))
  17308. (defun org-fill-element (&optional justify)
  17309. "Fill element at point, when applicable.
  17310. This function only applies to comment blocks, comments, example
  17311. blocks and paragraphs. Also, as a special case, re-align table
  17312. when point is at one.
  17313. If JUSTIFY is non-nil (interactively, with prefix argument),
  17314. justify as well. If `sentence-end-double-space' is non-nil, then
  17315. period followed by one space does not end a sentence, so don't
  17316. break a line there. The variable `fill-column' controls the
  17317. width for filling.
  17318. For convenience, when point is at a plain list, an item or
  17319. a footnote definition, try to fill the first paragraph within."
  17320. (with-syntax-table org-mode-transpose-word-syntax-table
  17321. ;; Move to end of line in order to get the first paragraph within
  17322. ;; a plain list or a footnote definition.
  17323. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17324. ;; First check if point is in a blank line at the beginning of
  17325. ;; the buffer. In that case, ignore filling.
  17326. (cl-case (org-element-type element)
  17327. ;; Use major mode filling function is source blocks.
  17328. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17329. ;; Align Org tables, leave table.el tables as-is.
  17330. (table-row (org-table-align) t)
  17331. (table
  17332. (when (eq (org-element-property :type element) 'org)
  17333. (save-excursion
  17334. (goto-char (org-element-property :post-affiliated element))
  17335. (org-table-align)))
  17336. t)
  17337. (paragraph
  17338. ;; Paragraphs may contain `line-break' type objects.
  17339. (let ((beg (max (point-min)
  17340. (org-element-property :contents-begin element)))
  17341. (end (min (point-max)
  17342. (org-element-property :contents-end element))))
  17343. ;; Do nothing if point is at an affiliated keyword.
  17344. (if (< (line-end-position) beg) t
  17345. ;; Fill paragraph, taking line breaks into account.
  17346. (save-excursion
  17347. (goto-char beg)
  17348. (let ((cuts (list beg)))
  17349. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17350. (when (eq 'line-break
  17351. (org-element-type
  17352. (save-excursion (backward-char)
  17353. (org-element-context))))
  17354. (push (point) cuts)))
  17355. (dolist (c (delq end cuts))
  17356. (fill-region-as-paragraph c end justify)
  17357. (setq end c))))
  17358. t)))
  17359. ;; Contents of `comment-block' type elements should be
  17360. ;; filled as plain text, but only if point is within block
  17361. ;; markers.
  17362. (comment-block
  17363. (let* ((case-fold-search t)
  17364. (beg (save-excursion
  17365. (goto-char (org-element-property :begin element))
  17366. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17367. (forward-line)
  17368. (point)))
  17369. (end (save-excursion
  17370. (goto-char (org-element-property :end element))
  17371. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17372. (line-beginning-position))))
  17373. (if (or (< (point) beg) (> (point) end)) t
  17374. (fill-region-as-paragraph
  17375. (save-excursion (end-of-line)
  17376. (re-search-backward "^[ \t]*$" beg 'move)
  17377. (line-beginning-position))
  17378. (save-excursion (beginning-of-line)
  17379. (re-search-forward "^[ \t]*$" end 'move)
  17380. (line-beginning-position))
  17381. justify))))
  17382. ;; Fill comments.
  17383. (comment
  17384. (let ((begin (org-element-property :post-affiliated element))
  17385. (end (org-element-property :end element)))
  17386. (when (and (>= (point) begin) (<= (point) end))
  17387. (let ((begin (save-excursion
  17388. (end-of-line)
  17389. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17390. (progn (forward-line) (point))
  17391. begin)))
  17392. (end (save-excursion
  17393. (end-of-line)
  17394. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17395. (1- (line-beginning-position))
  17396. (skip-chars-backward " \r\t\n")
  17397. (line-end-position)))))
  17398. ;; Do not fill comments when at a blank line.
  17399. (when (> end begin)
  17400. (let ((fill-prefix
  17401. (save-excursion
  17402. (beginning-of-line)
  17403. (looking-at "[ \t]*#")
  17404. (let ((comment-prefix (match-string 0)))
  17405. (goto-char (match-end 0))
  17406. (if (looking-at adaptive-fill-regexp)
  17407. (concat comment-prefix (match-string 0))
  17408. (concat comment-prefix " "))))))
  17409. (save-excursion
  17410. (fill-region-as-paragraph begin end justify))))))
  17411. t))
  17412. ;; Ignore every other element.
  17413. (otherwise t)))))
  17414. (defun org-fill-paragraph (&optional justify region)
  17415. "Fill element at point, when applicable.
  17416. This function only applies to comment blocks, comments, example
  17417. blocks and paragraphs. Also, as a special case, re-align table
  17418. when point is at one.
  17419. For convenience, when point is at a plain list, an item or
  17420. a footnote definition, try to fill the first paragraph within.
  17421. If JUSTIFY is non-nil (interactively, with prefix argument),
  17422. justify as well. If `sentence-end-double-space' is non-nil, then
  17423. period followed by one space does not end a sentence, so don't
  17424. break a line there. The variable `fill-column' controls the
  17425. width for filling.
  17426. The REGION argument is non-nil if called interactively; in that
  17427. case, if Transient Mark mode is enabled and the mark is active,
  17428. fill each of the elements in the active region, instead of just
  17429. filling the current element."
  17430. (interactive (progn
  17431. (barf-if-buffer-read-only)
  17432. (list (when current-prefix-arg 'full) t)))
  17433. (let ((hash (and (not (buffer-modified-p))
  17434. (org-buffer-hash))))
  17435. (cond
  17436. ((and region transient-mark-mode mark-active
  17437. (not (eq (region-beginning) (region-end))))
  17438. (let ((origin (point-marker))
  17439. (start (region-beginning)))
  17440. (unwind-protect
  17441. (progn
  17442. (goto-char (region-end))
  17443. (while (> (point) start)
  17444. (org-backward-paragraph)
  17445. (org-fill-element justify)))
  17446. (goto-char origin)
  17447. (set-marker origin nil))))
  17448. (t (org-fill-element justify)))
  17449. ;; If we didn't change anything in the buffer (and the buffer was
  17450. ;; previously unmodified), then flip the modification status back
  17451. ;; to "unchanged".
  17452. (when (and hash (equal hash (org-buffer-hash)))
  17453. (set-buffer-modified-p nil))))
  17454. (defun org-auto-fill-function ()
  17455. "Auto-fill function."
  17456. ;; Check if auto-filling is meaningful.
  17457. (let ((fc (current-fill-column)))
  17458. (when (and fc (> (current-column) fc))
  17459. (let* ((fill-prefix (org-adaptive-fill-function))
  17460. ;; Enforce empty fill prefix, if required. Otherwise, it
  17461. ;; will be computed again.
  17462. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17463. (when fill-prefix (do-auto-fill))))))
  17464. (defun org-comment-line-break-function (&optional soft)
  17465. "Break line at point and indent, continuing comment if within one.
  17466. The inserted newline is marked hard if variable
  17467. `use-hard-newlines' is true, unless optional argument SOFT is
  17468. non-nil."
  17469. (if soft (insert-and-inherit ?\n) (newline 1))
  17470. (save-excursion (forward-char -1) (delete-horizontal-space))
  17471. (delete-horizontal-space)
  17472. (indent-to-left-margin)
  17473. (insert-before-markers-and-inherit fill-prefix))
  17474. ;;; Fixed Width Areas
  17475. (defun org-toggle-fixed-width ()
  17476. "Toggle fixed-width markup.
  17477. Add or remove fixed-width markup on current line, whenever it
  17478. makes sense. Return an error otherwise.
  17479. If a region is active and if it contains only fixed-width areas
  17480. or blank lines, remove all fixed-width markup in it. If the
  17481. region contains anything else, convert all non-fixed-width lines
  17482. to fixed-width ones.
  17483. Blank lines at the end of the region are ignored unless the
  17484. region only contains such lines."
  17485. (interactive)
  17486. (if (not (org-region-active-p))
  17487. ;; No region:
  17488. ;;
  17489. ;; Remove fixed width marker only in a fixed-with element.
  17490. ;;
  17491. ;; Add fixed width maker in paragraphs, in blank lines after
  17492. ;; elements or at the beginning of a headline or an inlinetask,
  17493. ;; and before any one-line elements (e.g., a clock).
  17494. (progn
  17495. (beginning-of-line)
  17496. (let* ((element (org-element-at-point))
  17497. (type (org-element-type element)))
  17498. (cond
  17499. ((and (eq type 'fixed-width)
  17500. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17501. (replace-match
  17502. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17503. ((and (memq type '(babel-call clock comment diary-sexp headline
  17504. horizontal-rule keyword paragraph
  17505. planning))
  17506. (<= (org-element-property :post-affiliated element) (point)))
  17507. (skip-chars-forward " \t")
  17508. (insert ": "))
  17509. ((and (looking-at-p "[ \t]*$")
  17510. (or (eq type 'inlinetask)
  17511. (save-excursion
  17512. (skip-chars-forward " \r\t\n")
  17513. (<= (org-element-property :end element) (point)))))
  17514. (delete-region (point) (line-end-position))
  17515. (org-indent-line)
  17516. (insert ": "))
  17517. (t (user-error "Cannot insert a fixed-width line here")))))
  17518. ;; Region active.
  17519. (let* ((begin (save-excursion
  17520. (goto-char (region-beginning))
  17521. (line-beginning-position)))
  17522. (end (copy-marker
  17523. (save-excursion
  17524. (goto-char (region-end))
  17525. (unless (eolp) (beginning-of-line))
  17526. (if (save-excursion (re-search-backward "\\S-" begin t))
  17527. (progn (skip-chars-backward " \r\t\n") (point))
  17528. (point)))))
  17529. (all-fixed-width-p
  17530. (catch 'not-all-p
  17531. (save-excursion
  17532. (goto-char begin)
  17533. (skip-chars-forward " \r\t\n")
  17534. (when (eobp) (throw 'not-all-p nil))
  17535. (while (< (point) end)
  17536. (let ((element (org-element-at-point)))
  17537. (if (eq (org-element-type element) 'fixed-width)
  17538. (goto-char (org-element-property :end element))
  17539. (throw 'not-all-p nil))))
  17540. t))))
  17541. (if all-fixed-width-p
  17542. (save-excursion
  17543. (goto-char begin)
  17544. (while (< (point) end)
  17545. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17546. (replace-match
  17547. "" nil nil nil
  17548. (if (= (line-end-position) (match-end 0)) 0 1)))
  17549. (forward-line)))
  17550. (let ((min-ind (point-max)))
  17551. ;; Find minimum indentation across all lines.
  17552. (save-excursion
  17553. (goto-char begin)
  17554. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17555. (setq min-ind 0)
  17556. (catch 'zerop
  17557. (while (< (point) end)
  17558. (unless (looking-at-p "[ \t]*$")
  17559. (let ((ind (current-indentation)))
  17560. (setq min-ind (min min-ind ind))
  17561. (when (zerop ind) (throw 'zerop t))))
  17562. (forward-line)))))
  17563. ;; Loop over all lines and add fixed-width markup everywhere
  17564. ;; but in fixed-width lines.
  17565. (save-excursion
  17566. (goto-char begin)
  17567. (while (< (point) end)
  17568. (cond
  17569. ((org-at-heading-p)
  17570. (insert ": ")
  17571. (forward-line)
  17572. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17573. (insert ":")
  17574. (forward-line)))
  17575. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17576. (let* ((element (org-element-at-point))
  17577. (element-end (org-element-property :end element)))
  17578. (if (eq (org-element-type element) 'fixed-width)
  17579. (progn (goto-char element-end)
  17580. (skip-chars-backward " \r\t\n")
  17581. (forward-line))
  17582. (let ((limit (min end element-end)))
  17583. (while (< (point) limit)
  17584. (org-move-to-column min-ind t)
  17585. (insert ": ")
  17586. (forward-line))))))
  17587. (t
  17588. (org-move-to-column min-ind t)
  17589. (insert ": ")
  17590. (forward-line)))))))
  17591. (set-marker end nil))))
  17592. ;;; Blocks
  17593. (defun org-block-map (function &optional start end)
  17594. "Call FUNCTION at the head of all source blocks in the current buffer.
  17595. Optional arguments START and END can be used to limit the range."
  17596. (let ((start (or start (point-min)))
  17597. (end (or end (point-max))))
  17598. (save-excursion
  17599. (goto-char start)
  17600. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17601. (save-excursion
  17602. (save-match-data
  17603. (goto-char (match-beginning 0))
  17604. (funcall function)))))))
  17605. (defun org-next-block (arg &optional backward block-regexp)
  17606. "Jump to the next block.
  17607. With a prefix argument ARG, jump forward ARG many blocks.
  17608. When BACKWARD is non-nil, jump to the previous block.
  17609. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17610. Match data is set according to this regexp when the function
  17611. returns.
  17612. Return point at beginning of the opening line of found block.
  17613. Throw an error if no block is found."
  17614. (interactive "p")
  17615. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17616. (case-fold-search t)
  17617. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17618. (count (or arg 1))
  17619. (origin (point))
  17620. last-element)
  17621. (if backward (beginning-of-line) (end-of-line))
  17622. (while (and (> count 0) (funcall search-fn re nil t))
  17623. (let ((element (save-excursion
  17624. (goto-char (match-beginning 0))
  17625. (save-match-data (org-element-at-point)))))
  17626. (when (and (memq (org-element-type element)
  17627. '(center-block comment-block dynamic-block
  17628. example-block export-block quote-block
  17629. special-block src-block verse-block))
  17630. (<= (match-beginning 0)
  17631. (org-element-property :post-affiliated element)))
  17632. (setq last-element element)
  17633. (cl-decf count))))
  17634. (if (= count 0)
  17635. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17636. (save-match-data (org-show-context)))
  17637. (goto-char origin)
  17638. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17639. (defun org-previous-block (arg &optional block-regexp)
  17640. "Jump to the previous block.
  17641. With a prefix argument ARG, jump backward ARG many source blocks.
  17642. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17643. (interactive "p")
  17644. (org-next-block arg t block-regexp))
  17645. ;;; Comments
  17646. ;; Org comments syntax is quite complex. It requires the entire line
  17647. ;; to be just a comment. Also, even with the right syntax at the
  17648. ;; beginning of line, some elements (e.g., verse-block or
  17649. ;; example-block) don't accept comments. Usual Emacs comment commands
  17650. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17651. ;; Org still relies on `comment-dwim', but cannot trust
  17652. ;; `comment-only-p'. So, `comment-region-function' and
  17653. ;; `uncomment-region-function' both point
  17654. ;; to`org-comment-or-uncomment-region'. Eventually,
  17655. ;; `org-insert-comment' takes care of insertion of comments at the
  17656. ;; beginning of line.
  17657. ;; `org-setup-comments-handling' install comments related variables
  17658. ;; during `org-mode' initialization.
  17659. (defun org-setup-comments-handling ()
  17660. (interactive)
  17661. (setq-local comment-use-syntax nil)
  17662. (setq-local comment-start "# ")
  17663. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17664. (setq-local comment-insert-comment-function 'org-insert-comment)
  17665. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17666. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17667. (defun org-insert-comment ()
  17668. "Insert an empty comment above current line.
  17669. If the line is empty, insert comment at its beginning. When
  17670. point is within a source block, comment according to the related
  17671. major mode."
  17672. (if (let ((element (org-element-at-point)))
  17673. (and (eq (org-element-type element) 'src-block)
  17674. (< (save-excursion
  17675. (goto-char (org-element-property :post-affiliated element))
  17676. (line-end-position))
  17677. (point))
  17678. (> (save-excursion
  17679. (goto-char (org-element-property :end element))
  17680. (skip-chars-backward " \r\t\n")
  17681. (line-beginning-position))
  17682. (point))))
  17683. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17684. (beginning-of-line)
  17685. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17686. (open-line 1))
  17687. (org-indent-line)
  17688. (insert "# ")))
  17689. (defvar comment-empty-lines) ; From newcomment.el.
  17690. (defun org-comment-or-uncomment-region (beg end &rest _)
  17691. "Comment or uncomment each non-blank line in the region.
  17692. Uncomment each non-blank line between BEG and END if it only
  17693. contains commented lines. Otherwise, comment them. If region is
  17694. strictly within a source block, use appropriate comment syntax."
  17695. (if (let ((element (org-element-at-point)))
  17696. (and (eq (org-element-type element) 'src-block)
  17697. (< (save-excursion
  17698. (goto-char (org-element-property :post-affiliated element))
  17699. (line-end-position))
  17700. beg)
  17701. (>= (save-excursion
  17702. (goto-char (org-element-property :end element))
  17703. (skip-chars-backward " \r\t\n")
  17704. (line-beginning-position))
  17705. end)))
  17706. ;; Translate region boundaries for the Org buffer to the source
  17707. ;; buffer.
  17708. (let ((offset (- end beg)))
  17709. (save-excursion
  17710. (goto-char beg)
  17711. (org-babel-do-in-edit-buffer
  17712. (comment-or-uncomment-region (point) (+ offset (point))))))
  17713. (save-restriction
  17714. ;; Restrict region
  17715. (narrow-to-region (save-excursion (goto-char beg)
  17716. (skip-chars-forward " \r\t\n" end)
  17717. (line-beginning-position))
  17718. (save-excursion (goto-char end)
  17719. (skip-chars-backward " \r\t\n" beg)
  17720. (line-end-position)))
  17721. (let ((uncommentp
  17722. ;; UNCOMMENTP is non-nil when every non blank line between
  17723. ;; BEG and END is a comment.
  17724. (save-excursion
  17725. (goto-char (point-min))
  17726. (while (and (not (eobp))
  17727. (let ((element (org-element-at-point)))
  17728. (and (eq (org-element-type element) 'comment)
  17729. (goto-char (min (point-max)
  17730. (org-element-property
  17731. :end element)))))))
  17732. (eobp))))
  17733. (if uncommentp
  17734. ;; Only blank lines and comments in region: uncomment it.
  17735. (save-excursion
  17736. (goto-char (point-min))
  17737. (while (not (eobp))
  17738. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17739. (replace-match "" nil nil nil 1))
  17740. (forward-line)))
  17741. ;; Comment each line in region.
  17742. (let ((min-indent (point-max)))
  17743. ;; First find the minimum indentation across all lines.
  17744. (save-excursion
  17745. (goto-char (point-min))
  17746. (while (and (not (eobp)) (not (zerop min-indent)))
  17747. (unless (looking-at "[ \t]*$")
  17748. (setq min-indent (min min-indent (current-indentation))))
  17749. (forward-line)))
  17750. ;; Then loop over all lines.
  17751. (save-excursion
  17752. (goto-char (point-min))
  17753. (while (not (eobp))
  17754. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17755. ;; Don't get fooled by invisible text (e.g. link path)
  17756. ;; when moving to column MIN-INDENT.
  17757. (let ((buffer-invisibility-spec nil))
  17758. (org-move-to-column min-indent t))
  17759. (insert comment-start))
  17760. (forward-line)))))))))
  17761. (defun org-comment-dwim (_arg)
  17762. "Call the comment command you mean.
  17763. Call `org-toggle-comment' if on a heading, otherwise call
  17764. `comment-dwim', within a source edit buffer if needed."
  17765. (interactive "*P")
  17766. (cond ((org-at-heading-p)
  17767. (call-interactively #'org-toggle-comment))
  17768. ((org-in-src-block-p)
  17769. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17770. (t (call-interactively #'comment-dwim))))
  17771. ;;; Timestamps API
  17772. ;; This section contains tools to operate on, or create, timestamp
  17773. ;; objects, as returned by, e.g. `org-element-context'.
  17774. (defun org-timestamp-from-string (s)
  17775. "Convert Org timestamp S, as a string, into a timestamp object.
  17776. Return nil if S is not a valid timestamp string."
  17777. (when (org-string-nw-p s)
  17778. (with-temp-buffer
  17779. (save-excursion (insert s))
  17780. (org-element-timestamp-parser))))
  17781. (defun org-timestamp-from-time (time &optional with-time inactive)
  17782. "Convert a time value into a timestamp object.
  17783. TIME is an Emacs internal time representation, as returned, e.g.,
  17784. by `current-time'.
  17785. When optional argument WITH-TIME is non-nil, return a timestamp
  17786. object with a time part, i.e., with hours and minutes.
  17787. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17788. return an active timestamp."
  17789. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17790. (org-element-create 'timestamp
  17791. (list :type (if inactive 'inactive 'active)
  17792. :year-start year
  17793. :month-start month
  17794. :day-start day
  17795. :hour-start (and with-time hour)
  17796. :minute-start (and with-time minute)))))
  17797. (defun org-timestamp-to-time (timestamp &optional end)
  17798. "Convert TIMESTAMP object into an Emacs internal time value.
  17799. Use end of date range or time range when END is non-nil.
  17800. Otherwise, use its start."
  17801. (apply #'encode-time 0
  17802. (mapcar
  17803. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17804. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17805. '(:minute-start :hour-start :day-start :month-start
  17806. :year-start)))))
  17807. (defun org-timestamp-has-time-p (timestamp)
  17808. "Non-nil when TIMESTAMP has a time specified."
  17809. (org-element-property :hour-start timestamp))
  17810. (defun org-timestamp-format (timestamp format &optional end utc)
  17811. "Format a TIMESTAMP object into a string.
  17812. FORMAT is a format specifier to be passed to
  17813. `format-time-string'.
  17814. When optional argument END is non-nil, use end of date-range or
  17815. time-range, if possible.
  17816. When optional argument UTC is non-nil, time is be expressed as
  17817. Universal Time."
  17818. (format-time-string format (org-timestamp-to-time timestamp end)
  17819. (and utc t)))
  17820. (defun org-timestamp-split-range (timestamp &optional end)
  17821. "Extract a TIMESTAMP object from a date or time range.
  17822. END, when non-nil, means extract the end of the range.
  17823. Otherwise, extract its start.
  17824. Return a new timestamp object."
  17825. (let ((type (org-element-property :type timestamp)))
  17826. (if (memq type '(active inactive diary)) timestamp
  17827. (let ((split-ts (org-element-copy timestamp)))
  17828. ;; Set new type.
  17829. (org-element-put-property
  17830. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17831. ;; Copy start properties over end properties if END is
  17832. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17833. (let ((p-alist '((:minute-start . :minute-end)
  17834. (:hour-start . :hour-end)
  17835. (:day-start . :day-end)
  17836. (:month-start . :month-end)
  17837. (:year-start . :year-end))))
  17838. (dolist (p-cell p-alist)
  17839. (org-element-put-property
  17840. split-ts
  17841. (funcall (if end #'car #'cdr) p-cell)
  17842. (org-element-property
  17843. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17844. ;; Eventually refresh `:raw-value'.
  17845. (org-element-put-property split-ts :raw-value nil)
  17846. (org-element-put-property
  17847. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17848. (defun org-timestamp-translate (timestamp &optional boundary)
  17849. "Translate TIMESTAMP object to custom format.
  17850. Format string is defined in `org-time-stamp-custom-formats',
  17851. which see.
  17852. When optional argument BOUNDARY is non-nil, it is either the
  17853. symbol `start' or `end'. In this case, only translate the
  17854. starting or ending part of TIMESTAMP if it is a date or time
  17855. range. Otherwise, translate both parts.
  17856. Return timestamp as-is if `org-display-custom-times' is nil or if
  17857. it has a `diary' type."
  17858. (let ((type (org-element-property :type timestamp)))
  17859. (if (or (not org-display-custom-times) (eq type 'diary))
  17860. (org-element-interpret-data timestamp)
  17861. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17862. org-time-stamp-custom-formats)))
  17863. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17864. (concat (org-timestamp-format timestamp fmt)
  17865. "--"
  17866. (org-timestamp-format timestamp fmt t))
  17867. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17868. ;;; Other stuff
  17869. (defvar reftex-docstruct-symbol)
  17870. (defvar org--rds)
  17871. (defun org-reftex-citation ()
  17872. "Use reftex-citation to insert a citation into the buffer.
  17873. This looks for a line like
  17874. #+BIBLIOGRAPHY: foo plain option:-d
  17875. and derives from it that foo.bib is the bibliography file relevant
  17876. for this document. It then installs the necessary environment for RefTeX
  17877. to work in this buffer and calls `reftex-citation' to insert a citation
  17878. into the buffer.
  17879. Export of such citations to both LaTeX and HTML is handled by the contributed
  17880. package ox-bibtex by Taru Karttunen."
  17881. (interactive)
  17882. (let ((reftex-docstruct-symbol 'org--rds)
  17883. org--rds bib)
  17884. (org-with-wide-buffer
  17885. (let ((case-fold-search t)
  17886. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17887. (if (not (save-excursion
  17888. (or (re-search-forward re nil t)
  17889. (re-search-backward re nil t))))
  17890. (user-error "No bibliography defined in file")
  17891. (setq bib (concat (match-string 1) ".bib")
  17892. org--rds (list (list 'bib bib))))))
  17893. (call-interactively 'reftex-citation)))
  17894. ;;;; Functions extending outline functionality
  17895. (defun org-beginning-of-line (&optional n)
  17896. "Go to the beginning of the current visible line.
  17897. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17898. symbol `reversed', on the first attempt move to where the
  17899. headline text starts, and only move to beginning of line when the
  17900. cursor is already before the start of the text of the headline.
  17901. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17902. start of the text on the second attempt.
  17903. With argument N not nil or 1, move forward N - 1 lines first."
  17904. (interactive "^p")
  17905. (let ((origin (point))
  17906. (special (pcase org-special-ctrl-a/e
  17907. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17908. deactivate-mark)
  17909. ;; First move to a visible line.
  17910. (if (bound-and-true-p visual-line-mode)
  17911. (beginning-of-visual-line n)
  17912. (move-beginning-of-line n)
  17913. ;; `move-beginning-of-line' may leave point after invisible
  17914. ;; characters if line starts with such of these (e.g., with
  17915. ;; a link at column 0). Really move to the beginning of the
  17916. ;; current visible line.
  17917. (beginning-of-line))
  17918. (cond
  17919. ;; No special behavior. Point is already at the beginning of
  17920. ;; a line, logical or visual.
  17921. ((not special))
  17922. ;; `beginning-of-visual-line' left point before logical beginning
  17923. ;; of line: point is at the beginning of a visual line. Bail
  17924. ;; out.
  17925. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17926. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17927. ;; At a headline, special position is before the title, but
  17928. ;; after any TODO keyword or priority cookie.
  17929. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17930. (line-end-position)))
  17931. (bol (point)))
  17932. (if (eq special 'reversed)
  17933. (when (and (= origin bol) (eq last-command this-command))
  17934. (goto-char refpos))
  17935. (when (or (> origin refpos) (= origin bol))
  17936. (goto-char refpos)))))
  17937. ((and (looking-at org-list-full-item-re)
  17938. (memq (org-element-type (save-match-data (org-element-at-point)))
  17939. '(item plain-list)))
  17940. ;; Set special position at first white space character after
  17941. ;; bullet, and check-box, if any.
  17942. (let ((after-bullet
  17943. (let ((box (match-end 3)))
  17944. (cond ((not box) (match-end 1))
  17945. ((eq (char-after box) ?\s) (1+ box))
  17946. (t box)))))
  17947. (if (eq special 'reversed)
  17948. (when (and (= (point) origin) (eq last-command this-command))
  17949. (goto-char after-bullet))
  17950. (when (or (> origin after-bullet) (= (point) origin))
  17951. (goto-char after-bullet)))))
  17952. ;; No special context. Point is already at beginning of line.
  17953. (t nil))))
  17954. (defun org-end-of-line (&optional n)
  17955. "Go to the end of the line, but before ellipsis, if any.
  17956. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17957. symbol `reversed', ignore tags on the first attempt, and only
  17958. move to after the tags when the cursor is already beyond the end
  17959. of the headline.
  17960. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17961. on the second attempt.
  17962. With argument N not nil or 1, move forward N - 1 lines first."
  17963. (interactive "^p")
  17964. (let ((origin (point))
  17965. (special (pcase org-special-ctrl-a/e
  17966. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17967. deactivate-mark)
  17968. ;; First move to a visible line.
  17969. (if (bound-and-true-p visual-line-mode)
  17970. (beginning-of-visual-line n)
  17971. (move-beginning-of-line n))
  17972. (cond
  17973. ;; At a headline, with tags.
  17974. ((and special
  17975. (save-excursion
  17976. (beginning-of-line)
  17977. (let ((case-fold-search nil))
  17978. (looking-at org-complex-heading-regexp)))
  17979. (match-end 5))
  17980. (let ((tags (save-excursion
  17981. (goto-char (match-beginning 5))
  17982. (skip-chars-backward " \t")
  17983. (point)))
  17984. (visual-end (and (bound-and-true-p visual-line-mode)
  17985. (save-excursion
  17986. (end-of-visual-line)
  17987. (point)))))
  17988. ;; If `end-of-visual-line' brings us before end of line or
  17989. ;; even tags, i.e., the headline spans over multiple visual
  17990. ;; lines, move there.
  17991. (cond ((and visual-end
  17992. (< visual-end tags)
  17993. (<= origin visual-end))
  17994. (goto-char visual-end))
  17995. ((eq special 'reversed)
  17996. (if (and (= origin (line-end-position))
  17997. (eq this-command last-command))
  17998. (goto-char tags)
  17999. (end-of-line)))
  18000. (t
  18001. (if (or (< origin tags) (= origin (line-end-position)))
  18002. (goto-char tags)
  18003. (end-of-line))))))
  18004. ((bound-and-true-p visual-line-mode)
  18005. (let ((bol (line-beginning-position)))
  18006. (end-of-visual-line)
  18007. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18008. ;; end of a line, backtrack and use `end-of-line' instead.
  18009. (when (/= bol (line-beginning-position))
  18010. (goto-char bol)
  18011. (end-of-line))))
  18012. (t (end-of-line)))))
  18013. (defun org-backward-sentence (&optional _arg)
  18014. "Go to beginning of sentence, or beginning of table field.
  18015. This will call `backward-sentence' or `org-table-beginning-of-field',
  18016. depending on context."
  18017. (interactive)
  18018. (let* ((element (org-element-at-point))
  18019. (contents-begin (org-element-property :contents-begin element))
  18020. (table (org-element-lineage element '(table) t)))
  18021. (if (and table
  18022. (> (point) contents-begin)
  18023. (<= (point) (org-element-property :contents-end table)))
  18024. (call-interactively #'org-table-beginning-of-field)
  18025. (save-restriction
  18026. (when (and contents-begin
  18027. (< (point-min) contents-begin)
  18028. (> (point) contents-begin))
  18029. (narrow-to-region contents-begin
  18030. (org-element-property :contents-end element)))
  18031. (call-interactively #'backward-sentence)))))
  18032. (defun org-forward-sentence (&optional _arg)
  18033. "Go to end of sentence, or end of table field.
  18034. This will call `forward-sentence' or `org-table-end-of-field',
  18035. depending on context."
  18036. (interactive)
  18037. (if (and (org-at-heading-p)
  18038. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18039. (save-restriction
  18040. (narrow-to-region (line-beginning-position) (line-end-position))
  18041. (call-interactively #'forward-sentence))
  18042. (let* ((element (org-element-at-point))
  18043. (contents-end (org-element-property :contents-end element))
  18044. (table (org-element-lineage element '(table) t)))
  18045. (if (and table
  18046. (>= (point) (org-element-property :contents-begin table))
  18047. (< (point) contents-end))
  18048. (call-interactively #'org-table-end-of-field)
  18049. (save-restriction
  18050. (when (and contents-end
  18051. (> (point-max) contents-end)
  18052. ;; Skip blank lines between elements.
  18053. (< (org-element-property :end element)
  18054. (save-excursion (goto-char contents-end)
  18055. (skip-chars-forward " \r\t\n"))))
  18056. (narrow-to-region (org-element-property :contents-begin element)
  18057. contents-end))
  18058. ;; End of heading is considered as the end of a sentence.
  18059. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18060. (call-interactively #'forward-sentence)))))))
  18061. (defun org-kill-line (&optional _arg)
  18062. "Kill line, to tags or end of line."
  18063. (interactive)
  18064. (cond
  18065. ((or (not org-special-ctrl-k)
  18066. (bolp)
  18067. (not (org-at-heading-p)))
  18068. (when (and (get-char-property (line-end-position) 'invisible)
  18069. org-ctrl-k-protect-subtree
  18070. (or (eq org-ctrl-k-protect-subtree 'error)
  18071. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18072. (user-error
  18073. (substitute-command-keys
  18074. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18075. (call-interactively
  18076. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18077. ((org-match-line org-tag-line-re)
  18078. (let ((end (save-excursion
  18079. (goto-char (match-beginning 1))
  18080. (skip-chars-backward " \t")
  18081. (point))))
  18082. (if (<= end (point)) ;on tags part
  18083. (kill-region (point) (line-end-position))
  18084. (kill-region (point) end)))
  18085. (org-align-tags))
  18086. (t (kill-region (point) (line-end-position)))))
  18087. (defun org-yank (&optional arg)
  18088. "Yank. If the kill is a subtree, treat it specially.
  18089. This command will look at the current kill and check if is a single
  18090. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18091. cursor is at the beginning of a line or after the stars of a currently
  18092. empty headline, then the yank is handled specially. How exactly depends
  18093. on the value of the following variables.
  18094. `org-yank-folded-subtrees'
  18095. By default, this variable is non-nil, which results in
  18096. subtree(s) being folded after insertion, except if doing so
  18097. would swallow text after the yanked text.
  18098. `org-yank-adjusted-subtrees'
  18099. When non-nil (the default value is nil), the subtree will be
  18100. promoted or demoted in order to fit into the local outline tree
  18101. structure, which means that the level will be adjusted so that it
  18102. becomes the smaller one of the two *visible* surrounding headings.
  18103. Any prefix to this command will cause `yank' to be called directly with
  18104. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18105. will just
  18106. plainly yank the text as it is.
  18107. \[1] The test checks if the first non-white line is a heading
  18108. and if there are no other headings with fewer stars."
  18109. (interactive "P")
  18110. (org-yank-generic 'yank arg))
  18111. (defun org-yank-generic (command arg)
  18112. "Perform some yank-like command.
  18113. This function implements the behavior described in the `org-yank'
  18114. documentation. However, it has been generalized to work for any
  18115. interactive command with similar behavior."
  18116. ;; pretend to be command COMMAND
  18117. (setq this-command command)
  18118. (if arg
  18119. (call-interactively command)
  18120. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18121. (and (org-kill-is-subtree-p)
  18122. (or (bolp)
  18123. (and (looking-at "[ \t]*$")
  18124. (string-match
  18125. "\\`\\*+\\'"
  18126. (buffer-substring (point-at-bol) (point)))))))
  18127. swallowp)
  18128. (cond
  18129. ((and subtreep org-yank-folded-subtrees)
  18130. (let ((beg (point))
  18131. end)
  18132. (if (and subtreep org-yank-adjusted-subtrees)
  18133. (org-paste-subtree nil nil 'for-yank)
  18134. (call-interactively command))
  18135. (setq end (point))
  18136. (goto-char beg)
  18137. (when (and (bolp) subtreep
  18138. (not (setq swallowp
  18139. (org-yank-folding-would-swallow-text beg end))))
  18140. (org-with-limited-levels
  18141. (or (looking-at org-outline-regexp)
  18142. (re-search-forward org-outline-regexp-bol end t))
  18143. (while (and (< (point) end) (looking-at org-outline-regexp))
  18144. (org-flag-subtree t)
  18145. (org-cycle-show-empty-lines 'folded)
  18146. (condition-case nil
  18147. (outline-forward-same-level 1)
  18148. (error (goto-char end))))))
  18149. (when swallowp
  18150. (message
  18151. "Inserted text not folded because that would swallow text"))
  18152. (goto-char end)
  18153. (skip-chars-forward " \t\n\r")
  18154. (beginning-of-line 1)
  18155. (push-mark beg 'nomsg)))
  18156. ((and subtreep org-yank-adjusted-subtrees)
  18157. (let ((beg (point-at-bol)))
  18158. (org-paste-subtree nil nil 'for-yank)
  18159. (push-mark beg 'nomsg)))
  18160. (t
  18161. (call-interactively command))))))
  18162. (defun org-yank-folding-would-swallow-text (beg end)
  18163. "Would hide-subtree at BEG swallow any text after END?"
  18164. (let (level)
  18165. (org-with-limited-levels
  18166. (save-excursion
  18167. (goto-char beg)
  18168. (when (or (looking-at org-outline-regexp)
  18169. (re-search-forward org-outline-regexp-bol end t))
  18170. (setq level (org-outline-level)))
  18171. (goto-char end)
  18172. (skip-chars-forward " \t\r\n\v\f")
  18173. (not (or (eobp)
  18174. (and (bolp) (looking-at-p org-outline-regexp)
  18175. (<= (org-outline-level) level))))))))
  18176. (defun org-back-to-heading (&optional invisible-ok)
  18177. "Call `outline-back-to-heading', but provide a better error message."
  18178. (condition-case nil
  18179. (outline-back-to-heading invisible-ok)
  18180. (error
  18181. (user-error "Before first headline at position %d in buffer %s"
  18182. (point) (current-buffer)))))
  18183. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18184. "Go back to heading or first point in buffer.
  18185. If point is before first heading go to first point in buffer
  18186. instead of back to heading."
  18187. (condition-case nil
  18188. (outline-back-to-heading invisible-ok)
  18189. (error
  18190. (goto-char (point-min)))))
  18191. (defun org-before-first-heading-p ()
  18192. "Before first heading?"
  18193. (org-with-limited-levels
  18194. (save-excursion
  18195. (end-of-line)
  18196. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18197. (defun org-at-heading-p (&optional _)
  18198. "Non-nil when on a headline."
  18199. (outline-on-heading-p t))
  18200. (defun org-in-commented-heading-p (&optional no-inheritance)
  18201. "Non-nil if point is under a commented heading.
  18202. This function also checks ancestors of the current headline,
  18203. unless optional argument NO-INHERITANCE is non-nil."
  18204. (cond
  18205. ((org-before-first-heading-p) nil)
  18206. ((let ((headline (nth 4 (org-heading-components))))
  18207. (and headline
  18208. (let ((case-fold-search nil))
  18209. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18210. headline)))))
  18211. (no-inheritance nil)
  18212. (t
  18213. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18214. (defun org-at-comment-p nil
  18215. "Return t if cursor is in a commented line."
  18216. (save-excursion
  18217. (save-match-data
  18218. (beginning-of-line)
  18219. (looking-at "^[ \t]*# "))))
  18220. (defun org-at-keyword-p nil
  18221. "Return t if cursor is at a keyword-line."
  18222. (save-excursion
  18223. (move-beginning-of-line 1)
  18224. (looking-at org-keyword-regexp)))
  18225. (defun org-at-drawer-p nil
  18226. "Return t if cursor is at a drawer keyword."
  18227. (save-excursion
  18228. (move-beginning-of-line 1)
  18229. (looking-at org-drawer-regexp)))
  18230. (defun org-at-block-p nil
  18231. "Return t if cursor is at a block keyword."
  18232. (save-excursion
  18233. (move-beginning-of-line 1)
  18234. (looking-at org-block-regexp)))
  18235. (defun org-point-at-end-of-empty-headline ()
  18236. "If point is at the end of an empty headline, return t, else nil.
  18237. If the heading only contains a TODO keyword, it is still still considered
  18238. empty."
  18239. (let ((case-fold-search nil))
  18240. (and (looking-at "[ \t]*$")
  18241. org-todo-line-regexp
  18242. (save-excursion
  18243. (beginning-of-line)
  18244. (looking-at org-todo-line-regexp)
  18245. (string= (match-string 3) "")))))
  18246. (defun org-at-heading-or-item-p ()
  18247. (or (org-at-heading-p) (org-at-item-p)))
  18248. (defun org-up-heading-all (arg)
  18249. "Move to the heading line of which the present line is a subheading.
  18250. This function considers both visible and invisible heading lines.
  18251. With argument, move up ARG levels."
  18252. (outline-up-heading arg t))
  18253. (defun org-up-heading-safe ()
  18254. "Move to the heading line of which the present line is a subheading.
  18255. This version will not throw an error. It will return the level of the
  18256. headline found, or nil if no higher level is found.
  18257. Also, this function will be a lot faster than `outline-up-heading',
  18258. because it relies on stars being the outline starters. This can really
  18259. make a significant difference in outlines with very many siblings."
  18260. (when (ignore-errors (org-back-to-heading t))
  18261. (let ((level-up (1- (funcall outline-level))))
  18262. (and (> level-up 0)
  18263. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18264. (funcall outline-level)))))
  18265. (defun org-up-heading-or-point-min ()
  18266. "Move to the heading line of which the present is a subheading, or point-min.
  18267. This version is needed to make point-min behave like a virtual
  18268. heading of level 0 for property-inheritance. It will return the
  18269. level of the headline found (down to 0) or nil if already at a
  18270. point before the first headline or at point-min."
  18271. (when (ignore-errors (org-back-to-heading t))
  18272. (if (< 1 (funcall outline-level))
  18273. (org-up-heading-safe)
  18274. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18275. (defun org-first-sibling-p ()
  18276. "Is this heading the first child of its parents?"
  18277. (interactive)
  18278. (let ((re org-outline-regexp-bol)
  18279. level l)
  18280. (unless (org-at-heading-p t)
  18281. (user-error "Not at a heading"))
  18282. (setq level (funcall outline-level))
  18283. (save-excursion
  18284. (if (not (re-search-backward re nil t))
  18285. t
  18286. (setq l (funcall outline-level))
  18287. (< l level)))))
  18288. (defun org-goto-sibling (&optional previous)
  18289. "Goto the next sibling, even if it is invisible.
  18290. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18291. when a sibling was found. When none is found, return nil and don't
  18292. move point."
  18293. (let ((fun (if previous 're-search-backward 're-search-forward))
  18294. (pos (point))
  18295. (re org-outline-regexp-bol)
  18296. level l)
  18297. (when (ignore-errors (org-back-to-heading t))
  18298. (setq level (funcall outline-level))
  18299. (catch 'exit
  18300. (or previous (forward-char 1))
  18301. (while (funcall fun re nil t)
  18302. (setq l (funcall outline-level))
  18303. (when (< l level) (goto-char pos) (throw 'exit nil))
  18304. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18305. (goto-char pos)
  18306. nil))))
  18307. (defun org-show-siblings ()
  18308. "Show all siblings of the current headline."
  18309. (save-excursion
  18310. (while (org-goto-sibling) (org-flag-heading nil)))
  18311. (save-excursion
  18312. (while (org-goto-sibling 'previous)
  18313. (org-flag-heading nil))))
  18314. (defun org-goto-first-child ()
  18315. "Goto the first child, even if it is invisible.
  18316. Return t when a child was found. Otherwise don't move point and
  18317. return nil."
  18318. (let (level (pos (point)) (re org-outline-regexp-bol))
  18319. (when (ignore-errors (org-back-to-heading t))
  18320. (setq level (outline-level))
  18321. (forward-char 1)
  18322. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18323. (progn (goto-char (match-beginning 0)) t)
  18324. (goto-char pos) nil))))
  18325. (defun org-show-hidden-entry ()
  18326. "Show an entry where even the heading is hidden."
  18327. (save-excursion
  18328. (org-show-entry)))
  18329. (defun org-flag-heading (flag &optional entry)
  18330. "Flag the current heading. FLAG non-nil means make invisible.
  18331. When ENTRY is non-nil, show the entire entry."
  18332. (save-excursion
  18333. (org-back-to-heading t)
  18334. ;; Check if we should show the entire entry
  18335. (if (not entry)
  18336. (org-flag-region
  18337. (line-end-position 0) (line-end-position) flag 'outline)
  18338. (org-show-entry)
  18339. (save-excursion
  18340. (and (outline-next-heading)
  18341. (org-flag-heading nil))))))
  18342. (defun org-get-next-sibling ()
  18343. "Move to next heading of the same level, and return point.
  18344. If there is no such heading, return nil.
  18345. This is like outline-next-sibling, but invisible headings are ok."
  18346. (let ((level (funcall outline-level)))
  18347. (outline-next-heading)
  18348. (while (and (not (eobp)) (> (funcall outline-level) level))
  18349. (outline-next-heading))
  18350. (unless (or (eobp) (< (funcall outline-level) level))
  18351. (point))))
  18352. (defun org-get-last-sibling ()
  18353. "Move to previous heading of the same level, and return point.
  18354. If there is no such heading, return nil."
  18355. (let ((opoint (point))
  18356. (level (funcall outline-level)))
  18357. (outline-previous-heading)
  18358. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18359. (while (and (> (funcall outline-level) level)
  18360. (not (bobp)))
  18361. (outline-previous-heading))
  18362. (unless (< (funcall outline-level) level)
  18363. (point)))))
  18364. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18365. "Goto to the end of a subtree."
  18366. ;; This contains an exact copy of the original function, but it uses
  18367. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18368. ;; trees and before first headline. And is uses an invisible-ok argument.
  18369. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18370. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18371. ;; with many children and grandchildren etc, this can be much faster
  18372. ;; than the outline version.
  18373. (org-back-to-heading-or-point-min invisible-ok)
  18374. (let ((first t)
  18375. (level (funcall outline-level)))
  18376. (cond ((= level 0)
  18377. (goto-char (point-max)))
  18378. ((and (derived-mode-p 'org-mode) (< level 1000))
  18379. ;; A true heading (not a plain list item), in Org
  18380. ;; This means we can easily find the end by looking
  18381. ;; only for the right number of stars. Using a regexp to do
  18382. ;; this is so much faster than using a Lisp loop.
  18383. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18384. (forward-char 1)
  18385. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18386. (t
  18387. ;; something else, do it the slow way
  18388. (while (and (not (eobp))
  18389. (or first (> (funcall outline-level) level)))
  18390. (setq first nil)
  18391. (outline-next-heading))))
  18392. (unless to-heading
  18393. (when (memq (preceding-char) '(?\n ?\^M))
  18394. ;; Go to end of line before heading
  18395. (forward-char -1)
  18396. (when (memq (preceding-char) '(?\n ?\^M))
  18397. ;; leave blank line before heading
  18398. (forward-char -1)))))
  18399. (point))
  18400. (defun org-end-of-meta-data (&optional full)
  18401. "Skip planning line and properties drawer in current entry.
  18402. When optional argument FULL is non-nil, also skip empty lines,
  18403. clocking lines and regular drawers at the beginning of the
  18404. entry."
  18405. (org-back-to-heading t)
  18406. (forward-line)
  18407. (when (looking-at-p org-planning-line-re) (forward-line))
  18408. (when (looking-at org-property-drawer-re)
  18409. (goto-char (match-end 0))
  18410. (forward-line))
  18411. (when (and full (not (org-at-heading-p)))
  18412. (catch 'exit
  18413. (let ((end (save-excursion (outline-next-heading) (point)))
  18414. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18415. (while (not (eobp))
  18416. (cond ((looking-at-p org-drawer-regexp)
  18417. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18418. (forward-line)
  18419. (throw 'exit t)))
  18420. ((looking-at-p re) (forward-line))
  18421. (t (throw 'exit t))))))))
  18422. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18423. "Move forward to the ARG'th subheading at same level as this one.
  18424. Stop at the first and last subheadings of a superior heading.
  18425. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18426. non-nil it will also look at invisible ones."
  18427. (interactive "p")
  18428. (let ((backward? (and arg (< arg 0))))
  18429. (if (org-before-first-heading-p)
  18430. (if backward? (goto-char (point-min)) (outline-next-heading))
  18431. (org-back-to-heading invisible-ok)
  18432. (unless backward? (end-of-line)) ;do not match current headline
  18433. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18434. (f (if backward? #'re-search-backward #'re-search-forward))
  18435. (count (if arg (abs arg) 1))
  18436. (result (point)))
  18437. (while (and (> count 0)
  18438. (funcall f org-outline-regexp-bol nil 'move))
  18439. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18440. (cond ((< l level) (setq count 0))
  18441. ((and (= l level)
  18442. (or invisible-ok
  18443. (not (org-invisible-p
  18444. (line-beginning-position)))))
  18445. (cl-decf count)
  18446. (when (= l level) (setq result (point)))))))
  18447. (goto-char result))
  18448. (beginning-of-line))))
  18449. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18450. "Move backward to the ARG'th subheading at same level as this one.
  18451. Stop at the first and last subheadings of a superior heading."
  18452. (interactive "p")
  18453. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18454. (defun org-next-visible-heading (arg)
  18455. "Move to the next visible heading.
  18456. This function wraps `outline-next-visible-heading' with
  18457. `org-with-limited-levels' in order to skip over inline tasks and
  18458. respect customization of `org-odd-levels-only'."
  18459. (interactive "p")
  18460. (org-with-limited-levels
  18461. (outline-next-visible-heading arg)))
  18462. (defun org-previous-visible-heading (arg)
  18463. "Move to the previous visible heading.
  18464. This function wraps `outline-previous-visible-heading' with
  18465. `org-with-limited-levels' in order to skip over inline tasks and
  18466. respect customization of `org-odd-levels-only'."
  18467. (interactive "p")
  18468. (org-with-limited-levels
  18469. (outline-previous-visible-heading arg)))
  18470. (defun org-forward-paragraph ()
  18471. "Move forward to beginning of next paragraph or equivalent.
  18472. The function moves point to the beginning of the next visible
  18473. structural element, which can be a paragraph, a table, a list
  18474. item, etc. It also provides some special moves for convenience:
  18475. - On an affiliated keyword, jump to the beginning of the
  18476. relative element.
  18477. - On an item or a footnote definition, move to the second
  18478. element inside, if any.
  18479. - On a table or a property drawer, jump after it.
  18480. - On a verse or source block, stop after blank lines."
  18481. (interactive)
  18482. (unless (eobp)
  18483. (let* ((deactivate-mark nil)
  18484. (element (org-element-at-point))
  18485. (type (org-element-type element))
  18486. (post-affiliated (org-element-property :post-affiliated element))
  18487. (contents-begin (org-element-property :contents-begin element))
  18488. (contents-end (org-element-property :contents-end element))
  18489. (end (let ((end (org-element-property :end element)) (parent element))
  18490. (while (and (setq parent (org-element-property :parent parent))
  18491. (= (org-element-property :contents-end parent) end))
  18492. (setq end (org-element-property :end parent)))
  18493. end)))
  18494. (cond ((not element)
  18495. (skip-chars-forward " \r\t\n")
  18496. (or (eobp) (beginning-of-line)))
  18497. ;; On affiliated keywords, move to element's beginning.
  18498. ((< (point) post-affiliated)
  18499. (goto-char post-affiliated))
  18500. ;; At a table row, move to the end of the table. Similarly,
  18501. ;; at a node property, move to the end of the property
  18502. ;; drawer.
  18503. ((memq type '(node-property table-row))
  18504. (goto-char (org-element-property
  18505. :end (org-element-property :parent element))))
  18506. ((memq type '(property-drawer table)) (goto-char end))
  18507. ;; Consider blank lines as separators in verse and source
  18508. ;; blocks to ease editing.
  18509. ((memq type '(src-block verse-block))
  18510. (when (eq type 'src-block)
  18511. (setq contents-end
  18512. (save-excursion (goto-char end)
  18513. (skip-chars-backward " \r\t\n")
  18514. (line-beginning-position))))
  18515. (beginning-of-line)
  18516. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  18517. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  18518. (goto-char end)
  18519. (skip-chars-forward " \r\t\n")
  18520. (if (= (point) contents-end) (goto-char end)
  18521. (beginning-of-line))))
  18522. ;; With no contents, just skip element.
  18523. ((not contents-begin) (goto-char end))
  18524. ;; If contents are invisible, skip the element altogether.
  18525. ((org-invisible-p (line-end-position))
  18526. (cl-case type
  18527. (headline
  18528. (org-with-limited-levels (outline-next-visible-heading 1)))
  18529. ;; At a plain list, make sure we move to the next item
  18530. ;; instead of skipping the whole list.
  18531. (plain-list (forward-char)
  18532. (org-forward-paragraph))
  18533. (otherwise (goto-char end))))
  18534. ((>= (point) contents-end) (goto-char end))
  18535. ((>= (point) contents-begin)
  18536. ;; This can only happen on paragraphs and plain lists.
  18537. (cl-case type
  18538. (paragraph (goto-char end))
  18539. ;; At a plain list, try to move to second element in
  18540. ;; first item, if possible.
  18541. (plain-list (end-of-line)
  18542. (org-forward-paragraph))))
  18543. ;; When contents start on the middle of a line (e.g. in
  18544. ;; items and footnote definitions), try to reach first
  18545. ;; element starting after current line.
  18546. ((> (line-end-position) contents-begin)
  18547. (end-of-line)
  18548. (org-forward-paragraph))
  18549. (t (goto-char contents-begin))))))
  18550. (defun org-backward-paragraph ()
  18551. "Move backward to start of previous paragraph or equivalent.
  18552. The function moves point to the beginning of the current
  18553. structural element, which can be a paragraph, a table, a list
  18554. item, etc., or to the beginning of the previous visible one if
  18555. point is already there. It also provides some special moves for
  18556. convenience:
  18557. - On an affiliated keyword, jump to the first one.
  18558. - On a table or a property drawer, move to its beginning.
  18559. - On comment, example, export, src and verse blocks, stop
  18560. before blank lines."
  18561. (interactive)
  18562. (unless (bobp)
  18563. (let* ((deactivate-mark nil)
  18564. (element (org-element-at-point))
  18565. (type (org-element-type element))
  18566. (contents-end (org-element-property :contents-end element))
  18567. (post-affiliated (org-element-property :post-affiliated element))
  18568. (begin (org-element-property :begin element))
  18569. (special? ;blocks handled specially
  18570. (memq type '(comment-block example-block export-block src-block
  18571. verse-block)))
  18572. (contents-begin
  18573. (if special?
  18574. ;; These types have no proper contents. Fake line
  18575. ;; below the block opening line as contents beginning.
  18576. (save-excursion (goto-char begin) (line-beginning-position 2))
  18577. (org-element-property :contents-begin element))))
  18578. (cond
  18579. ((not element) (goto-char (point-min)))
  18580. ((= (point) begin)
  18581. (backward-char)
  18582. (org-backward-paragraph))
  18583. ((<= (point) post-affiliated) (goto-char begin))
  18584. ;; Special behavior: on a table or a property drawer, move to
  18585. ;; its beginning.
  18586. ((memq type '(node-property table-row))
  18587. (goto-char (org-element-property
  18588. :post-affiliated (org-element-property :parent element))))
  18589. (special?
  18590. (if (<= (point) contents-begin) (goto-char post-affiliated)
  18591. ;; Inside a verse block, see blank lines as paragraph
  18592. ;; separators.
  18593. (let ((origin (point)))
  18594. (skip-chars-backward " \r\t\n" contents-begin)
  18595. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  18596. (skip-chars-forward " \r\t\n" origin)
  18597. (if (= (point) origin) (goto-char contents-begin)
  18598. (beginning-of-line))))))
  18599. ((eq type 'paragraph) (goto-char contents-begin)
  18600. ;; When at first paragraph in an item or a footnote definition,
  18601. ;; move directly to beginning of line.
  18602. (let ((parent-contents
  18603. (org-element-property
  18604. :contents-begin (org-element-property :parent element))))
  18605. (when (and parent-contents (= parent-contents contents-begin))
  18606. (beginning-of-line))))
  18607. ;; At the end of a greater element, move to the beginning of
  18608. ;; the last element within.
  18609. ((and contents-end (>= (point) contents-end))
  18610. (goto-char (1- contents-end))
  18611. (org-backward-paragraph))
  18612. (t (goto-char (or post-affiliated begin))))
  18613. ;; Ensure we never leave point invisible.
  18614. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  18615. (defun org-forward-element ()
  18616. "Move forward by one element.
  18617. Move to the next element at the same level, when possible."
  18618. (interactive)
  18619. (cond ((eobp) (user-error "Cannot move further down"))
  18620. ((org-with-limited-levels (org-at-heading-p))
  18621. (let ((origin (point)))
  18622. (goto-char (org-end-of-subtree nil t))
  18623. (unless (org-with-limited-levels (org-at-heading-p))
  18624. (goto-char origin)
  18625. (user-error "Cannot move further down"))))
  18626. (t
  18627. (let* ((elem (org-element-at-point))
  18628. (end (org-element-property :end elem))
  18629. (parent (org-element-property :parent elem)))
  18630. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18631. (goto-char (org-element-property :end parent)))
  18632. ((integer-or-marker-p end) (goto-char end))
  18633. (t (message "No element at point")))))))
  18634. (defun org-backward-element ()
  18635. "Move backward by one element.
  18636. Move to the previous element at the same level, when possible."
  18637. (interactive)
  18638. (cond ((bobp) (user-error "Cannot move further up"))
  18639. ((org-with-limited-levels (org-at-heading-p))
  18640. ;; At a headline, move to the previous one, if any, or stay
  18641. ;; here.
  18642. (let ((origin (point)))
  18643. (org-with-limited-levels (org-backward-heading-same-level 1))
  18644. ;; When current headline has no sibling above, move to its
  18645. ;; parent.
  18646. (when (= (point) origin)
  18647. (or (org-with-limited-levels (org-up-heading-safe))
  18648. (progn (goto-char origin)
  18649. (user-error "Cannot move further up"))))))
  18650. (t
  18651. (let* ((elem (org-element-at-point))
  18652. (beg (org-element-property :begin elem)))
  18653. (cond
  18654. ;; Move to beginning of current element if point isn't
  18655. ;; there already.
  18656. ((null beg) (message "No element at point"))
  18657. ((/= (point) beg) (goto-char beg))
  18658. (t (goto-char beg)
  18659. (skip-chars-backward " \r\t\n")
  18660. (unless (bobp)
  18661. (let ((prev (org-element-at-point)))
  18662. (goto-char (org-element-property :begin prev))
  18663. (while (and (setq prev (org-element-property :parent prev))
  18664. (<= (org-element-property :end prev) beg))
  18665. (goto-char (org-element-property :begin prev)))))))))))
  18666. (defun org-up-element ()
  18667. "Move to upper element."
  18668. (interactive)
  18669. (if (org-with-limited-levels (org-at-heading-p))
  18670. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  18671. (let* ((elem (org-element-at-point))
  18672. (parent (org-element-property :parent elem)))
  18673. (if parent (goto-char (org-element-property :begin parent))
  18674. (if (org-with-limited-levels (org-before-first-heading-p))
  18675. (user-error "No surrounding element")
  18676. (org-with-limited-levels (org-back-to-heading)))))))
  18677. (defun org-down-element ()
  18678. "Move to inner element."
  18679. (interactive)
  18680. (let ((element (org-element-at-point)))
  18681. (cond
  18682. ((memq (org-element-type element) '(plain-list table))
  18683. (goto-char (org-element-property :contents-begin element))
  18684. (forward-char))
  18685. ((memq (org-element-type element) org-element-greater-elements)
  18686. ;; If contents are hidden, first disclose them.
  18687. (when (org-invisible-p (line-end-position)) (org-cycle))
  18688. (goto-char (or (org-element-property :contents-begin element)
  18689. (user-error "No content for this element"))))
  18690. (t (user-error "No inner element")))))
  18691. (defun org-drag-element-backward ()
  18692. "Move backward element at point."
  18693. (interactive)
  18694. (let ((elem (or (org-element-at-point)
  18695. (user-error "No element at point"))))
  18696. (if (eq (org-element-type elem) 'headline)
  18697. ;; Preserve point when moving a whole tree, even if point was
  18698. ;; on blank lines below the headline.
  18699. (let ((offset (skip-chars-backward " \t\n")))
  18700. (unwind-protect (org-move-subtree-up)
  18701. (forward-char (- offset))))
  18702. (let ((prev-elem
  18703. (save-excursion
  18704. (goto-char (org-element-property :begin elem))
  18705. (skip-chars-backward " \r\t\n")
  18706. (unless (bobp)
  18707. (let* ((beg (org-element-property :begin elem))
  18708. (prev (org-element-at-point))
  18709. (up prev))
  18710. (while (and (setq up (org-element-property :parent up))
  18711. (<= (org-element-property :end up) beg))
  18712. (setq prev up))
  18713. prev)))))
  18714. ;; Error out if no previous element or previous element is
  18715. ;; a parent of the current one.
  18716. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  18717. (user-error "Cannot drag element backward")
  18718. (let ((pos (point)))
  18719. (org-element-swap-A-B prev-elem elem)
  18720. (goto-char (+ (org-element-property :begin prev-elem)
  18721. (- pos (org-element-property :begin elem))))))))))
  18722. (defun org-drag-element-forward ()
  18723. "Move forward element at point."
  18724. (interactive)
  18725. (let* ((pos (point))
  18726. (elem (or (org-element-at-point)
  18727. (user-error "No element at point"))))
  18728. (when (= (point-max) (org-element-property :end elem))
  18729. (user-error "Cannot drag element forward"))
  18730. (goto-char (org-element-property :end elem))
  18731. (let ((next-elem (org-element-at-point)))
  18732. (when (or (org-element-nested-p elem next-elem)
  18733. (and (eq (org-element-type next-elem) 'headline)
  18734. (not (eq (org-element-type elem) 'headline))))
  18735. (goto-char pos)
  18736. (user-error "Cannot drag element forward"))
  18737. ;; Compute new position of point: it's shifted by NEXT-ELEM
  18738. ;; body's length (without final blanks) and by the length of
  18739. ;; blanks between ELEM and NEXT-ELEM.
  18740. (let ((size-next (- (save-excursion
  18741. (goto-char (org-element-property :end next-elem))
  18742. (skip-chars-backward " \r\t\n")
  18743. (forward-line)
  18744. ;; Small correction if buffer doesn't end
  18745. ;; with a newline character.
  18746. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  18747. (org-element-property :begin next-elem)))
  18748. (size-blank (- (org-element-property :end elem)
  18749. (save-excursion
  18750. (goto-char (org-element-property :end elem))
  18751. (skip-chars-backward " \r\t\n")
  18752. (forward-line)
  18753. (point)))))
  18754. (org-element-swap-A-B elem next-elem)
  18755. (goto-char (+ pos size-next size-blank))))))
  18756. (defun org-drag-line-forward (arg)
  18757. "Drag the line at point ARG lines forward."
  18758. (interactive "p")
  18759. (dotimes (_ (abs arg))
  18760. (let ((c (current-column)))
  18761. (if (< 0 arg)
  18762. (progn
  18763. (beginning-of-line 2)
  18764. (transpose-lines 1)
  18765. (beginning-of-line 0))
  18766. (transpose-lines 1)
  18767. (beginning-of-line -1))
  18768. (org-move-to-column c))))
  18769. (defun org-drag-line-backward (arg)
  18770. "Drag the line at point ARG lines backward."
  18771. (interactive "p")
  18772. (org-drag-line-forward (- arg)))
  18773. (defun org-mark-element ()
  18774. "Put point at beginning of this element, mark at end.
  18775. Interactively, if this command is repeated or (in Transient Mark
  18776. mode) if the mark is active, it marks the next element after the
  18777. ones already marked."
  18778. (interactive)
  18779. (let (deactivate-mark)
  18780. (if (and (called-interactively-p 'any)
  18781. (or (and (eq last-command this-command) (mark t))
  18782. (and transient-mark-mode mark-active)))
  18783. (set-mark
  18784. (save-excursion
  18785. (goto-char (mark))
  18786. (goto-char (org-element-property :end (org-element-at-point)))))
  18787. (let ((element (org-element-at-point)))
  18788. (end-of-line)
  18789. (push-mark (org-element-property :end element) t t)
  18790. (goto-char (org-element-property :begin element))))))
  18791. (defun org-narrow-to-element ()
  18792. "Narrow buffer to current element."
  18793. (interactive)
  18794. (let ((elem (org-element-at-point)))
  18795. (cond
  18796. ((eq (car elem) 'headline)
  18797. (narrow-to-region
  18798. (org-element-property :begin elem)
  18799. (org-element-property :end elem)))
  18800. ((memq (car elem) org-element-greater-elements)
  18801. (narrow-to-region
  18802. (org-element-property :contents-begin elem)
  18803. (org-element-property :contents-end elem)))
  18804. (t
  18805. (narrow-to-region
  18806. (org-element-property :begin elem)
  18807. (org-element-property :end elem))))))
  18808. (defun org-transpose-element ()
  18809. "Transpose current and previous elements, keeping blank lines between.
  18810. Point is moved after both elements."
  18811. (interactive)
  18812. (org-skip-whitespace)
  18813. (let ((end (org-element-property :end (org-element-at-point))))
  18814. (org-drag-element-backward)
  18815. (goto-char end)))
  18816. (defun org-unindent-buffer ()
  18817. "Un-indent the visible part of the buffer.
  18818. Relative indentation (between items, inside blocks, etc.) isn't
  18819. modified."
  18820. (interactive)
  18821. (unless (eq major-mode 'org-mode)
  18822. (user-error "Cannot un-indent a buffer not in Org mode"))
  18823. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  18824. (unindent-tree
  18825. (lambda (contents)
  18826. (dolist (element (reverse contents))
  18827. (if (memq (org-element-type element) '(headline section))
  18828. (funcall unindent-tree (org-element-contents element))
  18829. (save-excursion
  18830. (save-restriction
  18831. (narrow-to-region
  18832. (org-element-property :begin element)
  18833. (org-element-property :end element))
  18834. (org-do-remove-indentation))))))))
  18835. (funcall unindent-tree (org-element-contents parse-tree))))
  18836. (defun org-make-options-regexp (kwds &optional extra)
  18837. "Make a regular expression for keyword lines.
  18838. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  18839. when non-nil, is a regexp matching keywords names."
  18840. (concat "^[ \t]*#\\+\\("
  18841. (regexp-opt kwds)
  18842. (and extra (concat (and kwds "\\|") extra))
  18843. "\\):[ \t]*\\(.*\\)"))
  18844. ;;; Conveniently switch to Info nodes
  18845. (defun org-info-find-node (&optional nodename)
  18846. "Find Info documentation NODENAME or Org documentation according context.
  18847. Started from `gnus-info-find-node'."
  18848. (interactive)
  18849. (Info-goto-node
  18850. (or nodename
  18851. (let ((default-org-info-node "(org) Top"))
  18852. (cond
  18853. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  18854. ((eq 'org-mode major-mode)
  18855. (let* ((context (org-element-at-point))
  18856. (element-info-nodes ; compare to `org-element-all-elements'.
  18857. `((babel-call . "(org) Evaluating Code Blocks")
  18858. (center-block . "(org) Paragraphs")
  18859. (clock . ,default-org-info-node)
  18860. (comment . "(org) Comment Lines")
  18861. (comment-block . "(org) Comment Lines")
  18862. (diary-sexp . ,default-org-info-node)
  18863. (drawer . "(org) Drawers")
  18864. (dynamic-block . "(org) Dynamic Blocks")
  18865. (example-block . "(org) Literal Examples")
  18866. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  18867. (fixed-width . ,default-org-info-node)
  18868. (footnote-definition . "(org) Creating Footnotes")
  18869. (headline . "(org) Document Structure")
  18870. (horizontal-rule . "(org) Built-in Table Editor")
  18871. (inlinetask . ,default-org-info-node)
  18872. (item . "(org) Plain Lists")
  18873. (keyword . "(org) Per-file keywords")
  18874. (latex-environment . "(org) LaTeX Export")
  18875. (node-property . "(org) Properties and Columns")
  18876. (paragraph . "(org) Paragraphs")
  18877. (plain-list . "(org) Plain Lists")
  18878. (planning . "(org) Deadlines and Scheduling")
  18879. (property-drawer . "(org) Properties and Columns")
  18880. (quote-block . "(org) Paragraphs")
  18881. (section . ,default-org-info-node)
  18882. (special-block . ,default-org-info-node)
  18883. (src-block . "(org) Working with Source Code")
  18884. (table . "(org) Tables")
  18885. (table-row . "(org) Tables")
  18886. (verse-block . "(org) Paragraphs"))))
  18887. (or (cdr (assoc (car context) element-info-nodes))
  18888. default-org-info-node)))
  18889. (t default-org-info-node))))))
  18890. ;;; Finish up
  18891. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  18892. (lambda () (add-hook 'change-major-mode-hook
  18893. 'org-show-all 'append 'local)))
  18894. (provide 'org)
  18895. (run-hooks 'org-load-hook)
  18896. ;;; org.el ends here