org.el 804 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227
  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-2019 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: https://orgmode.org
  8. ;; Version: 9.3
  9. ;;
  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-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-export-dispatch "ox" (&optional arg))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-feed-goto-inbox "org-feed" (feed))
  153. (declare-function org-feed-update-all "org-feed" ())
  154. (declare-function org-goto "org-goto" (&optional alternative-interface))
  155. (declare-function org-id-find-id-file "org-id" (id))
  156. (declare-function org-id-get-create "org-id" (&optional force))
  157. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  158. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  159. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  160. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  161. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function org-timer "org-timer" (&optional restart no-insert))
  164. (declare-function org-timer-item "org-timer" (&optional arg))
  165. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  166. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  167. (declare-function org-timer-start "org-timer" (&optional offset))
  168. (declare-function org-timer-stop "org-timer" ())
  169. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  170. (declare-function org-update-radio-target-regexp "ol" ())
  171. (defvar ffap-url-regexp)
  172. (defvar org-element-paragraph-separate)
  173. (defvar org-indent-indentation-per-level)
  174. (defvar org-radio-target-regexp)
  175. (defvar org-target-link-regexp)
  176. (defvar org-target-regexp)
  177. ;; load languages based on value of `org-babel-load-languages'
  178. (defvar org-babel-load-languages)
  179. ;;;###autoload
  180. (defun org-babel-do-load-languages (sym value)
  181. "Load the languages defined in `org-babel-load-languages'."
  182. (set-default sym value)
  183. (dolist (pair org-babel-load-languages)
  184. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  185. (if active
  186. (require (intern (concat "ob-" lang)))
  187. (fmakunbound
  188. (intern (concat "org-babel-execute:" lang)))
  189. (fmakunbound
  190. (intern (concat "org-babel-expand-body:" lang)))))))
  191. ;;;###autoload
  192. (defun org-babel-load-file (file &optional compile)
  193. "Load Emacs Lisp source code blocks in the Org FILE.
  194. This function exports the source code using `org-babel-tangle'
  195. and then loads the resulting file using `load-file'. With
  196. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  197. byte-compiled before it is loaded."
  198. (interactive "fFile to load: \nP")
  199. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  200. ;; Tangle only if the Org file is newer than the Elisp file.
  201. (unless (org-file-newer-than-p
  202. tangled-file
  203. (file-attribute-modification-time (file-attributes file)))
  204. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  205. (if compile
  206. (progn
  207. (byte-compile-file tangled-file 'load)
  208. (message "Compiled and loaded %s" tangled-file))
  209. (load-file tangled-file)
  210. (message "Loaded %s" tangled-file))))
  211. (defcustom org-babel-load-languages '((emacs-lisp . t))
  212. "Languages which can be evaluated in Org buffers.
  213. \\<org-mode-map>
  214. This list can be used to load support for any of the languages
  215. below. Each language will depend on a different set of system
  216. executables and/or Emacs modes.
  217. When a language is \"loaded\", code blocks in that language can
  218. be evaluated with `org-babel-execute-src-block', which is bound
  219. by default to \\[org-ctrl-c-ctrl-c].
  220. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  221. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  222. default, only Emacs Lisp is loaded, since it has no specific
  223. requirement."
  224. :group 'org-babel
  225. :set 'org-babel-do-load-languages
  226. :version "24.1"
  227. :type '(alist :tag "Babel Languages"
  228. :key-type
  229. (choice
  230. (const :tag "Awk" awk)
  231. (const :tag "C" C)
  232. (const :tag "R" R)
  233. (const :tag "Asymptote" asymptote)
  234. (const :tag "Calc" calc)
  235. (const :tag "Clojure" clojure)
  236. (const :tag "CSS" css)
  237. (const :tag "Ditaa" ditaa)
  238. (const :tag "Dot" dot)
  239. (const :tag "Ebnf2ps" ebnf2ps)
  240. (const :tag "Emacs Lisp" emacs-lisp)
  241. (const :tag "Forth" forth)
  242. (const :tag "Fortran" fortran)
  243. (const :tag "Gnuplot" gnuplot)
  244. (const :tag "Haskell" haskell)
  245. (const :tag "hledger" hledger)
  246. (const :tag "IO" io)
  247. (const :tag "J" J)
  248. (const :tag "Java" java)
  249. (const :tag "Javascript" js)
  250. (const :tag "LaTeX" latex)
  251. (const :tag "Ledger" ledger)
  252. (const :tag "Lilypond" lilypond)
  253. (const :tag "Lisp" lisp)
  254. (const :tag "Makefile" makefile)
  255. (const :tag "Maxima" maxima)
  256. (const :tag "Matlab" matlab)
  257. (const :tag "Mscgen" mscgen)
  258. (const :tag "Ocaml" ocaml)
  259. (const :tag "Octave" octave)
  260. (const :tag "Org" org)
  261. (const :tag "Perl" perl)
  262. (const :tag "Pico Lisp" picolisp)
  263. (const :tag "PlantUML" plantuml)
  264. (const :tag "Python" python)
  265. (const :tag "Ruby" ruby)
  266. (const :tag "Sass" sass)
  267. (const :tag "Scala" scala)
  268. (const :tag "Scheme" scheme)
  269. (const :tag "Screen" screen)
  270. (const :tag "Shell Script" shell)
  271. (const :tag "Shen" shen)
  272. (const :tag "Sql" sql)
  273. (const :tag "Sqlite" sqlite)
  274. (const :tag "Stan" stan)
  275. (const :tag "Vala" vala))
  276. :value-type (boolean :tag "Activate" :value t)))
  277. ;;;; Customization variables
  278. (defcustom org-clone-delete-id nil
  279. "Remove ID property of clones of a subtree.
  280. When non-nil, clones of a subtree don't inherit the ID property.
  281. Otherwise they inherit the ID property with a new unique
  282. identifier."
  283. :type 'boolean
  284. :version "24.1"
  285. :group 'org-id)
  286. ;;; Version
  287. (org-check-version)
  288. ;;;###autoload
  289. (defun org-version (&optional here full message)
  290. "Show the Org version.
  291. Interactively, or when MESSAGE is non-nil, show it in echo area.
  292. With prefix argument, or when HERE is non-nil, insert it at point.
  293. In non-interactive uses, a reduced version string is output unless
  294. FULL is given."
  295. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  296. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  297. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  298. (load-suffixes (list ".el"))
  299. (org-install-dir
  300. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  301. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  302. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  303. (let* ((load-suffixes save-load-suffixes)
  304. (release (org-release))
  305. (git-version (org-git-version))
  306. (version (format "Org mode version %s (%s @ %s)"
  307. release
  308. git-version
  309. (if org-install-dir
  310. (if (string= org-dir org-install-dir)
  311. org-install-dir
  312. (concat "mixed installation! "
  313. org-install-dir
  314. " and "
  315. org-dir))
  316. "org-loaddefs.el can not be found!")))
  317. (version1 (if full version release)))
  318. (when here (insert version1))
  319. (when message (message "%s" version1))
  320. version1)))
  321. (defconst org-version (org-version))
  322. ;;; Syntax Constants
  323. ;;;; Block
  324. (defconst org-block-regexp
  325. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  326. "Regular expression for hiding blocks.")
  327. (defconst org-dblock-start-re
  328. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  329. "Matches the start line of a dynamic block, with parameters.")
  330. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  331. "Matches the end of a dynamic block.")
  332. ;;;; Clock and Planning
  333. (defconst org-clock-string "CLOCK:"
  334. "String used as prefix for timestamps clocking work hours on an item.")
  335. (defvar org-closed-string "CLOSED:"
  336. "String used as the prefix for timestamps logging closing a TODO entry.")
  337. (defvar org-deadline-string "DEADLINE:"
  338. "String to mark deadline entries.
  339. \\<org-mode-map>
  340. A deadline is this string, followed by a time stamp. It must be
  341. a word, terminated by a colon. You can insert a schedule keyword
  342. and a timestamp with `\\[org-deadline]'.")
  343. (defvar org-scheduled-string "SCHEDULED:"
  344. "String to mark scheduled TODO entries.
  345. \\<org-mode-map>
  346. A schedule is this string, followed by a time stamp. It must be
  347. a word, terminated by a colon. You can insert a schedule keyword
  348. and a timestamp with `\\[org-schedule]'.")
  349. (defconst org-ds-keyword-length
  350. (+ 2
  351. (apply #'max
  352. (mapcar #'length
  353. (list org-deadline-string org-scheduled-string
  354. org-clock-string org-closed-string))))
  355. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  356. (defconst org-planning-line-re
  357. (concat "^[ \t]*"
  358. (regexp-opt
  359. (list org-closed-string org-deadline-string org-scheduled-string)
  360. t))
  361. "Matches a line with planning info.
  362. Matched keyword is in group 1.")
  363. (defconst org-clock-line-re
  364. (concat "^[ \t]*" org-clock-string)
  365. "Matches a line with clock info.")
  366. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  367. "Matches the DEADLINE keyword.")
  368. (defconst org-deadline-time-regexp
  369. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  370. "Matches the DEADLINE keyword together with a time stamp.")
  371. (defconst org-deadline-time-hour-regexp
  372. (concat "\\<" org-deadline-string
  373. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  374. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  375. (defconst org-deadline-line-regexp
  376. (concat "\\<\\(" org-deadline-string "\\).*")
  377. "Matches the DEADLINE keyword and the rest of the line.")
  378. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  379. "Matches the SCHEDULED keyword.")
  380. (defconst org-scheduled-time-regexp
  381. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  382. "Matches the SCHEDULED keyword together with a time stamp.")
  383. (defconst org-scheduled-time-hour-regexp
  384. (concat "\\<" org-scheduled-string
  385. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  386. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  387. (defconst org-closed-time-regexp
  388. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  389. "Matches the CLOSED keyword together with a time stamp.")
  390. (defconst org-keyword-time-regexp
  391. (concat "\\<"
  392. (regexp-opt
  393. (list org-scheduled-string org-deadline-string org-closed-string
  394. org-clock-string)
  395. t)
  396. " *[[<]\\([^]>]+\\)[]>]")
  397. "Matches any of the 4 keywords, together with the time stamp.")
  398. (defconst org-keyword-time-not-clock-regexp
  399. (concat
  400. "\\<"
  401. (regexp-opt
  402. (list org-scheduled-string org-deadline-string org-closed-string) t)
  403. " *[[<]\\([^]>]+\\)[]>]")
  404. "Matches any of the 3 keywords, together with the time stamp.")
  405. (defconst org-maybe-keyword-time-regexp
  406. (concat "\\(\\<"
  407. (regexp-opt
  408. (list org-scheduled-string org-deadline-string org-closed-string
  409. org-clock-string)
  410. t)
  411. "\\)?"
  412. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  413. "\\|"
  414. "<%%([^\r\n>]*>\\)")
  415. "Matches a timestamp, possibly preceded by a keyword.")
  416. (defconst org-all-time-keywords
  417. (mapcar (lambda (w) (substring w 0 -1))
  418. (list org-scheduled-string org-deadline-string
  419. org-clock-string org-closed-string))
  420. "List of time keywords.")
  421. ;;;; Drawer
  422. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  423. "Matches first or last line of a hidden block.
  424. Group 1 contains drawer's name or \"END\".")
  425. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  426. "Regular expression matching the first line of a property drawer.")
  427. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  428. "Regular expression matching the last line of a property drawer.")
  429. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  430. "Regular expression matching the first line of a clock drawer.")
  431. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a clock drawer.")
  433. (defconst org-property-drawer-re
  434. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  435. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  436. "[ \t]*:END:[ \t]*$")
  437. "Matches an entire property drawer.")
  438. (defconst org-clock-drawer-re
  439. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  440. org-clock-drawer-end-re "\\)\n?")
  441. "Matches an entire clock drawer.")
  442. ;;;; Headline
  443. (defconst org-heading-keyword-regexp-format
  444. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  445. "Printf format for a regexp matching a headline with some keyword.
  446. This regexp will match the headline of any node which has the
  447. exact keyword that is put into the format. The keyword isn't in
  448. any group by default, but the stars and the body are.")
  449. (defconst org-heading-keyword-maybe-regexp-format
  450. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  451. "Printf format for a regexp matching a headline, possibly with some keyword.
  452. This regexp can match any headline with the specified keyword, or
  453. without a keyword. The keyword isn't in any group by default,
  454. but the stars and the body are.")
  455. (defconst org-archive-tag "ARCHIVE"
  456. "The tag that marks a subtree as archived.
  457. An archived subtree does not open during visibility cycling, and does
  458. not contribute to the agenda listings.")
  459. (defconst org-tag-re "[[:alnum:]_@#%]+"
  460. "Regexp matching a single tag.")
  461. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  462. "Regexp matching the tag group at the end of a line, with leading spaces.
  463. Tags are stored in match group 1. Match group 2 stores the tags
  464. without the enclosing colons.")
  465. (defconst org-tag-line-re
  466. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  467. "Regexp matching tags in a headline.
  468. Tags are stored in match group 1. Match group 2 stores the tags
  469. without the enclosing colons.")
  470. (eval-and-compile
  471. (defconst org-comment-string "COMMENT"
  472. "Entries starting with this keyword will never be exported.
  473. \\<org-mode-map>
  474. An entry can be toggled between COMMENT and normal with
  475. `\\[org-toggle-comment]'."))
  476. ;;;; LaTeX Environments and Fragments
  477. (defconst org-latex-regexps
  478. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  479. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  480. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  481. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  482. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  483. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  484. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  485. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  486. "Regular expressions for matching embedded LaTeX.")
  487. ;;;; Node Property
  488. (defconst org-effort-property "Effort"
  489. "The property that is being used to keep track of effort estimates.
  490. Effort estimates given in this property need to have the format H:MM.")
  491. ;;;; Timestamp
  492. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  493. "Regular expression for fast time stamp matching.")
  494. (defconst org-ts-regexp-inactive
  495. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  496. "Regular expression for fast inactive time stamp matching.")
  497. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp0
  500. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  501. "Regular expression matching time strings for analysis.
  502. This one does not require the space after the date, so it can be used
  503. on a string that terminates immediately after the date.")
  504. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  505. "Regular expression matching time strings for analysis.")
  506. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  507. "Regular expression matching time stamps, with groups.")
  508. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  509. "Regular expression matching time stamps (also [..]), with groups.")
  510. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  511. "Regular expression matching a time stamp range.")
  512. (defconst org-tr-regexp-both
  513. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  514. "Regular expression matching a time stamp range.")
  515. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  516. org-ts-regexp "\\)?")
  517. "Regular expression matching a time stamp or time stamp range.")
  518. (defconst org-tsr-regexp-both
  519. (concat org-ts-regexp-both "\\(--?-?"
  520. org-ts-regexp-both "\\)?")
  521. "Regular expression matching a time stamp or time stamp range.
  522. The time stamps may be either active or inactive.")
  523. (defconst org-repeat-re
  524. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  525. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  526. "Regular expression for specifying repeated events.
  527. After a match, group 1 contains the repeat expression.")
  528. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  529. "Formats for `format-time-string' which are used for time stamps.")
  530. ;;; The custom variables
  531. (defgroup org nil
  532. "Outline-based notes management and organizer."
  533. :tag "Org"
  534. :group 'outlines
  535. :group 'calendar)
  536. (defcustom org-mode-hook nil
  537. "Mode hook for Org mode, run after the mode was turned on."
  538. :group 'org
  539. :type 'hook)
  540. (defcustom org-load-hook nil
  541. "Hook that is run after org.el has been loaded."
  542. :group 'org
  543. :type 'hook)
  544. (defcustom org-log-buffer-setup-hook nil
  545. "Hook that is run after an Org log buffer is created."
  546. :group 'org
  547. :version "24.1"
  548. :type 'hook)
  549. (defvar org-modules) ; defined below
  550. (defvar org-modules-loaded nil
  551. "Have the modules been loaded already?")
  552. (defun org-load-modules-maybe (&optional force)
  553. "Load all extensions listed in `org-modules'."
  554. (when (or force (not org-modules-loaded))
  555. (dolist (ext org-modules)
  556. (condition-case nil (require ext)
  557. (error (message "Problems while trying to load feature `%s'" ext))))
  558. (setq org-modules-loaded t)))
  559. (defun org-set-modules (var value)
  560. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  561. (set var value)
  562. (when (featurep 'org)
  563. (org-load-modules-maybe 'force)
  564. (org-element-cache-reset 'all)))
  565. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  566. "Modules that should always be loaded together with org.el.
  567. If a description starts with <C>, the file is not part of Emacs
  568. and loading it will require that you have downloaded and properly
  569. installed the Org mode distribution.
  570. You can also use this system to load external packages (i.e. neither Org
  571. core modules, nor modules from the CONTRIB directory). Just add symbols
  572. to the end of the list. If the package is called org-xyz.el, then you need
  573. to add the symbol `xyz', and the package must have a call to:
  574. (provide \\='org-xyz)
  575. For export specific modules, see also `org-export-backends'."
  576. :group 'org
  577. :set 'org-set-modules
  578. :version "26.1"
  579. :package-version '(Org . "9.2")
  580. :type
  581. '(set :greedy t
  582. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  583. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  584. (const :tag " crypt: Encryption of subtrees" org-crypt)
  585. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  586. (const :tag " docview: Links to Docview buffers" ol-docview)
  587. (const :tag " eww: Store link to URL of Eww" ol-eww)
  588. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  589. (const :tag " habit: Track your consistency with habits" org-habit)
  590. (const :tag " id: Global IDs for identifying entries" org-id)
  591. (const :tag " info: Links to Info nodes" ol-info)
  592. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  593. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  594. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  595. (const :tag " mouse: Additional mouse support" org-mouse)
  596. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  597. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  598. (const :tag " tempo: Fast completion for structures" org-tempo)
  599. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  600. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  601. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  602. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  603. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  604. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  605. (const :tag "C collector: Collect properties into tables" org-collector)
  606. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  607. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  608. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  609. (const :tag "C eval: Include command output as text" org-eval)
  610. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  611. (const :tag "C git-link: Links to specific file version" ol-git-link)
  612. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  613. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  614. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  615. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  616. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  617. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  618. (const :tag "C man: Links to man pages in Org mode" ol-man)
  619. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  620. (const :tag "C notify: Notifications for Org mode" org-notify)
  621. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  622. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  623. (const :tag "C registry: A registry for Org links" org-registry)
  624. (const :tag "C screen: Visit screen sessions through links" org-screen)
  625. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  626. (const :tag "C secretary: Team management with Org" org-secretary)
  627. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  628. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  629. (const :tag "C track: Keep up with Org mode development" org-track)
  630. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  631. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  632. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  633. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  634. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  635. (defvar org-export-registered-backends) ; From ox.el.
  636. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  637. (declare-function org-export-backend-name "ox" (backend) t)
  638. (defcustom org-export-backends '(ascii html icalendar latex odt)
  639. "List of export back-ends that should be always available.
  640. If a description starts with <C>, the file is not part of Emacs
  641. and loading it will require that you have downloaded and properly
  642. installed the Org mode distribution.
  643. Unlike to `org-modules', libraries in this list will not be
  644. loaded along with Org, but only once the export framework is
  645. needed.
  646. This variable needs to be set before org.el is loaded. If you
  647. need to make a change while Emacs is running, use the customize
  648. interface or run the following code, where VAL stands for the new
  649. value of the variable, after updating it:
  650. (progn
  651. (setq org-export-registered-backends
  652. (cl-remove-if-not
  653. (lambda (backend)
  654. (let ((name (org-export-backend-name backend)))
  655. (or (memq name val)
  656. (catch \\='parentp
  657. (dolist (b val)
  658. (and (org-export-derived-backend-p b name)
  659. (throw \\='parentp t)))))))
  660. org-export-registered-backends))
  661. (let ((new-list (mapcar #\\='org-export-backend-name
  662. org-export-registered-backends)))
  663. (dolist (backend val)
  664. (cond
  665. ((not (load (format \"ox-%s\" backend) t t))
  666. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  667. backend))
  668. ((not (memq backend new-list)) (push backend new-list))))
  669. (set-default \\='org-export-backends new-list)))
  670. Adding a back-end to this list will also pull the back-end it
  671. depends on, if any."
  672. :group 'org
  673. :group 'org-export
  674. :version "26.1"
  675. :package-version '(Org . "9.0")
  676. :initialize 'custom-initialize-set
  677. :set (lambda (var val)
  678. (if (not (featurep 'ox)) (set-default var val)
  679. ;; Any back-end not required anymore (not present in VAL and not
  680. ;; a parent of any back-end in the new value) is removed from the
  681. ;; list of registered back-ends.
  682. (setq org-export-registered-backends
  683. (cl-remove-if-not
  684. (lambda (backend)
  685. (let ((name (org-export-backend-name backend)))
  686. (or (memq name val)
  687. (catch 'parentp
  688. (dolist (b val)
  689. (and (org-export-derived-backend-p b name)
  690. (throw 'parentp t)))))))
  691. org-export-registered-backends))
  692. ;; Now build NEW-LIST of both new back-ends and required
  693. ;; parents.
  694. (let ((new-list (mapcar #'org-export-backend-name
  695. org-export-registered-backends)))
  696. (dolist (backend val)
  697. (cond
  698. ((not (load (format "ox-%s" backend) t t))
  699. (message "Problems while trying to load export back-end `%s'"
  700. backend))
  701. ((not (memq backend new-list)) (push backend new-list))))
  702. ;; Set VAR to that list with fixed dependencies.
  703. (set-default var new-list))))
  704. :type '(set :greedy t
  705. (const :tag " ascii Export buffer to ASCII format" ascii)
  706. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  707. (const :tag " html Export buffer to HTML format" html)
  708. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  709. (const :tag " latex Export buffer to LaTeX format" latex)
  710. (const :tag " man Export buffer to MAN format" man)
  711. (const :tag " md Export buffer to Markdown format" md)
  712. (const :tag " odt Export buffer to ODT format" odt)
  713. (const :tag " org Export buffer to Org format" org)
  714. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  715. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  716. (const :tag "C deck Export buffer to deck.js presentations" deck)
  717. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  718. (const :tag "C groff Export buffer to Groff format" groff)
  719. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  720. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  721. (const :tag "C s5 Export buffer to s5 presentations" s5)
  722. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  723. (eval-after-load 'ox
  724. '(dolist (backend org-export-backends)
  725. (condition-case nil (require (intern (format "ox-%s" backend)))
  726. (error (message "Problems while trying to load export back-end `%s'"
  727. backend)))))
  728. (defcustom org-support-shift-select nil
  729. "Non-nil means make shift-cursor commands select text when possible.
  730. \\<org-mode-map>
  731. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  732. start selecting a region, or enlarge regions started in this way.
  733. In Org mode, in special contexts, these same keys are used for
  734. other purposes, important enough to compete with shift selection.
  735. Org tries to balance these needs by supporting `shift-select-mode'
  736. outside these special contexts, under control of this variable.
  737. The default of this variable is nil, to avoid confusing behavior. Shifted
  738. cursor keys will then execute Org commands in the following contexts:
  739. - on a headline, changing TODO state (left/right) and priority (up/down)
  740. - on a time stamp, changing the time
  741. - in a plain list item, changing the bullet type
  742. - in a property definition line, switching between allowed values
  743. - in the BEGIN line of a clock table (changing the time block).
  744. Outside these contexts, the commands will throw an error.
  745. When this variable is t and the cursor is not in a special
  746. context, Org mode will support shift-selection for making and
  747. enlarging regions. To make this more effective, the bullet
  748. cycling will no longer happen anywhere in an item line, but only
  749. if the cursor is exactly on the bullet.
  750. If you set this variable to the symbol `always', then the keys
  751. will not be special in headlines, property lines, and item lines,
  752. to make shift selection work there as well. If this is what you
  753. want, you can use the following alternative commands:
  754. `\\[org-todo]' and `\\[org-priority]' \
  755. to change TODO state and priority,
  756. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  757. can be used to switch TODO sets,
  758. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  759. and properties can be edited by hand or in column view.
  760. However, when the cursor is on a timestamp, shift-cursor commands
  761. will still edit the time stamp - this is just too good to give up."
  762. :group 'org
  763. :type '(choice
  764. (const :tag "Never" nil)
  765. (const :tag "When outside special context" t)
  766. (const :tag "Everywhere except timestamps" always)))
  767. (defcustom org-loop-over-headlines-in-active-region nil
  768. "Shall some commands act upon headlines in the active region?
  769. When set to t, some commands will be performed in all headlines
  770. within the active region.
  771. When set to `start-level', some commands will be performed in all
  772. headlines within the active region, provided that these headlines
  773. are of the same level than the first one.
  774. When set to a string, those commands will be performed on the
  775. matching headlines within the active region. Such string must be
  776. a tags/property/todo match as it is used in the agenda tags view.
  777. The list of commands is: `org-schedule', `org-deadline',
  778. `org-todo', `org-set-tags-command', `org-archive-subtree',
  779. `org-archive-set-tag', `org-toggle-archive-tag' and
  780. `org-archive-to-archive-sibling'. The archiving commands skip
  781. already archived entries."
  782. :type '(choice (const :tag "Don't loop" nil)
  783. (const :tag "All headlines in active region" t)
  784. (const :tag "In active region, headlines at the same level than the first one" start-level)
  785. (string :tag "Tags/Property/Todo matcher"))
  786. :version "24.1"
  787. :group 'org-todo
  788. :group 'org-archive)
  789. (defcustom org-startup-folded t
  790. "Non-nil means entering Org mode will switch to OVERVIEW.
  791. This can also be configured on a per-file basis by adding one of
  792. the following lines anywhere in the buffer:
  793. #+STARTUP: fold (or `overview', this is equivalent)
  794. #+STARTUP: nofold (or `showall', this is equivalent)
  795. #+STARTUP: content
  796. #+STARTUP: showeverything
  797. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  798. to ignore this option when Org opens agenda files for the first
  799. time."
  800. :group 'org-startup
  801. :type '(choice
  802. (const :tag "nofold: show all" nil)
  803. (const :tag "fold: overview" t)
  804. (const :tag "content: all headlines" content)
  805. (const :tag "show everything, even drawers" showeverything)))
  806. (defcustom org-startup-truncated t
  807. "Non-nil means entering Org mode will set `truncate-lines'.
  808. This is useful since some lines containing links can be very long and
  809. uninteresting. Also tables look terrible when wrapped.
  810. The variable `org-startup-truncated' allows to configure
  811. truncation for Org mode different to the other modes that use the
  812. variable `truncate-lines' and as a shortcut instead of putting
  813. the variable `truncate-lines' into the `org-mode-hook'. If one
  814. wants to configure truncation for Org mode not statically but
  815. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  816. the variable `truncate-lines' has to be used because in such a
  817. case it is too late to set the variable `org-startup-truncated'."
  818. :group 'org-startup
  819. :type 'boolean)
  820. (defcustom org-startup-indented nil
  821. "Non-nil means turn on `org-indent-mode' on startup.
  822. This can also be configured on a per-file basis by adding one of
  823. the following lines anywhere in the buffer:
  824. #+STARTUP: indent
  825. #+STARTUP: noindent"
  826. :group 'org-structure
  827. :type '(choice
  828. (const :tag "Not" nil)
  829. (const :tag "Globally (slow on startup in large files)" t)))
  830. (defcustom org-use-sub-superscripts t
  831. "Non-nil means interpret \"_\" and \"^\" for display.
  832. If you want to control how Org exports those characters, see
  833. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  834. used to be an alias for `org-export-with-sub-superscripts' in
  835. Org <8.0, it is not anymore.
  836. When this option is turned on, you can use TeX-like syntax for
  837. sub- and superscripts within the buffer. Several characters after
  838. \"_\" or \"^\" will be considered as a single item - so grouping
  839. with {} is normally not needed. For example, the following things
  840. will be parsed as single sub- or superscripts:
  841. 10^24 or 10^tau several digits will be considered 1 item.
  842. 10^-12 or 10^-tau a leading sign with digits or a word
  843. x^2-y^3 will be read as x^2 - y^3, because items are
  844. terminated by almost any nonword/nondigit char.
  845. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  846. Still, ambiguity is possible. So when in doubt, use {} to enclose
  847. the sub/superscript. If you set this variable to the symbol `{}',
  848. the braces are *required* in order to trigger interpretations as
  849. sub/superscript. This can be helpful in documents that need \"_\"
  850. frequently in plain text."
  851. :group 'org-startup
  852. :version "24.4"
  853. :package-version '(Org . "8.0")
  854. :type '(choice
  855. (const :tag "Always interpret" t)
  856. (const :tag "Only with braces" {})
  857. (const :tag "Never interpret" nil)))
  858. (defcustom org-startup-with-beamer-mode nil
  859. "Non-nil means turn on `org-beamer-mode' on startup.
  860. This can also be configured on a per-file basis by adding one of
  861. the following lines anywhere in the buffer:
  862. #+STARTUP: beamer"
  863. :group 'org-startup
  864. :version "24.1"
  865. :type 'boolean)
  866. (defcustom org-startup-align-all-tables nil
  867. "Non-nil means align all tables when visiting a file.
  868. This can also be configured on a per-file basis by adding one of
  869. the following lines anywhere in the buffer:
  870. #+STARTUP: align
  871. #+STARTUP: noalign"
  872. :group 'org-startup
  873. :type 'boolean)
  874. (defcustom org-startup-shrink-all-tables nil
  875. "Non-nil means shrink all table columns with a width cookie.
  876. This can also be configured on a per-file basis by adding one of
  877. the following lines anywhere in the buffer:
  878. #+STARTUP: shrink"
  879. :group 'org-startup
  880. :type 'boolean
  881. :version "27.1"
  882. :package-version '(Org . "9.2")
  883. :safe #'booleanp)
  884. (defcustom org-startup-with-inline-images nil
  885. "Non-nil means show inline images when loading a new Org file.
  886. This can also be configured on a per-file basis by adding one of
  887. the following lines anywhere in the buffer:
  888. #+STARTUP: inlineimages
  889. #+STARTUP: noinlineimages"
  890. :group 'org-startup
  891. :version "24.1"
  892. :type 'boolean)
  893. (defcustom org-startup-with-latex-preview nil
  894. "Non-nil means preview LaTeX fragments when loading a new Org file.
  895. This can also be configured on a per-file basis by adding one of
  896. the following lines anywhere in the buffer:
  897. #+STARTUP: latexpreview
  898. #+STARTUP: nolatexpreview"
  899. :group 'org-startup
  900. :version "24.4"
  901. :package-version '(Org . "8.0")
  902. :type 'boolean)
  903. (defcustom org-insert-mode-line-in-empty-file nil
  904. "Non-nil means insert the first line setting Org mode in empty files.
  905. When the function `org-mode' is called interactively in an empty file, this
  906. normally means that the file name does not automatically trigger Org mode.
  907. To ensure that the file will always be in Org mode in the future, a
  908. line enforcing Org mode will be inserted into the buffer, if this option
  909. has been set."
  910. :group 'org-startup
  911. :type 'boolean)
  912. (defcustom org-ellipsis nil
  913. "The ellipsis to use in the Org mode outline.
  914. When nil, just use the standard three dots. When a non-empty string,
  915. use that string instead.
  916. The change affects only Org mode (which will then use its own display table).
  917. Changing this requires executing `\\[org-mode]' in a buffer to become
  918. effective."
  919. :group 'org-startup
  920. :type '(choice (const :tag "Default" nil)
  921. (string :tag "String" :value "...#"))
  922. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  923. (defvar org-display-table nil
  924. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  925. (defgroup org-keywords nil
  926. "Keywords in Org mode."
  927. :tag "Org Keywords"
  928. :group 'org)
  929. (defcustom org-closed-keep-when-no-todo nil
  930. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  931. :group 'org-todo
  932. :group 'org-keywords
  933. :version "24.4"
  934. :package-version '(Org . "8.0")
  935. :type 'boolean)
  936. (defgroup org-structure nil
  937. "Options concerning the general structure of Org files."
  938. :tag "Org Structure"
  939. :group 'org)
  940. (defgroup org-reveal-location nil
  941. "Options about how to make context of a location visible."
  942. :tag "Org Reveal Location"
  943. :group 'org-structure)
  944. (defcustom org-show-context-detail '((agenda . local)
  945. (bookmark-jump . lineage)
  946. (isearch . lineage)
  947. (default . ancestors))
  948. "Alist between context and visibility span when revealing a location.
  949. \\<org-mode-map>Some actions may move point into invisible
  950. locations. As a consequence, Org always expose a neighborhood
  951. around point. How much is shown depends on the initial action,
  952. or context. Valid contexts are
  953. agenda when exposing an entry from the agenda
  954. org-goto when using the command `org-goto' (`\\[org-goto]')
  955. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  956. tags-tree when constructing a sparse tree based on tags matches
  957. link-search when exposing search matches associated with a link
  958. mark-goto when exposing the jump goal of a mark
  959. bookmark-jump when exposing a bookmark location
  960. isearch when exiting from an incremental search
  961. default default for all contexts not set explicitly
  962. Allowed visibility spans are
  963. minimal show current headline; if point is not on headline,
  964. also show entry
  965. local show current headline, entry and next headline
  966. ancestors show current headline and its direct ancestors; if
  967. point is not on headline, also show entry
  968. lineage show current headline, its direct ancestors and all
  969. their children; if point is not on headline, also show
  970. entry and first child
  971. tree show current headline, its direct ancestors and all
  972. their children; if point is not on headline, also show
  973. entry and all children
  974. canonical show current headline, its direct ancestors along with
  975. their entries and children; if point is not located on
  976. the headline, also show current entry and all children
  977. As special cases, a nil or t value means show all contexts in
  978. `minimal' or `canonical' view, respectively.
  979. Some views can make displayed information very compact, but also
  980. make it harder to edit the location of the match. In such
  981. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  982. more context."
  983. :group 'org-reveal-location
  984. :version "26.1"
  985. :package-version '(Org . "9.0")
  986. :type '(choice
  987. (const :tag "Canonical" t)
  988. (const :tag "Minimal" nil)
  989. (repeat :greedy t :tag "Individual contexts"
  990. (cons
  991. (choice :tag "Context"
  992. (const agenda)
  993. (const org-goto)
  994. (const occur-tree)
  995. (const tags-tree)
  996. (const link-search)
  997. (const mark-goto)
  998. (const bookmark-jump)
  999. (const isearch)
  1000. (const default))
  1001. (choice :tag "Detail level"
  1002. (const minimal)
  1003. (const local)
  1004. (const ancestors)
  1005. (const lineage)
  1006. (const tree)
  1007. (const canonical))))))
  1008. (defcustom org-indirect-buffer-display 'other-window
  1009. "How should indirect tree buffers be displayed?
  1010. This applies to indirect buffers created with the commands
  1011. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1012. Valid values are:
  1013. current-window Display in the current window
  1014. other-window Just display in another window.
  1015. dedicated-frame Create one new frame, and re-use it each time.
  1016. new-frame Make a new frame each time. Note that in this case
  1017. previously-made indirect buffers are kept, and you need to
  1018. kill these buffers yourself."
  1019. :group 'org-structure
  1020. :group 'org-agenda-windows
  1021. :type '(choice
  1022. (const :tag "In current window" current-window)
  1023. (const :tag "In current frame, other window" other-window)
  1024. (const :tag "Each time a new frame" new-frame)
  1025. (const :tag "One dedicated frame" dedicated-frame)))
  1026. (defconst org-file-apps-gnu
  1027. '((remote . emacs)
  1028. (system . mailcap)
  1029. (t . mailcap))
  1030. "Default file applications on a UNIX or GNU/Linux system.
  1031. See `org-file-apps'.")
  1032. (defconst org-file-apps-macos
  1033. '((remote . emacs)
  1034. (system . "open %s")
  1035. ("ps.gz" . "gv %s")
  1036. ("eps.gz" . "gv %s")
  1037. ("dvi" . "xdvi %s")
  1038. ("fig" . "xfig %s")
  1039. (t . "open %s"))
  1040. "Default file applications on a macOS system.
  1041. The system \"open\" is known as a default, but we use X11 applications
  1042. for some files for which the OS does not have a good default.
  1043. See `org-file-apps'.")
  1044. (defconst org-file-apps-windowsnt
  1045. (list '(remote . emacs)
  1046. (cons 'system (lambda (file _path)
  1047. (with-no-warnings (w32-shell-execute "open" file))))
  1048. (cons t (lambda (file _path)
  1049. (with-no-warnings (w32-shell-execute "open" file)))))
  1050. "Default file applications on a Windows NT system.
  1051. The system \"open\" is used for most files.
  1052. See `org-file-apps'.")
  1053. (defcustom org-file-apps
  1054. '((auto-mode . emacs)
  1055. ("\\.mm\\'" . default)
  1056. ("\\.x?html?\\'" . default)
  1057. ("\\.pdf\\'" . default))
  1058. "External applications for opening `file:path' items in a document.
  1059. \\<org-mode-map>
  1060. Org mode uses system defaults for different file types, but
  1061. you can use this variable to set the application for a given file
  1062. extension. The entries in this list are cons cells where the car identifies
  1063. files and the cdr the corresponding command.
  1064. Possible values for the file identifier are:
  1065. \"string\" A string as a file identifier can be interpreted in different
  1066. ways, depending on its contents:
  1067. - Alphanumeric characters only:
  1068. Match links with this file extension.
  1069. Example: (\"pdf\" . \"evince %s\")
  1070. to open PDFs with evince.
  1071. - Regular expression: Match links where the
  1072. filename matches the regexp. If you want to
  1073. use groups here, use shy groups.
  1074. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1075. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1076. to open *.html and *.xhtml with firefox.
  1077. - Regular expression which contains (non-shy) groups:
  1078. Match links where the whole link, including \"::\", and
  1079. anything after that, matches the regexp.
  1080. In a custom command string, %1, %2, etc. are replaced with
  1081. the parts of the link that were matched by the groups.
  1082. For backwards compatibility, if a command string is given
  1083. that does not use any of the group matches, this case is
  1084. handled identically to the second one (i.e. match against
  1085. file name only).
  1086. In a custom function, you can access the group matches with
  1087. (match-string n link).
  1088. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1089. \"evince -p %1 %s\")
  1090. to open [[file:document.pdf::5]] with evince at page 5.
  1091. `directory' Matches a directory
  1092. `remote' Matches a remote file, accessible through tramp or efs.
  1093. Remote files most likely should be visited through Emacs
  1094. because external applications cannot handle such paths.
  1095. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1096. so all files Emacs knows how to handle. Using this with
  1097. command `emacs' will open most files in Emacs. Beware that this
  1098. will also open html files inside Emacs, unless you add
  1099. (\"html\" . default) to the list as well.
  1100. `system' The system command to open files, like `open' on Windows
  1101. and macOS, and mailcap under GNU/Linux. This is the command
  1102. that will be selected if you call `org-open-at-point' with a
  1103. double prefix argument (`\\[universal-argument] \
  1104. \\[universal-argument] \\[org-open-at-point]').
  1105. t Default for files not matched by any of the other options.
  1106. Possible values for the command are:
  1107. `emacs' The file will be visited by the current Emacs process.
  1108. `default' Use the default application for this file type, which is the
  1109. association for t in the list, most likely in the system-specific
  1110. part. This can be used to overrule an unwanted setting in the
  1111. system-specific variable.
  1112. `system' Use the system command for opening files, like \"open\".
  1113. This command is specified by the entry whose car is `system'.
  1114. Most likely, the system-specific version of this variable
  1115. does define this command, but you can overrule/replace it
  1116. here.
  1117. `mailcap' Use command specified in the mailcaps.
  1118. string A command to be executed by a shell; %s will be replaced
  1119. by the path to the file.
  1120. function A Lisp function, which will be called with two arguments:
  1121. the file path and the original link string, without the
  1122. \"file:\" prefix.
  1123. For more examples, see the system specific constants
  1124. `org-file-apps-macos'
  1125. `org-file-apps-windowsnt'
  1126. `org-file-apps-gnu'."
  1127. :group 'org
  1128. :type '(repeat
  1129. (cons (choice :value ""
  1130. (string :tag "Extension")
  1131. (const :tag "System command to open files" system)
  1132. (const :tag "Default for unrecognized files" t)
  1133. (const :tag "Remote file" remote)
  1134. (const :tag "Links to a directory" directory)
  1135. (const :tag "Any files that have Emacs modes"
  1136. auto-mode))
  1137. (choice :value ""
  1138. (const :tag "Visit with Emacs" emacs)
  1139. (const :tag "Use default" default)
  1140. (const :tag "Use the system command" system)
  1141. (string :tag "Command")
  1142. (function :tag "Function")))))
  1143. (defcustom org-open-non-existing-files nil
  1144. "Non-nil means `org-open-file' opens non-existing files.
  1145. When nil, an error is thrown.
  1146. This variable applies only to external applications because they
  1147. might choke on non-existing files. If the link is to a file that
  1148. will be opened in Emacs, the variable is ignored."
  1149. :group 'org
  1150. :type 'boolean
  1151. :safe #'booleanp)
  1152. (defcustom org-open-directory-means-index-dot-org nil
  1153. "When non-nil a link to a directory really means to \"index.org\".
  1154. When nil, following a directory link runs Dired or opens
  1155. a finder/explorer window on that directory."
  1156. :group 'org
  1157. :type 'boolean
  1158. :safe #'booleanp)
  1159. (defcustom org-bookmark-names-plist
  1160. '(:last-capture "org-capture-last-stored"
  1161. :last-refile "org-refile-last-stored"
  1162. :last-capture-marker "org-capture-last-stored-marker")
  1163. "Names for bookmarks automatically set by some Org commands.
  1164. This can provide strings as names for a number of bookmarks Org sets
  1165. automatically. The following keys are currently implemented:
  1166. :last-capture
  1167. :last-capture-marker
  1168. :last-refile
  1169. When a key does not show up in the property list, the corresponding bookmark
  1170. is not set."
  1171. :group 'org-structure
  1172. :type 'plist)
  1173. (defgroup org-cycle nil
  1174. "Options concerning visibility cycling in Org mode."
  1175. :tag "Org Cycle"
  1176. :group 'org-structure)
  1177. (defcustom org-cycle-skip-children-state-if-no-children t
  1178. "Non-nil means skip CHILDREN state in entries that don't have any."
  1179. :group 'org-cycle
  1180. :type 'boolean)
  1181. (defcustom org-cycle-max-level nil
  1182. "Maximum level which should still be subject to visibility cycling.
  1183. Levels higher than this will, for cycling, be treated as text, not a headline.
  1184. When `org-odd-levels-only' is set, a value of N in this variable actually
  1185. means 2N-1 stars as the limiting headline.
  1186. When nil, cycle all levels.
  1187. Note that the limiting level of cycling is also influenced by
  1188. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1189. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1190. than its value."
  1191. :group 'org-cycle
  1192. :type '(choice
  1193. (const :tag "No limit" nil)
  1194. (integer :tag "Maximum level")))
  1195. (defcustom org-hide-block-startup nil
  1196. "Non-nil means entering Org mode will fold all blocks.
  1197. This can also be set in on a per-file basis with
  1198. #+STARTUP: hideblocks
  1199. #+STARTUP: showblocks"
  1200. :group 'org-startup
  1201. :group 'org-cycle
  1202. :type 'boolean)
  1203. (defcustom org-cycle-global-at-bob nil
  1204. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1205. This makes it possible to do global cycling without having to use `S-TAB'
  1206. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1207. line of the buffer
  1208. must not be a headline -- it may be empty or some other text.
  1209. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1210. sure the cursor stays at the beginning of the buffer.
  1211. When this option is nil, don't do anything special at the beginning of
  1212. the buffer."
  1213. :group 'org-cycle
  1214. :type 'boolean)
  1215. (defcustom org-cycle-level-after-item/entry-creation t
  1216. "Non-nil means cycle entry level or item indentation in new empty entries.
  1217. When the cursor is at the end of an empty headline, i.e., with only stars
  1218. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1219. and then all possible ancestor states, before returning to the original state.
  1220. This makes data entry extremely fast: M-RET to create a new headline,
  1221. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1222. When the cursor is at the end of an empty plain list item, one TAB will
  1223. make it a subitem, two or more tabs will back up to make this an item
  1224. higher up in the item hierarchy."
  1225. :group 'org-cycle
  1226. :type 'boolean)
  1227. (defcustom org-cycle-emulate-tab t
  1228. "Where should `org-cycle' emulate TAB.
  1229. nil Never
  1230. white Only in completely white lines
  1231. whitestart Only at the beginning of lines, before the first non-white char
  1232. t Everywhere except in headlines
  1233. exc-hl-bol Everywhere except at the start of a headline
  1234. If TAB is used in a place where it does not emulate TAB, the current subtree
  1235. visibility is cycled."
  1236. :group 'org-cycle
  1237. :type '(choice (const :tag "Never" nil)
  1238. (const :tag "Only in completely white lines" white)
  1239. (const :tag "Before first char in a line" whitestart)
  1240. (const :tag "Everywhere except in headlines" t)
  1241. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1242. (defcustom org-cycle-separator-lines 2
  1243. "Number of empty lines needed to keep an empty line between collapsed trees.
  1244. If you leave an empty line between the end of a subtree and the following
  1245. headline, this empty line is hidden when the subtree is folded.
  1246. Org mode will leave (exactly) one empty line visible if the number of
  1247. empty lines is equal or larger to the number given in this variable.
  1248. So the default 2 means at least 2 empty lines after the end of a subtree
  1249. are needed to produce free space between a collapsed subtree and the
  1250. following headline.
  1251. If the number is negative, and the number of empty lines is at least -N,
  1252. all empty lines are shown.
  1253. Special case: when 0, never leave empty lines in collapsed view."
  1254. :group 'org-cycle
  1255. :type 'integer)
  1256. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1257. (defcustom org-pre-cycle-hook nil
  1258. "Hook that is run before visibility cycling is happening.
  1259. The function(s) in this hook must accept a single argument which indicates
  1260. the new state that will be set right after running this hook. The
  1261. argument is a symbol. Before a global state change, it can have the values
  1262. `overview', `content', or `all'. Before a local state change, it can have
  1263. the values `folded', `children', or `subtree'."
  1264. :group 'org-cycle
  1265. :type 'hook)
  1266. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1267. org-cycle-show-empty-lines
  1268. org-optimize-window-after-visibility-change)
  1269. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1270. The function(s) in this hook must accept a single argument which indicates
  1271. the new state that was set by the most recent `org-cycle' command. The
  1272. argument is a symbol. After a global state change, it can have the values
  1273. `overview', `contents', or `all'. After a local state change, it can have
  1274. the values `folded', `children', or `subtree'."
  1275. :group 'org-cycle
  1276. :type 'hook
  1277. :version "26.1"
  1278. :package-version '(Org . "8.3"))
  1279. (defgroup org-edit-structure nil
  1280. "Options concerning structure editing in Org mode."
  1281. :tag "Org Edit Structure"
  1282. :group 'org-structure)
  1283. (defcustom org-odd-levels-only nil
  1284. "Non-nil means skip even levels and only use odd levels for the outline.
  1285. This has the effect that two stars are being added/taken away in
  1286. promotion/demotion commands. It also influences how levels are
  1287. handled by the exporters.
  1288. Changing it requires restart of `font-lock-mode' to become effective
  1289. for fontification also in regions already fontified.
  1290. You may also set this on a per-file basis by adding one of the following
  1291. lines to the buffer:
  1292. #+STARTUP: odd
  1293. #+STARTUP: oddeven"
  1294. :group 'org-edit-structure
  1295. :group 'org-appearance
  1296. :type 'boolean)
  1297. (defcustom org-adapt-indentation t
  1298. "Non-nil means adapt indentation to outline node level.
  1299. When this variable is set, Org assumes that you write outlines by
  1300. indenting text in each node to align with the headline (after the
  1301. stars). The following issues are influenced by this variable:
  1302. - The indentation is increased by one space in a demotion
  1303. command, and decreased by one in a promotion command. However,
  1304. in the latter case, if shifting some line in the entry body
  1305. would alter document structure (e.g., insert a new headline),
  1306. indentation is not changed at all.
  1307. - Property drawers and planning information is inserted indented
  1308. when this variable is set. When nil, they will not be indented.
  1309. - TAB indents a line relative to current level. The lines below
  1310. a headline will be indented when this variable is set.
  1311. Note that this is all about true indentation, by adding and
  1312. removing space characters. See also \"org-indent.el\" which does
  1313. level-dependent indentation in a virtual way, i.e. at display
  1314. time in Emacs."
  1315. :group 'org-edit-structure
  1316. :type 'boolean
  1317. :safe #'booleanp)
  1318. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1319. (defcustom org-special-ctrl-a/e nil
  1320. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1321. When t, `C-a' will bring back the cursor to the beginning of the
  1322. headline text, i.e. after the stars and after a possible TODO
  1323. keyword. In an item, this will be the position after bullet and
  1324. check-box, if any. When the cursor is already at that position,
  1325. another `C-a' will bring it to the beginning of the line.
  1326. `C-e' will jump to the end of the headline, ignoring the presence
  1327. of tags in the headline. A second `C-e' will then jump to the
  1328. true end of the line, after any tags. This also means that, when
  1329. this variable is non-nil, `C-e' also will never jump beyond the
  1330. end of the heading of a folded section, i.e. not after the
  1331. ellipses.
  1332. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1333. normally, going to the true line boundary first. Only a directly
  1334. following, identical keypress will bring the cursor to the
  1335. special positions.
  1336. This may also be a cons cell where the behavior for `C-a' and
  1337. `C-e' is set separately."
  1338. :group 'org-edit-structure
  1339. :type '(choice
  1340. (const :tag "off" nil)
  1341. (const :tag "on: after stars/bullet and before tags first" t)
  1342. (const :tag "reversed: true line boundary first" reversed)
  1343. (cons :tag "Set C-a and C-e separately"
  1344. (choice :tag "Special C-a"
  1345. (const :tag "off" nil)
  1346. (const :tag "on: after stars/bullet first" t)
  1347. (const :tag "reversed: before stars/bullet first" reversed))
  1348. (choice :tag "Special C-e"
  1349. (const :tag "off" nil)
  1350. (const :tag "on: before tags first" t)
  1351. (const :tag "reversed: after tags first" reversed)))))
  1352. (defcustom org-special-ctrl-k nil
  1353. "Non-nil means `C-k' will behave specially in headlines.
  1354. When nil, `C-k' will call the default `kill-line' command.
  1355. When t, the following will happen while the cursor is in the headline:
  1356. - When the cursor is at the beginning of a headline, kill the entire
  1357. line and possible the folded subtree below the line.
  1358. - When in the middle of the headline text, kill the headline up to the tags.
  1359. - When after the headline text, kill the tags."
  1360. :group 'org-edit-structure
  1361. :type 'boolean)
  1362. (defcustom org-ctrl-k-protect-subtree nil
  1363. "Non-nil means, do not delete a hidden subtree with C-k.
  1364. When set to the symbol `error', simply throw an error when C-k is
  1365. used to kill (part-of) a headline that has hidden text behind it.
  1366. Any other non-nil value will result in a query to the user, if it is
  1367. OK to kill that hidden subtree. When nil, kill without remorse."
  1368. :group 'org-edit-structure
  1369. :version "24.1"
  1370. :type '(choice
  1371. (const :tag "Do not protect hidden subtrees" nil)
  1372. (const :tag "Protect hidden subtrees with a security query" t)
  1373. (const :tag "Never kill a hidden subtree with C-k" error)))
  1374. (defcustom org-special-ctrl-o t
  1375. "Non-nil means, make `C-o' insert a row in tables."
  1376. :group 'org-edit-structure
  1377. :type 'boolean)
  1378. (defcustom org-catch-invisible-edits nil
  1379. "Check if in invisible region before inserting or deleting a character.
  1380. Valid values are:
  1381. nil Do not check, so just do invisible edits.
  1382. error Throw an error and do nothing.
  1383. show Make point visible, and do the requested edit.
  1384. show-and-error Make point visible, then throw an error and abort the edit.
  1385. smart Make point visible, and do insertion/deletion if it is
  1386. adjacent to visible text and the change feels predictable.
  1387. Never delete a previously invisible character or add in the
  1388. middle or right after an invisible region. Basically, this
  1389. allows insertion and backward-delete right before ellipses.
  1390. FIXME: maybe in this case we should not even show?"
  1391. :group 'org-edit-structure
  1392. :version "24.1"
  1393. :type '(choice
  1394. (const :tag "Do not check" nil)
  1395. (const :tag "Throw error when trying to edit" error)
  1396. (const :tag "Unhide, but do not do the edit" show-and-error)
  1397. (const :tag "Show invisible part and do the edit" show)
  1398. (const :tag "Be smart and do the right thing" smart)))
  1399. (defcustom org-yank-folded-subtrees t
  1400. "Non-nil means when yanking subtrees, fold them.
  1401. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1402. it starts with a heading and all other headings in it are either children
  1403. or siblings, then fold all the subtrees. However, do this only if no
  1404. text after the yank would be swallowed into a folded tree by this action."
  1405. :group 'org-edit-structure
  1406. :type 'boolean)
  1407. (defcustom org-yank-adjusted-subtrees nil
  1408. "Non-nil means when yanking subtrees, adjust the level.
  1409. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1410. this function for details."
  1411. :group 'org-edit-structure
  1412. :type 'boolean)
  1413. (defcustom org-M-RET-may-split-line '((default . t))
  1414. "Non-nil means M-RET will split the line at the cursor position.
  1415. When nil, it will go to the end of the line before making a
  1416. new line.
  1417. You may also set this option in a different way for different
  1418. contexts. Valid contexts are:
  1419. headline when creating a new headline
  1420. item when creating a new item
  1421. table in a table field
  1422. default the value to be used for all contexts not explicitly
  1423. customized"
  1424. :group 'org-structure
  1425. :group 'org-table
  1426. :type '(choice
  1427. (const :tag "Always" t)
  1428. (const :tag "Never" nil)
  1429. (repeat :greedy t :tag "Individual contexts"
  1430. (cons
  1431. (choice :tag "Context"
  1432. (const headline)
  1433. (const item)
  1434. (const table)
  1435. (const default))
  1436. (boolean)))))
  1437. (defcustom org-insert-heading-respect-content nil
  1438. "Non-nil means insert new headings after the current subtree.
  1439. \\<org-mode-map>
  1440. When nil, the new heading is created directly after the current line.
  1441. The commands `\\[org-insert-heading-respect-content]' and \
  1442. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1443. for the duration of the command."
  1444. :group 'org-structure
  1445. :type 'boolean)
  1446. (defcustom org-blank-before-new-entry '((heading . auto)
  1447. (plain-list-item . auto))
  1448. "Should `org-insert-heading' leave a blank line before new heading/item?
  1449. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1450. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1451. which case Org will look at the surrounding headings/items and try to
  1452. make an intelligent decision whether to insert a blank line or not."
  1453. :group 'org-edit-structure
  1454. :type '(list
  1455. (cons (const heading)
  1456. (choice (const :tag "Never" nil)
  1457. (const :tag "Always" t)
  1458. (const :tag "Auto" auto)))
  1459. (cons (const plain-list-item)
  1460. (choice (const :tag "Never" nil)
  1461. (const :tag "Always" t)
  1462. (const :tag "Auto" auto)))))
  1463. (defcustom org-insert-heading-hook nil
  1464. "Hook being run after inserting a new heading."
  1465. :group 'org-edit-structure
  1466. :type 'hook)
  1467. (defgroup org-sparse-trees nil
  1468. "Options concerning sparse trees in Org mode."
  1469. :tag "Org Sparse Trees"
  1470. :group 'org-structure)
  1471. (defcustom org-highlight-sparse-tree-matches t
  1472. "Non-nil means highlight all matches that define a sparse tree.
  1473. The highlights will automatically disappear the next time the buffer is
  1474. changed by an edit command."
  1475. :group 'org-sparse-trees
  1476. :type 'boolean)
  1477. (defcustom org-remove-highlights-with-change t
  1478. "Non-nil means any change to the buffer will remove temporary highlights.
  1479. \\<org-mode-map>\
  1480. Such highlights are created by `org-occur' and `org-clock-display'.
  1481. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1482. to get rid of the highlights.
  1483. The highlights created by `org-latex-preview' always need
  1484. `\\[org-latex-preview]' to be removed."
  1485. :group 'org-sparse-trees
  1486. :group 'org-time
  1487. :type 'boolean)
  1488. (defcustom org-occur-case-fold-search t
  1489. "Non-nil means `org-occur' should be case-insensitive.
  1490. If set to `smart' the search will be case-insensitive only if it
  1491. doesn't specify any upper case character."
  1492. :group 'org-sparse-trees
  1493. :version "26.1"
  1494. :type '(choice
  1495. (const :tag "Case-sensitive" nil)
  1496. (const :tag "Case-insensitive" t)
  1497. (const :tag "Case-insensitive for lower case searches only" smart)))
  1498. (defcustom org-occur-hook '(org-first-headline-recenter)
  1499. "Hook that is run after `org-occur' has constructed a sparse tree.
  1500. This can be used to recenter the window to show as much of the structure
  1501. as possible."
  1502. :group 'org-sparse-trees
  1503. :type 'hook)
  1504. (defcustom org-self-insert-cluster-for-undo nil
  1505. "Non-nil means cluster self-insert commands for undo when possible.
  1506. If this is set, then, like in the Emacs command loop, 20 consecutive
  1507. characters will be undone together.
  1508. This is configurable, because there is some impact on typing performance."
  1509. :group 'org-table
  1510. :type 'boolean)
  1511. (defvaralias 'org-activate-links 'org-highlight-links)
  1512. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1513. "Types of links that should be highlighted in Org files.
  1514. This is a list of symbols, each one of them leading to the
  1515. highlighting of a certain link type.
  1516. You can still open links that are not highlighted.
  1517. In principle, it does not hurt to turn on highlighting for all
  1518. link types. There may be a small gain when turning off unused
  1519. link types. The types are:
  1520. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1521. angle Links in angular brackets that may contain whitespace like
  1522. <bbdb:Carsten Dominik>.
  1523. plain Plain links in normal text, no whitespace, like http://google.com.
  1524. radio Text that is matched by a radio target, see manual for details.
  1525. tag Tag settings in a headline (link to tag search).
  1526. date Time stamps (link to calendar).
  1527. footnote Footnote labels.
  1528. If you set this variable during an Emacs session, use `org-mode-restart'
  1529. in the Org buffer so that the change takes effect."
  1530. :group 'org-appearance
  1531. :type '(set :greedy t
  1532. (const :tag "Double bracket links" bracket)
  1533. (const :tag "Angular bracket links" angle)
  1534. (const :tag "Plain text links" plain)
  1535. (const :tag "Radio target matches" radio)
  1536. (const :tag "Tags" tag)
  1537. (const :tag "Timestamps" date)
  1538. (const :tag "Footnotes" footnote)))
  1539. (defcustom org-mark-ring-length 4
  1540. "Number of different positions to be recorded in the ring.
  1541. Changing this requires a restart of Emacs to work correctly."
  1542. :group 'org-link-follow
  1543. :type 'integer)
  1544. (defgroup org-refile nil
  1545. "Options concerning refiling entries in Org mode."
  1546. :tag "Org Refile"
  1547. :group 'org)
  1548. (defcustom org-directory "~/org"
  1549. "Directory with Org files.
  1550. This is just a default location to look for Org files. There is no need
  1551. at all to put your files into this directory. It is used in the
  1552. following situations:
  1553. 1. When a capture template specifies a target file that is not an
  1554. absolute path. The path will then be interpreted relative to
  1555. `org-directory'
  1556. 2. When the value of variable `org-agenda-files' is a single file, any
  1557. relative paths in this file will be taken as relative to
  1558. `org-directory'."
  1559. :group 'org-refile
  1560. :group 'org-capture
  1561. :type 'directory)
  1562. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1563. "Default target for storing notes.
  1564. Used as a fall back file for org-capture.el, for templates that
  1565. do not specify a target file."
  1566. :group 'org-refile
  1567. :group 'org-capture
  1568. :type 'file)
  1569. (defcustom org-reverse-note-order nil
  1570. "Non-nil means store new notes at the beginning of a file or entry.
  1571. When nil, new notes will be filed to the end of a file or entry.
  1572. This can also be a list with cons cells of regular expressions that
  1573. are matched against file names, and values."
  1574. :group 'org-capture
  1575. :group 'org-refile
  1576. :type '(choice
  1577. (const :tag "Reverse always" t)
  1578. (const :tag "Reverse never" nil)
  1579. (repeat :tag "By file name regexp"
  1580. (cons regexp boolean))))
  1581. (defcustom org-log-refile nil
  1582. "Information to record when a task is refiled.
  1583. Possible values are:
  1584. nil Don't add anything
  1585. time Add a time stamp to the task
  1586. note Prompt for a note and add it with template `org-log-note-headings'
  1587. This option can also be set with on a per-file-basis with
  1588. #+STARTUP: nologrefile
  1589. #+STARTUP: logrefile
  1590. #+STARTUP: lognoterefile
  1591. You can have local logging settings for a subtree by setting the LOGGING
  1592. property to one or more of these keywords.
  1593. When bulk-refiling, e.g., from the agenda, the value `note' is
  1594. forbidden and will temporarily be changed to `time'."
  1595. :group 'org-refile
  1596. :group 'org-progress
  1597. :version "24.1"
  1598. :type '(choice
  1599. (const :tag "No logging" nil)
  1600. (const :tag "Record timestamp" time)
  1601. (const :tag "Record timestamp with note." note)))
  1602. (defcustom org-refile-targets nil
  1603. "Targets for refiling entries with `\\[org-refile]'.
  1604. This is a list of cons cells. Each cell contains:
  1605. - a specification of the files to be considered, either a list of files,
  1606. or a symbol whose function or variable value will be used to retrieve
  1607. a file name or a list of file names. If you use `org-agenda-files' for
  1608. that, all agenda files will be scanned for targets. Nil means consider
  1609. headings in the current buffer.
  1610. - A specification of how to find candidate refile targets. This may be
  1611. any of:
  1612. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1613. This tag has to be present in all target headlines, inheritance will
  1614. not be considered.
  1615. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1616. todo keyword.
  1617. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1618. headlines that are refiling targets.
  1619. - a cons cell (:level . N). Any headline of level N is considered a target.
  1620. Note that, when `org-odd-levels-only' is set, level corresponds to
  1621. order in hierarchy, not to the number of stars.
  1622. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1623. Note that, when `org-odd-levels-only' is set, level corresponds to
  1624. order in hierarchy, not to the number of stars.
  1625. Each element of this list generates a set of possible targets.
  1626. The union of these sets is presented (with completion) to
  1627. the user by `org-refile'.
  1628. You can set the variable `org-refile-target-verify-function' to a function
  1629. to verify each headline found by the simple criteria above.
  1630. When this variable is nil, all top-level headlines in the current buffer
  1631. are used, equivalent to the value `((nil . (:level . 1))'."
  1632. :group 'org-refile
  1633. :type '(repeat
  1634. (cons
  1635. (choice :value org-agenda-files
  1636. (const :tag "All agenda files" org-agenda-files)
  1637. (const :tag "Current buffer" nil)
  1638. (function) (variable) (file))
  1639. (choice :tag "Identify target headline by"
  1640. (cons :tag "Specific tag" (const :value :tag) (string))
  1641. (cons :tag "TODO keyword" (const :value :todo) (string))
  1642. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1643. (cons :tag "Level number" (const :value :level) (integer))
  1644. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1645. (defcustom org-refile-target-verify-function nil
  1646. "Function to verify if the headline at point should be a refile target.
  1647. The function will be called without arguments, with point at the
  1648. beginning of the headline. It should return t and leave point
  1649. where it is if the headline is a valid target for refiling.
  1650. If the target should not be selected, the function must return nil.
  1651. In addition to this, it may move point to a place from where the search
  1652. should be continued. For example, the function may decide that the entire
  1653. subtree of the current entry should be excluded and move point to the end
  1654. of the subtree."
  1655. :group 'org-refile
  1656. :type '(choice
  1657. (const nil)
  1658. (function)))
  1659. (defcustom org-refile-use-cache nil
  1660. "Non-nil means cache refile targets to speed up the process.
  1661. \\<org-mode-map>\
  1662. The cache for a particular file will be updated automatically when
  1663. the buffer has been killed, or when any of the marker used for flagging
  1664. refile targets no longer points at a live buffer.
  1665. If you have added new entries to a buffer that might themselves be targets,
  1666. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1667. if you find that easier, \
  1668. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1669. \\[org-refile]'."
  1670. :group 'org-refile
  1671. :version "24.1"
  1672. :type 'boolean)
  1673. (defcustom org-refile-use-outline-path nil
  1674. "Non-nil means provide refile targets as paths.
  1675. So a level 3 headline will be available as level1/level2/level3.
  1676. When the value is `file', also include the file name (without directory)
  1677. into the path. In this case, you can also stop the completion after
  1678. the file name, to get entries inserted as top level in the file.
  1679. When `full-file-path', include the full file path.
  1680. When `buffer-name', use the buffer name."
  1681. :group 'org-refile
  1682. :type '(choice
  1683. (const :tag "Not" nil)
  1684. (const :tag "Yes" t)
  1685. (const :tag "Start with file name" file)
  1686. (const :tag "Start with full file path" full-file-path)
  1687. (const :tag "Start with buffer name" buffer-name)))
  1688. (defcustom org-outline-path-complete-in-steps t
  1689. "Non-nil means complete the outline path in hierarchical steps.
  1690. When Org uses the refile interface to select an outline path (see
  1691. `org-refile-use-outline-path'), the completion of the path can be
  1692. done in a single go, or it can be done in steps down the headline
  1693. hierarchy. Going in steps is probably the best if you do not use
  1694. a special completion package like `ido' or `icicles'. However,
  1695. when using these packages, going in one step can be very fast,
  1696. while still showing the whole path to the entry."
  1697. :group 'org-refile
  1698. :type 'boolean)
  1699. (defcustom org-refile-allow-creating-parent-nodes nil
  1700. "Non-nil means allow the creation of new nodes as refile targets.
  1701. New nodes are then created by adding \"/new node name\" to the completion
  1702. of an existing node. When the value of this variable is `confirm',
  1703. new node creation must be confirmed by the user (recommended).
  1704. When nil, the completion must match an existing entry.
  1705. Note that, if the new heading is not seen by the criteria
  1706. listed in `org-refile-targets', multiple instances of the same
  1707. heading would be created by trying again to file under the new
  1708. heading."
  1709. :group 'org-refile
  1710. :type '(choice
  1711. (const :tag "Never" nil)
  1712. (const :tag "Always" t)
  1713. (const :tag "Prompt for confirmation" confirm)))
  1714. (defcustom org-refile-active-region-within-subtree nil
  1715. "Non-nil means also refile active region within a subtree.
  1716. By default `org-refile' doesn't allow refiling regions if they
  1717. don't contain a set of subtrees, but it might be convenient to
  1718. do so sometimes: in that case, the first line of the region is
  1719. converted to a headline before refiling."
  1720. :group 'org-refile
  1721. :version "24.1"
  1722. :type 'boolean)
  1723. (defgroup org-todo nil
  1724. "Options concerning TODO items in Org mode."
  1725. :tag "Org TODO"
  1726. :group 'org)
  1727. (defgroup org-progress nil
  1728. "Options concerning Progress logging in Org mode."
  1729. :tag "Org Progress"
  1730. :group 'org-time)
  1731. (defvar org-todo-interpretation-widgets
  1732. '((:tag "Sequence (cycling hits every state)" sequence)
  1733. (:tag "Type (cycling directly to DONE)" type))
  1734. "The available interpretation symbols for customizing `org-todo-keywords'.
  1735. Interested libraries should add to this list.")
  1736. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1737. "List of TODO entry keyword sequences and their interpretation.
  1738. \\<org-mode-map>This is a list of sequences.
  1739. Each sequence starts with a symbol, either `sequence' or `type',
  1740. indicating if the keywords should be interpreted as a sequence of
  1741. action steps, or as different types of TODO items. The first
  1742. keywords are states requiring action - these states will select a headline
  1743. for inclusion into the global TODO list Org produces. If one of the
  1744. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1745. signify that no further action is necessary. If \"|\" is not found,
  1746. the last keyword is treated as the only DONE state of the sequence.
  1747. The command `\\[org-todo]' cycles an entry through these states, and one
  1748. additional state where no keyword is present. For details about this
  1749. cycling, see the manual.
  1750. TODO keywords and interpretation can also be set on a per-file basis with
  1751. the special #+SEQ_TODO and #+TYP_TODO lines.
  1752. Each keyword can optionally specify a character for fast state selection
  1753. \(in combination with the variable `org-use-fast-todo-selection')
  1754. and specifiers for state change logging, using the same syntax that
  1755. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1756. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1757. indicates to record a time stamp each time this state is selected.
  1758. Each keyword may also specify if a timestamp or a note should be
  1759. recorded when entering or leaving the state, by adding additional
  1760. characters in the parenthesis after the keyword. This looks like this:
  1761. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1762. record only the time of the state change. With X and Y being either
  1763. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1764. Y when leaving the state if and only if the *target* state does not
  1765. define X. You may omit any of the fast-selection key or X or /Y,
  1766. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1767. For backward compatibility, this variable may also be just a list
  1768. of keywords. In this case the interpretation (sequence or type) will be
  1769. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1770. :group 'org-todo
  1771. :group 'org-keywords
  1772. :type '(choice
  1773. (repeat :tag "Old syntax, just keywords"
  1774. (string :tag "Keyword"))
  1775. (repeat :tag "New syntax"
  1776. (cons
  1777. (choice
  1778. :tag "Interpretation"
  1779. ;;Quick and dirty way to see
  1780. ;;`org-todo-interpretations'. This takes the
  1781. ;;place of item arguments
  1782. :convert-widget
  1783. (lambda (widget)
  1784. (widget-put widget
  1785. :args (mapcar
  1786. (lambda (x)
  1787. (widget-convert
  1788. (cons 'const x)))
  1789. org-todo-interpretation-widgets))
  1790. widget))
  1791. (repeat
  1792. (string :tag "Keyword"))))))
  1793. (defvar-local org-todo-keywords-1 nil
  1794. "All TODO and DONE keywords active in a buffer.")
  1795. (defvar org-todo-keywords-for-agenda nil)
  1796. (defvar org-done-keywords-for-agenda nil)
  1797. (defvar org-todo-keyword-alist-for-agenda nil)
  1798. (defvar org-tag-alist-for-agenda nil
  1799. "Alist of all tags from all agenda files.")
  1800. (defvar org-tag-groups-alist-for-agenda nil
  1801. "Alist of all groups tags from all current agenda files.")
  1802. (defvar-local org-tag-groups-alist nil)
  1803. (defvar org-agenda-contributing-files nil)
  1804. (defvar-local org-current-tag-alist nil
  1805. "Alist of all tag groups in current buffer.
  1806. This variable takes into consideration `org-tag-alist',
  1807. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1808. (defvar-local org-not-done-keywords nil)
  1809. (defvar-local org-done-keywords nil)
  1810. (defvar-local org-todo-heads nil)
  1811. (defvar-local org-todo-sets nil)
  1812. (defvar-local org-todo-log-states nil)
  1813. (defvar-local org-todo-kwd-alist nil)
  1814. (defvar-local org-todo-key-alist nil)
  1815. (defvar-local org-todo-key-trigger nil)
  1816. (defcustom org-todo-interpretation 'sequence
  1817. "Controls how TODO keywords are interpreted.
  1818. This variable is in principle obsolete and is only used for
  1819. backward compatibility, if the interpretation of todo keywords is
  1820. not given already in `org-todo-keywords'. See that variable for
  1821. more information."
  1822. :group 'org-todo
  1823. :group 'org-keywords
  1824. :type '(choice (const sequence)
  1825. (const type)))
  1826. (defcustom org-use-fast-todo-selection 'auto
  1827. "\\<org-mode-map>\
  1828. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1829. This variable describes if and under what circumstances the cycling
  1830. mechanism for TODO keywords will be replaced by a single-key, direct
  1831. selection scheme, where the choices are displayed in a little window.
  1832. When nil, fast selection is never used. This means that the command
  1833. will always switch to the next state.
  1834. When it is the symbol `auto', fast selection is whenever selection
  1835. keys have been defined.
  1836. `expert' is like `auto', but no special window with the keyword
  1837. will be shown, choices will only be listed in the prompt.
  1838. In all cases, the special interface is only used if access keys have
  1839. actually been assigned by the user, i.e. if keywords in the configuration
  1840. are followed by a letter in parenthesis, like TODO(t)."
  1841. :group 'org-todo
  1842. :set (lambda (var val)
  1843. (cond
  1844. ((eq var t) (set var 'auto))
  1845. ((eq var 'prefix) (set var nil))
  1846. (t (set var val))))
  1847. :type '(choice
  1848. (const :tag "Never" nil)
  1849. (const :tag "Automatically, when key letter have been defined" auto)
  1850. (const :tag "Automatically, but don't show the selection window" expert)))
  1851. (defcustom org-provide-todo-statistics t
  1852. "Non-nil means update todo statistics after insert and toggle.
  1853. ALL-HEADLINES means update todo statistics by including headlines
  1854. with no TODO keyword as well, counting them as not done.
  1855. A list of TODO keywords means the same, but skip keywords that are
  1856. not in this list.
  1857. When set to a list of two lists, the first list contains keywords
  1858. to consider as TODO keywords, the second list contains keywords
  1859. to consider as DONE keywords.
  1860. When this is set, todo statistics is updated in the parent of the
  1861. current entry each time a todo state is changed."
  1862. :group 'org-todo
  1863. :type '(choice
  1864. (const :tag "Yes, only for TODO entries" t)
  1865. (const :tag "Yes, including all entries" all-headlines)
  1866. (repeat :tag "Yes, for TODOs in this list"
  1867. (string :tag "TODO keyword"))
  1868. (list :tag "Yes, for TODOs and DONEs in these lists"
  1869. (repeat (string :tag "TODO keyword"))
  1870. (repeat (string :tag "DONE keyword")))
  1871. (other :tag "No TODO statistics" nil)))
  1872. (defcustom org-hierarchical-todo-statistics t
  1873. "Non-nil means TODO statistics covers just direct children.
  1874. When nil, all entries in the subtree are considered.
  1875. This has only an effect if `org-provide-todo-statistics' is set.
  1876. To set this to nil for only a single subtree, use a COOKIE_DATA
  1877. property and include the word \"recursive\" into the value."
  1878. :group 'org-todo
  1879. :type 'boolean)
  1880. (defcustom org-after-todo-state-change-hook nil
  1881. "Hook which is run after the state of a TODO item was changed.
  1882. The new state (a string with a TODO keyword, or nil) is available in the
  1883. Lisp variable `org-state'."
  1884. :group 'org-todo
  1885. :type 'hook)
  1886. (defvar org-blocker-hook nil
  1887. "Hook for functions that are allowed to block a state change.
  1888. Functions in this hook should not modify the buffer.
  1889. Each function gets as its single argument a property list,
  1890. see `org-trigger-hook' for more information about this list.
  1891. If any of the functions in this hook returns nil, the state change
  1892. is blocked.")
  1893. (defvar org-trigger-hook nil
  1894. "Hook for functions that are triggered by a state change.
  1895. Each function gets as its single argument a property list with at
  1896. least the following elements:
  1897. (:type type-of-change :position pos-at-entry-start
  1898. :from old-state :to new-state)
  1899. Depending on the type, more properties may be present.
  1900. This mechanism is currently implemented for:
  1901. TODO state changes
  1902. ------------------
  1903. :type todo-state-change
  1904. :from previous state (keyword as a string), or nil, or a symbol
  1905. `todo' or `done', to indicate the general type of state.
  1906. :to new state, like in :from")
  1907. (defcustom org-enforce-todo-dependencies nil
  1908. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1909. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1910. be blocked if any prior sibling is not yet done.
  1911. Finally, if the parent is blocked because of ordered siblings of its own,
  1912. the child will also be blocked."
  1913. :set (lambda (var val)
  1914. (set var val)
  1915. (if val
  1916. (add-hook 'org-blocker-hook
  1917. 'org-block-todo-from-children-or-siblings-or-parent)
  1918. (remove-hook 'org-blocker-hook
  1919. 'org-block-todo-from-children-or-siblings-or-parent)))
  1920. :group 'org-todo
  1921. :type 'boolean)
  1922. (defcustom org-enforce-todo-checkbox-dependencies nil
  1923. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1924. When this is nil, checkboxes have no influence on switching TODO states.
  1925. When non-nil, you first need to check off all check boxes before the TODO
  1926. entry can be switched to DONE.
  1927. This variable needs to be set before org.el is loaded, and you need to
  1928. restart Emacs after a change to make the change effective. The only way
  1929. to change it while Emacs is running is through the customize interface."
  1930. :set (lambda (var val)
  1931. (set var val)
  1932. (if val
  1933. (add-hook 'org-blocker-hook
  1934. 'org-block-todo-from-checkboxes)
  1935. (remove-hook 'org-blocker-hook
  1936. 'org-block-todo-from-checkboxes)))
  1937. :group 'org-todo
  1938. :type 'boolean)
  1939. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1940. "Non-nil means inserting a TODO heading is treated as state change.
  1941. So when the command `\\[org-insert-todo-heading]' is used, state change
  1942. logging will apply if appropriate. When nil, the new TODO item will
  1943. be inserted directly, and no logging will take place."
  1944. :group 'org-todo
  1945. :type 'boolean)
  1946. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1947. "Non-nil means switching TODO states with S-cursor counts as state change.
  1948. This is the default behavior. However, setting this to nil allows a
  1949. convenient way to select a TODO state and bypass any logging associated
  1950. with that."
  1951. :group 'org-todo
  1952. :type 'boolean)
  1953. (defcustom org-todo-state-tags-triggers nil
  1954. "Tag changes that should be triggered by TODO state changes.
  1955. This is a list. Each entry is
  1956. (state-change (tag . flag) .......)
  1957. State-change can be a string with a state, and empty string to indicate the
  1958. state that has no TODO keyword, or it can be one of the symbols `todo'
  1959. or `done', meaning any not-done or done state, respectively."
  1960. :group 'org-todo
  1961. :group 'org-tags
  1962. :type '(repeat
  1963. (cons (choice :tag "When changing to"
  1964. (const :tag "Not-done state" todo)
  1965. (const :tag "Done state" done)
  1966. (string :tag "State"))
  1967. (repeat
  1968. (cons :tag "Tag action"
  1969. (string :tag "Tag")
  1970. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1971. (defcustom org-log-done nil
  1972. "Information to record when a task moves to the DONE state.
  1973. Possible values are:
  1974. nil Don't add anything, just change the keyword
  1975. time Add a time stamp to the task
  1976. note Prompt for a note and add it with template `org-log-note-headings'
  1977. This option can also be set with on a per-file-basis with
  1978. #+STARTUP: nologdone
  1979. #+STARTUP: logdone
  1980. #+STARTUP: lognotedone
  1981. You can have local logging settings for a subtree by setting the LOGGING
  1982. property to one or more of these keywords."
  1983. :group 'org-todo
  1984. :group 'org-progress
  1985. :type '(choice
  1986. (const :tag "No logging" nil)
  1987. (const :tag "Record CLOSED timestamp" time)
  1988. (const :tag "Record CLOSED timestamp with note." note)))
  1989. ;; Normalize old uses of org-log-done.
  1990. (cond
  1991. ((eq org-log-done t) (setq org-log-done 'time))
  1992. ((and (listp org-log-done) (memq 'done org-log-done))
  1993. (setq org-log-done 'note)))
  1994. (defcustom org-log-reschedule nil
  1995. "Information to record when the scheduling date of a task is modified.
  1996. Possible values are:
  1997. nil Don't add anything, just change the date
  1998. time Add a time stamp to the task
  1999. note Prompt for a note and add it with template `org-log-note-headings'
  2000. This option can also be set with on a per-file-basis with
  2001. #+STARTUP: nologreschedule
  2002. #+STARTUP: logreschedule
  2003. #+STARTUP: lognotereschedule
  2004. You can have local logging settings for a subtree by setting the LOGGING
  2005. property to one or more of these keywords.
  2006. This variable has an effect when calling `org-schedule' or
  2007. `org-agenda-schedule' only."
  2008. :group 'org-todo
  2009. :group 'org-progress
  2010. :type '(choice
  2011. (const :tag "No logging" nil)
  2012. (const :tag "Record timestamp" time)
  2013. (const :tag "Record timestamp with note" note)))
  2014. (defcustom org-log-redeadline nil
  2015. "Information to record when the deadline date of a task is modified.
  2016. Possible values are:
  2017. nil Don't add anything, just change the date
  2018. time Add a time stamp to the task
  2019. note Prompt for a note and add it with template `org-log-note-headings'
  2020. This option can also be set with on a per-file-basis with
  2021. #+STARTUP: nologredeadline
  2022. #+STARTUP: logredeadline
  2023. #+STARTUP: lognoteredeadline
  2024. You can have local logging settings for a subtree by setting the LOGGING
  2025. property to one or more of these keywords.
  2026. This variable has an effect when calling `org-deadline' or
  2027. `org-agenda-deadline' only."
  2028. :group 'org-todo
  2029. :group 'org-progress
  2030. :type '(choice
  2031. (const :tag "No logging" nil)
  2032. (const :tag "Record timestamp" time)
  2033. (const :tag "Record timestamp with note." note)))
  2034. (defcustom org-log-note-clock-out nil
  2035. "Non-nil means record a note when clocking out of an item.
  2036. This can also be configured on a per-file basis by adding one of
  2037. the following lines anywhere in the buffer:
  2038. #+STARTUP: lognoteclock-out
  2039. #+STARTUP: nolognoteclock-out"
  2040. :group 'org-todo
  2041. :group 'org-progress
  2042. :type 'boolean)
  2043. (defcustom org-log-done-with-time t
  2044. "Non-nil means the CLOSED time stamp will contain date and time.
  2045. When nil, only the date will be recorded."
  2046. :group 'org-progress
  2047. :type 'boolean)
  2048. (defcustom org-log-note-headings
  2049. '((done . "CLOSING NOTE %t")
  2050. (state . "State %-12s from %-12S %t")
  2051. (note . "Note taken on %t")
  2052. (reschedule . "Rescheduled from %S on %t")
  2053. (delschedule . "Not scheduled, was %S on %t")
  2054. (redeadline . "New deadline from %S on %t")
  2055. (deldeadline . "Removed deadline, was %S on %t")
  2056. (refile . "Refiled on %t")
  2057. (clock-out . ""))
  2058. "Headings for notes added to entries.
  2059. The value is an alist, with the car being a symbol indicating the
  2060. note context, and the cdr is the heading to be used. The heading
  2061. may also be the empty string. The following placeholders can be
  2062. used:
  2063. %t a time stamp.
  2064. %T an active time stamp instead the default inactive one
  2065. %d a short-format time stamp.
  2066. %D an active short-format time stamp.
  2067. %s the new TODO state or time stamp (inactive), in double quotes.
  2068. %S the old TODO state or time stamp (inactive), in double quotes.
  2069. %u the user name.
  2070. %U full user name.
  2071. In fact, it is not a good idea to change the `state' entry,
  2072. because Agenda Log mode depends on the format of these entries."
  2073. :group 'org-todo
  2074. :group 'org-progress
  2075. :type '(list :greedy t
  2076. (cons (const :tag "Heading when closing an item" done) string)
  2077. (cons (const :tag
  2078. "Heading when changing todo state (todo sequence only)"
  2079. state) string)
  2080. (cons (const :tag "Heading when just taking a note" note) string)
  2081. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2082. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2083. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2084. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2085. (cons (const :tag "Heading when refiling" refile) string)
  2086. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2087. (unless (assq 'note org-log-note-headings)
  2088. (push '(note . "%t") org-log-note-headings))
  2089. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2090. (defcustom org-log-into-drawer nil
  2091. "Non-nil means insert state change notes and time stamps into a drawer.
  2092. When nil, state changes notes will be inserted after the headline and
  2093. any scheduling and clock lines, but not inside a drawer.
  2094. The value of this variable should be the name of the drawer to use.
  2095. LOGBOOK is proposed as the default drawer for this purpose, you can
  2096. also set this to a string to define the drawer of your choice.
  2097. A value of t is also allowed, representing \"LOGBOOK\".
  2098. A value of t or nil can also be set with on a per-file-basis with
  2099. #+STARTUP: logdrawer
  2100. #+STARTUP: nologdrawer
  2101. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2102. will be ignored.
  2103. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2104. a subtree.
  2105. Do not check directly this variable in a Lisp program. Call
  2106. function `org-log-into-drawer' instead."
  2107. :group 'org-todo
  2108. :group 'org-progress
  2109. :type '(choice
  2110. (const :tag "Not into a drawer" nil)
  2111. (const :tag "LOGBOOK" t)
  2112. (string :tag "Other")))
  2113. (defun org-log-into-drawer ()
  2114. "Name of the log drawer, as a string, or nil.
  2115. This is the value of `org-log-into-drawer'. However, if the
  2116. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2117. be used instead of the default value."
  2118. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2119. (cond ((equal p "nil") nil)
  2120. ((equal p "t") "LOGBOOK")
  2121. ((stringp p) p)
  2122. (p "LOGBOOK")
  2123. ((stringp org-log-into-drawer) org-log-into-drawer)
  2124. (org-log-into-drawer "LOGBOOK"))))
  2125. (defcustom org-log-state-notes-insert-after-drawers nil
  2126. "Non-nil means insert state change notes after any drawers in entry.
  2127. Only the drawers that *immediately* follow the headline and the
  2128. deadline/scheduled line are skipped.
  2129. When nil, insert notes right after the heading and perhaps the line
  2130. with deadline/scheduling if present.
  2131. This variable will have no effect if `org-log-into-drawer' is
  2132. set."
  2133. :group 'org-todo
  2134. :group 'org-progress
  2135. :type 'boolean)
  2136. (defcustom org-log-states-order-reversed t
  2137. "Non-nil means the latest state note will be directly after heading.
  2138. When nil, the state change notes will be ordered according to time.
  2139. This option can also be set with on a per-file-basis with
  2140. #+STARTUP: logstatesreversed
  2141. #+STARTUP: nologstatesreversed"
  2142. :group 'org-todo
  2143. :group 'org-progress
  2144. :type 'boolean)
  2145. (defcustom org-todo-repeat-to-state nil
  2146. "The TODO state to which a repeater should return the repeating task.
  2147. By default this is the first task of a TODO sequence or the
  2148. previous state of a TYPE_TODO set. But you can specify to use
  2149. the previous state in a TODO sequence or a string.
  2150. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2151. entry, which has precedence over this option."
  2152. :group 'org-todo
  2153. :version "24.1"
  2154. :type '(choice (const :tag "Use the previous TODO state" t)
  2155. (const :tag "Use the head of the TODO sequence" nil)
  2156. (string :tag "Use a specific TODO state")))
  2157. (defcustom org-log-repeat 'time
  2158. "Non-nil means record moving through the DONE state when triggering repeat.
  2159. An auto-repeating task is immediately switched back to TODO when
  2160. marked DONE. If you are not logging state changes (by adding \"@\"
  2161. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2162. record a closing note, there will be no record of the task moving
  2163. through DONE. This variable forces taking a note anyway.
  2164. nil Don't force a record
  2165. time Record a time stamp
  2166. note Prompt for a note and add it with template `org-log-note-headings'
  2167. This option can also be set with on a per-file-basis with
  2168. #+STARTUP: nologrepeat
  2169. #+STARTUP: logrepeat
  2170. #+STARTUP: lognoterepeat
  2171. You can have local logging settings for a subtree by setting the LOGGING
  2172. property to one or more of these keywords."
  2173. :group 'org-todo
  2174. :group 'org-progress
  2175. :type '(choice
  2176. (const :tag "Don't force a record" nil)
  2177. (const :tag "Force recording the DONE state" time)
  2178. (const :tag "Force recording a note with the DONE state" note)))
  2179. (defcustom org-todo-repeat-hook nil
  2180. "Hook that is run after a task has been repeated."
  2181. :package-version '(Org . "9.2")
  2182. :group 'org-todo
  2183. :type 'hook)
  2184. (defgroup org-priorities nil
  2185. "Priorities in Org mode."
  2186. :tag "Org Priorities"
  2187. :group 'org-todo)
  2188. (defcustom org-enable-priority-commands t
  2189. "Non-nil means priority commands are active.
  2190. When nil, these commands will be disabled, so that you never accidentally
  2191. set a priority."
  2192. :group 'org-priorities
  2193. :type 'boolean)
  2194. (defcustom org-highest-priority ?A
  2195. "The highest priority of TODO items. A character like ?A, ?B etc.
  2196. Must have a smaller ASCII number than `org-lowest-priority'."
  2197. :group 'org-priorities
  2198. :type 'character)
  2199. (defcustom org-lowest-priority ?C
  2200. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2201. Must have a larger ASCII number than `org-highest-priority'."
  2202. :group 'org-priorities
  2203. :type 'character)
  2204. (defcustom org-default-priority ?B
  2205. "The default priority of TODO items.
  2206. This is the priority an item gets if no explicit priority is given.
  2207. When starting to cycle on an empty priority the first step in the cycle
  2208. depends on `org-priority-start-cycle-with-default'. The resulting first
  2209. step priority must not exceed the range from `org-highest-priority' to
  2210. `org-lowest-priority' which means that `org-default-priority' has to be
  2211. in this range exclusive or inclusive the range boundaries. Else the
  2212. first step refuses to set the default and the second will fall back
  2213. to (depending on the command used) the highest or lowest priority."
  2214. :group 'org-priorities
  2215. :type 'character)
  2216. (defcustom org-priority-start-cycle-with-default t
  2217. "Non-nil means start with default priority when starting to cycle.
  2218. When this is nil, the first step in the cycle will be (depending on the
  2219. command used) one higher or lower than the default priority.
  2220. See also `org-default-priority'."
  2221. :group 'org-priorities
  2222. :type 'boolean)
  2223. (defcustom org-get-priority-function nil
  2224. "Function to extract the priority from a string.
  2225. The string is normally the headline. If this is nil Org computes the
  2226. priority from the priority cookie like [#A] in the headline. It returns
  2227. an integer, increasing by 1000 for each priority level.
  2228. The user can set a different function here, which should take a string
  2229. as an argument and return the numeric priority."
  2230. :group 'org-priorities
  2231. :version "24.1"
  2232. :type '(choice
  2233. (const nil)
  2234. (function)))
  2235. (defgroup org-time nil
  2236. "Options concerning time stamps and deadlines in Org mode."
  2237. :tag "Org Time"
  2238. :group 'org)
  2239. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2240. "Number of minutes to round time stamps to.
  2241. \\<org-mode-map>\
  2242. These are two values, the first applies when first creating a time stamp.
  2243. The second applies when changing it with the commands `S-up' and `S-down'.
  2244. When changing the time stamp, this means that it will change in steps
  2245. of N minutes, as given by the second value.
  2246. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2247. numbers should be factors of 60, so for example 5, 10, 15.
  2248. When this is larger than 1, you can still force an exact time stamp by using
  2249. a double prefix argument to a time stamp command like \
  2250. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2251. and by using a prefix arg to `S-up/down' to specify the exact number
  2252. of minutes to shift."
  2253. :group 'org-time
  2254. :get (lambda (var) ; Make sure both elements are there
  2255. (if (integerp (default-value var))
  2256. (list (default-value var) 5)
  2257. (default-value var)))
  2258. :type '(list
  2259. (integer :tag "when inserting times")
  2260. (integer :tag "when modifying times")))
  2261. ;; Normalize old customizations of this variable.
  2262. (when (integerp org-time-stamp-rounding-minutes)
  2263. (setq org-time-stamp-rounding-minutes
  2264. (list org-time-stamp-rounding-minutes
  2265. org-time-stamp-rounding-minutes)))
  2266. (defcustom org-display-custom-times nil
  2267. "Non-nil means overlay custom formats over all time stamps.
  2268. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2269. To turn this on on a per-file basis, insert anywhere in the file:
  2270. #+STARTUP: customtime"
  2271. :group 'org-time
  2272. :set 'set-default
  2273. :type 'sexp)
  2274. (make-variable-buffer-local 'org-display-custom-times)
  2275. (defcustom org-time-stamp-custom-formats
  2276. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2277. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2278. These are overlaid over the default ISO format if the variable
  2279. `org-display-custom-times' is set. Time like %H:%M should be at the
  2280. end of the second format. The custom formats are also honored by export
  2281. commands, if custom time display is turned on at the time of export."
  2282. :group 'org-time
  2283. :type 'sexp)
  2284. (defun org-time-stamp-format (&optional long inactive)
  2285. "Get the right format for a time string."
  2286. (let ((f (if long (cdr org-time-stamp-formats)
  2287. (car org-time-stamp-formats))))
  2288. (if inactive
  2289. (concat "[" (substring f 1 -1) "]")
  2290. f)))
  2291. (defcustom org-deadline-warning-days 14
  2292. "Number of days before expiration during which a deadline becomes active.
  2293. This variable governs the display in sparse trees and in the agenda.
  2294. When 0 or negative, it means use this number (the absolute value of it)
  2295. even if a deadline has a different individual lead time specified.
  2296. Custom commands can set this variable in the options section."
  2297. :group 'org-time
  2298. :group 'org-agenda-daily/weekly
  2299. :type 'integer)
  2300. (defcustom org-scheduled-delay-days 0
  2301. "Number of days before a scheduled item becomes active.
  2302. This variable governs the display in sparse trees and in the agenda.
  2303. The default value (i.e. 0) means: don't delay scheduled item.
  2304. When negative, it means use this number (the absolute value of it)
  2305. even if a scheduled item has a different individual delay time
  2306. specified.
  2307. Custom commands can set this variable in the options section."
  2308. :group 'org-time
  2309. :group 'org-agenda-daily/weekly
  2310. :version "24.4"
  2311. :package-version '(Org . "8.0")
  2312. :type 'integer)
  2313. (defcustom org-read-date-prefer-future t
  2314. "Non-nil means assume future for incomplete date input from user.
  2315. This affects the following situations:
  2316. 1. The user gives a month but not a year.
  2317. For example, if it is April and you enter \"feb 2\", this will be read
  2318. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2319. 2. The user gives a day, but no month.
  2320. For example, if today is the 15th, and you enter \"3\", Org will read
  2321. this as the third of *next* month. However, if you enter \"17\",
  2322. it will be considered as *this* month.
  2323. If you set this variable to the symbol `time', then also the following
  2324. will work:
  2325. 3. If the user gives a time.
  2326. If the time is before now, it will be interpreted as tomorrow.
  2327. Currently none of this works for ISO week specifications.
  2328. When this option is nil, the current day, month and year will always be
  2329. used as defaults.
  2330. See also `org-agenda-jump-prefer-future'."
  2331. :group 'org-time
  2332. :type '(choice
  2333. (const :tag "Never" nil)
  2334. (const :tag "Check month and day" t)
  2335. (const :tag "Check month, day, and time" time)))
  2336. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2337. "Should the agenda jump command prefer the future for incomplete dates?
  2338. The default is to do the same as configured in `org-read-date-prefer-future'.
  2339. But you can also set a deviating value here.
  2340. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2341. :group 'org-agenda
  2342. :group 'org-time
  2343. :version "24.1"
  2344. :type '(choice
  2345. (const :tag "Use org-read-date-prefer-future"
  2346. org-read-date-prefer-future)
  2347. (const :tag "Never" nil)
  2348. (const :tag "Always" t)))
  2349. (defcustom org-read-date-force-compatible-dates t
  2350. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2351. Depending on the system Emacs is running on, certain dates cannot
  2352. be represented with the type used internally to represent time.
  2353. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2354. correctly. Some systems allow for earlier dates, some for later,
  2355. some for both. One way to find out is to insert any date into an
  2356. Org buffer, putting the cursor on the year and hitting S-up and
  2357. S-down to test the range.
  2358. When this variable is set to t, the date/time prompt will not let
  2359. you specify dates outside the 1970-2037 range, so it is certain that
  2360. these dates will work in whatever version of Emacs you are
  2361. running, and also that you can move a file from one Emacs implementation
  2362. to another. Whenever Org is forcing the year for you, it will display
  2363. a message and beep.
  2364. When this variable is nil, Org will check if the date is
  2365. representable in the specific Emacs implementation you are using.
  2366. If not, it will force a year, usually the current year, and beep
  2367. to remind you. Currently this setting is not recommended because
  2368. the likelihood that you will open your Org files in an Emacs that
  2369. has limited date range is not negligible.
  2370. A workaround for this problem is to use diary sexp dates for time
  2371. stamps outside of this range."
  2372. :group 'org-time
  2373. :version "24.1"
  2374. :type 'boolean)
  2375. (defcustom org-read-date-display-live t
  2376. "Non-nil means display current interpretation of date prompt live.
  2377. This display will be in an overlay, in the minibuffer."
  2378. :group 'org-time
  2379. :type 'boolean)
  2380. (defvaralias 'org-popup-calendar-for-date-prompt
  2381. 'org-read-date-popup-calendar)
  2382. (defcustom org-read-date-popup-calendar t
  2383. "Non-nil means pop up a calendar when prompting for a date.
  2384. In the calendar, the date can be selected with mouse-1. However, the
  2385. minibuffer will also be active, and you can simply enter the date as well.
  2386. When nil, only the minibuffer will be available."
  2387. :group 'org-time
  2388. :type 'boolean)
  2389. (defcustom org-extend-today-until 0
  2390. "The hour when your day really ends. Must be an integer.
  2391. This has influence for the following applications:
  2392. - When switching the agenda to \"today\". If it is still earlier than
  2393. the time given here, the day recognized as TODAY is actually yesterday.
  2394. - When a date is read from the user and it is still before the time given
  2395. here, the current date and time will be assumed to be yesterday, 23:59.
  2396. Also, timestamps inserted in capture templates follow this rule.
  2397. IMPORTANT: This is a feature whose implementation is and likely will
  2398. remain incomplete. Really, it is only here because past midnight seems to
  2399. be the favorite working time of John Wiegley :-)"
  2400. :group 'org-time
  2401. :type 'integer)
  2402. (defcustom org-use-effective-time nil
  2403. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2404. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2405. \"effective time\" of any timestamps between midnight and 8am will be
  2406. 23:59 of the previous day."
  2407. :group 'org-time
  2408. :version "24.1"
  2409. :type 'boolean)
  2410. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2411. "When non-nil, use the last clock out time for `org-todo'.
  2412. Note that this option has precedence over the combined use of
  2413. `org-use-effective-time' and `org-extend-today-until'."
  2414. :group 'org-time
  2415. :version "24.4"
  2416. :package-version '(Org . "8.0")
  2417. :type 'boolean)
  2418. (defcustom org-edit-timestamp-down-means-later nil
  2419. "Non-nil means S-down will increase the time in a time stamp.
  2420. When nil, S-up will increase."
  2421. :group 'org-time
  2422. :type 'boolean)
  2423. (defcustom org-calendar-follow-timestamp-change t
  2424. "Non-nil means make the calendar window follow timestamp changes.
  2425. When a timestamp is modified and the calendar window is visible, it will be
  2426. moved to the new date."
  2427. :group 'org-time
  2428. :type 'boolean)
  2429. (defgroup org-tags nil
  2430. "Options concerning tags in Org mode."
  2431. :tag "Org Tags"
  2432. :group 'org)
  2433. (defcustom org-tag-alist nil
  2434. "Default tags available in Org files.
  2435. The value of this variable is an alist. Associations either:
  2436. (TAG)
  2437. (TAG . SELECT)
  2438. (SPECIAL)
  2439. where TAG is a tag as a string, SELECT is character, used to
  2440. select that tag through the fast tag selection interface, and
  2441. SPECIAL is one of the following keywords: `:startgroup',
  2442. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2443. `:newline'. These keywords are used to define a hierarchy of
  2444. tags. See manual for details.
  2445. When this variable is nil, Org mode bases tag input on what is
  2446. already in the buffer. The value can be overridden locally by
  2447. using a TAGS keyword, e.g.,
  2448. #+TAGS: tag1 tag2
  2449. See also `org-tag-persistent-alist' to sidestep this behavior."
  2450. :group 'org-tags
  2451. :type '(repeat
  2452. (choice
  2453. (cons :tag "Tag with key"
  2454. (string :tag "Tag name")
  2455. (character :tag "Access char"))
  2456. (list :tag "Tag" (string :tag "Tag name"))
  2457. (const :tag "Start radio group" (:startgroup))
  2458. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2459. (const :tag "Group tags delimiter" (:grouptags))
  2460. (const :tag "End radio group" (:endgroup))
  2461. (const :tag "End tag group, non distinct" (:endgrouptag))
  2462. (const :tag "New line" (:newline)))))
  2463. (defcustom org-tag-persistent-alist nil
  2464. "Tags always available in Org files.
  2465. The value of this variable is an alist. Associations either:
  2466. (TAG)
  2467. (TAG . SELECT)
  2468. (SPECIAL)
  2469. where TAG is a tag as a string, SELECT is a character, used to
  2470. select that tag through the fast tag selection interface, and
  2471. SPECIAL is one of the following keywords: `:startgroup',
  2472. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2473. `:newline'. These keywords are used to define a hierarchy of
  2474. tags. See manual for details.
  2475. Unlike to `org-tag-alist', tags defined in this variable do not
  2476. depend on a local TAGS keyword. Instead, to disable these tags
  2477. on a per-file basis, insert anywhere in the file:
  2478. #+STARTUP: noptag"
  2479. :group 'org-tags
  2480. :type '(repeat
  2481. (choice
  2482. (cons :tag "Tag with key"
  2483. (string :tag "Tag name")
  2484. (character :tag "Access char"))
  2485. (list :tag "Tag" (string :tag "Tag name"))
  2486. (const :tag "Start radio group" (:startgroup))
  2487. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2488. (const :tag "Group tags delimiter" (:grouptags))
  2489. (const :tag "End radio group" (:endgroup))
  2490. (const :tag "End tag group, non distinct" (:endgrouptag))
  2491. (const :tag "New line" (:newline)))))
  2492. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2493. "If non-nil, always offer completion for all tags of all agenda files.
  2494. Setting this variable locally allows for dynamic generation of tag
  2495. completions in capture buffers.
  2496. (add-hook \\='org-capture-mode-hook
  2497. (lambda ()
  2498. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2499. :group 'org-tags
  2500. :version "24.1"
  2501. :type 'boolean)
  2502. (defvar org-file-tags nil
  2503. "List of tags that can be inherited by all entries in the file.
  2504. The tags will be inherited if the variable `org-use-tag-inheritance'
  2505. says they should be.
  2506. This variable is populated from #+FILETAGS lines.")
  2507. (defcustom org-use-fast-tag-selection 'auto
  2508. "Non-nil means use fast tag selection scheme.
  2509. This is a special interface to select and deselect tags with single keys.
  2510. When nil, fast selection is never used.
  2511. When the symbol `auto', fast selection is used if and only if selection
  2512. characters for tags have been configured, either through the variable
  2513. `org-tag-alist' or through a #+TAGS line in the buffer.
  2514. When t, fast selection is always used and selection keys are assigned
  2515. automatically if necessary."
  2516. :group 'org-tags
  2517. :type '(choice
  2518. (const :tag "Always" t)
  2519. (const :tag "Never" nil)
  2520. (const :tag "When selection characters are configured" auto)))
  2521. (defcustom org-fast-tag-selection-single-key nil
  2522. "Non-nil means fast tag selection exits after first change.
  2523. When nil, you have to press RET to exit it.
  2524. During fast tag selection, you can toggle this flag with `C-c'.
  2525. This variable can also have the value `expert'. In this case, the window
  2526. displaying the tags menu is not even shown, until you press C-c again."
  2527. :group 'org-tags
  2528. :type '(choice
  2529. (const :tag "No" nil)
  2530. (const :tag "Yes" t)
  2531. (const :tag "Expert" expert)))
  2532. (defvar org-fast-tag-selection-include-todo nil
  2533. "Non-nil means fast tags selection interface will also offer TODO states.
  2534. This is an undocumented feature, you should not rely on it.")
  2535. (defcustom org-tags-column -77
  2536. "The column to which tags should be indented in a headline.
  2537. If this number is positive, it specifies the column. If it is negative,
  2538. it means that the tags should be flushright to that column. For example,
  2539. -80 works well for a normal 80 character screen.
  2540. When 0, place tags directly after headline text, with only one space in
  2541. between."
  2542. :group 'org-tags
  2543. :type 'integer)
  2544. (defcustom org-auto-align-tags t
  2545. "Non-nil keeps tags aligned when modifying headlines.
  2546. Some operations (i.e. demoting) change the length of a headline and
  2547. therefore shift the tags around. With this option turned on, after
  2548. each such operation the tags are again aligned to `org-tags-column'."
  2549. :group 'org-tags
  2550. :type 'boolean)
  2551. (defcustom org-use-tag-inheritance t
  2552. "Non-nil means tags in levels apply also for sublevels.
  2553. When nil, only the tags directly given in a specific line apply there.
  2554. This may also be a list of tags that should be inherited, or a regexp that
  2555. matches tags that should be inherited. Additional control is possible
  2556. with the variable `org-tags-exclude-from-inheritance' which gives an
  2557. explicit list of tags to be excluded from inheritance, even if the value of
  2558. `org-use-tag-inheritance' would select it for inheritance.
  2559. If this option is t, a match early-on in a tree can lead to a large
  2560. number of matches in the subtree when constructing the agenda or creating
  2561. a sparse tree. If you only want to see the first match in a tree during
  2562. a search, check out the variable `org-tags-match-list-sublevels'."
  2563. :group 'org-tags
  2564. :type '(choice
  2565. (const :tag "Not" nil)
  2566. (const :tag "Always" t)
  2567. (repeat :tag "Specific tags" (string :tag "Tag"))
  2568. (regexp :tag "Tags matched by regexp")))
  2569. (defcustom org-tags-exclude-from-inheritance nil
  2570. "List of tags that should never be inherited.
  2571. This is a way to exclude a few tags from inheritance. For way to do
  2572. the opposite, to actively allow inheritance for selected tags,
  2573. see the variable `org-use-tag-inheritance'."
  2574. :group 'org-tags
  2575. :type '(repeat (string :tag "Tag")))
  2576. (defun org-tag-inherit-p (tag)
  2577. "Check if TAG is one that should be inherited."
  2578. (cond
  2579. ((member tag org-tags-exclude-from-inheritance) nil)
  2580. ((eq org-use-tag-inheritance t) t)
  2581. ((not org-use-tag-inheritance) nil)
  2582. ((stringp org-use-tag-inheritance)
  2583. (string-match org-use-tag-inheritance tag))
  2584. ((listp org-use-tag-inheritance)
  2585. (member tag org-use-tag-inheritance))
  2586. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2587. (defcustom org-tags-match-list-sublevels t
  2588. "Non-nil means list also sublevels of headlines matching a search.
  2589. This variable applies to tags/property searches, and also to stuck
  2590. projects because this search is based on a tags match as well.
  2591. When set to the symbol `indented', sublevels are indented with
  2592. leading dots.
  2593. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2594. the sublevels of a headline matching a tag search often also match
  2595. the same search. Listing all of them can create very long lists.
  2596. Setting this variable to nil causes subtrees of a match to be skipped.
  2597. This variable is semi-obsolete and probably should always be true. It
  2598. is better to limit inheritance to certain tags using the variables
  2599. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2600. :group 'org-tags
  2601. :type '(choice
  2602. (const :tag "No, don't list them" nil)
  2603. (const :tag "Yes, do list them" t)
  2604. (const :tag "List them, indented with leading dots" indented)))
  2605. (defcustom org-tags-sort-function nil
  2606. "When set, tags are sorted using this function as a comparator."
  2607. :group 'org-tags
  2608. :type '(choice
  2609. (const :tag "No sorting" nil)
  2610. (const :tag "Alphabetical" org-string-collate-lessp)
  2611. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2612. (function :tag "Custom function" nil)))
  2613. (defvar org-tags-history nil
  2614. "History of minibuffer reads for tags.")
  2615. (defvar org-last-tags-completion-table nil
  2616. "The last used completion table for tags.")
  2617. (defvar org-after-tags-change-hook nil
  2618. "Hook that is run after the tags in a line have changed.")
  2619. (defgroup org-properties nil
  2620. "Options concerning properties in Org mode."
  2621. :tag "Org Properties"
  2622. :group 'org)
  2623. (defcustom org-property-format "%-10s %s"
  2624. "How property key/value pairs should be formatted by `indent-line'.
  2625. When `indent-line' hits a property definition, it will format the line
  2626. according to this format, mainly to make sure that the values are
  2627. lined-up with respect to each other."
  2628. :group 'org-properties
  2629. :type 'string)
  2630. (defcustom org-properties-postprocess-alist nil
  2631. "Alist of properties and functions to adjust inserted values.
  2632. Elements of this alist must be of the form
  2633. ([string] [function])
  2634. where [string] must be a property name and [function] must be a
  2635. lambda expression: this lambda expression must take one argument,
  2636. the value to adjust, and return the new value as a string.
  2637. For example, this element will allow the property \"Remaining\"
  2638. to be updated wrt the relation between the \"Effort\" property
  2639. and the clock summary:
  2640. ((\"Remaining\" (lambda(value)
  2641. (let ((clocksum (org-clock-sum-current-item))
  2642. (effort (org-duration-to-minutes
  2643. (org-entry-get (point) \"Effort\"))))
  2644. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2645. :group 'org-properties
  2646. :version "24.1"
  2647. :type '(alist :key-type (string :tag "Property")
  2648. :value-type (function :tag "Function")))
  2649. (defcustom org-use-property-inheritance nil
  2650. "Non-nil means properties apply also for sublevels.
  2651. This setting is chiefly used during property searches. Turning it on can
  2652. cause significant overhead when doing a search, which is why it is not
  2653. on by default.
  2654. When nil, only the properties directly given in the current entry count.
  2655. When t, every property is inherited. The value may also be a list of
  2656. properties that should have inheritance, or a regular expression matching
  2657. properties that should be inherited.
  2658. However, note that some special properties use inheritance under special
  2659. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2660. and the properties ending in \"_ALL\" when they are used as descriptor
  2661. for valid values of a property.
  2662. Note for programmers:
  2663. When querying an entry with `org-entry-get', you can control if inheritance
  2664. should be used. By default, `org-entry-get' looks only at the local
  2665. properties. You can request inheritance by setting the inherit argument
  2666. to t (to force inheritance) or to `selective' (to respect the setting
  2667. in this variable)."
  2668. :group 'org-properties
  2669. :type '(choice
  2670. (const :tag "Not" nil)
  2671. (const :tag "Always" t)
  2672. (repeat :tag "Specific properties" (string :tag "Property"))
  2673. (regexp :tag "Properties matched by regexp")))
  2674. (defun org-property-inherit-p (property)
  2675. "Return a non-nil value if PROPERTY should be inherited."
  2676. (cond
  2677. ((eq org-use-property-inheritance t) t)
  2678. ((not org-use-property-inheritance) nil)
  2679. ((stringp org-use-property-inheritance)
  2680. (string-match org-use-property-inheritance property))
  2681. ((listp org-use-property-inheritance)
  2682. (member-ignore-case property org-use-property-inheritance))
  2683. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2684. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2685. "The default column format, if no other format has been defined.
  2686. This variable can be set on the per-file basis by inserting a line
  2687. #+COLUMNS: %25ITEM ....."
  2688. :group 'org-properties
  2689. :type 'string)
  2690. (defcustom org-columns-default-format-for-agenda nil
  2691. "The default column format in an agenda buffer.
  2692. This will be used for column view in the agenda unless a format has
  2693. been set by adding `org-overriding-columns-format' to the local
  2694. settings list of a custom agenda view. When nil, the columns format
  2695. for the first item in the agenda list will be used, or as a fall-back,
  2696. `org-columns-default-format'."
  2697. :group 'org-properties
  2698. :type '(choice
  2699. (const :tag "No default" nil)
  2700. (string :tag "Format string")))
  2701. (defcustom org-columns-ellipses ".."
  2702. "The ellipses to be used when a field in column view is truncated.
  2703. When this is the empty string, as many characters as possible are shown,
  2704. but then there will be no visual indication that the field has been truncated.
  2705. When this is a string of length N, the last N characters of a truncated
  2706. field are replaced by this string. If the column is narrower than the
  2707. ellipses string, only part of the ellipses string will be shown."
  2708. :group 'org-properties
  2709. :type 'string)
  2710. (defconst org-global-properties-fixed
  2711. '(("VISIBILITY_ALL" . "folded children content all")
  2712. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2713. "List of property/value pairs that can be inherited by any entry.
  2714. These are fixed values, for the preset properties. The user variable
  2715. that can be used to add to this list is `org-global-properties'.
  2716. The entries in this list are cons cells where the car is a property
  2717. name and cdr is a string with the value. If the value represents
  2718. multiple items like an \"_ALL\" property, separate the items by
  2719. spaces.")
  2720. (defcustom org-global-properties nil
  2721. "List of property/value pairs that can be inherited by any entry.
  2722. This list will be combined with the constant `org-global-properties-fixed'.
  2723. The entries in this list are cons cells where the car is a property
  2724. name and cdr is a string with the value.
  2725. You can set buffer-local values for the same purpose in the variable
  2726. `org-file-properties' this by adding lines like
  2727. #+PROPERTY: NAME VALUE"
  2728. :group 'org-properties
  2729. :type '(repeat
  2730. (cons (string :tag "Property")
  2731. (string :tag "Value"))))
  2732. (defvar-local org-file-properties nil
  2733. "List of property/value pairs that can be inherited by any entry.
  2734. Valid for the current buffer.
  2735. This variable is populated from #+PROPERTY lines.")
  2736. (defgroup org-agenda nil
  2737. "Options concerning agenda views in Org mode."
  2738. :tag "Org Agenda"
  2739. :group 'org)
  2740. (defvar-local org-category nil
  2741. "Variable used by Org files to set a category for agenda display.
  2742. Such files should use a file variable to set it, for example
  2743. # -*- mode: org; org-category: \"ELisp\"
  2744. or contain a special line
  2745. #+CATEGORY: ELisp
  2746. If the file does not specify a category, then file's base name
  2747. is used instead.")
  2748. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2749. (defcustom org-agenda-files nil
  2750. "The files to be used for agenda display.
  2751. If an entry is a directory, all files in that directory that are matched
  2752. by `org-agenda-file-regexp' will be part of the file list.
  2753. If the value of the variable is not a list but a single file name, then
  2754. the list of agenda files is actually stored and maintained in that file,
  2755. one agenda file per line. In this file paths can be given relative to
  2756. `org-directory'. Tilde expansion and environment variable substitution
  2757. are also made.
  2758. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2759. and removed with `\\[org-remove-file]'."
  2760. :group 'org-agenda
  2761. :type '(choice
  2762. (repeat :tag "List of files and directories" file)
  2763. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2764. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2765. "Regular expression to match files for `org-agenda-files'.
  2766. If any element in the list in that variable contains a directory instead
  2767. of a normal file, all files in that directory that are matched by this
  2768. regular expression will be included."
  2769. :group 'org-agenda
  2770. :type 'regexp)
  2771. (defvaralias 'org-agenda-multi-occur-extra-files
  2772. 'org-agenda-text-search-extra-files)
  2773. (defcustom org-agenda-text-search-extra-files nil
  2774. "List of extra files to be searched by text search commands.
  2775. These files will be searched in addition to the agenda files by the
  2776. commands `org-search-view' (`\\[org-agenda] s') \
  2777. and `org-occur-in-agenda-files'.
  2778. Note that these files will only be searched for text search commands,
  2779. not for the other agenda views like todo lists, tag searches or the weekly
  2780. agenda. This variable is intended to list notes and possibly archive files
  2781. that should also be searched by these two commands.
  2782. In fact, if the first element in the list is the symbol `agenda-archives',
  2783. then all archive files of all agenda files will be added to the search
  2784. scope."
  2785. :group 'org-agenda
  2786. :type '(set :greedy t
  2787. (const :tag "Agenda Archives" agenda-archives)
  2788. (repeat :inline t (file))))
  2789. (defcustom org-agenda-skip-unavailable-files nil
  2790. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2791. A nil value means to remove them, after a query, from the list."
  2792. :group 'org-agenda
  2793. :type 'boolean)
  2794. (defcustom org-agenda-diary-file 'diary-file
  2795. "File to which to add new entries with the `i' key in agenda and calendar.
  2796. When this is the symbol `diary-file', the functionality in the Emacs
  2797. calendar will be used to add entries to the `diary-file'. But when this
  2798. points to a file, `org-agenda-diary-entry' will be used instead."
  2799. :group 'org-agenda
  2800. :type '(choice
  2801. (const :tag "The standard Emacs diary file" diary-file)
  2802. (file :tag "Special Org file diary entries")))
  2803. (defgroup org-latex nil
  2804. "Options for embedding LaTeX code into Org mode."
  2805. :tag "Org LaTeX"
  2806. :group 'org)
  2807. (defcustom org-format-latex-options
  2808. '(:foreground default :background default :scale 1.0
  2809. :html-foreground "Black" :html-background "Transparent"
  2810. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2811. "Options for creating images from LaTeX fragments.
  2812. This is a property list with the following properties:
  2813. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2814. `default' means use the foreground of the default face.
  2815. `auto' means use the foreground from the text face.
  2816. :background the background color, or \"Transparent\".
  2817. `default' means use the background of the default face.
  2818. `auto' means use the background from the text face.
  2819. :scale a scaling factor for the size of the images, to get more pixels
  2820. :html-foreground, :html-background, :html-scale
  2821. the same numbers for HTML export.
  2822. :matchers a list indicating which matchers should be used to
  2823. find LaTeX fragments. Valid members of this list are:
  2824. \"begin\" find environments
  2825. \"$1\" find single characters surrounded by $.$
  2826. \"$\" find math expressions surrounded by $...$
  2827. \"$$\" find math expressions surrounded by $$....$$
  2828. \"\\(\" find math expressions surrounded by \\(...\\)
  2829. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2830. :group 'org-latex
  2831. :type 'plist)
  2832. (defcustom org-format-latex-signal-error t
  2833. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2834. When nil, just push out a message."
  2835. :group 'org-latex
  2836. :version "24.1"
  2837. :type 'boolean)
  2838. (defcustom org-latex-to-mathml-jar-file nil
  2839. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2840. Use this to specify additional executable file say a jar file.
  2841. When using MathToWeb as the converter, specify the full-path to
  2842. your mathtoweb.jar file."
  2843. :group 'org-latex
  2844. :version "24.1"
  2845. :type '(choice
  2846. (const :tag "None" nil)
  2847. (file :tag "JAR file" :must-match t)))
  2848. (defcustom org-latex-to-mathml-convert-command nil
  2849. "Command to convert LaTeX fragments to MathML.
  2850. Replace format-specifiers in the command as noted below and use
  2851. `shell-command' to convert LaTeX to MathML.
  2852. %j: Executable file in fully expanded form as specified by
  2853. `org-latex-to-mathml-jar-file'.
  2854. %I: Input LaTeX file in fully expanded form.
  2855. %i: The latex fragment to be converted.
  2856. %o: Output MathML file.
  2857. This command is used by `org-create-math-formula'.
  2858. When using MathToWeb as the converter, set this option to
  2859. \"java -jar %j -unicode -force -df %o %I\".
  2860. When using LaTeXML set this option to
  2861. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2862. :group 'org-latex
  2863. :version "24.1"
  2864. :type '(choice
  2865. (const :tag "None" nil)
  2866. (string :tag "\nShell command")))
  2867. (defcustom org-preview-latex-default-process 'dvipng
  2868. "The default process to convert LaTeX fragments to image files.
  2869. All available processes and theirs documents can be found in
  2870. `org-preview-latex-process-alist', which see."
  2871. :group 'org-latex
  2872. :version "26.1"
  2873. :package-version '(Org . "9.0")
  2874. :type 'symbol)
  2875. (defcustom org-preview-latex-process-alist
  2876. '((dvipng
  2877. :programs ("latex" "dvipng")
  2878. :description "dvi > png"
  2879. :message "you need to install the programs: latex and dvipng."
  2880. :image-input-type "dvi"
  2881. :image-output-type "png"
  2882. :image-size-adjust (1.0 . 1.0)
  2883. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2884. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2885. (dvisvgm
  2886. :programs ("latex" "dvisvgm")
  2887. :description "dvi > svg"
  2888. :message "you need to install the programs: latex and dvisvgm."
  2889. :image-input-type "dvi"
  2890. :image-output-type "svg"
  2891. :image-size-adjust (1.7 . 1.5)
  2892. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2893. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2894. (imagemagick
  2895. :programs ("latex" "convert")
  2896. :description "pdf > png"
  2897. :message "you need to install the programs: latex and imagemagick."
  2898. :image-input-type "pdf"
  2899. :image-output-type "png"
  2900. :image-size-adjust (1.0 . 1.0)
  2901. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2902. :image-converter
  2903. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2904. "Definitions of external processes for LaTeX previewing.
  2905. Org mode can use some external commands to generate TeX snippet's images for
  2906. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2907. `org-create-formula-image' how to call them.
  2908. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2909. PROPERTIES accepts the following attributes:
  2910. :programs list of strings, required programs.
  2911. :description string, describe the process.
  2912. :message string, message it when required programs cannot be found.
  2913. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2914. :image-output-type string, output file type of image converter (e.g., \"png\").
  2915. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2916. image size showed in buffer and the cdr element is for
  2917. HTML file. This option is only useful for process
  2918. developers, users should use variable
  2919. `org-format-latex-options' instead.
  2920. :post-clean list of strings, files matched are to be cleaned up once
  2921. the image is generated. When nil, the files with \".dvi\",
  2922. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2923. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2924. be cleaned up.
  2925. :latex-header list of strings, the LaTeX header of the snippet file.
  2926. When nil, the fallback value is used instead, which is
  2927. controlled by `org-format-latex-header',
  2928. `org-latex-default-packages-alist' and
  2929. `org-latex-packages-alist', which see.
  2930. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2931. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2932. replaced with values defined below.
  2933. :image-converter list of image converter commands strings. Each of them is
  2934. given to the shell and supports any of the following
  2935. place-holders defined below.
  2936. Place-holders used by `:image-converter' and `:latex-compiler':
  2937. %f input file name
  2938. %b base name of input file
  2939. %o base directory of input file
  2940. %O absolute output file name
  2941. Place-holders only used by `:image-converter':
  2942. %D dpi, which is used to adjust image size by some processing commands.
  2943. %S the image size scale ratio, which is used to adjust image size by some
  2944. processing commands."
  2945. :group 'org-latex
  2946. :version "26.1"
  2947. :package-version '(Org . "9.0")
  2948. :type '(alist :tag "LaTeX to image backends"
  2949. :value-type (plist)))
  2950. (defcustom org-preview-latex-image-directory "ltximg/"
  2951. "Path to store latex preview images.
  2952. A relative path here creates many directories relative to the
  2953. processed Org files paths. An absolute path puts all preview
  2954. images at the same place."
  2955. :group 'org-latex
  2956. :version "26.1"
  2957. :package-version '(Org . "9.0")
  2958. :type 'string)
  2959. (defun org-format-latex-mathml-available-p ()
  2960. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2961. (save-match-data
  2962. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2963. org-latex-to-mathml-convert-command)
  2964. (let ((executable (car (split-string
  2965. org-latex-to-mathml-convert-command))))
  2966. (when (executable-find executable)
  2967. (if (string-match
  2968. "%j" org-latex-to-mathml-convert-command)
  2969. (file-readable-p org-latex-to-mathml-jar-file)
  2970. t))))))
  2971. (defcustom org-format-latex-header "\\documentclass{article}
  2972. \\usepackage[usenames]{color}
  2973. \[PACKAGES]
  2974. \[DEFAULT-PACKAGES]
  2975. \\pagestyle{empty} % do not remove
  2976. % The settings below are copied from fullpage.sty
  2977. \\setlength{\\textwidth}{\\paperwidth}
  2978. \\addtolength{\\textwidth}{-3cm}
  2979. \\setlength{\\oddsidemargin}{1.5cm}
  2980. \\addtolength{\\oddsidemargin}{-2.54cm}
  2981. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2982. \\setlength{\\textheight}{\\paperheight}
  2983. \\addtolength{\\textheight}{-\\headheight}
  2984. \\addtolength{\\textheight}{-\\headsep}
  2985. \\addtolength{\\textheight}{-\\footskip}
  2986. \\addtolength{\\textheight}{-3cm}
  2987. \\setlength{\\topmargin}{1.5cm}
  2988. \\addtolength{\\topmargin}{-2.54cm}"
  2989. "The document header used for processing LaTeX fragments.
  2990. It is imperative that this header make sure that no page number
  2991. appears on the page. The package defined in the variables
  2992. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2993. will either replace the placeholder \"[PACKAGES]\" in this
  2994. header, or they will be appended."
  2995. :group 'org-latex
  2996. :type 'string)
  2997. (defun org-set-packages-alist (var val)
  2998. "Set the packages alist and make sure it has 3 elements per entry."
  2999. (set var (mapcar (lambda (x)
  3000. (if (and (consp x) (= (length x) 2))
  3001. (list (car x) (nth 1 x) t)
  3002. x))
  3003. val)))
  3004. (defun org-get-packages-alist (var)
  3005. "Get the packages alist and make sure it has 3 elements per entry."
  3006. (mapcar (lambda (x)
  3007. (if (and (consp x) (= (length x) 2))
  3008. (list (car x) (nth 1 x) t)
  3009. x))
  3010. (default-value var)))
  3011. (defcustom org-latex-default-packages-alist
  3012. '(("AUTO" "inputenc" t ("pdflatex"))
  3013. ("T1" "fontenc" t ("pdflatex"))
  3014. ("" "graphicx" t)
  3015. ("" "grffile" t)
  3016. ("" "longtable" nil)
  3017. ("" "wrapfig" nil)
  3018. ("" "rotating" nil)
  3019. ("normalem" "ulem" t)
  3020. ("" "amsmath" t)
  3021. ("" "textcomp" t)
  3022. ("" "amssymb" t)
  3023. ("" "capt-of" nil)
  3024. ("" "hyperref" nil))
  3025. "Alist of default packages to be inserted in the header.
  3026. Change this only if one of the packages here causes an
  3027. incompatibility with another package you are using.
  3028. The packages in this list are needed by one part or another of
  3029. Org mode to function properly:
  3030. - inputenc, fontenc: for basic font and character selection
  3031. - graphicx: for including images
  3032. - grffile: allow periods and spaces in graphics file names
  3033. - longtable: For multipage tables
  3034. - wrapfig: for figure placement
  3035. - rotating: for sideways figures and tables
  3036. - ulem: for underline and strike-through
  3037. - amsmath: for subscript and superscript and math environments
  3038. - textcomp, amssymb: for various symbols used
  3039. for interpreting the entities in `org-entities'. You can skip
  3040. some of these packages if you don't use any of their symbols.
  3041. - capt-of: for captions outside of floats
  3042. - hyperref: for cross references
  3043. Therefore you should not modify this variable unless you know
  3044. what you are doing. The one reason to change it anyway is that
  3045. you might be loading some other package that conflicts with one
  3046. of the default packages. Each element is either a cell or
  3047. a string.
  3048. A cell is of the format
  3049. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3050. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3051. when compiling LaTeX snippets into images for inclusion into
  3052. non-LaTeX output.
  3053. COMPILERS is a list of compilers that should include the package,
  3054. see `org-latex-compiler'. If the document compiler is not in the
  3055. list, and the list is non-nil, the package will not be inserted
  3056. in the final document.
  3057. A string will be inserted as-is in the header of the document."
  3058. :group 'org-latex
  3059. :group 'org-export-latex
  3060. :set 'org-set-packages-alist
  3061. :get 'org-get-packages-alist
  3062. :version "26.1"
  3063. :package-version '(Org . "8.3")
  3064. :type '(repeat
  3065. (choice
  3066. (list :tag "options/package pair"
  3067. (string :tag "options")
  3068. (string :tag "package")
  3069. (boolean :tag "Snippet")
  3070. (choice
  3071. (const :tag "For all compilers" nil)
  3072. (repeat :tag "Allowed compiler" string)))
  3073. (string :tag "A line of LaTeX"))))
  3074. (defcustom org-latex-packages-alist nil
  3075. "Alist of packages to be inserted in every LaTeX header.
  3076. These will be inserted after `org-latex-default-packages-alist'.
  3077. Each element is either a cell or a string.
  3078. A cell is of the format:
  3079. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3080. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3081. needed when turning LaTeX snippets into images for inclusion into
  3082. non-LaTeX output.
  3083. COMPILERS is a list of compilers that should include the package,
  3084. see `org-latex-compiler'. If the document compiler is not in the
  3085. list, and the list is non-nil, the package will not be inserted
  3086. in the final document.
  3087. A string will be inserted as-is in the header of the document.
  3088. Make sure that you only list packages here which:
  3089. - you want in every file;
  3090. - do not conflict with the setup in `org-format-latex-header';
  3091. - do not conflict with the default packages in
  3092. `org-latex-default-packages-alist'."
  3093. :group 'org-latex
  3094. :group 'org-export-latex
  3095. :set 'org-set-packages-alist
  3096. :get 'org-get-packages-alist
  3097. :type '(repeat
  3098. (choice
  3099. (list :tag "options/package pair"
  3100. (string :tag "options")
  3101. (string :tag "package")
  3102. (boolean :tag "Snippet"))
  3103. (string :tag "A line of LaTeX"))))
  3104. (defgroup org-appearance nil
  3105. "Settings for Org mode appearance."
  3106. :tag "Org Appearance"
  3107. :group 'org)
  3108. (defcustom org-level-color-stars-only nil
  3109. "Non-nil means fontify only the stars in each headline.
  3110. When nil, the entire headline is fontified.
  3111. Changing it requires restart of `font-lock-mode' to become effective
  3112. also in regions already fontified."
  3113. :group 'org-appearance
  3114. :type 'boolean)
  3115. (defcustom org-hide-leading-stars nil
  3116. "Non-nil means hide the first N-1 stars in a headline.
  3117. This works by using the face `org-hide' for these stars. This
  3118. face is white for a light background, and black for a dark
  3119. background. You may have to customize the face `org-hide' to
  3120. make this work.
  3121. Changing it requires restart of `font-lock-mode' to become effective
  3122. also in regions already fontified.
  3123. You may also set this on a per-file basis by adding one of the following
  3124. lines to the buffer:
  3125. #+STARTUP: hidestars
  3126. #+STARTUP: showstars"
  3127. :group 'org-appearance
  3128. :type 'boolean)
  3129. (defcustom org-hidden-keywords nil
  3130. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3131. For example, a value \\='(title) for this list makes the document's title
  3132. appear in the buffer without the initial \"#+TITLE:\" part."
  3133. :group 'org-appearance
  3134. :version "24.1"
  3135. :type '(set (const :tag "#+AUTHOR" author)
  3136. (const :tag "#+DATE" date)
  3137. (const :tag "#+EMAIL" email)
  3138. (const :tag "#+TITLE" title)))
  3139. (defcustom org-custom-properties nil
  3140. "List of properties (as strings) with a special meaning.
  3141. The default use of these custom properties is to let the user
  3142. hide them with `org-toggle-custom-properties-visibility'."
  3143. :group 'org-properties
  3144. :group 'org-appearance
  3145. :version "24.3"
  3146. :type '(repeat (string :tag "Property Name")))
  3147. (defcustom org-fontify-done-headline nil
  3148. "Non-nil means change the face of a headline if it is marked DONE.
  3149. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3150. When this is non-nil, the headline after the keyword is set to the
  3151. `org-headline-done' as an additional indication."
  3152. :group 'org-appearance
  3153. :type 'boolean)
  3154. (defcustom org-fontify-emphasized-text t
  3155. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3156. Changing this variable requires a restart of Emacs to take effect."
  3157. :group 'org-appearance
  3158. :type 'boolean)
  3159. (defcustom org-fontify-whole-heading-line nil
  3160. "Non-nil means fontify the whole line for headings.
  3161. This is useful when setting a background color for the
  3162. org-level-* faces."
  3163. :group 'org-appearance
  3164. :type 'boolean)
  3165. (defcustom org-fontify-whole-block-delimiter-line t
  3166. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3167. This is useful when setting a background color for the
  3168. org-block-begin-line and org-block-end-line faces."
  3169. :group 'org-appearance
  3170. :type 'boolean)
  3171. (defcustom org-highlight-latex-and-related nil
  3172. "Non-nil means highlight LaTeX related syntax in the buffer.
  3173. When non-nil, the value should be a list containing any of the
  3174. following symbols:
  3175. `native' Highlight LaTeX snippets and environments natively.
  3176. `latex' Highlight LaTeX snippets and environments.
  3177. `script' Highlight subscript and superscript.
  3178. `entities' Highlight entities."
  3179. :group 'org-appearance
  3180. :version "24.4"
  3181. :package-version '(Org . "8.0")
  3182. :type '(choice
  3183. (const :tag "No highlighting" nil)
  3184. (set :greedy t :tag "Highlight"
  3185. (const :tag "LaTeX snippets and environments (native)" native)
  3186. (const :tag "LaTeX snippets and environments" latex)
  3187. (const :tag "Subscript and superscript" script)
  3188. (const :tag "Entities" entities))))
  3189. (defcustom org-hide-emphasis-markers nil
  3190. "Non-nil mean font-lock should hide the emphasis marker characters."
  3191. :group 'org-appearance
  3192. :type 'boolean
  3193. :safe #'booleanp)
  3194. (defcustom org-hide-macro-markers nil
  3195. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3196. :group 'org-appearance
  3197. :type 'boolean)
  3198. (defcustom org-pretty-entities nil
  3199. "Non-nil means show entities as UTF8 characters.
  3200. When nil, the \\name form remains in the buffer."
  3201. :group 'org-appearance
  3202. :version "24.1"
  3203. :type 'boolean)
  3204. (defcustom org-pretty-entities-include-sub-superscripts t
  3205. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3206. :group 'org-appearance
  3207. :version "24.1"
  3208. :type 'boolean)
  3209. (defvar org-emph-re nil
  3210. "Regular expression for matching emphasis.
  3211. After a match, the match groups contain these elements:
  3212. 0 The match of the full regular expression, including the characters
  3213. before and after the proper match
  3214. 1 The character before the proper match, or empty at beginning of line
  3215. 2 The proper match, including the leading and trailing markers
  3216. 3 The leading marker like * or /, indicating the type of highlighting
  3217. 4 The text between the emphasis markers, not including the markers
  3218. 5 The character after the match, empty at the end of a line")
  3219. (defvar org-verbatim-re nil
  3220. "Regular expression for matching verbatim text.")
  3221. (defvar org-emphasis-regexp-components) ; defined just below
  3222. (defvar org-emphasis-alist) ; defined just below
  3223. (defun org-set-emph-re (var val)
  3224. "Set variable and compute the emphasis regular expression."
  3225. (set var val)
  3226. (when (and (boundp 'org-emphasis-alist)
  3227. (boundp 'org-emphasis-regexp-components)
  3228. org-emphasis-alist org-emphasis-regexp-components)
  3229. (pcase-let*
  3230. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3231. (body (if (<= nl 0) body
  3232. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3233. (template
  3234. (format (concat "\\([%s]\\|^\\)" ;before markers
  3235. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3236. "\\([%s]\\|$\\)") ;after markers
  3237. pre border border body border post)))
  3238. (setq org-emph-re (format template "*/_+"))
  3239. (setq org-verbatim-re (format template "=~")))))
  3240. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3241. ;; set this option proved cumbersome. See this message/thread:
  3242. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3243. (defvar org-emphasis-regexp-components
  3244. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3245. "Components used to build the regular expression for emphasis.
  3246. This is a list with five entries. Terminology: In an emphasis string
  3247. like \" *strong word* \", we call the initial space PREMATCH, the final
  3248. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3249. and \"trong wor\" is the body. The different components in this variable
  3250. specify what is allowed/forbidden in each part:
  3251. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3252. post Chars allowed as postmatch. End of line will be allowed too.
  3253. border The chars *forbidden* as border characters.
  3254. body-regexp A regexp like \".\" to match a body character. Don't use
  3255. non-shy groups here, and don't allow newline here.
  3256. newline The maximum number of newlines allowed in an emphasis exp.
  3257. You need to reload Org or to restart Emacs after setting this.")
  3258. (defcustom org-emphasis-alist
  3259. '(("*" bold)
  3260. ("/" italic)
  3261. ("_" underline)
  3262. ("=" org-verbatim verbatim)
  3263. ("~" org-code verbatim)
  3264. ("+" (:strike-through t)))
  3265. "Alist of characters and faces to emphasize text.
  3266. Text starting and ending with a special character will be emphasized,
  3267. for example *bold*, _underlined_ and /italic/. This variable sets the
  3268. marker characters and the face to be used by font-lock for highlighting
  3269. in Org buffers.
  3270. You need to reload Org or to restart Emacs after customizing this."
  3271. :group 'org-appearance
  3272. :set 'org-set-emph-re
  3273. :version "24.4"
  3274. :package-version '(Org . "8.0")
  3275. :type '(repeat
  3276. (list
  3277. (string :tag "Marker character")
  3278. (choice
  3279. (face :tag "Font-lock-face")
  3280. (plist :tag "Face property list"))
  3281. (option (const verbatim)))))
  3282. (defvar org-protecting-blocks '("src" "example" "export")
  3283. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3284. This is needed for font-lock setup.")
  3285. ;;; Functions and variables from their packages
  3286. ;; Declared here to avoid compiler warnings
  3287. (defvar mark-active)
  3288. ;; Various packages
  3289. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3290. (declare-function calendar-forward-day "cal-move" (arg))
  3291. (declare-function calendar-goto-date "cal-move" (date))
  3292. (declare-function calendar-goto-today "cal-move" ())
  3293. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3294. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3295. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3296. (declare-function cdlatex-tab "ext:cdlatex" ())
  3297. (declare-function dired-get-filename
  3298. "dired"
  3299. (&optional localp no-error-if-not-filep))
  3300. (declare-function iswitchb-read-buffer
  3301. "iswitchb"
  3302. (prompt &optional
  3303. default require-match _predicate start matches-set))
  3304. (declare-function org-agenda-change-all-lines
  3305. "org-agenda"
  3306. (newhead hdmarker &optional fixface just-this))
  3307. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3308. "org-agenda"
  3309. (&optional end))
  3310. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3311. (declare-function org-agenda-format-item
  3312. "org-agenda"
  3313. (extra txt &optional level category tags dotime
  3314. remove-re habitp))
  3315. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3316. (declare-function org-agenda-save-markers-for-cut-and-paste
  3317. "org-agenda"
  3318. (beg end))
  3319. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3320. (declare-function org-agenda-skip "org-agenda" ())
  3321. (declare-function org-attach-expand "org-attach" (file))
  3322. (declare-function org-attach-reveal "org-attach" ())
  3323. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3324. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3325. (declare-function org-indent-mode "org-indent" (&optional arg))
  3326. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3327. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3328. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3329. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3330. (declare-function parse-time-string "parse-time" (string))
  3331. (defvar align-mode-rules-list)
  3332. (defvar calc-embedded-close-formula)
  3333. (defvar calc-embedded-open-formula)
  3334. (defvar calc-embedded-open-mode)
  3335. (defvar font-lock-unfontify-region-function)
  3336. (defvar iswitchb-temp-buflist)
  3337. (defvar org-agenda-tags-todo-honor-ignore-options)
  3338. (defvar remember-data-file)
  3339. (defvar texmathp-why)
  3340. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3341. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3342. (declare-function org-resolve-clocks "org-clock"
  3343. (&optional also-non-dangling-p prompt last-valid))
  3344. (defvar org-clock-start-time)
  3345. (defvar org-clock-marker (make-marker)
  3346. "Marker recording the last clock-in.")
  3347. (defvar org-clock-hd-marker (make-marker)
  3348. "Marker recording the last clock-in, but the headline position.")
  3349. (defvar org-clock-heading ""
  3350. "The heading of the current clock entry.")
  3351. (defun org-clock-is-active ()
  3352. "Return the buffer where the clock is currently running.
  3353. Return nil if no clock is running."
  3354. (marker-buffer org-clock-marker))
  3355. (defun org-check-running-clock ()
  3356. "Check if the current buffer contains the running clock.
  3357. If yes, offer to stop it and to save the buffer with the changes."
  3358. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3359. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3360. (buffer-name))))
  3361. (org-clock-out)
  3362. (when (y-or-n-p "Save changed buffer?")
  3363. (save-buffer))))
  3364. (defun org-clocktable-try-shift (dir n)
  3365. "Check if this line starts a clock table, if yes, shift the time block."
  3366. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3367. (org-clocktable-shift dir n)))
  3368. ;;;###autoload
  3369. (defun org-clock-persistence-insinuate ()
  3370. "Set up hooks for clock persistence."
  3371. (require 'org-clock)
  3372. (add-hook 'org-mode-hook 'org-clock-load)
  3373. (add-hook 'kill-emacs-hook 'org-clock-save))
  3374. (defgroup org-archive nil
  3375. "Options concerning archiving in Org mode."
  3376. :tag "Org Archive"
  3377. :group 'org-structure)
  3378. (defcustom org-archive-location "%s_archive::"
  3379. "The location where subtrees should be archived.
  3380. The value of this variable is a string, consisting of two parts,
  3381. separated by a double-colon. The first part is a filename and
  3382. the second part is a headline.
  3383. When the filename is omitted, archiving happens in the same file.
  3384. %s in the filename will be replaced by the current file
  3385. name (without the directory part). Archiving to a different file
  3386. is useful to keep archived entries from contributing to the
  3387. Org Agenda.
  3388. The archived entries will be filed as subtrees of the specified
  3389. headline. When the headline is omitted, the subtrees are simply
  3390. filed away at the end of the file, as top-level entries. Also in
  3391. the heading you can use %s to represent the file name, this can be
  3392. useful when using the same archive for a number of different files.
  3393. Here are a few examples:
  3394. \"%s_archive::\"
  3395. If the current file is Projects.org, archive in file
  3396. Projects.org_archive, as top-level trees. This is the default.
  3397. \"::* Archived Tasks\"
  3398. Archive in the current file, under the top-level headline
  3399. \"* Archived Tasks\".
  3400. \"~/org/archive.org::\"
  3401. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3402. \"~/org/archive.org::* From %s\"
  3403. Archive in file ~/org/archive.org (absolute path), under headlines
  3404. \"From FILENAME\" where file name is the current file name.
  3405. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3406. The \"datetree/\" string is special, signifying to archive
  3407. items to the datetree. Items are placed in either the CLOSED
  3408. date of the item, or the current date if there is no CLOSED date.
  3409. The heading will be a subentry to the current date. There doesn't
  3410. need to be a heading, but there always needs to be a slash after
  3411. datetree. For example, to store archived items directly in the
  3412. datetree, use \"~/org/datetree.org::datetree/\".
  3413. \"basement::** Finished Tasks\"
  3414. Archive in file ./basement (relative path), as level 3 trees
  3415. below the level 2 heading \"** Finished Tasks\".
  3416. You may set this option on a per-file basis by adding to the buffer a
  3417. line like
  3418. #+ARCHIVE: basement::** Finished Tasks
  3419. You may also define it locally for a subtree by setting an ARCHIVE property
  3420. in the entry. If such a property is found in an entry, or anywhere up
  3421. the hierarchy, it will be used."
  3422. :group 'org-archive
  3423. :type 'string)
  3424. (defcustom org-agenda-skip-archived-trees t
  3425. "Non-nil means the agenda will skip any items located in archived trees.
  3426. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3427. variable is no longer recommended, you should leave it at the value t.
  3428. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3429. :group 'org-archive
  3430. :group 'org-agenda-skip
  3431. :type 'boolean)
  3432. (defcustom org-columns-skip-archived-trees t
  3433. "Non-nil means ignore archived trees when creating column view."
  3434. :group 'org-archive
  3435. :group 'org-properties
  3436. :type 'boolean)
  3437. (defcustom org-cycle-open-archived-trees nil
  3438. "Non-nil means `org-cycle' will open archived trees.
  3439. An archived tree is a tree marked with the tag ARCHIVE.
  3440. When nil, archived trees will stay folded. You can still open them with
  3441. normal outline commands like `show-all', but not with the cycling commands."
  3442. :group 'org-archive
  3443. :group 'org-cycle
  3444. :type 'boolean)
  3445. (defcustom org-sparse-tree-open-archived-trees nil
  3446. "Non-nil means sparse tree construction shows matches in archived trees.
  3447. When nil, matches in these trees are highlighted, but the trees are kept in
  3448. collapsed state."
  3449. :group 'org-archive
  3450. :group 'org-sparse-trees
  3451. :type 'boolean)
  3452. (defcustom org-sparse-tree-default-date-type nil
  3453. "The default date type when building a sparse tree.
  3454. When this is nil, a date is a scheduled or a deadline timestamp.
  3455. Otherwise, these types are allowed:
  3456. all: all timestamps
  3457. active: only active timestamps (<...>)
  3458. inactive: only inactive timestamps ([...])
  3459. scheduled: only scheduled timestamps
  3460. deadline: only deadline timestamps"
  3461. :type '(choice (const :tag "Scheduled or deadline" nil)
  3462. (const :tag "All timestamps" all)
  3463. (const :tag "Only active timestamps" active)
  3464. (const :tag "Only inactive timestamps" inactive)
  3465. (const :tag "Only scheduled timestamps" scheduled)
  3466. (const :tag "Only deadline timestamps" deadline)
  3467. (const :tag "Only closed timestamps" closed))
  3468. :version "26.1"
  3469. :package-version '(Org . "8.3")
  3470. :group 'org-sparse-trees)
  3471. (defun org-cycle-hide-archived-subtrees (state)
  3472. "Re-hide all archived subtrees after a visibility state change.
  3473. STATE should be one of the symbols listed in the docstring of
  3474. `org-cycle-hook'."
  3475. (when (and (not org-cycle-open-archived-trees)
  3476. (not (memq state '(overview folded))))
  3477. (save-excursion
  3478. (let* ((globalp (memq state '(contents all)))
  3479. (beg (if globalp (point-min) (point)))
  3480. (end (if globalp (point-max) (org-end-of-subtree t))))
  3481. (org-hide-archived-subtrees beg end)
  3482. (goto-char beg)
  3483. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3484. (message "%s" (substitute-command-keys
  3485. "Subtree is archived and stays closed. Use \
  3486. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3487. (defun org-force-cycle-archived ()
  3488. "Cycle subtree even if it is archived."
  3489. (interactive)
  3490. (setq this-command 'org-cycle)
  3491. (let ((org-cycle-open-archived-trees t))
  3492. (call-interactively 'org-cycle)))
  3493. (defun org-hide-archived-subtrees (beg end)
  3494. "Re-hide all archived subtrees after a visibility state change."
  3495. (org-with-wide-buffer
  3496. (let ((case-fold-search nil)
  3497. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3498. (goto-char beg)
  3499. ;; Include headline point is currently on.
  3500. (beginning-of-line)
  3501. (while (and (< (point) end) (re-search-forward re end t))
  3502. (when (member org-archive-tag (org-get-tags nil t))
  3503. (org-flag-subtree t)
  3504. (org-end-of-subtree t))))))
  3505. (defun org-flag-subtree (flag)
  3506. (save-excursion
  3507. (org-back-to-heading t)
  3508. (org-flag-region (line-end-position)
  3509. (progn (org-end-of-subtree t) (point))
  3510. flag
  3511. 'outline)))
  3512. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3513. ;; Declare Column View Code
  3514. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3515. (declare-function org-columns-compute "org-colview" (property))
  3516. ;; Declare ID code
  3517. (declare-function org-id-store-link "org-id")
  3518. (declare-function org-id-locations-load "org-id")
  3519. (declare-function org-id-locations-save "org-id")
  3520. (defvar org-id-track-globally)
  3521. ;;; Variables for pre-computed regular expressions, all buffer local
  3522. (defvar-local org-todo-regexp nil
  3523. "Matches any of the TODO state keywords.
  3524. Since TODO keywords are case-sensitive, `case-fold-search' is
  3525. expected to be bound to nil when matching against this regexp.")
  3526. (defvar-local org-not-done-regexp nil
  3527. "Matches any of the TODO state keywords except the last one.
  3528. Since TODO keywords are case-sensitive, `case-fold-search' is
  3529. expected to be bound to nil when matching against this regexp.")
  3530. (defvar-local org-not-done-heading-regexp nil
  3531. "Matches a TODO headline that is not done.
  3532. Since TODO keywords are case-sensitive, `case-fold-search' is
  3533. expected to be bound to nil when matching against this regexp.")
  3534. (defvar-local org-todo-line-regexp nil
  3535. "Matches a headline and puts TODO state into group 2 if present.
  3536. Since TODO keywords are case-sensitive, `case-fold-search' is
  3537. expected to be bound to nil when matching against this regexp.")
  3538. (defvar-local org-complex-heading-regexp nil
  3539. "Matches a headline and puts everything into groups:
  3540. group 1: Stars
  3541. group 2: The TODO keyword, maybe
  3542. group 3: Priority cookie
  3543. group 4: True headline
  3544. group 5: Tags
  3545. Since TODO keywords are case-sensitive, `case-fold-search' is
  3546. expected to be bound to nil when matching against this regexp.")
  3547. (defvar-local org-complex-heading-regexp-format nil
  3548. "Printf format to make regexp to match an exact headline.
  3549. This regexp will match the headline of any node which has the
  3550. exact headline text that is put into the format, but may have any
  3551. TODO state, priority and tags.")
  3552. (defvar-local org-todo-line-tags-regexp nil
  3553. "Matches a headline and puts TODO state into group 2 if present.
  3554. Also put tags into group 4 if tags are present.")
  3555. (defconst org-plain-time-of-day-regexp
  3556. (concat
  3557. "\\(\\<[012]?[0-9]"
  3558. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3559. "\\(--?"
  3560. "\\(\\<[012]?[0-9]"
  3561. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3562. "\\)?")
  3563. "Regular expression to match a plain time or time range.
  3564. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3565. groups carry important information:
  3566. 0 the full match
  3567. 1 the first time, range or not
  3568. 8 the second time, if it is a range.")
  3569. (defconst org-plain-time-extension-regexp
  3570. (concat
  3571. "\\(\\<[012]?[0-9]"
  3572. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3573. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3574. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3575. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3576. groups carry important information:
  3577. 0 the full match
  3578. 7 hours of duration
  3579. 9 minutes of duration")
  3580. (defconst org-stamp-time-of-day-regexp
  3581. (concat
  3582. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3583. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3584. "\\(--?"
  3585. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3586. "Regular expression to match a timestamp time or time range.
  3587. After a match, the following groups carry important information:
  3588. 0 the full match
  3589. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3590. 2 the first time, range or not
  3591. 4 the second time, if it is a range.")
  3592. (defconst org-startup-options
  3593. '(("fold" org-startup-folded t)
  3594. ("overview" org-startup-folded t)
  3595. ("nofold" org-startup-folded nil)
  3596. ("showall" org-startup-folded nil)
  3597. ("showeverything" org-startup-folded showeverything)
  3598. ("content" org-startup-folded content)
  3599. ("indent" org-startup-indented t)
  3600. ("noindent" org-startup-indented nil)
  3601. ("hidestars" org-hide-leading-stars t)
  3602. ("showstars" org-hide-leading-stars nil)
  3603. ("odd" org-odd-levels-only t)
  3604. ("oddeven" org-odd-levels-only nil)
  3605. ("align" org-startup-align-all-tables t)
  3606. ("noalign" org-startup-align-all-tables nil)
  3607. ("shrink" org-startup-shrink-all-tables t)
  3608. ("inlineimages" org-startup-with-inline-images t)
  3609. ("noinlineimages" org-startup-with-inline-images nil)
  3610. ("latexpreview" org-startup-with-latex-preview t)
  3611. ("nolatexpreview" org-startup-with-latex-preview nil)
  3612. ("customtime" org-display-custom-times t)
  3613. ("logdone" org-log-done time)
  3614. ("lognotedone" org-log-done note)
  3615. ("nologdone" org-log-done nil)
  3616. ("lognoteclock-out" org-log-note-clock-out t)
  3617. ("nolognoteclock-out" org-log-note-clock-out nil)
  3618. ("logrepeat" org-log-repeat state)
  3619. ("lognoterepeat" org-log-repeat note)
  3620. ("logdrawer" org-log-into-drawer t)
  3621. ("nologdrawer" org-log-into-drawer nil)
  3622. ("logstatesreversed" org-log-states-order-reversed t)
  3623. ("nologstatesreversed" org-log-states-order-reversed nil)
  3624. ("nologrepeat" org-log-repeat nil)
  3625. ("logreschedule" org-log-reschedule time)
  3626. ("lognotereschedule" org-log-reschedule note)
  3627. ("nologreschedule" org-log-reschedule nil)
  3628. ("logredeadline" org-log-redeadline time)
  3629. ("lognoteredeadline" org-log-redeadline note)
  3630. ("nologredeadline" org-log-redeadline nil)
  3631. ("logrefile" org-log-refile time)
  3632. ("lognoterefile" org-log-refile note)
  3633. ("nologrefile" org-log-refile nil)
  3634. ("fninline" org-footnote-define-inline t)
  3635. ("nofninline" org-footnote-define-inline nil)
  3636. ("fnlocal" org-footnote-section nil)
  3637. ("fnauto" org-footnote-auto-label t)
  3638. ("fnprompt" org-footnote-auto-label nil)
  3639. ("fnconfirm" org-footnote-auto-label confirm)
  3640. ("fnplain" org-footnote-auto-label plain)
  3641. ("fnadjust" org-footnote-auto-adjust t)
  3642. ("nofnadjust" org-footnote-auto-adjust nil)
  3643. ("constcgs" constants-unit-system cgs)
  3644. ("constSI" constants-unit-system SI)
  3645. ("noptag" org-tag-persistent-alist nil)
  3646. ("hideblocks" org-hide-block-startup t)
  3647. ("nohideblocks" org-hide-block-startup nil)
  3648. ("beamer" org-startup-with-beamer-mode t)
  3649. ("entitiespretty" org-pretty-entities t)
  3650. ("entitiesplain" org-pretty-entities nil))
  3651. "Variable associated with STARTUP options for Org.
  3652. Each element is a list of three items: the startup options (as written
  3653. in the #+STARTUP line), the corresponding variable, and the value to set
  3654. this variable to if the option is found. An optional forth element PUSH
  3655. means to push this value onto the list in the variable.")
  3656. (defcustom org-group-tags t
  3657. "When non-nil (the default), use group tags.
  3658. This can be turned on/off through `org-toggle-tags-groups'."
  3659. :group 'org-tags
  3660. :group 'org-startup
  3661. :type 'boolean)
  3662. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3663. (defun org-toggle-tags-groups ()
  3664. "Toggle support for group tags.
  3665. Support for group tags is controlled by the option
  3666. `org-group-tags', which is non-nil by default."
  3667. (interactive)
  3668. (setq org-group-tags (not org-group-tags))
  3669. (cond ((and (derived-mode-p 'org-agenda-mode)
  3670. org-group-tags)
  3671. (org-agenda-redo))
  3672. ((derived-mode-p 'org-mode)
  3673. (let ((org-inhibit-startup t)) (org-mode))))
  3674. (message "Groups tags support has been turned %s"
  3675. (if org-group-tags "on" "off")))
  3676. (defun org--tag-add-to-alist (alist1 alist2)
  3677. "Merge tags from ALIST1 into ALIST2.
  3678. Duplicates tags outside a group are removed. Keywords and order
  3679. are preserved.
  3680. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3681. See `org-tag-alist' for their structure."
  3682. (cond
  3683. ((null alist2) alist1)
  3684. ((null alist1) alist2)
  3685. (t
  3686. (let ((to-add nil)
  3687. (group-flag nil))
  3688. (dolist (tag-pair alist1)
  3689. (pcase tag-pair
  3690. (`(,(or :startgrouptag :startgroup))
  3691. (setq group-flag t)
  3692. (push tag-pair to-add))
  3693. (`(,(or :endgrouptag :endgroup))
  3694. (setq group-flag nil)
  3695. (push tag-pair to-add))
  3696. (`(,(or :grouptags :newline))
  3697. (push tag-pair to-add))
  3698. (`(,tag . ,_)
  3699. ;; Remove duplicates from ALIST1, unless they are in
  3700. ;; a group. Indeed, it makes sense to have a tag appear in
  3701. ;; multiple groups.
  3702. (when (or group-flag (not (assoc tag alist2)))
  3703. (push tag-pair to-add)))
  3704. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3705. ;; Preserve order of ALIST1.
  3706. (append (nreverse to-add) alist2)))))
  3707. (defun org-set-regexps-and-options (&optional tags-only)
  3708. "Precompute regular expressions used in the current buffer.
  3709. When optional argument TAGS-ONLY is non-nil, only compute tags
  3710. related expressions."
  3711. (when (derived-mode-p 'org-mode)
  3712. (let ((alist (org--setup-collect-keywords
  3713. (org-make-options-regexp
  3714. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3715. (and (not tags-only)
  3716. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3717. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3718. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3719. ;; Startup options. Get this early since it does change
  3720. ;; behavior for other options (e.g., tags).
  3721. (let ((startup (cdr (assq 'startup alist))))
  3722. (dolist (option startup)
  3723. (let ((entry (assoc-string option org-startup-options t)))
  3724. (when entry
  3725. (let ((var (nth 1 entry))
  3726. (val (nth 2 entry)))
  3727. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3728. (unless (listp (symbol-value var))
  3729. (set (make-local-variable var) nil))
  3730. (add-to-list var val)))))))
  3731. (setq-local org-file-tags
  3732. (mapcar #'org-add-prop-inherited
  3733. (cdr (assq 'filetags alist))))
  3734. (setq org-current-tag-alist
  3735. (org--tag-add-to-alist
  3736. org-tag-persistent-alist
  3737. (let ((tags (cdr (assq 'tags alist))))
  3738. (if tags (org-tag-string-to-alist tags)
  3739. org-tag-alist))))
  3740. (setq org-tag-groups-alist
  3741. (org-tag-alist-to-groups org-current-tag-alist))
  3742. (unless tags-only
  3743. ;; File properties.
  3744. (setq-local org-file-properties (cdr (assq 'property alist)))
  3745. ;; Archive location.
  3746. (let ((archive (cdr (assq 'archive alist))))
  3747. (when archive (setq-local org-archive-location archive)))
  3748. ;; Category.
  3749. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3750. (when cat
  3751. (setq-local org-category (intern cat))
  3752. (setq-local org-file-properties
  3753. (org--update-property-plist
  3754. "CATEGORY" cat org-file-properties))))
  3755. ;; Columns.
  3756. (let ((column (cdr (assq 'columns alist))))
  3757. (when column (setq-local org-columns-default-format column)))
  3758. ;; Constants.
  3759. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3760. ;; Link abbreviations.
  3761. (let ((links (cdr (assq 'link alist))))
  3762. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3763. ;; Priorities.
  3764. (let ((priorities (cdr (assq 'priorities alist))))
  3765. (when priorities
  3766. (setq-local org-highest-priority (nth 0 priorities))
  3767. (setq-local org-lowest-priority (nth 1 priorities))
  3768. (setq-local org-default-priority (nth 2 priorities))))
  3769. ;; Scripts.
  3770. (let ((scripts (assq 'scripts alist)))
  3771. (when scripts
  3772. (setq-local org-use-sub-superscripts (cdr scripts))))
  3773. ;; TODO keywords.
  3774. (setq-local org-todo-kwd-alist nil)
  3775. (setq-local org-todo-key-alist nil)
  3776. (setq-local org-todo-key-trigger nil)
  3777. (setq-local org-todo-keywords-1 nil)
  3778. (setq-local org-done-keywords nil)
  3779. (setq-local org-todo-heads nil)
  3780. (setq-local org-todo-sets nil)
  3781. (setq-local org-todo-log-states nil)
  3782. (let ((todo-sequences
  3783. (or (nreverse (cdr (assq 'todo alist)))
  3784. (let ((d (default-value 'org-todo-keywords)))
  3785. (if (not (stringp (car d))) d
  3786. ;; XXX: Backward compatibility code.
  3787. (list (cons org-todo-interpretation d)))))))
  3788. (dolist (sequence todo-sequences)
  3789. (let* ((sequence (or (run-hook-with-args-until-success
  3790. 'org-todo-setup-filter-hook sequence)
  3791. sequence))
  3792. (sequence-type (car sequence))
  3793. (keywords (cdr sequence))
  3794. (sep (member "|" keywords))
  3795. names alist)
  3796. (dolist (k (remove "|" keywords))
  3797. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3798. k)
  3799. (error "Invalid TODO keyword %s" k))
  3800. (let ((name (match-string 1 k))
  3801. (key (match-string 2 k))
  3802. (log (org-extract-log-state-settings k)))
  3803. (push name names)
  3804. (push (cons name (and key (string-to-char key))) alist)
  3805. (when log (push log org-todo-log-states))))
  3806. (let* ((names (nreverse names))
  3807. (done (if sep (org-remove-keyword-keys (cdr sep))
  3808. (last names)))
  3809. (head (car names))
  3810. (tail (list sequence-type head (car done) (org-last done))))
  3811. (add-to-list 'org-todo-heads head 'append)
  3812. (push names org-todo-sets)
  3813. (setq org-done-keywords (append org-done-keywords done nil))
  3814. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3815. (setq org-todo-key-alist
  3816. (append org-todo-key-alist
  3817. (and alist
  3818. (append '((:startgroup))
  3819. (nreverse alist)
  3820. '((:endgroup))))))
  3821. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3822. (setq org-todo-sets (nreverse org-todo-sets)
  3823. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3824. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3825. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3826. ;; Compute the regular expressions and other local variables.
  3827. ;; Using `org-outline-regexp-bol' would complicate them much,
  3828. ;; because of the fixed white space at the end of that string.
  3829. (unless org-done-keywords
  3830. (setq org-done-keywords
  3831. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3832. (setq org-not-done-keywords
  3833. (org-delete-all org-done-keywords
  3834. (copy-sequence org-todo-keywords-1))
  3835. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3836. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3837. org-not-done-heading-regexp
  3838. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3839. org-todo-line-regexp
  3840. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3841. org-complex-heading-regexp
  3842. (concat "^\\(\\*+\\)"
  3843. "\\(?: +" org-todo-regexp "\\)?"
  3844. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3845. "\\(?: +\\(.*?\\)\\)??"
  3846. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3847. "[ \t]*$")
  3848. org-complex-heading-regexp-format
  3849. (concat "^\\(\\*+\\)"
  3850. "\\(?: +" org-todo-regexp "\\)?"
  3851. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3852. "\\(?: +"
  3853. ;; Stats cookies can be stuck to body.
  3854. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3855. "\\(%s\\)"
  3856. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3857. "\\)"
  3858. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3859. "[ \t]*$")
  3860. org-todo-line-tags-regexp
  3861. (concat "^\\(\\*+\\)"
  3862. "\\(?: +" org-todo-regexp "\\)?"
  3863. "\\(?: +\\(.*?\\)\\)??"
  3864. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3865. "[ \t]*$"))
  3866. (org-compute-latex-and-related-regexp)))))
  3867. (defun org--setup-collect-keywords (regexp &optional files alist)
  3868. "Return setup keywords values as an alist.
  3869. REGEXP matches a subset of setup keywords. FILES is a list of
  3870. file names already visited. It is used to avoid circular setup
  3871. files. ALIST, when non-nil, is the alist computed so far.
  3872. Return value contains the following keys: `archive', `category',
  3873. `columns', `constants', `filetags', `link', `priorities',
  3874. `property', `scripts', `startup', `tags' and `todo'."
  3875. (org-with-wide-buffer
  3876. (goto-char (point-min))
  3877. (let ((case-fold-search t))
  3878. (while (re-search-forward regexp nil t)
  3879. (let ((element (org-element-at-point)))
  3880. (when (eq (org-element-type element) 'keyword)
  3881. (let ((key (org-element-property :key element))
  3882. (value (org-element-property :value element)))
  3883. (cond
  3884. ((equal key "ARCHIVE")
  3885. (when (org-string-nw-p value)
  3886. (push (cons 'archive value) alist)))
  3887. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3888. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3889. ((equal key "CONSTANTS")
  3890. (let* ((constants (assq 'constants alist))
  3891. (store (cdr constants)))
  3892. (dolist (pair (split-string value))
  3893. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3894. pair)
  3895. (let* ((name (match-string 1 pair))
  3896. (value (match-string 2 pair))
  3897. (old (assoc name store)))
  3898. (if old (setcdr old value)
  3899. (push (cons name value) store)))))
  3900. (if constants (setcdr constants store)
  3901. (push (cons 'constants store) alist))))
  3902. ((equal key "FILETAGS")
  3903. (when (org-string-nw-p value)
  3904. (let ((old (assq 'filetags alist))
  3905. (new (apply #'nconc
  3906. (mapcar (lambda (x) (org-split-string x ":"))
  3907. (split-string value)))))
  3908. (if old (setcdr old (append new (cdr old)))
  3909. (push (cons 'filetags new) alist)))))
  3910. ((equal key "LINK")
  3911. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3912. (let ((links (assq 'link alist))
  3913. (pair (cons (match-string-no-properties 1 value)
  3914. (match-string-no-properties 2 value))))
  3915. (if links (push pair (cdr links))
  3916. (push (list 'link pair) alist)))))
  3917. ((equal key "OPTIONS")
  3918. (when (and (org-string-nw-p value)
  3919. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3920. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3921. ((equal key "PRIORITIES")
  3922. (push (cons 'priorities
  3923. (let ((prio (split-string value)))
  3924. (if (< (length prio) 3) '(?A ?C ?B)
  3925. (mapcar #'string-to-char prio))))
  3926. alist))
  3927. ((equal key "PROPERTY")
  3928. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3929. (let* ((property (assq 'property alist))
  3930. (value (org--update-property-plist
  3931. (match-string-no-properties 1 value)
  3932. (match-string-no-properties 2 value)
  3933. (cdr property))))
  3934. (if property (setcdr property value)
  3935. (push (cons 'property value) alist)))))
  3936. ((equal key "STARTUP")
  3937. (let ((startup (assq 'startup alist)))
  3938. (if startup
  3939. (setcdr startup
  3940. (append (cdr startup) (split-string value)))
  3941. (push (cons 'startup (split-string value)) alist))))
  3942. ((equal key "TAGS")
  3943. (let ((tag-cell (assq 'tags alist)))
  3944. (if tag-cell
  3945. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3946. (push (cons 'tags value) alist))))
  3947. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3948. (let ((todo (assq 'todo alist))
  3949. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3950. (split-string value))))
  3951. (if todo (push value (cdr todo))
  3952. (push (list 'todo value) alist))))
  3953. ((equal key "SETUPFILE")
  3954. (unless buffer-read-only ; Do not check in Gnus messages.
  3955. (let ((f (and (org-string-nw-p value)
  3956. (expand-file-name (org-strip-quotes value)))))
  3957. (when (and f (file-readable-p f) (not (member f files)))
  3958. (with-temp-buffer
  3959. (setq default-directory (file-name-directory f))
  3960. (insert-file-contents f)
  3961. (setq alist
  3962. ;; Fake Org mode to benefit from cache
  3963. ;; without recurring needlessly.
  3964. (let ((major-mode 'org-mode))
  3965. (org--setup-collect-keywords
  3966. regexp (cons f files) alist)))))))))))))))
  3967. alist)
  3968. (defun org-tag-string-to-alist (s)
  3969. "Return tag alist associated to string S.
  3970. S is a value for TAGS keyword or produced with
  3971. `org-tag-alist-to-string'. Return value is an alist suitable for
  3972. `org-tag-alist' or `org-tag-persistent-alist'."
  3973. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3974. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3975. "\\(?:(\\(.\\))\\)?\\'"))
  3976. alist group-flag)
  3977. (dolist (tokens lines (cdr (nreverse alist)))
  3978. (push '(:newline) alist)
  3979. (while tokens
  3980. (let ((token (pop tokens)))
  3981. (pcase token
  3982. ("{"
  3983. (push '(:startgroup) alist)
  3984. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3985. ("}"
  3986. (push '(:endgroup) alist)
  3987. (setq group-flag nil))
  3988. ("["
  3989. (push '(:startgrouptag) alist)
  3990. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3991. ("]"
  3992. (push '(:endgrouptag) alist)
  3993. (setq group-flag nil))
  3994. (":"
  3995. (push '(:grouptags) alist))
  3996. ((guard (string-match tag-re token))
  3997. (let ((tag (match-string 1 token))
  3998. (key (and (match-beginning 2)
  3999. (string-to-char (match-string 2 token)))))
  4000. ;; Push all tags in groups, no matter if they already
  4001. ;; appear somewhere else in the list.
  4002. (when (or group-flag (not (assoc tag alist)))
  4003. (push (cons tag key) alist))))))))))
  4004. (defun org-tag-alist-to-string (alist &optional skip-key)
  4005. "Return tag string associated to ALIST.
  4006. ALIST is an alist, as defined in `org-tag-alist' or
  4007. `org-tag-persistent-alist', or produced with
  4008. `org-tag-string-to-alist'.
  4009. Return value is a string suitable as a value for \"TAGS\"
  4010. keyword.
  4011. When optional argument SKIP-KEY is non-nil, skip selection keys
  4012. next to tags."
  4013. (mapconcat (lambda (token)
  4014. (pcase token
  4015. (`(:startgroup) "{")
  4016. (`(:endgroup) "}")
  4017. (`(:startgrouptag) "[")
  4018. (`(:endgrouptag) "]")
  4019. (`(:grouptags) ":")
  4020. (`(:newline) "\\n")
  4021. ((and
  4022. (guard (not skip-key))
  4023. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4024. (format "%s(%c)" tag key))
  4025. (`(,(and tag (pred stringp)) . ,_) tag)
  4026. (_ (user-error "Invalid tag token: %S" token))))
  4027. alist
  4028. " "))
  4029. (defun org-tag-alist-to-groups (alist)
  4030. "Return group alist from tag ALIST.
  4031. ALIST is an alist, as defined in `org-tag-alist' or
  4032. `org-tag-persistent-alist', or produced with
  4033. `org-tag-string-to-alist'. Return value is an alist following
  4034. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4035. a string, summarizing TAGS, as a list of strings."
  4036. (let (groups group-status current-group)
  4037. (dolist (token alist (nreverse groups))
  4038. (pcase token
  4039. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4040. (`(,(or :endgroup :endgrouptag))
  4041. (when (eq group-status 'append)
  4042. (push (nreverse current-group) groups))
  4043. (setq group-status nil current-group nil))
  4044. (`(:grouptags) (setq group-status 'append))
  4045. ((and `(,tag . ,_) (guard group-status))
  4046. (if (eq group-status 'append) (push tag current-group)
  4047. (setq current-group (list tag))))
  4048. (_ nil)))))
  4049. (defvar org--file-cache (make-hash-table :test #'equal)
  4050. "Hash table to store contents of files referenced via a URL.
  4051. This is the cache of file URLs read using `org-file-contents'.")
  4052. (defun org-reset-file-cache ()
  4053. "Reset the cache of files downloaded by `org-file-contents'."
  4054. (clrhash org--file-cache))
  4055. (defun org-file-url-p (file)
  4056. "Non-nil if FILE is a URL."
  4057. (require 'ffap)
  4058. (string-match-p ffap-url-regexp file))
  4059. (defun org-file-contents (file &optional noerror nocache)
  4060. "Return the contents of FILE, as a string.
  4061. FILE can be a file name or URL.
  4062. If FILE is a URL, download the contents. If the URL contents are
  4063. already cached in the `org--file-cache' hash table, the download step
  4064. is skipped.
  4065. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4066. from file or URL.
  4067. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4068. is available. This option applies only if FILE is a URL."
  4069. (let* ((is-url (org-file-url-p file))
  4070. (cache (and is-url
  4071. (not nocache)
  4072. (gethash file org--file-cache))))
  4073. (cond
  4074. (cache)
  4075. (is-url
  4076. (with-current-buffer (url-retrieve-synchronously file)
  4077. (goto-char (point-min))
  4078. ;; Move point to after the url-retrieve header.
  4079. (search-forward "\n\n" nil :move)
  4080. ;; Search for the success code only in the url-retrieve header.
  4081. (if (save-excursion
  4082. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4083. ;; Update the cache `org--file-cache' and return contents.
  4084. (puthash file
  4085. (buffer-substring-no-properties (point) (point-max))
  4086. org--file-cache)
  4087. (funcall (if noerror #'message #'user-error)
  4088. "Unable to fetch file from %S"
  4089. file))))
  4090. (t
  4091. (with-temp-buffer
  4092. (condition-case nil
  4093. (progn
  4094. (insert-file-contents file)
  4095. (buffer-string))
  4096. (file-error
  4097. (funcall (if noerror #'message #'user-error)
  4098. "Unable to read file %S"
  4099. file))))))))
  4100. (defun org-extract-log-state-settings (x)
  4101. "Extract the log state setting from a TODO keyword string.
  4102. This will extract info from a string like \"WAIT(w@/!)\"."
  4103. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4104. (let ((kw (match-string 1 x))
  4105. (log1 (and (match-end 3) (match-string 3 x)))
  4106. (log2 (and (match-end 4) (match-string 4 x))))
  4107. (and (or log1 log2)
  4108. (list kw
  4109. (and log1 (if (equal log1 "!") 'time 'note))
  4110. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4111. (defun org-remove-keyword-keys (list)
  4112. "Remove a pair of parenthesis at the end of each string in LIST."
  4113. (mapcar (lambda (x)
  4114. (if (string-match "(.*)$" x)
  4115. (substring x 0 (match-beginning 0))
  4116. x))
  4117. list))
  4118. (defun org-assign-fast-keys (alist)
  4119. "Assign fast keys to a keyword-key alist.
  4120. Respect keys that are already there."
  4121. (let (new e (alt ?0))
  4122. (while (setq e (pop alist))
  4123. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4124. (cdr e)) ;; Key already assigned.
  4125. (push e new)
  4126. (let ((clist (string-to-list (downcase (car e))))
  4127. (used (append new alist)))
  4128. (when (= (car clist) ?@)
  4129. (pop clist))
  4130. (while (and clist (rassoc (car clist) used))
  4131. (pop clist))
  4132. (unless clist
  4133. (while (rassoc alt used)
  4134. (cl-incf alt)))
  4135. (push (cons (car e) (or (car clist) alt)) new))))
  4136. (nreverse new)))
  4137. ;;; Some variables used in various places
  4138. (defvar org-window-configuration nil
  4139. "Used in various places to store a window configuration.")
  4140. (defvar org-selected-window nil
  4141. "Used in various places to store a window configuration.")
  4142. (defvar org-finish-function nil
  4143. "Function to be called when `C-c C-c' is used.
  4144. This is for getting out of special buffers like capture.")
  4145. (defvar org-last-state)
  4146. ;; Defined somewhere in this file, but used before definition.
  4147. (defvar org-entities) ;; defined in org-entities.el
  4148. (defvar org-struct-menu)
  4149. (defvar org-org-menu)
  4150. (defvar org-tbl-menu)
  4151. ;;;; Define the Org mode
  4152. (defun org-before-change-function (_beg _end)
  4153. "Every change indicates that a table might need an update."
  4154. (setq org-table-may-need-update t))
  4155. (defvar org-mode-map)
  4156. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4157. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4158. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4159. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4160. (defvar bidi-paragraph-direction)
  4161. (defvar buffer-face-mode-face)
  4162. (require 'outline)
  4163. ;; Other stuff we need.
  4164. (require 'time-date)
  4165. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4166. (require 'easymenu)
  4167. (autoload 'easy-menu-add "easymenu")
  4168. (require 'overlay)
  4169. ;; (require 'org-macs) moved higher up in the file before it is first used
  4170. (require 'org-entities)
  4171. ;; (require 'org-compat) moved higher up in the file before it is first used
  4172. (require 'org-faces)
  4173. (require 'org-list)
  4174. (require 'org-pcomplete)
  4175. (require 'org-src)
  4176. (require 'org-footnote)
  4177. (require 'org-macro)
  4178. ;; babel
  4179. (require 'ob)
  4180. ;;;###autoload
  4181. (define-derived-mode org-mode outline-mode "Org"
  4182. "Outline-based notes management and organizer, alias
  4183. \"Carsten's outline-mode for keeping track of everything.\"
  4184. Org mode develops organizational tasks around a NOTES file which
  4185. contains information about projects as plain text. Org mode is
  4186. implemented on top of Outline mode, which is ideal to keep the content
  4187. of large files well structured. It supports ToDo items, deadlines and
  4188. time stamps, which magically appear in the diary listing of the Emacs
  4189. calendar. Tables are easily created with a built-in table editor.
  4190. Plain text URL-like links connect to websites, emails (VM), Usenet
  4191. messages (Gnus), BBDB entries, and any files related to the project.
  4192. For printing and sharing of notes, an Org file (or a part of it)
  4193. can be exported as a structured ASCII or HTML file.
  4194. The following commands are available:
  4195. \\{org-mode-map}"
  4196. (org-load-modules-maybe)
  4197. (org-install-agenda-files-menu)
  4198. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4199. (add-to-invisibility-spec '(org-hide-block . t))
  4200. (add-to-invisibility-spec '(org-hide-drawer . t))
  4201. (setq-local outline-regexp org-outline-regexp)
  4202. (setq-local outline-level 'org-outline-level)
  4203. (setq bidi-paragraph-direction 'left-to-right)
  4204. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4205. (unless org-display-table
  4206. (setq org-display-table (make-display-table)))
  4207. (set-display-table-slot
  4208. org-display-table 4
  4209. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4210. org-ellipsis)))
  4211. (setq buffer-display-table org-display-table))
  4212. (org-set-regexps-and-options)
  4213. (org-set-font-lock-defaults)
  4214. (when (and org-tag-faces (not org-tags-special-faces-re))
  4215. ;; tag faces set outside customize.... force initialization.
  4216. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4217. ;; Calc embedded
  4218. (setq-local calc-embedded-open-mode "# ")
  4219. ;; Modify a few syntax entries
  4220. (modify-syntax-entry ?\" "\"")
  4221. (modify-syntax-entry ?\\ "_")
  4222. (modify-syntax-entry ?~ "_")
  4223. (modify-syntax-entry ?< "(>")
  4224. (modify-syntax-entry ?> ")<")
  4225. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4226. ;; Activate before-change-function
  4227. (setq-local org-table-may-need-update t)
  4228. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4229. ;; Check for running clock before killing a buffer
  4230. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4231. ;; Initialize macros templates.
  4232. (org-macro-initialize-templates)
  4233. ;; Initialize radio targets.
  4234. (org-update-radio-target-regexp)
  4235. ;; Indentation.
  4236. (setq-local indent-line-function 'org-indent-line)
  4237. (setq-local indent-region-function 'org-indent-region)
  4238. ;; Filling and auto-filling.
  4239. (org-setup-filling)
  4240. ;; Comments.
  4241. (org-setup-comments-handling)
  4242. ;; Initialize cache.
  4243. (org-element-cache-reset)
  4244. ;; Beginning/end of defun
  4245. (setq-local beginning-of-defun-function 'org-backward-element)
  4246. (setq-local end-of-defun-function
  4247. (lambda ()
  4248. (if (not (org-at-heading-p))
  4249. (org-forward-element)
  4250. (org-forward-element)
  4251. (forward-char -1))))
  4252. ;; Next error for sparse trees
  4253. (setq-local next-error-function 'org-occur-next-match)
  4254. ;; Make commit log messages from Org documents easier.
  4255. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4256. ;; Make sure dependence stuff works reliably, even for users who set it
  4257. ;; too late :-(
  4258. (if org-enforce-todo-dependencies
  4259. (add-hook 'org-blocker-hook
  4260. 'org-block-todo-from-children-or-siblings-or-parent)
  4261. (remove-hook 'org-blocker-hook
  4262. 'org-block-todo-from-children-or-siblings-or-parent))
  4263. (if org-enforce-todo-checkbox-dependencies
  4264. (add-hook 'org-blocker-hook
  4265. 'org-block-todo-from-checkboxes)
  4266. (remove-hook 'org-blocker-hook
  4267. 'org-block-todo-from-checkboxes))
  4268. ;; Align options lines
  4269. (setq-local
  4270. align-mode-rules-list
  4271. '((org-in-buffer-settings
  4272. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4273. (modes . '(org-mode)))))
  4274. ;; Make isearch reveal context
  4275. (setq-local outline-isearch-open-invisible-function
  4276. (lambda (&rest _) (org-show-context 'isearch)))
  4277. ;; Setup the pcomplete hooks
  4278. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4279. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4280. (setq-local pcomplete-default-completion-function 'ignore)
  4281. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4282. (setq-local pcomplete-termination-string "")
  4283. (setq-local buffer-face-mode-face 'org-default)
  4284. ;; If empty file that did not turn on Org mode automatically, make
  4285. ;; it to.
  4286. (when (and org-insert-mode-line-in-empty-file
  4287. (called-interactively-p 'any)
  4288. (= (point-min) (point-max)))
  4289. (insert "# -*- mode: org -*-\n\n"))
  4290. (unless org-inhibit-startup
  4291. (org-unmodified
  4292. (when org-startup-with-beamer-mode (org-beamer-mode))
  4293. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4294. (org-table-map-tables
  4295. (cond ((and org-startup-align-all-tables
  4296. org-startup-shrink-all-tables)
  4297. (lambda () (org-table-align) (org-table-shrink)))
  4298. (org-startup-align-all-tables #'org-table-align)
  4299. (t #'org-table-shrink))
  4300. t))
  4301. (when org-startup-with-inline-images (org-display-inline-images))
  4302. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4303. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4304. (when org-startup-truncated (setq truncate-lines t))
  4305. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4306. ;; Try to set `org-hide' face correctly.
  4307. (let ((foreground (org-find-invisible-foreground)))
  4308. (when foreground
  4309. (set-face-foreground 'org-hide foreground))))
  4310. ;; Update `customize-package-emacs-version-alist'
  4311. (add-to-list 'customize-package-emacs-version-alist
  4312. '(Org ("8.0" . "24.4")
  4313. ("8.1" . "24.4")
  4314. ("8.2" . "24.4")
  4315. ("8.2.7" . "24.4")
  4316. ("8.3" . "26.1")
  4317. ("9.0" . "26.1")
  4318. ("9.1" . "26.1")
  4319. ("9.2" . "27.1")))
  4320. (defvar org-mode-transpose-word-syntax-table
  4321. (let ((st (make-syntax-table text-mode-syntax-table)))
  4322. (dolist (c org-emphasis-alist st)
  4323. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4324. (when (fboundp 'abbrev-table-put)
  4325. (abbrev-table-put org-mode-abbrev-table
  4326. :parents (list text-mode-abbrev-table)))
  4327. (defun org-find-invisible-foreground ()
  4328. (let ((candidates (remove
  4329. "unspecified-bg"
  4330. (nconc
  4331. (list (face-background 'default)
  4332. (face-background 'org-default))
  4333. (mapcar
  4334. (lambda (alist)
  4335. (when (boundp alist)
  4336. (cdr (assq 'background-color (symbol-value alist)))))
  4337. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4338. (list (face-foreground 'org-hide))))))
  4339. (car (remove nil candidates))))
  4340. (defun org-current-time (&optional rounding-minutes past)
  4341. "Current time, possibly rounded to ROUNDING-MINUTES.
  4342. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4343. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4344. the rounding returns a past time."
  4345. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4346. (car org-time-stamp-rounding-minutes)))
  4347. (now (current-time)))
  4348. (if (< r 1)
  4349. now
  4350. (let* ((time (decode-time now))
  4351. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4352. (nthcdr 2 time))))
  4353. (if (or (not past) (org-time-less-p res now))
  4354. res
  4355. (org-time-subtract res (* r 60)))))))
  4356. (defun org-today ()
  4357. "Return today date, considering `org-extend-today-until'."
  4358. (time-to-days
  4359. (org-time-since (* 3600 org-extend-today-until))))
  4360. ;;;; Font-Lock stuff, including the activators
  4361. (require 'font-lock)
  4362. (defconst org-match-sexp-depth 3
  4363. "Number of stacked braces for sub/superscript matching.")
  4364. (defun org-create-multibrace-regexp (left right n)
  4365. "Create a regular expression which will match a balanced sexp.
  4366. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4367. as single character strings.
  4368. The regexp returned will match the entire expression including the
  4369. delimiters. It will also define a single group which contains the
  4370. match except for the outermost delimiters. The maximum depth of
  4371. stacked delimiters is N. Escaping delimiters is not possible."
  4372. (let* ((nothing (concat "[^" left right "]*?"))
  4373. (or "\\|")
  4374. (re nothing)
  4375. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4376. (while (> n 1)
  4377. (setq n (1- n)
  4378. re (concat re or next)
  4379. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4380. (concat left "\\(" re "\\)" right)))
  4381. (defconst org-match-substring-regexp
  4382. (concat
  4383. "\\(\\S-\\)\\([_^]\\)\\("
  4384. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4385. "\\|"
  4386. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4387. "\\|"
  4388. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4389. "The regular expression matching a sub- or superscript.")
  4390. (defconst org-match-substring-with-braces-regexp
  4391. (concat
  4392. "\\(\\S-\\)\\([_^]\\)"
  4393. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4394. "The regular expression matching a sub- or superscript, forcing braces.")
  4395. (defvar org-emph-face nil)
  4396. (defun org-do-emphasis-faces (limit)
  4397. "Run through the buffer and emphasize strings."
  4398. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4399. (car org-emphasis-regexp-components))))
  4400. (catch :exit
  4401. (while (re-search-forward quick-re limit t)
  4402. (let* ((marker (match-string 2))
  4403. (verbatim? (member marker '("~" "="))))
  4404. (when (save-excursion
  4405. (goto-char (match-beginning 0))
  4406. (and
  4407. ;; Do not match table hlines.
  4408. (not (and (equal marker "+")
  4409. (org-match-line
  4410. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4411. ;; Do not match headline stars. Do not consider
  4412. ;; stars of a headline as closing marker for bold
  4413. ;; markup either.
  4414. (not (and (equal marker "*")
  4415. (save-excursion
  4416. (forward-char)
  4417. (skip-chars-backward "*")
  4418. (looking-at-p org-outline-regexp-bol))))
  4419. ;; Match full emphasis markup regexp.
  4420. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4421. ;; Do not span over paragraph boundaries.
  4422. (not (string-match-p org-element-paragraph-separate
  4423. (match-string 2)))
  4424. ;; Do not span over cells in table rows.
  4425. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4426. (string-match-p "|" (match-string 4))))))
  4427. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4428. (font-lock-prepend-text-property
  4429. (match-beginning 2) (match-end 2) 'face face)
  4430. (when verbatim?
  4431. (org-remove-flyspell-overlays-in
  4432. (match-beginning 0) (match-end 0))
  4433. (remove-text-properties (match-beginning 2) (match-end 2)
  4434. '(display t invisible t intangible t)))
  4435. (add-text-properties (match-beginning 2) (match-end 2)
  4436. '(font-lock-multiline t org-emphasis t))
  4437. (when org-hide-emphasis-markers
  4438. (add-text-properties (match-end 4) (match-beginning 5)
  4439. '(invisible org-link))
  4440. (add-text-properties (match-beginning 3) (match-end 3)
  4441. '(invisible org-link)))
  4442. (throw :exit t))))))))
  4443. (defun org-emphasize (&optional char)
  4444. "Insert or change an emphasis, i.e. a font like bold or italic.
  4445. If there is an active region, change that region to a new emphasis.
  4446. If there is no region, just insert the marker characters and position
  4447. the cursor between them.
  4448. CHAR should be the marker character. If it is a space, it means to
  4449. remove the emphasis of the selected region.
  4450. If CHAR is not given (for example in an interactive call) it will be
  4451. prompted for."
  4452. (interactive)
  4453. (let ((erc org-emphasis-regexp-components)
  4454. (string "") beg end move s)
  4455. (if (org-region-active-p)
  4456. (setq beg (region-beginning)
  4457. end (region-end)
  4458. string (buffer-substring beg end))
  4459. (setq move t))
  4460. (unless char
  4461. (message "Emphasis marker or tag: [%s]"
  4462. (mapconcat #'car org-emphasis-alist ""))
  4463. (setq char (read-char-exclusive)))
  4464. (if (equal char ?\s)
  4465. (setq s ""
  4466. move nil)
  4467. (unless (assoc (char-to-string char) org-emphasis-alist)
  4468. (user-error "No such emphasis marker: \"%c\"" char))
  4469. (setq s (char-to-string char)))
  4470. (while (and (> (length string) 1)
  4471. (equal (substring string 0 1) (substring string -1))
  4472. (assoc (substring string 0 1) org-emphasis-alist))
  4473. (setq string (substring string 1 -1)))
  4474. (setq string (concat s string s))
  4475. (when beg (delete-region beg end))
  4476. (unless (or (bolp)
  4477. (string-match (concat "[" (nth 0 erc) "\n]")
  4478. (char-to-string (char-before (point)))))
  4479. (insert " "))
  4480. (unless (or (eobp)
  4481. (string-match (concat "[" (nth 1 erc) "\n]")
  4482. (char-to-string (char-after (point)))))
  4483. (insert " ") (backward-char 1))
  4484. (insert string)
  4485. (and move (backward-char 1))))
  4486. (defconst org-nonsticky-props
  4487. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4488. (defsubst org-rear-nonsticky-at (pos)
  4489. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4490. (defun org-activate-links (limit)
  4491. "Add link properties to links.
  4492. This includes angle, plain, and bracket links."
  4493. (catch :exit
  4494. (while (re-search-forward org-link-any-re limit t)
  4495. (let* ((start (match-beginning 0))
  4496. (end (match-end 0))
  4497. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4498. (visible-end (or (match-end 3) (match-end 2)))
  4499. (style (cond ((eq ?< (char-after start)) 'angle)
  4500. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4501. (t 'plain))))
  4502. (when (and (memq style org-highlight-links)
  4503. ;; Do not span over paragraph boundaries.
  4504. (not (string-match-p org-element-paragraph-separate
  4505. (match-string 0)))
  4506. ;; Do not confuse plain links with tags.
  4507. (not (and (eq style 'plain)
  4508. (let ((face (get-text-property
  4509. (max (1- start) (point-min)) 'face)))
  4510. (if (consp face) (memq 'org-tag face)
  4511. (eq 'org-tag face))))))
  4512. (let* ((link-object (save-excursion
  4513. (goto-char start)
  4514. (save-match-data (org-element-link-parser))))
  4515. (link (org-element-property :raw-link link-object))
  4516. (type (org-element-property :type link-object))
  4517. (path (org-element-property :path link-object))
  4518. (properties ;for link's visible part
  4519. (list
  4520. 'face (pcase (org-link-get-parameter type :face)
  4521. ((and (pred functionp) face) (funcall face path))
  4522. ((and (pred facep) face) face)
  4523. ((and (pred consp) face) face) ;anonymous
  4524. (_ 'org-link))
  4525. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4526. 'highlight)
  4527. 'keymap (or (org-link-get-parameter type :keymap)
  4528. org-mouse-map)
  4529. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4530. ((and (pred stringp) echo) echo)
  4531. ((and (pred functionp) echo) echo)
  4532. (_ (concat "LINK: " link)))
  4533. 'htmlize-link (pcase (org-link-get-parameter type
  4534. :htmlize-link)
  4535. ((and (pred functionp) f) (funcall f))
  4536. (_ `(:uri ,link)))
  4537. 'font-lock-multiline t)))
  4538. (org-remove-flyspell-overlays-in start end)
  4539. (org-rear-nonsticky-at end)
  4540. (if (not (eq 'bracket style))
  4541. (add-text-properties start end properties)
  4542. ;; Handle invisible parts in bracket links.
  4543. (remove-text-properties start end '(invisible nil))
  4544. (let ((hidden
  4545. (append `(invisible
  4546. ,(or (org-link-get-parameter type :display)
  4547. 'org-link))
  4548. properties)))
  4549. (add-text-properties start visible-start hidden)
  4550. (add-text-properties visible-start visible-end properties)
  4551. (add-text-properties visible-end end hidden)
  4552. (org-rear-nonsticky-at visible-start)
  4553. (org-rear-nonsticky-at visible-end)))
  4554. (let ((f (org-link-get-parameter type :activate-func)))
  4555. (when (functionp f)
  4556. (funcall f start end path (eq style 'bracket))))
  4557. (throw :exit t))))) ;signal success
  4558. nil))
  4559. (defun org-activate-code (limit)
  4560. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4561. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4562. (remove-text-properties (match-beginning 0) (match-end 0)
  4563. '(display t invisible t intangible t))
  4564. t))
  4565. (defcustom org-src-fontify-natively t
  4566. "When non-nil, fontify code in code blocks.
  4567. See also the `org-block' face."
  4568. :type 'boolean
  4569. :version "26.1"
  4570. :package-version '(Org . "8.3")
  4571. :group 'org-appearance
  4572. :group 'org-babel)
  4573. (defcustom org-allow-promoting-top-level-subtree nil
  4574. "When non-nil, allow promoting a top level subtree.
  4575. The leading star of the top level headline will be replaced
  4576. by a #."
  4577. :type 'boolean
  4578. :version "24.1"
  4579. :group 'org-appearance)
  4580. (defun org-fontify-meta-lines-and-blocks (limit)
  4581. (condition-case nil
  4582. (org-fontify-meta-lines-and-blocks-1 limit)
  4583. (error (message "Org mode fontification error in %S at %d"
  4584. (current-buffer)
  4585. (line-number-at-pos)))))
  4586. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4587. "Fontify #+ lines and blocks."
  4588. (let ((case-fold-search t))
  4589. (when (re-search-forward
  4590. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  4591. limit t)
  4592. (let ((beg (match-beginning 0))
  4593. (end-of-beginline (match-end 0))
  4594. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4595. (block-end nil) ; will include \n after end of block content
  4596. (lang (match-string 7)) ; the language, if it is an src block
  4597. (bol-after-beginline (line-beginning-position 2))
  4598. (dc1 (downcase (match-string 2)))
  4599. (dc3 (downcase (match-string 3)))
  4600. (whole-blockline org-fontify-whole-block-delimiter-line)
  4601. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4602. (cond
  4603. ((and (match-end 4) (equal dc3 "+begin"))
  4604. ;; Truly a block
  4605. (setq block-type (downcase (match-string 5))
  4606. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4607. (when (re-search-forward
  4608. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  4609. nil t) ;; on purpose, we look further than LIMIT
  4610. ;; We do have a matching #+end line
  4611. (setq beg-of-endline (match-beginning 0)
  4612. end-of-endline (match-end 0)
  4613. nl-before-endline (1- (match-beginning 0)))
  4614. (setq block-end (match-beginning 0)) ; includes the final newline.
  4615. (when quoting
  4616. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4617. (remove-text-properties beg end-of-endline
  4618. '(display t invisible t intangible t)))
  4619. (add-text-properties
  4620. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4621. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4622. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4623. (cond
  4624. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4625. (org-src-font-lock-fontify-block lang block-start block-end)
  4626. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4627. (quoting
  4628. (add-text-properties
  4629. bol-after-beginline beg-of-endline
  4630. (list 'face
  4631. (list :inherit
  4632. (let ((face-name
  4633. (intern (format "org-block-%s" lang))))
  4634. (append (and (facep face-name) (list face-name))
  4635. '(org-block)))))))
  4636. ((not org-fontify-quote-and-verse-blocks))
  4637. ((string= block-type "quote")
  4638. (add-face-text-property
  4639. bol-after-beginline beg-of-endline 'org-quote t))
  4640. ((string= block-type "verse")
  4641. (add-face-text-property
  4642. bol-after-beginline beg-of-endline 'org-verse t)))
  4643. ;; Fontify the #+begin and #+end lines of the blocks
  4644. (add-text-properties
  4645. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4646. '(face org-block-begin-line))
  4647. (add-text-properties
  4648. beg-of-endline
  4649. (min (point-max) (if whole-blockline (min (point-max) (1+ end-of-endline)) end-of-endline))
  4650. '(face org-block-end-line))
  4651. t))
  4652. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4653. (org-remove-flyspell-overlays-in
  4654. (match-beginning 0)
  4655. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4656. (add-text-properties
  4657. beg (match-end 3)
  4658. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4659. '(font-lock-fontified t invisible t)
  4660. '(font-lock-fontified t face org-document-info-keyword)))
  4661. (add-text-properties
  4662. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4663. (if (string-equal dc1 "+title:")
  4664. '(font-lock-fontified t face org-document-title)
  4665. '(font-lock-fontified t face org-document-info))))
  4666. ((string-prefix-p "+caption" dc1)
  4667. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4668. (remove-text-properties (match-beginning 0) (match-end 0)
  4669. '(display t invisible t intangible t))
  4670. ;; Handle short captions.
  4671. (save-excursion
  4672. (beginning-of-line)
  4673. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  4674. (add-text-properties (line-beginning-position) (match-end 1)
  4675. '(font-lock-fontified t face org-meta-line))
  4676. (add-text-properties (match-end 0) (line-end-position)
  4677. '(font-lock-fontified t face org-block))
  4678. t)
  4679. ((member dc3 '(" " ""))
  4680. ; Just a comment, the plus was not there
  4681. (org-remove-flyspell-overlays-in beg (match-end 0))
  4682. (add-text-properties
  4683. beg (match-end 0)
  4684. '(font-lock-fontified t face font-lock-comment-face)))
  4685. (t ;; just any other in-buffer setting, but not indented
  4686. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4687. (remove-text-properties (match-beginning 0) (match-end 0)
  4688. '(display t invisible t intangible t))
  4689. (add-text-properties beg (match-end 0)
  4690. '(font-lock-fontified t face org-meta-line))
  4691. t))))))
  4692. (defun org-fontify-drawers (limit)
  4693. "Fontify drawers."
  4694. (when (re-search-forward org-drawer-regexp limit t)
  4695. (add-text-properties
  4696. (line-beginning-position) (line-beginning-position 2)
  4697. '(font-lock-fontified t face org-drawer))
  4698. (org-remove-flyspell-overlays-in
  4699. (line-beginning-position) (line-beginning-position 2))
  4700. t))
  4701. (defun org-fontify-macros (limit)
  4702. "Fontify macros."
  4703. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4704. (let ((begin (match-beginning 0))
  4705. (opening-end (match-beginning 1)))
  4706. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4707. (match-string 1))
  4708. (let ((end (match-end 1))
  4709. (closing-start (match-beginning 1)))
  4710. (add-text-properties
  4711. begin end
  4712. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4713. (org-remove-flyspell-overlays-in begin end)
  4714. (when org-hide-macro-markers
  4715. (add-text-properties begin opening-end '(invisible t))
  4716. (add-text-properties closing-start end '(invisible t)))
  4717. t)))))
  4718. (defun org-fontify-extend-region (beg end _old-len)
  4719. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4720. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4721. (extend (lambda (r1 r2 dir)
  4722. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4723. (replace-regexp-in-string "[][]" r2
  4724. (match-string-no-properties 0)))))
  4725. (re-search-forward (regexp-quote re) nil t dir)))))
  4726. (save-match-data
  4727. (save-excursion
  4728. (goto-char beg)
  4729. (back-to-indentation)
  4730. (cond ((looking-at end-re)
  4731. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4732. ((looking-at begin-re)
  4733. (cons beg (or (funcall extend "end" "]" 1) end)))
  4734. (t (cons beg end)))))))
  4735. (defun org-activate-footnote-links (limit)
  4736. "Add text properties for footnotes."
  4737. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4738. (when fn
  4739. (let* ((beg (nth 1 fn))
  4740. (end (nth 2 fn))
  4741. (label (car fn))
  4742. (referencep (/= (line-beginning-position) beg)))
  4743. (when (and referencep (nth 3 fn))
  4744. (save-excursion
  4745. (goto-char beg)
  4746. (search-forward (or label "fn:"))
  4747. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4748. (add-text-properties beg end
  4749. (list 'mouse-face 'highlight
  4750. 'keymap org-mouse-map
  4751. 'help-echo
  4752. (if referencep "Footnote reference"
  4753. "Footnote definition")
  4754. 'font-lock-fontified t
  4755. 'font-lock-multiline t
  4756. 'face 'org-footnote))))))
  4757. (defun org-activate-dates (limit)
  4758. "Add text properties for dates."
  4759. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4760. (not (equal (char-before (match-beginning 0)) 91)))
  4761. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4762. (add-text-properties (match-beginning 0) (match-end 0)
  4763. (list 'mouse-face 'highlight
  4764. 'keymap org-mouse-map))
  4765. (org-rear-nonsticky-at (match-end 0))
  4766. (when org-display-custom-times
  4767. ;; If it's a date range, activate custom time for second date.
  4768. (when (match-end 3)
  4769. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4770. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4771. t))
  4772. (defun org-activate-target-links (limit)
  4773. "Add text properties for target matches."
  4774. (when org-target-link-regexp
  4775. (let ((case-fold-search t))
  4776. ;; `org-target-link-regexp' matches one character before the
  4777. ;; actual target.
  4778. (unless (bolp) (forward-char -1))
  4779. (when (re-search-forward org-target-link-regexp limit t)
  4780. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4781. (add-text-properties (match-beginning 1) (match-end 1)
  4782. (list 'mouse-face 'highlight
  4783. 'keymap org-mouse-map
  4784. 'help-echo "Radio target link"
  4785. 'org-linked-text t))
  4786. (org-rear-nonsticky-at (match-end 1))
  4787. t))))
  4788. (defvar org-latex-and-related-regexp nil
  4789. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4790. (defun org-compute-latex-and-related-regexp ()
  4791. "Compute regular expression for LaTeX, entities and sub/superscript.
  4792. Result depends on variable `org-highlight-latex-and-related'."
  4793. (let ((re-sub
  4794. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4795. ((eq org-use-sub-superscripts '{})
  4796. (list org-match-substring-with-braces-regexp))
  4797. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4798. (re-latex
  4799. (when (or (memq 'latex org-highlight-latex-and-related)
  4800. (memq 'native org-highlight-latex-and-related))
  4801. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4802. (delq nil
  4803. (mapcar (lambda (x)
  4804. (and (member (car x) matchers) (nth 1 x)))
  4805. org-latex-regexps)))))
  4806. (re-entities
  4807. (when (memq 'entities org-highlight-latex-and-related)
  4808. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4809. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4810. (setq-local org-latex-and-related-regexp
  4811. (mapconcat #'identity
  4812. (append re-latex re-entities re-sub)
  4813. "\\|"))))
  4814. (defun org-do-latex-and-related (_limit)
  4815. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4816. Stop at first highlighted object, if any. Return t if some
  4817. highlighting was done, nil otherwise."
  4818. (when (org-string-nw-p org-latex-and-related-regexp)
  4819. (catch 'found
  4820. (while (re-search-forward org-latex-and-related-regexp
  4821. nil t) ;; on purpose, we ignore LIMIT
  4822. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4823. org-special-keyword)))
  4824. (save-excursion
  4825. (goto-char (1+ (match-beginning 0)))
  4826. (face-at-point nil t)))
  4827. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4828. '(?_ ?^))
  4829. 1
  4830. 0))
  4831. (start (+ offset (match-beginning 0)))
  4832. (end (match-end 0)))
  4833. (if (memq 'native org-highlight-latex-and-related)
  4834. (org-src-font-lock-fontify-block "latex" start end)
  4835. (font-lock-prepend-text-property start end
  4836. 'face 'org-latex-and-related))
  4837. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4838. '(font-lock-multiline t)))
  4839. (throw 'found t)))
  4840. nil)))
  4841. (defun org-restart-font-lock ()
  4842. "Restart `font-lock-mode', to force refontification."
  4843. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4844. (font-lock-mode -1)
  4845. (font-lock-mode 1)))
  4846. (defun org-activate-tags (limit)
  4847. (when (re-search-forward org-tag-line-re limit t)
  4848. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4849. (add-text-properties (match-beginning 1) (match-end 1)
  4850. (list 'mouse-face 'highlight
  4851. 'keymap org-mouse-map))
  4852. (org-rear-nonsticky-at (match-end 1))
  4853. t))
  4854. (defun org-outline-level ()
  4855. "Compute the outline level of the heading at point.
  4856. If this is called at a normal headline, the level is the number
  4857. of stars. Use `org-reduced-level' to remove the effect of
  4858. `org-odd-levels'. Unlike to `org-current-level', this function
  4859. takes into consideration inlinetasks."
  4860. (org-with-wide-buffer
  4861. (end-of-line)
  4862. (if (re-search-backward org-outline-regexp-bol nil t)
  4863. (1- (- (match-end 0) (match-beginning 0)))
  4864. 0)))
  4865. (defvar org-font-lock-keywords nil)
  4866. (defsubst org-re-property (property &optional literal allow-null value)
  4867. "Return a regexp matching a PROPERTY line.
  4868. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4869. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4870. non-nil, match properties even without a value.
  4871. Match group 3 is set to the value when it exists. If there is no
  4872. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4873. With optional argument VALUE, match only property lines with
  4874. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4875. unless LITERAL is non-nil."
  4876. (concat
  4877. "^\\(?4:[ \t]*\\)"
  4878. (format "\\(?1::\\(?2:%s\\):\\)"
  4879. (if literal property (regexp-quote property)))
  4880. (cond (value
  4881. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4882. (if literal value (regexp-quote value))))
  4883. (allow-null
  4884. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4885. (t
  4886. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4887. (defconst org-property-re
  4888. (org-re-property "\\S-+" 'literal t)
  4889. "Regular expression matching a property line.
  4890. There are four matching groups:
  4891. 1: :PROPKEY: including the leading and trailing colon,
  4892. 2: PROPKEY without the leading and trailing colon,
  4893. 3: PROPVAL without leading or trailing spaces,
  4894. 4: the indentation of the current line,
  4895. 5: trailing whitespace.")
  4896. (defvar org-font-lock-hook nil
  4897. "Functions to be called for special font lock stuff.")
  4898. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4899. (defvar org-font-lock-set-keywords-hook nil
  4900. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4901. This is called after `org-font-lock-extra-keywords' is defined, but before
  4902. it is installed to be used by font lock. This can be useful if something
  4903. needs to be inserted at a specific position in the font-lock sequence.")
  4904. (defun org-font-lock-hook (limit)
  4905. "Run `org-font-lock-hook' within LIMIT."
  4906. (run-hook-with-args 'org-font-lock-hook limit))
  4907. (defun org-set-font-lock-defaults ()
  4908. "Set font lock defaults for the current buffer."
  4909. (let* ((em org-fontify-emphasized-text)
  4910. (lk org-highlight-links)
  4911. (org-font-lock-extra-keywords
  4912. (list
  4913. ;; Call the hook
  4914. '(org-font-lock-hook)
  4915. ;; Headlines
  4916. `(,(if org-fontify-whole-heading-line
  4917. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4918. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4919. (1 (org-get-level-face 1))
  4920. (2 (org-get-level-face 2))
  4921. (3 (org-get-level-face 3)))
  4922. ;; Table lines
  4923. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4924. (1 'org-table t))
  4925. ;; Table internals
  4926. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4927. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4928. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4929. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4930. ;; Properties
  4931. (list org-property-re
  4932. '(1 'org-special-keyword t)
  4933. '(3 'org-property-value t))
  4934. ;; Drawers
  4935. '(org-fontify-drawers)
  4936. ;; Link related fontification.
  4937. '(org-activate-links)
  4938. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4939. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4940. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4941. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4942. ;; Targets.
  4943. (list org-radio-target-regexp '(0 'org-target t))
  4944. (list org-target-regexp '(0 'org-target t))
  4945. ;; Diary sexps.
  4946. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4947. ;; Macro
  4948. '(org-fontify-macros)
  4949. ;; TODO keyword
  4950. (list (format org-heading-keyword-regexp-format
  4951. org-todo-regexp)
  4952. '(2 (org-get-todo-face 2) t))
  4953. ;; DONE
  4954. (if org-fontify-done-headline
  4955. (list (format org-heading-keyword-regexp-format
  4956. (concat
  4957. "\\(?:"
  4958. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4959. "\\)"))
  4960. '(2 'org-headline-done t))
  4961. nil)
  4962. ;; Priorities
  4963. '(org-font-lock-add-priority-faces)
  4964. ;; Tags
  4965. '(org-font-lock-add-tag-faces)
  4966. ;; Tags groups
  4967. (when (and org-group-tags org-tag-groups-alist)
  4968. (list (concat org-outline-regexp-bol ".+\\(:"
  4969. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4970. ":\\).*$")
  4971. '(1 'org-tag-group prepend)))
  4972. ;; Special keywords
  4973. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4974. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4975. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4976. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4977. ;; Emphasis
  4978. (when em '(org-do-emphasis-faces))
  4979. ;; Checkboxes
  4980. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4981. 1 'org-checkbox prepend)
  4982. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4983. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4984. (0 (org-get-checkbox-statistics-face) t)))
  4985. ;; Description list items
  4986. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4987. 1 'org-list-dt prepend)
  4988. ;; ARCHIVEd headings
  4989. (list (concat
  4990. org-outline-regexp-bol
  4991. "\\(.*:" org-archive-tag ":.*\\)")
  4992. '(1 'org-archived prepend))
  4993. ;; Specials
  4994. '(org-do-latex-and-related)
  4995. '(org-fontify-entities)
  4996. '(org-raise-scripts)
  4997. ;; Code
  4998. '(org-activate-code (1 'org-code t))
  4999. ;; COMMENT
  5000. (list (format
  5001. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5002. org-todo-regexp
  5003. org-comment-string)
  5004. '(9 'org-special-keyword t))
  5005. ;; Blocks and meta lines
  5006. '(org-fontify-meta-lines-and-blocks))))
  5007. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5008. (run-hooks 'org-font-lock-set-keywords-hook)
  5009. ;; Now set the full font-lock-keywords
  5010. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5011. (setq-local font-lock-defaults
  5012. '(org-font-lock-keywords t nil nil backward-paragraph))
  5013. (setq-local font-lock-extend-after-change-region-function
  5014. #'org-fontify-extend-region)
  5015. (kill-local-variable 'font-lock-keywords)
  5016. nil))
  5017. (defun org-toggle-pretty-entities ()
  5018. "Toggle the composition display of entities as UTF8 characters."
  5019. (interactive)
  5020. (setq-local org-pretty-entities (not org-pretty-entities))
  5021. (org-restart-font-lock)
  5022. (if org-pretty-entities
  5023. (message "Entities are now displayed as UTF8 characters")
  5024. (save-restriction
  5025. (widen)
  5026. (decompose-region (point-min) (point-max))
  5027. (message "Entities are now displayed as plain text"))))
  5028. (defvar-local org-custom-properties-overlays nil
  5029. "List of overlays used for custom properties.")
  5030. (defun org-toggle-custom-properties-visibility ()
  5031. "Display or hide properties in `org-custom-properties'."
  5032. (interactive)
  5033. (if org-custom-properties-overlays
  5034. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5035. (setq org-custom-properties-overlays nil))
  5036. (when org-custom-properties
  5037. (org-with-wide-buffer
  5038. (goto-char (point-min))
  5039. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5040. (while (re-search-forward regexp nil t)
  5041. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5042. (when (and end (< (point) end))
  5043. ;; Hide first custom property in current drawer.
  5044. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5045. (overlay-put o 'invisible t)
  5046. (overlay-put o 'org-custom-property t)
  5047. (push o org-custom-properties-overlays))
  5048. ;; Hide additional custom properties in the same drawer.
  5049. (while (re-search-forward regexp end t)
  5050. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5051. (overlay-put o 'invisible t)
  5052. (overlay-put o 'org-custom-property t)
  5053. (push o org-custom-properties-overlays)))))
  5054. ;; Each entry is limited to a single property drawer.
  5055. (outline-next-heading)))))))
  5056. (defun org-fontify-entities (limit)
  5057. "Find an entity to fontify."
  5058. (let (ee)
  5059. (when org-pretty-entities
  5060. (catch 'match
  5061. ;; "\_ "-family is left out on purpose. Only the first one,
  5062. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5063. ;; confusing when adding a second white space character.
  5064. (while (re-search-forward
  5065. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5066. limit t)
  5067. (when (and (not (org-at-comment-p))
  5068. (setq ee (org-entity-get (match-string 1)))
  5069. (= (length (nth 6 ee)) 1))
  5070. (let* ((end (if (equal (match-string 2) "{}")
  5071. (match-end 2)
  5072. (match-end 1))))
  5073. (add-text-properties
  5074. (match-beginning 0) end
  5075. (list 'font-lock-fontified t))
  5076. (compose-region (match-beginning 0) end
  5077. (nth 6 ee) nil)
  5078. (backward-char 1)
  5079. (throw 'match t))))
  5080. nil))))
  5081. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5082. "Fontify string S like in Org mode."
  5083. (with-temp-buffer
  5084. (insert s)
  5085. (let ((org-odd-levels-only odd-levels))
  5086. (org-mode)
  5087. (org-font-lock-ensure)
  5088. (buffer-string))))
  5089. (defvar org-m nil)
  5090. (defvar org-l nil)
  5091. (defvar org-f nil)
  5092. (defun org-get-level-face (n)
  5093. "Get the right face for match N in font-lock matching of headlines."
  5094. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5095. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5096. (if org-cycle-level-faces
  5097. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5098. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5099. (cond
  5100. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5101. ((eq n 2) org-f)
  5102. (t (unless org-level-color-stars-only org-f))))
  5103. (defun org-face-from-face-or-color (context inherit face-or-color)
  5104. "Create a face list that inherits INHERIT, but sets the foreground color.
  5105. When FACE-OR-COLOR is not a string, just return it."
  5106. (if (stringp face-or-color)
  5107. (list :inherit inherit
  5108. (cdr (assoc context org-faces-easy-properties))
  5109. face-or-color)
  5110. face-or-color))
  5111. (defun org-get-todo-face (kwd)
  5112. "Get the right face for a TODO keyword KWD.
  5113. If KWD is a number, get the corresponding match group."
  5114. (when (numberp kwd) (setq kwd (match-string kwd)))
  5115. (or (org-face-from-face-or-color
  5116. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5117. (and (member kwd org-done-keywords) 'org-done)
  5118. 'org-todo))
  5119. (defun org-get-priority-face (priority)
  5120. "Get the right face for PRIORITY.
  5121. PRIORITY is a character."
  5122. (or (org-face-from-face-or-color
  5123. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5124. 'org-priority))
  5125. (defun org-get-tag-face (tag)
  5126. "Get the right face for TAG.
  5127. If TAG is a number, get the corresponding match group."
  5128. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5129. (or (org-face-from-face-or-color
  5130. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5131. 'org-tag)))
  5132. (defun org-font-lock-add-priority-faces (limit)
  5133. "Add the special priority faces."
  5134. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5135. (add-text-properties
  5136. (match-beginning 1) (match-end 1)
  5137. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5138. 'font-lock-fontified t))))
  5139. (defun org-font-lock-add-tag-faces (limit)
  5140. "Add the special tag faces."
  5141. (when (and org-tag-faces org-tags-special-faces-re)
  5142. (while (re-search-forward org-tags-special-faces-re limit t)
  5143. (add-text-properties (match-beginning 1) (match-end 1)
  5144. (list 'face (org-get-tag-face 1)
  5145. 'font-lock-fontified t))
  5146. (backward-char 1))))
  5147. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5148. "Remove fontification and activation overlays from links."
  5149. (font-lock-default-unfontify-region beg end)
  5150. (let* ((buffer-undo-list t)
  5151. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5152. (inhibit-modification-hooks t)
  5153. deactivate-mark buffer-file-name buffer-file-truename)
  5154. (decompose-region beg end)
  5155. (remove-text-properties beg end
  5156. '(mouse-face t keymap t org-linked-text t
  5157. invisible t intangible t
  5158. org-emphasis t))
  5159. (org-remove-font-lock-display-properties beg end)))
  5160. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5161. ((raise 0.3) (height 0.7))
  5162. ((raise -0.5))
  5163. ((raise 0.5)))
  5164. "Display properties for showing superscripts and subscripts.")
  5165. (defun org-remove-font-lock-display-properties (beg end)
  5166. "Remove specific display properties that have been added by font lock.
  5167. The will remove the raise properties that are used to show superscripts
  5168. and subscripts."
  5169. (let (next prop)
  5170. (while (< beg end)
  5171. (setq next (next-single-property-change beg 'display nil end)
  5172. prop (get-text-property beg 'display))
  5173. (when (member prop org-script-display)
  5174. (put-text-property beg next 'display nil))
  5175. (setq beg next))))
  5176. (defun org-raise-scripts (limit)
  5177. "Add raise properties to sub/superscripts."
  5178. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5179. (re-search-forward
  5180. (if (eq org-use-sub-superscripts t)
  5181. org-match-substring-regexp
  5182. org-match-substring-with-braces-regexp)
  5183. limit t))
  5184. (let* ((pos (point)) table-p comment-p
  5185. (mpos (match-beginning 3))
  5186. (emph-p (get-text-property mpos 'org-emphasis))
  5187. (link-p (get-text-property mpos 'mouse-face))
  5188. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5189. (goto-char (point-at-bol))
  5190. (setq table-p (looking-at-p org-table-dataline-regexp)
  5191. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5192. (goto-char pos)
  5193. ;; Handle a_b^c
  5194. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5195. (unless (or comment-p emph-p link-p keyw-p)
  5196. (put-text-property (match-beginning 3) (match-end 0)
  5197. 'display
  5198. (if (equal (char-after (match-beginning 2)) ?^)
  5199. (nth (if table-p 3 1) org-script-display)
  5200. (nth (if table-p 2 0) org-script-display)))
  5201. (add-text-properties (match-beginning 2) (match-end 2)
  5202. (list 'invisible t))
  5203. (when (and (eq (char-after (match-beginning 3)) ?{)
  5204. (eq (char-before (match-end 3)) ?}))
  5205. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5206. (list 'invisible t))
  5207. (add-text-properties (1- (match-end 3)) (match-end 3)
  5208. (list 'invisible t))))
  5209. t)))
  5210. (defun org-remove-empty-overlays-at (pos)
  5211. "Remove outline overlays that do not contain non-white stuff."
  5212. (dolist (o (overlays-at pos))
  5213. (and (eq 'outline (overlay-get o 'invisible))
  5214. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5215. (overlay-end o))))
  5216. (delete-overlay o))))
  5217. (defun org-show-empty-lines-in-parent ()
  5218. "Move to the parent and re-show empty lines before visible headlines."
  5219. (save-excursion
  5220. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5221. (org-cycle-show-empty-lines context))))
  5222. (defun org-files-list ()
  5223. "Return `org-agenda-files' list, plus all open Org files.
  5224. This is useful for operations that need to scan all of a user's
  5225. open and agenda-wise Org files."
  5226. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5227. (dolist (buf (buffer-list))
  5228. (with-current-buffer buf
  5229. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5230. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5231. :test #'equal))))
  5232. files))
  5233. (defsubst org-entry-beginning-position ()
  5234. "Return the beginning position of the current entry."
  5235. (save-excursion (org-back-to-heading t) (point)))
  5236. (defsubst org-entry-end-position ()
  5237. "Return the end position of the current entry."
  5238. (save-excursion (outline-next-heading) (point)))
  5239. (defun org-subtree-end-visible-p ()
  5240. "Is the end of the current subtree visible?"
  5241. (pos-visible-in-window-p
  5242. (save-excursion (org-end-of-subtree t) (point))))
  5243. (defun org-first-headline-recenter ()
  5244. "Move cursor to the first headline and recenter the headline."
  5245. (let ((window (get-buffer-window)))
  5246. (when window
  5247. (goto-char (point-min))
  5248. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5249. (set-window-start window (line-beginning-position))))))
  5250. ;;; Visibility (headlines, blocks, drawers)
  5251. ;;;; Headlines visibility
  5252. (defun org-show-entry ()
  5253. "Show the body directly following this heading.
  5254. Show the heading too, if it is currently invisible."
  5255. (interactive)
  5256. (save-excursion
  5257. (ignore-errors
  5258. (org-back-to-heading t)
  5259. (org-flag-region
  5260. (line-end-position 0)
  5261. (save-excursion
  5262. (if (re-search-forward
  5263. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5264. (match-beginning 1)
  5265. (point-max)))
  5266. nil
  5267. 'outline))))
  5268. (defun org-show-children (&optional level)
  5269. "Show all direct subheadings of this heading.
  5270. Prefix arg LEVEL is how many levels below the current level
  5271. should be shown. Default is enough to cause the following
  5272. heading to appear."
  5273. (interactive "p")
  5274. (save-excursion
  5275. (org-back-to-heading t)
  5276. (let* ((current-level (funcall outline-level))
  5277. (max-level (org-get-valid-level
  5278. current-level
  5279. (if level (prefix-numeric-value level) 1)))
  5280. (end (save-excursion (org-end-of-subtree t t)))
  5281. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5282. (past-first-child nil)
  5283. ;; Make sure to skip inlinetasks.
  5284. (re (format regexp-fmt
  5285. current-level
  5286. (cond
  5287. ((not (featurep 'org-inlinetask)) "")
  5288. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5289. 3))
  5290. (t (1- org-inlinetask-min-level))))))
  5291. ;; Display parent heading.
  5292. (org-flag-heading nil)
  5293. (forward-line)
  5294. ;; Display children. First child may be deeper than expected
  5295. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5296. ;; MAX-LEVEL accordingly.
  5297. (while (re-search-forward re end t)
  5298. (unless past-first-child
  5299. (setq re (format regexp-fmt
  5300. current-level
  5301. (max (funcall outline-level) max-level)))
  5302. (setq past-first-child t))
  5303. (org-flag-heading nil)))))
  5304. (defun org-show-subtree ()
  5305. "Show everything after this heading at deeper levels."
  5306. (interactive)
  5307. (org-flag-region
  5308. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5309. ;;;; Blocks visibility
  5310. (defun org-hide-block-toggle-maybe ()
  5311. "Toggle visibility of block at point.
  5312. Unlike to `org-hide-block-toggle', this function does not throw
  5313. an error. Return a non-nil value when toggling is successful."
  5314. (interactive)
  5315. (ignore-errors (org-hide-block-toggle)))
  5316. (defun org-hide-block-toggle (&optional force)
  5317. "Toggle the visibility of the current block.
  5318. When optional argument FORCE is `off', make block visible. If it
  5319. is non-nil, hide it unconditionally. Throw an error when not at
  5320. a block. Return a non-nil value when toggling is successful."
  5321. (interactive)
  5322. (let ((element (org-element-at-point)))
  5323. (unless (memq (org-element-type element)
  5324. '(center-block comment-block dynamic-block example-block
  5325. export-block quote-block special-block
  5326. src-block verse-block))
  5327. (user-error "Not at a block"))
  5328. (let* ((post (org-element-property :post-affiliated element))
  5329. (start (save-excursion
  5330. (goto-char post)
  5331. (line-end-position)))
  5332. (end (save-excursion
  5333. (goto-char (org-element-property :end element))
  5334. (skip-chars-backward " \t\n")
  5335. (line-end-position))))
  5336. ;; Do nothing when not before or at the block opening line or at
  5337. ;; the block closing line.
  5338. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5339. (cond ((eq force 'off)
  5340. (org-flag-region start end nil 'org-hide-block))
  5341. (force
  5342. (org-flag-region start end t 'org-hide-block))
  5343. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5344. (org-flag-region start end nil 'org-hide-block))
  5345. (t
  5346. (org-flag-region start end t 'org-hide-block)))
  5347. ;; When the block is hidden away, make sure point is left in
  5348. ;; a visible part of the buffer.
  5349. (when (invisible-p (max (1- (point)) (point-min)))
  5350. (goto-char post))
  5351. ;; Signal success.
  5352. t))))
  5353. (defun org-hide-block-toggle-all ()
  5354. "Toggle the visibility of all blocks in the current buffer."
  5355. (org-block-map 'org-hide-block-toggle))
  5356. (defun org-hide-block-all ()
  5357. "Fold all blocks in the current buffer."
  5358. (interactive)
  5359. (org-show-all '(blocks))
  5360. (org-block-map 'org-hide-block-toggle-maybe))
  5361. ;;;; Drawers visibility
  5362. (defun org-cycle-hide-drawers (state &optional exceptions)
  5363. "Re-hide all drawers after a visibility state change.
  5364. STATE should be one of the symbols listed in the docstring of
  5365. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5366. a list of strings specifying which drawers should not be hidden."
  5367. (when (and (derived-mode-p 'org-mode)
  5368. (not (memq state '(overview folded contents))))
  5369. (save-excursion
  5370. (let* ((globalp (eq state 'all))
  5371. (beg (if globalp (point-min) (point)))
  5372. (end (if globalp (point-max)
  5373. (if (eq state 'children)
  5374. (save-excursion (outline-next-heading) (point))
  5375. (org-end-of-subtree t)))))
  5376. (goto-char beg)
  5377. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5378. (unless (member-ignore-case (match-string 1) exceptions)
  5379. (let ((drawer (org-element-at-point)))
  5380. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5381. (org-flag-drawer t drawer)
  5382. ;; Make sure to skip drawer entirely or we might flag
  5383. ;; it another time when matching its ending line with
  5384. ;; `org-drawer-regexp'.
  5385. (goto-char (org-element-property :end drawer))))))))))
  5386. (defun org-flag-drawer (flag &optional element beg end)
  5387. "When FLAG is non-nil, hide the drawer we are at.
  5388. Otherwise make it visible.
  5389. When optional argument ELEMENT is a parsed drawer, as returned by
  5390. `org-element-at-point', hide or show that drawer instead.
  5391. When buffer positions BEG and END are provided, hide or show that
  5392. region as a drawer without further ado."
  5393. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5394. (let ((drawer (or element
  5395. (and (save-excursion
  5396. (beginning-of-line)
  5397. (looking-at-p org-drawer-regexp))
  5398. (org-element-at-point)))))
  5399. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5400. (let ((post (org-element-property :post-affiliated drawer)))
  5401. (org-flag-region
  5402. (save-excursion (goto-char post) (line-end-position))
  5403. (save-excursion (goto-char (org-element-property :end drawer))
  5404. (skip-chars-backward " \t\n")
  5405. (line-end-position))
  5406. flag 'org-hide-drawer)
  5407. ;; When the drawer is hidden away, make sure point lies in
  5408. ;; a visible part of the buffer.
  5409. (when (invisible-p (max (1- (point)) (point-min)))
  5410. (goto-char post)))))))
  5411. ;;;; Visibility cycling
  5412. (defvar-local org-cycle-global-status nil)
  5413. (put 'org-cycle-global-status 'org-state t)
  5414. (defvar-local org-cycle-subtree-status nil)
  5415. (put 'org-cycle-subtree-status 'org-state t)
  5416. (defun org-show-all (&optional types)
  5417. "Show all contents in the visible part of the buffer.
  5418. By default, the function expands headings, blocks and drawers.
  5419. When optional argument TYPE is a list of symbols among `blocks',
  5420. `drawers' and `headings', to only expand one specific type."
  5421. (interactive)
  5422. (dolist (type (or types '(blocks drawers headings)))
  5423. (org-flag-region (point-min) (point-max) nil
  5424. (pcase type
  5425. (`blocks 'org-hide-block)
  5426. (`drawers 'org-hide-drawer)
  5427. (`headings 'outline)
  5428. (_ (error "Invalid type: %S" type))))))
  5429. ;;;###autoload
  5430. (defun org-cycle (&optional arg)
  5431. "TAB-action and visibility cycling for Org mode.
  5432. This is the command invoked in Org mode by the `TAB' key. Its main
  5433. purpose is outline visibility cycling, but it also invokes other actions
  5434. in special contexts.
  5435. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5436. the entire
  5437. buffer through 3 states (global cycling)
  5438. 1. OVERVIEW: Show only top-level headlines.
  5439. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5440. 3. SHOW ALL: Show everything.
  5441. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5442. switch to the startup visibility,
  5443. determined by the variable `org-startup-folded', and by any VISIBILITY
  5444. properties in the buffer.
  5445. With a `\\[universal-argument] \\[universal-argument] \
  5446. \\[universal-argument]' prefix argument, show the entire buffer, including
  5447. any drawers.
  5448. When inside a table, re-align the table and move to the next field.
  5449. When point is at the beginning of a headline, rotate the subtree started
  5450. by this line through 3 different states (local cycling)
  5451. 1. FOLDED: Only the main headline is shown.
  5452. 2. CHILDREN: The main headline and the direct children are shown.
  5453. From this state, you can move to one of the children
  5454. and zoom in further.
  5455. 3. SUBTREE: Show the entire subtree, including body text.
  5456. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5457. When point is at the beginning of an empty headline and the variable
  5458. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5459. of the headline by demoting and promoting it to likely levels. This
  5460. speeds up creation document structure by pressing `TAB' once or several
  5461. times right after creating a new headline.
  5462. When there is a numeric prefix, go up to a heading with level ARG, do
  5463. a `show-subtree' and return to the previous cursor position. If ARG
  5464. is negative, go up that many levels.
  5465. When point is not at the beginning of a headline, execute the global
  5466. binding for `TAB', which is re-indenting the line. See the option
  5467. `org-cycle-emulate-tab' for details.
  5468. As a special case, if point is at the beginning of the buffer and there is
  5469. no headline in line 1, this function will act as if called with prefix arg
  5470. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5471. prefix arg, but only
  5472. if the variable `org-cycle-global-at-bob' is t."
  5473. (interactive "P")
  5474. (org-load-modules-maybe)
  5475. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5476. (and org-cycle-level-after-item/entry-creation
  5477. (or (org-cycle-level)
  5478. (org-cycle-item-indentation))))
  5479. (let* ((limit-level
  5480. (or org-cycle-max-level
  5481. (and (boundp 'org-inlinetask-min-level)
  5482. org-inlinetask-min-level
  5483. (1- org-inlinetask-min-level))))
  5484. (nstars (and limit-level
  5485. (if org-odd-levels-only
  5486. (and limit-level (1- (* limit-level 2)))
  5487. limit-level)))
  5488. (org-outline-regexp
  5489. (if (not (derived-mode-p 'org-mode))
  5490. outline-regexp
  5491. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5492. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5493. (not (looking-at org-outline-regexp))))
  5494. (org-cycle-hook
  5495. (if bob-special
  5496. (delq 'org-optimize-window-after-visibility-change
  5497. (copy-sequence org-cycle-hook))
  5498. org-cycle-hook))
  5499. (pos (point)))
  5500. (cond
  5501. ((equal arg '(16))
  5502. (setq last-command 'dummy)
  5503. (org-set-startup-visibility)
  5504. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5505. ((equal arg '(64))
  5506. (org-show-all)
  5507. (org-unlogged-message "Entire buffer visible, including drawers"))
  5508. ((equal arg '(4)) (org-cycle-internal-global))
  5509. ;; Try hiding block at point.
  5510. ((org-hide-block-toggle-maybe))
  5511. ;; Try cdlatex TAB completion
  5512. ((org-try-cdlatex-tab))
  5513. ;; Table: enter it or move to the next field.
  5514. ((org-at-table-p 'any)
  5515. (if (org-at-table.el-p)
  5516. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5517. Use `\\[org-edit-special]' to edit table.el tables"))
  5518. (if arg (org-table-edit-field t)
  5519. (org-table-justify-field-maybe)
  5520. (call-interactively 'org-table-next-field))))
  5521. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5522. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5523. (bob-special (org-cycle-internal-global))
  5524. ;; Drawers: delegate to `org-flag-drawer'.
  5525. ((save-excursion
  5526. (beginning-of-line 1)
  5527. (looking-at org-drawer-regexp))
  5528. (org-flag-drawer ; toggle block visibility
  5529. (not (get-char-property (match-end 0) 'invisible))))
  5530. ;; Show-subtree, ARG levels up from here.
  5531. ((integerp arg)
  5532. (save-excursion
  5533. (org-back-to-heading)
  5534. (outline-up-heading (if (< arg 0) (- arg)
  5535. (- (funcall outline-level) arg)))
  5536. (org-show-subtree)))
  5537. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5538. ((and (featurep 'org-inlinetask)
  5539. (org-inlinetask-at-task-p)
  5540. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5541. (org-inlinetask-toggle-visibility))
  5542. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5543. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5544. (save-excursion (move-beginning-of-line 1)
  5545. (looking-at org-outline-regexp)))
  5546. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5547. (org-cycle-internal-local))
  5548. ;; From there: TAB emulation and template completion.
  5549. (buffer-read-only (org-back-to-heading))
  5550. ((run-hook-with-args-until-success
  5551. 'org-tab-after-check-for-cycling-hook))
  5552. ((run-hook-with-args-until-success
  5553. 'org-tab-before-tab-emulation-hook))
  5554. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5555. (or (not (bolp))
  5556. (not (looking-at org-outline-regexp))))
  5557. (call-interactively (global-key-binding "\t")))
  5558. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5559. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5560. (or (and (eq org-cycle-emulate-tab 'white)
  5561. (= (match-end 0) (point-at-eol)))
  5562. (and (eq org-cycle-emulate-tab 'whitestart)
  5563. (>= (match-end 0) pos))))
  5564. t
  5565. (eq org-cycle-emulate-tab t))
  5566. (call-interactively (global-key-binding "\t")))
  5567. (t (save-excursion
  5568. (org-back-to-heading)
  5569. (org-cycle)))))))
  5570. (defun org-cycle-internal-global ()
  5571. "Do the global cycling action."
  5572. ;; Hack to avoid display of messages for .org attachments in Gnus
  5573. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5574. (cond
  5575. ((and (eq last-command this-command)
  5576. (eq org-cycle-global-status 'overview))
  5577. ;; We just created the overview - now do table of contents
  5578. ;; This can be slow in very large buffers, so indicate action
  5579. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5580. (unless ga (org-unlogged-message "CONTENTS..."))
  5581. (org-content)
  5582. (unless ga (org-unlogged-message "CONTENTS...done"))
  5583. (setq org-cycle-global-status 'contents)
  5584. (run-hook-with-args 'org-cycle-hook 'contents))
  5585. ((and (eq last-command this-command)
  5586. (eq org-cycle-global-status 'contents))
  5587. ;; We just showed the table of contents - now show everything
  5588. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5589. (org-show-all '(headings blocks))
  5590. (unless ga (org-unlogged-message "SHOW ALL"))
  5591. (setq org-cycle-global-status 'all)
  5592. (run-hook-with-args 'org-cycle-hook 'all))
  5593. (t
  5594. ;; Default action: go to overview
  5595. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5596. (org-overview)
  5597. (unless ga (org-unlogged-message "OVERVIEW"))
  5598. (setq org-cycle-global-status 'overview)
  5599. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5600. (defvar org-called-with-limited-levels nil
  5601. "Non-nil when `org-with-limited-levels' is currently active.")
  5602. (defun org-cycle-internal-local ()
  5603. "Do the local cycling action."
  5604. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5605. ;; First, determine end of headline (EOH), end of subtree or item
  5606. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5607. (save-excursion
  5608. (if (org-at-item-p)
  5609. (progn
  5610. (beginning-of-line)
  5611. (setq struct (org-list-struct))
  5612. (setq eoh (point-at-eol))
  5613. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5614. (setq has-children (org-list-has-child-p (point) struct)))
  5615. (org-back-to-heading)
  5616. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5617. (setq eos (save-excursion (org-end-of-subtree t t)
  5618. (when (bolp) (backward-char)) (point)))
  5619. (setq has-children
  5620. (or (save-excursion
  5621. (let ((level (funcall outline-level)))
  5622. (outline-next-heading)
  5623. (and (org-at-heading-p t)
  5624. (> (funcall outline-level) level))))
  5625. (save-excursion
  5626. (org-list-search-forward (org-item-beginning-re) eos t)))))
  5627. ;; Determine end invisible part of buffer (EOL)
  5628. (beginning-of-line 2)
  5629. (while (and (not (eobp)) ;This is like `next-line'.
  5630. (get-char-property (1- (point)) 'invisible))
  5631. (goto-char (next-single-char-property-change (point) 'invisible))
  5632. (and (eolp) (beginning-of-line 2)))
  5633. (setq eol (point)))
  5634. ;; Find out what to do next and set `this-command'
  5635. (cond
  5636. ((= eos eoh)
  5637. ;; Nothing is hidden behind this heading
  5638. (unless (org-before-first-heading-p)
  5639. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5640. (org-unlogged-message "EMPTY ENTRY")
  5641. (setq org-cycle-subtree-status nil)
  5642. (save-excursion
  5643. (goto-char eos)
  5644. (outline-next-heading)
  5645. (when (org-invisible-p) (org-flag-heading nil))))
  5646. ((and (or (>= eol eos)
  5647. (not (string-match "\\S-" (buffer-substring eol eos))))
  5648. (or has-children
  5649. (not (setq children-skipped
  5650. org-cycle-skip-children-state-if-no-children))))
  5651. ;; Entire subtree is hidden in one line: children view
  5652. (unless (org-before-first-heading-p)
  5653. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5654. (if (org-at-item-p)
  5655. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5656. (org-show-entry)
  5657. (org-with-limited-levels (org-show-children))
  5658. (org-show-set-visibility 'canonical)
  5659. ;; Fold every list in subtree to top-level items.
  5660. (when (eq org-cycle-include-plain-lists 'integrate)
  5661. (save-excursion
  5662. (org-back-to-heading)
  5663. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5664. (beginning-of-line 1)
  5665. (let* ((struct (org-list-struct))
  5666. (prevs (org-list-prevs-alist struct))
  5667. (end (org-list-get-bottom-point struct)))
  5668. (dolist (e (org-list-get-all-items (point) struct prevs))
  5669. (org-list-set-item-visibility e struct 'folded))
  5670. (goto-char (if (< end eos) end eos)))))))
  5671. (org-unlogged-message "CHILDREN")
  5672. (save-excursion
  5673. (goto-char eos)
  5674. (outline-next-heading)
  5675. (when (org-invisible-p) (org-flag-heading nil)))
  5676. (setq org-cycle-subtree-status 'children)
  5677. (unless (org-before-first-heading-p)
  5678. (run-hook-with-args 'org-cycle-hook 'children)))
  5679. ((or children-skipped
  5680. (and (eq last-command this-command)
  5681. (eq org-cycle-subtree-status 'children)))
  5682. ;; We just showed the children, or no children are there,
  5683. ;; now show everything.
  5684. (unless (org-before-first-heading-p)
  5685. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5686. (org-flag-region eoh eos nil 'outline)
  5687. (org-unlogged-message
  5688. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5689. (setq org-cycle-subtree-status 'subtree)
  5690. (unless (org-before-first-heading-p)
  5691. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5692. (t
  5693. ;; Default action: hide the subtree.
  5694. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5695. (org-flag-region eoh eos t 'outline)
  5696. (org-unlogged-message "FOLDED")
  5697. (setq org-cycle-subtree-status 'folded)
  5698. (unless (org-before-first-heading-p)
  5699. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5700. ;;;###autoload
  5701. (defun org-global-cycle (&optional arg)
  5702. "Cycle the global visibility. For details see `org-cycle'.
  5703. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5704. With a numeric prefix, show all headlines up to that level."
  5705. (interactive "P")
  5706. (let ((org-cycle-include-plain-lists
  5707. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5708. (cond
  5709. ((integerp arg)
  5710. (org-show-all '(headings blocks))
  5711. (outline-hide-sublevels arg)
  5712. (setq org-cycle-global-status 'contents))
  5713. ((equal arg '(4))
  5714. (org-set-startup-visibility)
  5715. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5716. (t
  5717. (org-cycle '(4))))))
  5718. (defun org-set-startup-visibility ()
  5719. "Set the visibility required by startup options and properties."
  5720. (cond
  5721. ((eq org-startup-folded t)
  5722. (org-overview))
  5723. ((eq org-startup-folded 'content)
  5724. (org-content))
  5725. ((or (eq org-startup-folded 'showeverything)
  5726. (eq org-startup-folded nil))
  5727. (org-show-all)))
  5728. (unless (eq org-startup-folded 'showeverything)
  5729. (when org-hide-block-startup (org-hide-block-all))
  5730. (org-set-visibility-according-to-property)
  5731. (org-cycle-hide-archived-subtrees 'all)
  5732. (org-cycle-hide-drawers 'all)
  5733. (org-cycle-show-empty-lines t)))
  5734. (defun org-set-visibility-according-to-property ()
  5735. "Switch subtree visibility according to VISIBILITY property."
  5736. (interactive)
  5737. (let ((regexp (org-re-property "VISIBILITY")))
  5738. (org-with-point-at 1
  5739. (while (re-search-forward regexp nil t)
  5740. (let ((state (match-string 3)))
  5741. (if (not (org-at-property-p)) (outline-next-heading)
  5742. (save-excursion
  5743. (org-back-to-heading t)
  5744. (org-flag-subtree t)
  5745. (org-reveal)
  5746. (pcase state
  5747. ("folded"
  5748. (org-flag-subtree t))
  5749. ("children"
  5750. (org-show-hidden-entry)
  5751. (org-show-children))
  5752. ("content"
  5753. (save-excursion
  5754. (save-restriction
  5755. (org-narrow-to-subtree)
  5756. (org-content))))
  5757. ((or "all" "showall")
  5758. (outline-show-subtree))
  5759. (_ nil)))
  5760. (org-end-of-subtree)))))))
  5761. (defun org-overview ()
  5762. "Switch to overview mode, showing only top-level headlines.
  5763. This shows all headlines with a level equal or greater than the level
  5764. of the first headline in the buffer. This is important, because if the
  5765. first headline is not level one, then (hide-sublevels 1) gives confusing
  5766. results."
  5767. (interactive)
  5768. (save-excursion
  5769. (let ((level
  5770. (save-excursion
  5771. (goto-char (point-min))
  5772. (when (re-search-forward org-outline-regexp-bol nil t)
  5773. (goto-char (match-beginning 0))
  5774. (funcall outline-level)))))
  5775. (and level (outline-hide-sublevels level)))))
  5776. (defun org-content (&optional arg)
  5777. "Show all headlines in the buffer, like a table of contents.
  5778. With numerical argument N, show content up to level N."
  5779. (interactive "P")
  5780. (org-overview)
  5781. (save-excursion
  5782. ;; Visit all headings and show their offspring
  5783. (and (integerp arg) (org-overview))
  5784. (goto-char (point-max))
  5785. (catch 'exit
  5786. (while (and (progn (condition-case nil
  5787. (outline-previous-visible-heading 1)
  5788. (error (goto-char (point-min))))
  5789. t)
  5790. (looking-at org-outline-regexp))
  5791. (if (integerp arg)
  5792. (org-show-children (1- arg))
  5793. (outline-show-branches))
  5794. (when (bobp) (throw 'exit nil))))))
  5795. (defun org-optimize-window-after-visibility-change (state)
  5796. "Adjust the window after a change in outline visibility.
  5797. This function is the default value of the hook `org-cycle-hook'."
  5798. (when (get-buffer-window (current-buffer))
  5799. (cond
  5800. ((eq state 'content) nil)
  5801. ((eq state 'all) nil)
  5802. ((eq state 'folded) nil)
  5803. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5804. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5805. (defun org-clean-visibility-after-subtree-move ()
  5806. "Fix visibility issues after moving a subtree."
  5807. ;; First, find a reasonable region to look at:
  5808. ;; Start two siblings above, end three below
  5809. (let* ((beg (save-excursion
  5810. (and (org-get-last-sibling)
  5811. (org-get-last-sibling))
  5812. (point)))
  5813. (end (save-excursion
  5814. (and (org-get-next-sibling)
  5815. (org-get-next-sibling)
  5816. (org-get-next-sibling))
  5817. (if (org-at-heading-p)
  5818. (point-at-eol)
  5819. (point))))
  5820. (level (looking-at "\\*+"))
  5821. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5822. (save-excursion
  5823. (save-restriction
  5824. (narrow-to-region beg end)
  5825. (when re
  5826. ;; Properly fold already folded siblings
  5827. (goto-char (point-min))
  5828. (while (re-search-forward re nil t)
  5829. (when (and (not (org-invisible-p))
  5830. (org-invisible-p (line-end-position)))
  5831. (outline-hide-entry))))
  5832. (org-cycle-hide-drawers 'all)
  5833. (org-cycle-show-empty-lines 'overview)))))
  5834. (defun org-cycle-show-empty-lines (state)
  5835. "Show empty lines above all visible headlines.
  5836. The region to be covered depends on STATE when called through
  5837. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5838. entire buffer covered. Note that an empty line is only shown if there
  5839. are at least `org-cycle-separator-lines' empty lines before the headline."
  5840. (when (/= org-cycle-separator-lines 0)
  5841. (save-excursion
  5842. (let* ((n (abs org-cycle-separator-lines))
  5843. (re (cond
  5844. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5845. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5846. (t (let ((ns (number-to-string (- n 2))))
  5847. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5848. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5849. beg end)
  5850. (cond
  5851. ((memq state '(overview contents t))
  5852. (setq beg (point-min) end (point-max)))
  5853. ((memq state '(children folded))
  5854. (setq beg (point)
  5855. end (progn (org-end-of-subtree t t)
  5856. (line-beginning-position 2)))))
  5857. (when beg
  5858. (goto-char beg)
  5859. (while (re-search-forward re end t)
  5860. (unless (get-char-property (match-end 1) 'invisible)
  5861. (let ((e (match-end 1))
  5862. (b (if (>= org-cycle-separator-lines 0)
  5863. (match-beginning 1)
  5864. (save-excursion
  5865. (goto-char (match-beginning 0))
  5866. (skip-chars-backward " \t\n")
  5867. (line-end-position)))))
  5868. (org-flag-region b e nil 'outline))))))))
  5869. ;; Never hide empty lines at the end of the file.
  5870. (save-excursion
  5871. (goto-char (point-max))
  5872. (outline-previous-heading)
  5873. (outline-end-of-heading)
  5874. (when (and (looking-at "[ \t\n]+")
  5875. (= (match-end 0) (point-max)))
  5876. (org-flag-region (point) (match-end 0) nil 'outline))))
  5877. ;;;; Reveal point location
  5878. (defun org-show-context (&optional key)
  5879. "Make sure point and context are visible.
  5880. Optional argument KEY, when non-nil, is a symbol. See
  5881. `org-show-context-detail' for allowed values and how much is to
  5882. be shown."
  5883. (org-show-set-visibility
  5884. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5885. ((cdr (assq key org-show-context-detail)))
  5886. (t (cdr (assq 'default org-show-context-detail))))))
  5887. (defun org-show-set-visibility (detail)
  5888. "Set visibility around point according to DETAIL.
  5889. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5890. `tree', `canonical' or t. See `org-show-context-detail' for more
  5891. information."
  5892. ;; Show current heading and possibly its entry, following headline
  5893. ;; or all children.
  5894. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5895. (org-flag-heading nil)
  5896. (org-show-entry)
  5897. ;; If point is hidden within a drawer or a block, make sure to
  5898. ;; expose it.
  5899. (dolist (o (overlays-at (point)))
  5900. (when (memq (overlay-get o 'invisible)
  5901. '(org-hide-block org-hide-drawer outline))
  5902. (delete-overlay o)))
  5903. (unless (org-before-first-heading-p)
  5904. (org-with-limited-levels
  5905. (cl-case detail
  5906. ((tree canonical t) (org-show-children))
  5907. ((nil minimal ancestors))
  5908. (t (save-excursion
  5909. (outline-next-heading)
  5910. (org-flag-heading nil)))))))
  5911. ;; Show all siblings.
  5912. (when (eq detail 'lineage) (org-show-siblings))
  5913. ;; Show ancestors, possibly with their children.
  5914. (when (memq detail '(ancestors lineage tree canonical t))
  5915. (save-excursion
  5916. (while (org-up-heading-safe)
  5917. (org-flag-heading nil)
  5918. (when (memq detail '(canonical t)) (org-show-entry))
  5919. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5920. (defvar org-reveal-start-hook nil
  5921. "Hook run before revealing a location.")
  5922. (defun org-reveal (&optional siblings)
  5923. "Show current entry, hierarchy above it, and the following headline.
  5924. This can be used to show a consistent set of context around
  5925. locations exposed with `org-show-context'.
  5926. With optional argument SIBLINGS, on each level of the hierarchy all
  5927. siblings are shown. This repairs the tree structure to what it would
  5928. look like when opened with hierarchical calls to `org-cycle'.
  5929. With a \\[universal-argument] \\[universal-argument] prefix, \
  5930. go to the parent and show the entire tree."
  5931. (interactive "P")
  5932. (run-hooks 'org-reveal-start-hook)
  5933. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5934. ((equal siblings '(16))
  5935. (save-excursion
  5936. (when (org-up-heading-safe)
  5937. (org-show-subtree)
  5938. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5939. (t (org-show-set-visibility 'lineage))))
  5940. ;;; Indirect buffer display of subtrees
  5941. (defvar org-indirect-dedicated-frame nil
  5942. "This is the frame being used for indirect tree display.")
  5943. (defvar org-last-indirect-buffer nil)
  5944. (defun org-tree-to-indirect-buffer (&optional arg)
  5945. "Create indirect buffer and narrow it to current subtree.
  5946. With a numerical prefix ARG, go up to this level and then take that tree.
  5947. If ARG is negative, go up that many levels.
  5948. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5949. indirect buffer previously made with this command, to avoid proliferation of
  5950. indirect buffers. However, when you call the command with a \
  5951. `\\[universal-argument]' prefix, or
  5952. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5953. so that you can work with several indirect buffers at the same time. If
  5954. `org-indirect-buffer-display' is `dedicated-frame', the \
  5955. `\\[universal-argument]' prefix also
  5956. requests that a new frame be made for the new buffer, so that the dedicated
  5957. frame is not changed."
  5958. (interactive "P")
  5959. (let ((cbuf (current-buffer))
  5960. (cwin (selected-window))
  5961. (pos (point))
  5962. beg end level heading ibuf)
  5963. (save-excursion
  5964. (org-back-to-heading t)
  5965. (when (numberp arg)
  5966. (setq level (org-outline-level))
  5967. (when (< arg 0) (setq arg (+ level arg)))
  5968. (while (> (setq level (org-outline-level)) arg)
  5969. (org-up-heading-safe)))
  5970. (setq beg (point)
  5971. heading (org-get-heading 'no-tags))
  5972. (org-end-of-subtree t t)
  5973. (when (org-at-heading-p) (backward-char 1))
  5974. (setq end (point)))
  5975. (when (and (buffer-live-p org-last-indirect-buffer)
  5976. (not (eq org-indirect-buffer-display 'new-frame))
  5977. (not arg))
  5978. (kill-buffer org-last-indirect-buffer))
  5979. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5980. org-last-indirect-buffer ibuf)
  5981. (cond
  5982. ((or (eq org-indirect-buffer-display 'new-frame)
  5983. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5984. (select-frame (make-frame))
  5985. (delete-other-windows)
  5986. (pop-to-buffer-same-window ibuf)
  5987. (org-set-frame-title heading))
  5988. ((eq org-indirect-buffer-display 'dedicated-frame)
  5989. (raise-frame
  5990. (select-frame (or (and org-indirect-dedicated-frame
  5991. (frame-live-p org-indirect-dedicated-frame)
  5992. org-indirect-dedicated-frame)
  5993. (setq org-indirect-dedicated-frame (make-frame)))))
  5994. (delete-other-windows)
  5995. (pop-to-buffer-same-window ibuf)
  5996. (org-set-frame-title (concat "Indirect: " heading)))
  5997. ((eq org-indirect-buffer-display 'current-window)
  5998. (pop-to-buffer-same-window ibuf))
  5999. ((eq org-indirect-buffer-display 'other-window)
  6000. (pop-to-buffer ibuf))
  6001. (t (error "Invalid value")))
  6002. (narrow-to-region beg end)
  6003. (org-show-all '(headings blocks))
  6004. (goto-char pos)
  6005. (run-hook-with-args 'org-cycle-hook 'all)
  6006. (and (window-live-p cwin) (select-window cwin))))
  6007. (defun org-get-indirect-buffer (&optional buffer heading)
  6008. (setq buffer (or buffer (current-buffer)))
  6009. (let ((n 1) (base (buffer-name buffer)) bname)
  6010. (while (buffer-live-p
  6011. (get-buffer
  6012. (setq bname
  6013. (concat base "-"
  6014. (if heading (concat heading "-" (number-to-string n))
  6015. (number-to-string n))))))
  6016. (setq n (1+ n)))
  6017. (condition-case nil
  6018. (make-indirect-buffer buffer bname 'clone)
  6019. (error (make-indirect-buffer buffer bname)))))
  6020. (defun org-set-frame-title (title)
  6021. "Set the title of the current frame to the string TITLE."
  6022. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6023. ;;;; Structure editing
  6024. ;;; Inserting headlines
  6025. (defun org--line-empty-p (n)
  6026. "Is the Nth next line empty?
  6027. Counts the current line as N = 1 and the previous line as N = 0;
  6028. see `beginning-of-line'."
  6029. (save-excursion
  6030. (and (not (bobp))
  6031. (or (beginning-of-line n) t)
  6032. (save-match-data
  6033. (looking-at "[ \t]*$")))))
  6034. (defun org-previous-line-empty-p ()
  6035. "Is the previous line a blank line?
  6036. When NEXT is non-nil, check the next line instead."
  6037. (org--line-empty-p 0))
  6038. (defun org-next-line-empty-p ()
  6039. "Is the previous line a blank line?
  6040. When NEXT is non-nil, check the next line instead."
  6041. (org--line-empty-p 2))
  6042. (defun org--blank-before-heading-p (&optional parent)
  6043. "Non-nil when an empty line should precede a new heading here.
  6044. When optional argument PARENT is non-nil, consider parent
  6045. headline instead of current one."
  6046. (pcase (assq 'heading org-blank-before-new-entry)
  6047. (`(heading . auto)
  6048. (save-excursion
  6049. (org-with-limited-levels
  6050. (unless (and (org-before-first-heading-p)
  6051. (not (outline-next-heading)))
  6052. (org-back-to-heading t)
  6053. (when parent (org-up-heading-safe))
  6054. (cond ((not (bobp))
  6055. (org-previous-line-empty-p))
  6056. ((outline-next-heading)
  6057. (org-previous-line-empty-p))
  6058. ;; Ignore trailing spaces on last buffer line.
  6059. ((progn (skip-chars-backward " \t") (bolp))
  6060. (org-previous-line-empty-p))
  6061. (t nil))))))
  6062. (`(heading . ,value) value)
  6063. (_ nil)))
  6064. (defun org-insert-heading (&optional arg invisible-ok top)
  6065. "Insert a new heading or an item with the same depth at point.
  6066. If point is at the beginning of a heading, insert a new heading
  6067. or a new headline above the current one. When at the beginning
  6068. of a regular line of text, turn it into a heading.
  6069. If point is in the middle of a line, split it and create a new
  6070. headline with the text in the current line after point (see
  6071. `org-M-RET-may-split-line' on how to modify this behavior). As
  6072. a special case, on a headline, splitting can only happen on the
  6073. title itself. E.g., this excludes breaking stars or tags.
  6074. With a `\\[universal-argument]' prefix, set \
  6075. `org-insert-heading-respect-content' to
  6076. a non-nil value for the duration of the command. This forces the
  6077. insertion of a heading after the current subtree, independently
  6078. on the location of point.
  6079. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6080. insert the heading at the end of the tree
  6081. above the current heading. For example, if point is within a
  6082. 2nd-level heading, then it will insert a 2nd-level heading at
  6083. the end of the 1st-level parent subtree.
  6084. When INVISIBLE-OK is set, stop at invisible headlines when going
  6085. back. This is important for non-interactive uses of the
  6086. command.
  6087. When optional argument TOP is non-nil, insert a level 1 heading,
  6088. unconditionally."
  6089. (interactive "P")
  6090. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6091. (level (org-current-level))
  6092. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6093. (cond
  6094. ((or org-insert-heading-respect-content
  6095. (member arg '((4) (16)))
  6096. (and (not invisible-ok)
  6097. (invisible-p (max (1- (point)) (point-min)))))
  6098. ;; Position point at the location of insertion. Make sure we
  6099. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6100. (org-with-limited-levels
  6101. (if (not level) (outline-next-heading) ;before first headline
  6102. (org-back-to-heading invisible-ok)
  6103. (when (equal arg '(16)) (org-up-heading-safe))
  6104. (org-end-of-subtree)))
  6105. (unless (bolp) (insert "\n"))
  6106. (unless (and blank? (org-previous-line-empty-p))
  6107. (org-N-empty-lines-before-current (if blank? 1 0)))
  6108. (insert stars " ")
  6109. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6110. ;; is visible.
  6111. (unless invisible-ok
  6112. (pcase (get-char-property-and-overlay (point) 'invisible)
  6113. (`(outline . ,o)
  6114. (move-overlay o (overlay-start o) (line-end-position 0)))
  6115. (_ nil))))
  6116. ;; At a headline...
  6117. ((org-at-heading-p)
  6118. (cond ((bolp)
  6119. (when blank? (save-excursion (insert "\n")))
  6120. (save-excursion (insert stars " \n"))
  6121. (unless (and blank? (org-previous-line-empty-p))
  6122. (org-N-empty-lines-before-current (if blank? 1 0)))
  6123. (end-of-line))
  6124. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6125. (org-match-line org-complex-heading-regexp)
  6126. (org-pos-in-match-range (point) 4))
  6127. ;; Grab the text that should moved to the new headline.
  6128. ;; Preserve tags.
  6129. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6130. (if (looking-at "[ \t]*$") (replace-match "")
  6131. (org-align-tags))
  6132. (end-of-line)
  6133. (when blank? (insert "\n"))
  6134. (insert "\n" stars " ")
  6135. (when (org-string-nw-p split) (insert split))))
  6136. (t
  6137. (end-of-line)
  6138. (when blank? (insert "\n"))
  6139. (insert "\n" stars " "))))
  6140. ;; On regular text, turn line into a headline or split, if
  6141. ;; appropriate.
  6142. ((bolp)
  6143. (insert stars " ")
  6144. (unless (and blank? (org-previous-line-empty-p))
  6145. (org-N-empty-lines-before-current (if blank? 1 0))))
  6146. (t
  6147. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6148. (end-of-line))
  6149. (insert "\n" stars " ")
  6150. (unless (and blank? (org-previous-line-empty-p))
  6151. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6152. (run-hooks 'org-insert-heading-hook))
  6153. (defun org-N-empty-lines-before-current (n)
  6154. "Make the number of empty lines before current exactly N.
  6155. So this will delete or add empty lines."
  6156. (let ((column (current-column)))
  6157. (beginning-of-line)
  6158. (unless (bobp)
  6159. (let ((start (save-excursion
  6160. (skip-chars-backward " \r\t\n")
  6161. (line-end-position))))
  6162. (delete-region start (line-end-position 0))))
  6163. (insert (make-string n ?\n))
  6164. (move-to-column column)))
  6165. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6166. "Return the heading of the current entry, without the stars.
  6167. When NO-TAGS is non-nil, don't include tags.
  6168. When NO-TODO is non-nil, don't include TODO keywords.
  6169. When NO-PRIORITY is non-nil, don't include priority cookie.
  6170. When NO-COMMENT is non-nil, don't include COMMENT string.
  6171. Return nil before first heading."
  6172. (unless (org-before-first-heading-p)
  6173. (save-excursion
  6174. (org-back-to-heading t)
  6175. (let ((case-fold-search nil))
  6176. (looking-at org-complex-heading-regexp)
  6177. (let ((todo (and (not no-todo) (match-string 2)))
  6178. (priority (and (not no-priority) (match-string 3)))
  6179. (headline (pcase (match-string 4)
  6180. (`nil "")
  6181. ((and (guard no-comment) h)
  6182. (replace-regexp-in-string
  6183. (eval-when-compile
  6184. (format "\\`%s[ \t]+" org-comment-string))
  6185. "" h))
  6186. (h h)))
  6187. (tags (and (not no-tags) (match-string 5))))
  6188. (mapconcat #'identity
  6189. (delq nil (list todo priority headline tags))
  6190. " "))))))
  6191. (defun org-heading-components ()
  6192. "Return the components of the current heading.
  6193. This is a list with the following elements:
  6194. - the level as an integer
  6195. - the reduced level, different if `org-odd-levels-only' is set.
  6196. - the TODO keyword, or nil
  6197. - the priority character, like ?A, or nil if no priority is given
  6198. - the headline text itself, or the tags string if no headline text
  6199. - the tags string, or nil."
  6200. (save-excursion
  6201. (org-back-to-heading t)
  6202. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6203. (list (length (match-string 1))
  6204. (org-reduced-level (length (match-string 1)))
  6205. (match-string-no-properties 2)
  6206. (and (match-end 3) (aref (match-string 3) 2))
  6207. (match-string-no-properties 4)
  6208. (match-string-no-properties 5)))))
  6209. (defun org-get-entry ()
  6210. "Get the entry text, after heading, entire subtree."
  6211. (save-excursion
  6212. (org-back-to-heading t)
  6213. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6214. (defun org-edit-headline (&optional heading)
  6215. "Edit the current headline.
  6216. Set it to HEADING when provided."
  6217. (interactive)
  6218. (org-with-wide-buffer
  6219. (org-back-to-heading t)
  6220. (let ((case-fold-search nil))
  6221. (when (looking-at org-complex-heading-regexp)
  6222. (let* ((old (match-string-no-properties 4))
  6223. (new (save-match-data
  6224. (org-trim (or heading (read-string "Edit: " old))))))
  6225. (unless (equal old new)
  6226. (if old (replace-match new t t nil 4)
  6227. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6228. (insert " " new))
  6229. (org-align-tags)
  6230. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6231. (defun org-insert-heading-after-current ()
  6232. "Insert a new heading with same level as current, after current subtree."
  6233. (interactive)
  6234. (org-back-to-heading)
  6235. (org-insert-heading)
  6236. (org-move-subtree-down)
  6237. (end-of-line 1))
  6238. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6239. "Insert heading with `org-insert-heading-respect-content' set to t."
  6240. (interactive)
  6241. (org-insert-heading '(4) invisible-ok))
  6242. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6243. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6244. (interactive)
  6245. (org-insert-todo-heading force-state '(4)))
  6246. (defun org-insert-todo-heading (arg &optional force-heading)
  6247. "Insert a new heading with the same level and TODO state as current heading.
  6248. If the heading has no TODO state, or if the state is DONE, use
  6249. the first state (TODO by default). Also with one prefix arg,
  6250. force first state. With two prefix args, force inserting at the
  6251. end of the parent subtree.
  6252. When called at a plain list item, insert a new item with an
  6253. unchecked check box."
  6254. (interactive "P")
  6255. (when (or force-heading (not (org-insert-item 'checkbox)))
  6256. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6257. force-heading))
  6258. (save-excursion
  6259. (org-forward-heading-same-level -1)
  6260. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6261. (let* ((new-mark-x
  6262. (if (or (equal arg '(4))
  6263. (not (match-beginning 2))
  6264. (member (match-string 2) org-done-keywords))
  6265. (car org-todo-keywords-1)
  6266. (match-string 2)))
  6267. (new-mark
  6268. (or
  6269. (run-hook-with-args-until-success
  6270. 'org-todo-get-default-hook new-mark-x nil)
  6271. new-mark-x)))
  6272. (beginning-of-line 1)
  6273. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6274. (if org-treat-insert-todo-heading-as-state-change
  6275. (org-todo new-mark)
  6276. (insert new-mark " "))))
  6277. (when org-provide-todo-statistics
  6278. (org-update-parent-todo-statistics))))
  6279. (defun org-insert-subheading (arg)
  6280. "Insert a new subheading and demote it.
  6281. Works for outline headings and for plain lists alike."
  6282. (interactive "P")
  6283. (org-insert-heading arg)
  6284. (cond
  6285. ((org-at-heading-p) (org-do-demote))
  6286. ((org-at-item-p) (org-indent-item))))
  6287. (defun org-insert-todo-subheading (arg)
  6288. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6289. Works for outline headings and for plain lists alike."
  6290. (interactive "P")
  6291. (org-insert-todo-heading arg)
  6292. (cond
  6293. ((org-at-heading-p) (org-do-demote))
  6294. ((org-at-item-p) (org-indent-item))))
  6295. ;;; Promotion and Demotion
  6296. (defvar org-after-demote-entry-hook nil
  6297. "Hook run after an entry has been demoted.
  6298. The cursor will be at the beginning of the entry.
  6299. When a subtree is being demoted, the hook will be called for each node.")
  6300. (defvar org-after-promote-entry-hook nil
  6301. "Hook run after an entry has been promoted.
  6302. The cursor will be at the beginning of the entry.
  6303. When a subtree is being promoted, the hook will be called for each node.")
  6304. (defun org-promote-subtree ()
  6305. "Promote the entire subtree.
  6306. See also `org-promote'."
  6307. (interactive)
  6308. (save-excursion
  6309. (org-with-limited-levels (org-map-tree 'org-promote)))
  6310. (org-fix-position-after-promote))
  6311. (defun org-demote-subtree ()
  6312. "Demote the entire subtree.
  6313. See `org-demote' and `org-promote'."
  6314. (interactive)
  6315. (save-excursion
  6316. (org-with-limited-levels (org-map-tree 'org-demote)))
  6317. (org-fix-position-after-promote))
  6318. (defun org-do-promote ()
  6319. "Promote the current heading higher up the tree.
  6320. If the region is active in `transient-mark-mode', promote all
  6321. headings in the region."
  6322. (interactive)
  6323. (save-excursion
  6324. (if (org-region-active-p)
  6325. (org-map-region 'org-promote (region-beginning) (region-end))
  6326. (org-promote)))
  6327. (org-fix-position-after-promote))
  6328. (defun org-do-demote ()
  6329. "Demote the current heading lower down the tree.
  6330. If the region is active in `transient-mark-mode', demote all
  6331. headings in the region."
  6332. (interactive)
  6333. (save-excursion
  6334. (if (org-region-active-p)
  6335. (org-map-region 'org-demote (region-beginning) (region-end))
  6336. (org-demote)))
  6337. (org-fix-position-after-promote))
  6338. (defun org-fix-position-after-promote ()
  6339. "Fix cursor position and indentation after demoting/promoting."
  6340. (let ((pos (point)))
  6341. (when (save-excursion
  6342. (beginning-of-line)
  6343. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6344. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6345. (cond ((eobp) (insert " "))
  6346. ((eolp) (insert " "))
  6347. ((equal (char-after) ?\s) (forward-char 1))))))
  6348. (defun org-current-level ()
  6349. "Return the level of the current entry, or nil if before the first headline.
  6350. The level is the number of stars at the beginning of the
  6351. headline. Use `org-reduced-level' to remove the effect of
  6352. `org-odd-levels'. Unlike to `org-outline-level', this function
  6353. ignores inlinetasks."
  6354. (let ((level (org-with-limited-levels (org-outline-level))))
  6355. (and (> level 0) level)))
  6356. (defun org-get-previous-line-level ()
  6357. "Return the outline depth of the last headline before the current line.
  6358. Returns 0 for the first headline in the buffer, and nil if before the
  6359. first headline."
  6360. (and (org-current-level)
  6361. (or (and (/= (line-beginning-position) (point-min))
  6362. (save-excursion (beginning-of-line 0) (org-current-level)))
  6363. 0)))
  6364. (defun org-reduced-level (l)
  6365. "Compute the effective level of a heading.
  6366. This takes into account the setting of `org-odd-levels-only'."
  6367. (cond
  6368. ((zerop l) 0)
  6369. (org-odd-levels-only (1+ (floor (/ l 2))))
  6370. (t l)))
  6371. (defun org-level-increment ()
  6372. "Return the number of stars that will be added or removed at a
  6373. time to headlines when structure editing, based on the value of
  6374. `org-odd-levels-only'."
  6375. (if org-odd-levels-only 2 1))
  6376. (defun org-get-valid-level (level &optional change)
  6377. "Rectify a level change under the influence of `org-odd-levels-only'.
  6378. LEVEL is a current level, CHANGE is by how much the level should
  6379. be modified. Even if CHANGE is nil, LEVEL may be returned
  6380. modified because even level numbers will become the next higher
  6381. odd number. Returns values greater than 0."
  6382. (if org-odd-levels-only
  6383. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6384. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6385. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6386. (max 1 (+ level (or change 0)))))
  6387. (defun org-promote ()
  6388. "Promote the current heading higher up the tree."
  6389. (org-with-wide-buffer
  6390. (org-back-to-heading t)
  6391. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6392. after-change-functions))
  6393. (level (save-match-data (funcall outline-level)))
  6394. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6395. (diff (abs (- level (length up-head) -1))))
  6396. (cond
  6397. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6398. (replace-match "# " nil t))
  6399. ((= level 1)
  6400. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6401. (t (replace-match up-head nil t)))
  6402. (unless (= level 1)
  6403. (when org-auto-align-tags (org-align-tags))
  6404. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6405. (run-hooks 'org-after-promote-entry-hook))))
  6406. (defun org-demote ()
  6407. "Demote the current heading lower down the tree."
  6408. (org-with-wide-buffer
  6409. (org-back-to-heading t)
  6410. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6411. after-change-functions))
  6412. (level (save-match-data (funcall outline-level)))
  6413. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6414. (diff (abs (- level (length down-head) -1))))
  6415. (replace-match down-head nil t)
  6416. (when org-auto-align-tags (org-align-tags))
  6417. (when org-adapt-indentation (org-fixup-indentation diff))
  6418. (run-hooks 'org-after-demote-entry-hook))))
  6419. (defun org-cycle-level ()
  6420. "Cycle the level of an empty headline through possible states.
  6421. This goes first to child, then to parent, level, then up the hierarchy.
  6422. After top level, it switches back to sibling level."
  6423. (interactive)
  6424. (let ((org-adapt-indentation nil))
  6425. (when (org-point-at-end-of-empty-headline)
  6426. (setq this-command 'org-cycle-level) ; Only needed for caching
  6427. (let ((cur-level (org-current-level))
  6428. (prev-level (org-get-previous-line-level)))
  6429. (cond
  6430. ;; If first headline in file, promote to top-level.
  6431. ((= prev-level 0)
  6432. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6433. do (org-do-promote)))
  6434. ;; If same level as prev, demote one.
  6435. ((= prev-level cur-level)
  6436. (org-do-demote))
  6437. ;; If parent is top-level, promote to top level if not already.
  6438. ((= prev-level 1)
  6439. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6440. do (org-do-promote)))
  6441. ;; If top-level, return to prev-level.
  6442. ((= cur-level 1)
  6443. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6444. do (org-do-demote)))
  6445. ;; If less than prev-level, promote one.
  6446. ((< cur-level prev-level)
  6447. (org-do-promote))
  6448. ;; If deeper than prev-level, promote until higher than
  6449. ;; prev-level.
  6450. ((> cur-level prev-level)
  6451. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6452. do (org-do-promote))))
  6453. t))))
  6454. (defun org-map-tree (fun)
  6455. "Call FUN for every heading underneath the current one."
  6456. (org-back-to-heading t)
  6457. (let ((level (funcall outline-level)))
  6458. (save-excursion
  6459. (funcall fun)
  6460. (while (and (progn
  6461. (outline-next-heading)
  6462. (> (funcall outline-level) level))
  6463. (not (eobp)))
  6464. (funcall fun)))))
  6465. (defun org-map-region (fun beg end)
  6466. "Call FUN for every heading between BEG and END."
  6467. (let ((org-ignore-region t))
  6468. (save-excursion
  6469. (setq end (copy-marker end))
  6470. (goto-char beg)
  6471. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6472. (< (point) end))
  6473. (funcall fun))
  6474. (while (and (progn
  6475. (outline-next-heading)
  6476. (< (point) end))
  6477. (not (eobp)))
  6478. (funcall fun)))))
  6479. (defun org-fixup-indentation (diff)
  6480. "Change the indentation in the current entry by DIFF.
  6481. DIFF is an integer. Indentation is done according to the
  6482. following rules:
  6483. - Planning information and property drawers are always indented
  6484. according to the new level of the headline;
  6485. - Footnote definitions and their contents are ignored;
  6486. - Inlinetasks' boundaries are not shifted;
  6487. - Empty lines are ignored;
  6488. - Other lines' indentation are shifted by DIFF columns, unless
  6489. it would introduce a structural change in the document, in
  6490. which case no shifting is done at all.
  6491. Assume point is at a heading or an inlinetask beginning."
  6492. (org-with-wide-buffer
  6493. (narrow-to-region (line-beginning-position)
  6494. (save-excursion
  6495. (if (org-with-limited-levels (org-at-heading-p))
  6496. (org-with-limited-levels (outline-next-heading))
  6497. (org-inlinetask-goto-end))
  6498. (point)))
  6499. (forward-line)
  6500. ;; Indent properly planning info and property drawer.
  6501. (when (looking-at-p org-planning-line-re)
  6502. (org-indent-line)
  6503. (forward-line))
  6504. (when (looking-at org-property-drawer-re)
  6505. (goto-char (match-end 0))
  6506. (forward-line)
  6507. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6508. (catch 'no-shift
  6509. (when (zerop diff) (throw 'no-shift nil))
  6510. ;; If DIFF is negative, first check if a shift is possible at all
  6511. ;; (e.g., it doesn't break structure). This can only happen if
  6512. ;; some contents are not properly indented.
  6513. (let ((case-fold-search t))
  6514. (when (< diff 0)
  6515. (let ((diff (- diff))
  6516. (forbidden-re (concat org-outline-regexp
  6517. "\\|"
  6518. (substring org-footnote-definition-re 1))))
  6519. (save-excursion
  6520. (while (not (eobp))
  6521. (cond
  6522. ((looking-at-p "[ \t]*$") (forward-line))
  6523. ((and (looking-at-p org-footnote-definition-re)
  6524. (let ((e (org-element-at-point)))
  6525. (and (eq (org-element-type e) 'footnote-definition)
  6526. (goto-char (org-element-property :end e))))))
  6527. ((looking-at-p org-outline-regexp) (forward-line))
  6528. ;; Give up if shifting would move before column 0 or
  6529. ;; if it would introduce a headline or a footnote
  6530. ;; definition.
  6531. (t
  6532. (skip-chars-forward " \t")
  6533. (let ((ind (current-column)))
  6534. (when (or (< ind diff)
  6535. (and (= ind diff) (looking-at-p forbidden-re)))
  6536. (throw 'no-shift nil)))
  6537. ;; Ignore contents of example blocks and source
  6538. ;; blocks if their indentation is meant to be
  6539. ;; preserved. Jump to block's closing line.
  6540. (beginning-of-line)
  6541. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6542. (let ((e (org-element-at-point)))
  6543. (and (memq (org-element-type e)
  6544. '(example-block src-block))
  6545. (or org-src-preserve-indentation
  6546. (org-element-property :preserve-indent e))
  6547. (goto-char (org-element-property :end e))
  6548. (progn (skip-chars-backward " \r\t\n")
  6549. (beginning-of-line)
  6550. t))))
  6551. (forward-line))))))))
  6552. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6553. ;; by DIFF. Also skip contents of source or example blocks
  6554. ;; when indentation is meant to be preserved.
  6555. (while (not (eobp))
  6556. (cond
  6557. ((and (looking-at-p org-footnote-definition-re)
  6558. (let ((e (org-element-at-point)))
  6559. (and (eq (org-element-type e) 'footnote-definition)
  6560. (goto-char (org-element-property :end e))))))
  6561. ((looking-at-p org-outline-regexp) (forward-line))
  6562. ((looking-at-p "[ \t]*$") (forward-line))
  6563. (t
  6564. (indent-line-to (+ (current-indentation) diff))
  6565. (beginning-of-line)
  6566. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6567. (let ((e (org-element-at-point)))
  6568. (and (memq (org-element-type e)
  6569. '(example-block src-block))
  6570. (or org-src-preserve-indentation
  6571. (org-element-property :preserve-indent e))
  6572. (goto-char (org-element-property :end e))
  6573. (progn (skip-chars-backward " \r\t\n")
  6574. (beginning-of-line)
  6575. t))))
  6576. (forward-line)))))))))
  6577. (defun org-convert-to-odd-levels ()
  6578. "Convert an Org file with all levels allowed to one with odd levels.
  6579. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6580. level 5 etc."
  6581. (interactive)
  6582. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6583. (let ((outline-level 'org-outline-level)
  6584. (org-odd-levels-only nil) n)
  6585. (save-excursion
  6586. (goto-char (point-min))
  6587. (while (re-search-forward "^\\*\\*+ " nil t)
  6588. (setq n (- (length (match-string 0)) 2))
  6589. (while (>= (setq n (1- n)) 0)
  6590. (org-demote))
  6591. (end-of-line 1))))))
  6592. (defun org-convert-to-oddeven-levels ()
  6593. "Convert an Org file with only odd levels to one with odd/even levels.
  6594. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6595. file contains a section with an even level, conversion would
  6596. destroy the structure of the file. An error is signaled in this
  6597. case."
  6598. (interactive)
  6599. (goto-char (point-min))
  6600. ;; First check if there are no even levels
  6601. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6602. (org-show-set-visibility 'canonical)
  6603. (error "Not all levels are odd in this file. Conversion not possible"))
  6604. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6605. (let ((outline-regexp org-outline-regexp)
  6606. (outline-level 'org-outline-level)
  6607. (org-odd-levels-only nil) n)
  6608. (save-excursion
  6609. (goto-char (point-min))
  6610. (while (re-search-forward "^\\*\\*+ " nil t)
  6611. (setq n (/ (1- (length (match-string 0))) 2))
  6612. (while (>= (setq n (1- n)) 0)
  6613. (org-promote))
  6614. (end-of-line 1))))))
  6615. (defun org-tr-level (n)
  6616. "Make N odd if required."
  6617. (if org-odd-levels-only (1+ (/ n 2)) n))
  6618. ;;; Vertical tree motion, cutting and pasting of subtrees
  6619. (defun org-move-subtree-up (&optional arg)
  6620. "Move the current subtree up past ARG headlines of the same level."
  6621. (interactive "p")
  6622. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6623. (defun org-move-subtree-down (&optional arg)
  6624. "Move the current subtree down past ARG headlines of the same level."
  6625. (interactive "p")
  6626. (setq arg (prefix-numeric-value arg))
  6627. (org-preserve-local-variables
  6628. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6629. 'org-get-last-sibling))
  6630. (ins-point (make-marker))
  6631. (cnt (abs arg))
  6632. (col (current-column))
  6633. beg end txt folded)
  6634. ;; Select the tree
  6635. (org-back-to-heading)
  6636. (setq beg (point))
  6637. (save-match-data
  6638. (save-excursion (outline-end-of-heading)
  6639. (setq folded (org-invisible-p)))
  6640. (progn (org-end-of-subtree nil t)
  6641. (unless (eobp) (backward-char))))
  6642. (outline-next-heading)
  6643. (setq end (point))
  6644. (goto-char beg)
  6645. ;; Find insertion point, with error handling
  6646. (while (> cnt 0)
  6647. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6648. (goto-char beg)
  6649. (user-error "Cannot move past superior level or buffer limit"))
  6650. (setq cnt (1- cnt)))
  6651. (when (> arg 0)
  6652. ;; Moving forward - still need to move over subtree
  6653. (org-end-of-subtree t t)
  6654. (save-excursion
  6655. (org-back-over-empty-lines)
  6656. (or (bolp) (newline))))
  6657. (move-marker ins-point (point))
  6658. (setq txt (buffer-substring beg end))
  6659. (org-save-markers-in-region beg end)
  6660. (delete-region beg end)
  6661. (org-remove-empty-overlays-at beg)
  6662. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6663. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6664. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6665. (let ((bbb (point)))
  6666. (insert-before-markers txt)
  6667. (org-reinstall-markers-in-region bbb)
  6668. (move-marker ins-point bbb))
  6669. (or (bolp) (insert "\n"))
  6670. (goto-char ins-point)
  6671. (org-skip-whitespace)
  6672. (move-marker ins-point nil)
  6673. (if folded
  6674. (org-flag-subtree t)
  6675. (org-show-entry)
  6676. (org-show-children))
  6677. (org-clean-visibility-after-subtree-move)
  6678. ;; move back to the initial column we were at
  6679. (move-to-column col))))
  6680. (defvar org-subtree-clip ""
  6681. "Clipboard for cut and paste of subtrees.
  6682. This is actually only a copy of the kill, because we use the normal kill
  6683. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6684. (defvar org-subtree-clip-folded nil
  6685. "Was the last copied subtree folded?
  6686. This is used to fold the tree back after pasting.")
  6687. (defun org-cut-subtree (&optional n)
  6688. "Cut the current subtree into the clipboard.
  6689. With prefix arg N, cut this many sequential subtrees.
  6690. This is a short-hand for marking the subtree and then cutting it."
  6691. (interactive "p")
  6692. (org-copy-subtree n 'cut))
  6693. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6694. "Copy the current subtree into the clipboard.
  6695. With prefix arg N, copy this many sequential subtrees.
  6696. This is a short-hand for marking the subtree and then copying it.
  6697. If CUT is non-nil, actually cut the subtree.
  6698. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6699. of some markers in the region, even if CUT is non-nil. This is
  6700. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6701. (interactive "p")
  6702. (org-preserve-local-variables
  6703. (let (beg end folded (beg0 (point)))
  6704. (if (called-interactively-p 'any)
  6705. (org-back-to-heading nil) ; take what looks like a subtree
  6706. (org-back-to-heading t)) ; take what is really there
  6707. (setq beg (point))
  6708. (skip-chars-forward " \t\r\n")
  6709. (save-match-data
  6710. (if nosubtrees
  6711. (outline-next-heading)
  6712. (save-excursion (outline-end-of-heading)
  6713. (setq folded (org-invisible-p)))
  6714. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6715. (org-end-of-subtree t t)))
  6716. ;; Include the end of an inlinetask
  6717. (when (and (featurep 'org-inlinetask)
  6718. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6719. "END[ \t]*$")))
  6720. (end-of-line))
  6721. (setq end (point))
  6722. (goto-char beg0)
  6723. (when (> end beg)
  6724. (setq org-subtree-clip-folded folded)
  6725. (when (or cut force-store-markers)
  6726. (org-save-markers-in-region beg end))
  6727. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6728. (setq org-subtree-clip (current-kill 0))
  6729. (message "%s: Subtree(s) with %d characters"
  6730. (if cut "Cut" "Copied")
  6731. (length org-subtree-clip))))))
  6732. (defun org-paste-subtree (&optional level tree for-yank remove)
  6733. "Paste the clipboard as a subtree, with modification of headline level.
  6734. The entire subtree is promoted or demoted in order to match a new headline
  6735. level.
  6736. If the cursor is at the beginning of a headline, the same level as
  6737. that headline is used to paste the tree.
  6738. If not, the new level is derived from the *visible* headings
  6739. before and after the insertion point, and taken to be the inferior headline
  6740. level of the two. So if the previous visible heading is level 3 and the
  6741. next is level 4 (or vice versa), level 4 will be used for insertion.
  6742. This makes sure that the subtree remains an independent subtree and does
  6743. not swallow low level entries.
  6744. You can also force a different level, either by using a numeric prefix
  6745. argument, or by inserting the heading marker by hand. For example, if the
  6746. cursor is after \"*****\", then the tree will be shifted to level 5.
  6747. If optional TREE is given, use this text instead of the kill ring.
  6748. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6749. move back over whitespace before inserting, and move point to the end of
  6750. the inserted text when done.
  6751. When REMOVE is non-nil, remove the subtree from the clipboard."
  6752. (interactive "P")
  6753. (setq tree (or tree (and kill-ring (current-kill 0))))
  6754. (unless (org-kill-is-subtree-p tree)
  6755. (user-error
  6756. (substitute-command-keys
  6757. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6758. (org-with-limited-levels
  6759. (let* ((visp (not (org-invisible-p)))
  6760. (txt tree)
  6761. (old-level (if (string-match org-outline-regexp-bol txt)
  6762. (- (match-end 0) (match-beginning 0) 1)
  6763. -1))
  6764. (force-level
  6765. (cond
  6766. (level (prefix-numeric-value level))
  6767. ;; When point is after the stars in an otherwise empty
  6768. ;; headline, use the number of stars as the forced level.
  6769. ((and (org-match-line "^\\*+[ \t]*$")
  6770. (not (eq ?* (char-after))))
  6771. (org-outline-level))
  6772. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6773. (previous-level
  6774. (save-excursion
  6775. (org-previous-visible-heading 1)
  6776. (if (org-at-heading-p) (org-outline-level) 1)))
  6777. (next-level
  6778. (save-excursion
  6779. (if (org-at-heading-p) (org-outline-level)
  6780. (org-next-visible-heading 1)
  6781. (if (org-at-heading-p) (org-outline-level) 1))))
  6782. (new-level (or force-level (max previous-level next-level)))
  6783. (shift (if (or (= old-level -1)
  6784. (= new-level -1)
  6785. (= old-level new-level))
  6786. 0
  6787. (- new-level old-level)))
  6788. (delta (if (> shift 0) -1 1))
  6789. (func (if (> shift 0) #'org-demote #'org-promote))
  6790. (org-odd-levels-only nil)
  6791. beg end newend)
  6792. ;; Remove the forced level indicator.
  6793. (when (and force-level (not level))
  6794. (delete-region (line-beginning-position) (point)))
  6795. ;; Paste before the next visible heading or at end of buffer,
  6796. ;; unless point is at the beginning of a headline.
  6797. (unless (and (bolp) (org-at-heading-p))
  6798. (org-next-visible-heading 1)
  6799. (unless (bolp) (insert "\n")))
  6800. (setq beg (point))
  6801. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6802. (insert-before-markers txt)
  6803. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6804. (setq newend (point))
  6805. (org-reinstall-markers-in-region beg)
  6806. (setq end (point))
  6807. (goto-char beg)
  6808. (skip-chars-forward " \t\n\r")
  6809. (setq beg (point))
  6810. (when (and (org-invisible-p) visp)
  6811. (save-excursion (outline-show-heading)))
  6812. ;; Shift if necessary.
  6813. (unless (= shift 0)
  6814. (save-restriction
  6815. (narrow-to-region beg end)
  6816. (while (not (= shift 0))
  6817. (org-map-region func (point-min) (point-max))
  6818. (setq shift (+ delta shift)))
  6819. (goto-char (point-min))
  6820. (setq newend (point-max))))
  6821. (when (or for-yank (called-interactively-p 'interactive))
  6822. (message "Clipboard pasted as level %d subtree" new-level))
  6823. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6824. kill-ring
  6825. (equal org-subtree-clip (current-kill 0))
  6826. org-subtree-clip-folded)
  6827. ;; The tree was folded before it was killed/copied
  6828. (org-flag-subtree t))
  6829. (when for-yank (goto-char newend))
  6830. (when remove (pop kill-ring)))))
  6831. (defun org-kill-is-subtree-p (&optional txt)
  6832. "Check if the current kill is an outline subtree, or a set of trees.
  6833. Returns nil if kill does not start with a headline, or if the first
  6834. headline level is not the largest headline level in the tree.
  6835. So this will actually accept several entries of equal levels as well,
  6836. which is OK for `org-paste-subtree'.
  6837. If optional TXT is given, check this string instead of the current kill."
  6838. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6839. (re (org-get-limited-outline-regexp))
  6840. (^re (concat "^" re))
  6841. (start-level (and kill
  6842. (string-match
  6843. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6844. kill)
  6845. (- (match-end 2) (match-beginning 2) 1)))
  6846. (start (1+ (or (match-beginning 2) -1))))
  6847. (if (not start-level)
  6848. (progn
  6849. nil) ;; does not even start with a heading
  6850. (catch 'exit
  6851. (while (setq start (string-match ^re kill (1+ start)))
  6852. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6853. (throw 'exit nil)))
  6854. t))))
  6855. (defvar org-markers-to-move nil
  6856. "Markers that should be moved with a cut-and-paste operation.
  6857. Those markers are stored together with their positions relative to
  6858. the start of the region.")
  6859. (defun org-save-markers-in-region (beg end)
  6860. "Check markers in region.
  6861. If these markers are between BEG and END, record their position relative
  6862. to BEG, so that after moving the block of text, we can put the markers back
  6863. into place.
  6864. This function gets called just before an entry or tree gets cut from the
  6865. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6866. called immediately, to move the markers with the entries."
  6867. (setq org-markers-to-move nil)
  6868. (when (featurep 'org-clock)
  6869. (org-clock-save-markers-for-cut-and-paste beg end))
  6870. (when (featurep 'org-agenda)
  6871. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6872. (defun org-check-and-save-marker (marker beg end)
  6873. "Check if MARKER is between BEG and END.
  6874. If yes, remember the marker and the distance to BEG."
  6875. (when (and (marker-buffer marker)
  6876. (equal (marker-buffer marker) (current-buffer))
  6877. (>= marker beg) (< marker end))
  6878. (push (cons marker (- marker beg)) org-markers-to-move)))
  6879. (defun org-reinstall-markers-in-region (beg)
  6880. "Move all remembered markers to their position relative to BEG."
  6881. (dolist (x org-markers-to-move)
  6882. (move-marker (car x) (+ beg (cdr x))))
  6883. (setq org-markers-to-move nil))
  6884. (defun org-narrow-to-subtree ()
  6885. "Narrow buffer to the current subtree."
  6886. (interactive)
  6887. (save-excursion
  6888. (save-match-data
  6889. (org-with-limited-levels
  6890. (narrow-to-region
  6891. (progn (org-back-to-heading t) (point))
  6892. (progn (org-end-of-subtree t t)
  6893. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6894. (point)))))))
  6895. (defun org-toggle-narrow-to-subtree ()
  6896. "Narrow to the subtree at point or widen a narrowed buffer."
  6897. (interactive)
  6898. (if (buffer-narrowed-p)
  6899. (widen)
  6900. (org-narrow-to-subtree)))
  6901. (defun org-narrow-to-block ()
  6902. "Narrow buffer to the current block."
  6903. (interactive)
  6904. (let* ((case-fold-search t)
  6905. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6906. "^[ \t]*#\\+end_.*")))
  6907. (if blockp
  6908. (narrow-to-region (car blockp) (cdr blockp))
  6909. (user-error "Not in a block"))))
  6910. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6911. "Clone the task (subtree) at point N times.
  6912. The clones will be inserted as siblings.
  6913. In interactive use, the user will be prompted for the number of
  6914. clones to be produced. If the entry has a timestamp, the user
  6915. will also be prompted for a time shift, which may be a repeater
  6916. as used in time stamps, for example `+3d'. To disable this,
  6917. you can call the function with a universal prefix argument.
  6918. When a valid repeater is given and the entry contains any time
  6919. stamps, the clones will become a sequence in time, with time
  6920. stamps in the subtree shifted for each clone produced. If SHIFT
  6921. is nil or the empty string, time stamps will be left alone. The
  6922. ID property of the original subtree is removed.
  6923. In each clone, all the CLOCK entries will be removed. This
  6924. prevents Org from considering that the clocked times overlap.
  6925. If the original subtree did contain time stamps with a repeater,
  6926. the following will happen:
  6927. - the repeater will be removed in each clone
  6928. - an additional clone will be produced, with the current, unshifted
  6929. date(s) in the entry.
  6930. - the original entry will be placed *after* all the clones, with
  6931. repeater intact.
  6932. - the start days in the repeater in the original entry will be shifted
  6933. to past the last clone.
  6934. In this way you can spell out a number of instances of a repeating task,
  6935. and still retain the repeater to cover future instances of the task.
  6936. As described above, N+1 clones are produced when the original
  6937. subtree has a repeater. Setting N to 0, then, can be used to
  6938. remove the repeater from a subtree and create a shifted clone
  6939. with the original repeater."
  6940. (interactive "nNumber of clones to produce: ")
  6941. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6942. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6943. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6944. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6945. (shift
  6946. (or shift
  6947. (if (and (not (equal current-prefix-arg '(4)))
  6948. (save-excursion
  6949. (goto-char beg)
  6950. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6951. (read-from-minibuffer
  6952. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6953. ""))) ;No time shift
  6954. (doshift
  6955. (and (org-string-nw-p shift)
  6956. (or (string-match "\\`[ \t]*\\([\\+\\-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6957. shift)
  6958. (user-error "Invalid shift specification %s" shift)))))
  6959. (goto-char end-of-tree)
  6960. (unless (bolp) (insert "\n"))
  6961. (let* ((end (point))
  6962. (template (buffer-substring beg end))
  6963. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6964. (shift-what (pcase (and doshift (match-string 2 shift))
  6965. (`nil nil)
  6966. ("d" 'day)
  6967. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6968. ("m" 'month)
  6969. ("y" 'year)
  6970. (_ (error "Unsupported time unit"))))
  6971. (nmin 1)
  6972. (nmax n)
  6973. (n-no-remove -1)
  6974. (idprop (org-entry-get nil "ID")))
  6975. (when (and doshift
  6976. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6977. template))
  6978. (delete-region beg end)
  6979. (setq end beg)
  6980. (setq nmin 0)
  6981. (setq nmax (1+ nmax))
  6982. (setq n-no-remove nmax))
  6983. (goto-char end)
  6984. (cl-loop for n from nmin to nmax do
  6985. (insert
  6986. ;; Prepare clone.
  6987. (with-temp-buffer
  6988. (insert template)
  6989. (org-mode)
  6990. (goto-char (point-min))
  6991. (org-show-subtree)
  6992. (and idprop (if org-clone-delete-id
  6993. (org-entry-delete nil "ID")
  6994. (org-id-get-create t)))
  6995. (unless (= n 0)
  6996. (while (re-search-forward org-clock-line-re nil t)
  6997. (delete-region (line-beginning-position)
  6998. (line-beginning-position 2)))
  6999. (goto-char (point-min))
  7000. (while (re-search-forward org-drawer-regexp nil t)
  7001. (org-remove-empty-drawer-at (point))))
  7002. (goto-char (point-min))
  7003. (when doshift
  7004. (while (re-search-forward org-ts-regexp-both nil t)
  7005. (org-timestamp-change (* n shift-n) shift-what))
  7006. (unless (= n n-no-remove)
  7007. (goto-char (point-min))
  7008. (while (re-search-forward org-ts-regexp nil t)
  7009. (save-excursion
  7010. (goto-char (match-beginning 0))
  7011. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7012. (delete-region (match-beginning 1) (match-end 1)))))))
  7013. (buffer-string)))))
  7014. (goto-char beg)))
  7015. ;;; Outline Sorting
  7016. (defun org-sort (&optional with-case)
  7017. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7018. Optional argument WITH-CASE means sort case-sensitively."
  7019. (interactive "P")
  7020. (org-call-with-arg
  7021. (cond ((org-at-table-p) #'org-table-sort-lines)
  7022. ((org-at-item-p) #'org-sort-list)
  7023. (t #'org-sort-entries))
  7024. with-case))
  7025. (defun org-sort-remove-invisible (s)
  7026. "Remove invisible part of links and emphasis markers from string S."
  7027. (remove-text-properties 0 (length s) org-rm-props s)
  7028. (replace-regexp-in-string
  7029. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7030. (replace-regexp-in-string
  7031. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7032. (org-link-display-format s)
  7033. t t) t t))
  7034. (defvar org-priority-regexp) ; defined later in the file
  7035. (defvar org-after-sorting-entries-or-items-hook nil
  7036. "Hook that is run after a bunch of entries or items have been sorted.
  7037. When children are sorted, the cursor is in the parent line when this
  7038. hook gets called. When a region or a plain list is sorted, the cursor
  7039. will be in the first entry of the sorted region/list.")
  7040. (defun org-sort-entries
  7041. (&optional with-case sorting-type getkey-func compare-func property
  7042. interactive?)
  7043. "Sort entries on a certain level of an outline tree.
  7044. If there is an active region, the entries in the region are sorted.
  7045. Else, if the cursor is before the first entry, sort the top-level items.
  7046. Else, the children of the entry at point are sorted.
  7047. Sorting can be alphabetically, numerically, by date/time as given by
  7048. a time stamp, by a property, by priority order, or by a custom function.
  7049. The command prompts for the sorting type unless it has been given to the
  7050. function through the SORTING-TYPE argument, which needs to be a character,
  7051. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7052. the precise meaning of each character:
  7053. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7054. c By creation time, which is assumed to be the first inactive time stamp
  7055. at the beginning of a line.
  7056. d By deadline date/time.
  7057. k By clocking time.
  7058. n Numerically, by converting the beginning of the entry/item to a number.
  7059. o By order of TODO keywords.
  7060. p By priority according to the cookie.
  7061. r By the value of a property.
  7062. s By scheduled date/time.
  7063. t By date/time, either the first active time stamp in the entry, or, if
  7064. none exist, by the first inactive one.
  7065. Capital letters will reverse the sort order.
  7066. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7067. called with point at the beginning of the record. It must return a
  7068. value that is compatible with COMPARE-FUNC, the function used to
  7069. compare entries.
  7070. Comparing entries ignores case by default. However, with an optional argument
  7071. WITH-CASE, the sorting considers case as well.
  7072. Sorting is done against the visible part of the headlines, it ignores hidden
  7073. links.
  7074. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7075. A non-nil value for INTERACTIVE? is used to signal that this
  7076. function is being called interactively."
  7077. (interactive (list current-prefix-arg nil nil nil nil t))
  7078. (let ((case-func (if with-case 'identity 'downcase))
  7079. start beg end stars re re2
  7080. txt what tmp)
  7081. ;; Find beginning and end of region to sort
  7082. (cond
  7083. ((org-region-active-p)
  7084. ;; we will sort the region
  7085. (setq end (region-end)
  7086. what "region")
  7087. (goto-char (region-beginning))
  7088. (unless (org-at-heading-p) (outline-next-heading))
  7089. (setq start (point)))
  7090. ((or (org-at-heading-p)
  7091. (ignore-errors (progn (org-back-to-heading) t)))
  7092. ;; we will sort the children of the current headline
  7093. (org-back-to-heading)
  7094. (setq start (point)
  7095. end (progn (org-end-of-subtree t t)
  7096. (or (bolp) (insert "\n"))
  7097. (when (>= (org-back-over-empty-lines) 1)
  7098. (forward-line 1))
  7099. (point))
  7100. what "children")
  7101. (goto-char start)
  7102. (outline-show-subtree)
  7103. (outline-next-heading))
  7104. (t
  7105. ;; we will sort the top-level entries in this file
  7106. (goto-char (point-min))
  7107. (or (org-at-heading-p) (outline-next-heading))
  7108. (setq start (point))
  7109. (goto-char (point-max))
  7110. (beginning-of-line 1)
  7111. (when (looking-at ".*?\\S-")
  7112. ;; File ends in a non-white line
  7113. (end-of-line 1)
  7114. (insert "\n"))
  7115. (setq end (point-max))
  7116. (setq what "top-level")
  7117. (goto-char start)
  7118. (org-show-all '(headings blocks))))
  7119. (setq beg (point))
  7120. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7121. (looking-at "\\(\\*+\\)")
  7122. (setq stars (match-string 1)
  7123. re (concat "^" (regexp-quote stars) " +")
  7124. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7125. txt (buffer-substring beg end))
  7126. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7127. (when (and (not (equal stars "*")) (string-match re2 txt))
  7128. (user-error "Region to sort contains a level above the first entry"))
  7129. (unless sorting-type
  7130. (message
  7131. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7132. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7133. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7134. what)
  7135. (setq sorting-type (read-char-exclusive)))
  7136. (unless getkey-func
  7137. (and (= (downcase sorting-type) ?f)
  7138. (setq getkey-func
  7139. (or (and interactive?
  7140. (org-read-function
  7141. "Function for extracting keys: "))
  7142. (error "Missing key extractor")))))
  7143. (and (= (downcase sorting-type) ?r)
  7144. (not property)
  7145. (setq property
  7146. (completing-read "Property: "
  7147. (mapcar #'list (org-buffer-property-keys t))
  7148. nil t)))
  7149. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7150. (message "Sorting entries...")
  7151. (save-restriction
  7152. (narrow-to-region start end)
  7153. (let ((restore-clock?
  7154. ;; The clock marker is lost when using `sort-subr'; mark
  7155. ;; the clock with temporary `:org-clock-marker-backup'
  7156. ;; text property.
  7157. (when (and (eq (org-clock-is-active) (current-buffer))
  7158. (<= start (marker-position org-clock-marker))
  7159. (>= end (marker-position org-clock-marker)))
  7160. (with-silent-modifications
  7161. (put-text-property (1- org-clock-marker) org-clock-marker
  7162. :org-clock-marker-backup t))
  7163. t))
  7164. (dcst (downcase sorting-type))
  7165. (case-fold-search nil)
  7166. (now (current-time)))
  7167. (org-preserve-local-variables
  7168. (sort-subr
  7169. (/= dcst sorting-type)
  7170. ;; This function moves to the beginning character of the
  7171. ;; "record" to be sorted.
  7172. (lambda nil
  7173. (if (re-search-forward re nil t)
  7174. (goto-char (match-beginning 0))
  7175. (goto-char (point-max))))
  7176. ;; This function moves to the last character of the "record" being
  7177. ;; sorted.
  7178. (lambda nil
  7179. (save-match-data
  7180. (condition-case nil
  7181. (outline-forward-same-level 1)
  7182. (error
  7183. (goto-char (point-max))))))
  7184. ;; This function returns the value that gets sorted against.
  7185. (lambda ()
  7186. (cond
  7187. ((= dcst ?n)
  7188. (string-to-number
  7189. (org-sort-remove-invisible (org-get-heading t t t t))))
  7190. ((= dcst ?a)
  7191. (funcall case-func
  7192. (org-sort-remove-invisible (org-get-heading t t t t))))
  7193. ((= dcst ?k)
  7194. (or (get-text-property (point) :org-clock-minutes) 0))
  7195. ((= dcst ?t)
  7196. (let ((end (save-excursion (outline-next-heading) (point))))
  7197. (if (or (re-search-forward org-ts-regexp end t)
  7198. (re-search-forward org-ts-regexp-both end t))
  7199. (org-time-string-to-seconds (match-string 0))
  7200. (float-time now))))
  7201. ((= dcst ?c)
  7202. (let ((end (save-excursion (outline-next-heading) (point))))
  7203. (if (re-search-forward
  7204. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7205. end t)
  7206. (org-time-string-to-seconds (match-string 0))
  7207. (float-time now))))
  7208. ((= dcst ?s)
  7209. (let ((end (save-excursion (outline-next-heading) (point))))
  7210. (if (re-search-forward org-scheduled-time-regexp end t)
  7211. (org-time-string-to-seconds (match-string 1))
  7212. (float-time now))))
  7213. ((= dcst ?d)
  7214. (let ((end (save-excursion (outline-next-heading) (point))))
  7215. (if (re-search-forward org-deadline-time-regexp end t)
  7216. (org-time-string-to-seconds (match-string 1))
  7217. (float-time now))))
  7218. ((= dcst ?p)
  7219. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7220. (string-to-char (match-string 2))
  7221. org-default-priority))
  7222. ((= dcst ?r)
  7223. (or (org-entry-get nil property) ""))
  7224. ((= dcst ?o)
  7225. (when (looking-at org-complex-heading-regexp)
  7226. (let* ((m (match-string 2))
  7227. (s (if (member m org-done-keywords) '- '+)))
  7228. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7229. ((= dcst ?f)
  7230. (if getkey-func
  7231. (progn
  7232. (setq tmp (funcall getkey-func))
  7233. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7234. tmp)
  7235. (error "Invalid key function `%s'" getkey-func)))
  7236. (t (error "Invalid sorting type `%c'" sorting-type))))
  7237. nil
  7238. (cond
  7239. ((= dcst ?a) 'org-string-collate-lessp)
  7240. ((= dcst ?f)
  7241. (or compare-func
  7242. (and interactive?
  7243. (org-read-function
  7244. (concat "Function for comparing keys "
  7245. "(empty for default `sort-subr' predicate): ")
  7246. 'allow-empty))))
  7247. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7248. (org-cycle-hide-drawers 'all)
  7249. (when restore-clock?
  7250. (move-marker org-clock-marker
  7251. (1+ (next-single-property-change
  7252. start :org-clock-marker-backup)))
  7253. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7254. '(:org-clock-marker-backup t)))))
  7255. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7256. (message "Sorting entries...done")))
  7257. (defun org-contextualize-keys (alist contexts)
  7258. "Return valid elements in ALIST depending on CONTEXTS.
  7259. `org-agenda-custom-commands' or `org-capture-templates' are the
  7260. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7261. or `org-capture-templates-contexts' are the associated contexts
  7262. definitions."
  7263. (let ((contexts
  7264. ;; normalize contexts
  7265. (mapcar
  7266. (lambda(c) (cond ((listp (cadr c))
  7267. (list (car c) (car c) (nth 1 c)))
  7268. ((string= "" (cadr c))
  7269. (list (car c) (car c) (nth 2 c)))
  7270. (t c)))
  7271. contexts))
  7272. (a alist) r s)
  7273. ;; loop over all commands or templates
  7274. (dolist (c a)
  7275. (let (vrules repl)
  7276. (cond
  7277. ((not (assoc (car c) contexts))
  7278. (push c r))
  7279. ((and (assoc (car c) contexts)
  7280. (setq vrules (org-contextualize-validate-key
  7281. (car c) contexts)))
  7282. (mapc (lambda (vr)
  7283. (unless (equal (car vr) (cadr vr))
  7284. (setq repl vr)))
  7285. vrules)
  7286. (if (not repl) (push c r)
  7287. (push (cadr repl) s)
  7288. (push
  7289. (cons (car c)
  7290. (cdr (or (assoc (cadr repl) alist)
  7291. (error "Undefined key `%s' as contextual replacement for `%s'"
  7292. (cadr repl) (car c)))))
  7293. r))))))
  7294. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7295. (delq
  7296. nil
  7297. (delete-dups
  7298. (mapcar (lambda (x)
  7299. (let ((tpl (car x)))
  7300. (unless (delq
  7301. nil
  7302. (mapcar (lambda (y)
  7303. (equal y tpl))
  7304. s))
  7305. x)))
  7306. (reverse r))))))
  7307. (defun org-contextualize-validate-key (key contexts)
  7308. "Check CONTEXTS for agenda or capture KEY."
  7309. (let (res)
  7310. (dolist (r contexts)
  7311. (dolist (rr (car (last r)))
  7312. (when
  7313. (and (equal key (car r))
  7314. (if (functionp rr) (funcall rr)
  7315. (or (and (eq (car rr) 'in-file)
  7316. (buffer-file-name)
  7317. (string-match (cdr rr) (buffer-file-name)))
  7318. (and (eq (car rr) 'in-mode)
  7319. (string-match (cdr rr) (symbol-name major-mode)))
  7320. (and (eq (car rr) 'in-buffer)
  7321. (string-match (cdr rr) (buffer-name)))
  7322. (when (and (eq (car rr) 'not-in-file)
  7323. (buffer-file-name))
  7324. (not (string-match (cdr rr) (buffer-file-name))))
  7325. (when (eq (car rr) 'not-in-mode)
  7326. (not (string-match (cdr rr) (symbol-name major-mode))))
  7327. (when (eq (car rr) 'not-in-buffer)
  7328. (not (string-match (cdr rr) (buffer-name)))))))
  7329. (push r res))))
  7330. (delete-dups (delq nil res))))
  7331. ;; Defined to provide a value for defcustom, since there is no
  7332. ;; string-collate-greaterp in Emacs.
  7333. (defun org-string-collate-greaterp (s1 s2)
  7334. "Return non-nil if S1 is greater than S2 in collation order."
  7335. (not (org-string-collate-lessp s1 s2)))
  7336. ;;;###autoload
  7337. (defun org-run-like-in-org-mode (cmd)
  7338. "Run a command, pretending that the current buffer is in Org mode.
  7339. This will temporarily bind local variables that are typically bound in
  7340. Org mode to the values they have in Org mode, and then interactively
  7341. call CMD."
  7342. (org-load-modules-maybe)
  7343. (let (binds)
  7344. (dolist (var (org-get-local-variables))
  7345. (when (or (not (boundp (car var)))
  7346. (eq (symbol-value (car var))
  7347. (default-value (car var))))
  7348. (push (list (car var) `(quote ,(cadr var))) binds)))
  7349. (eval `(let ,binds
  7350. (call-interactively (quote ,cmd))))))
  7351. (defun org-get-category (&optional pos force-refresh)
  7352. "Get the category applying to position POS."
  7353. (save-match-data
  7354. (when force-refresh (org-refresh-category-properties))
  7355. (let ((pos (or pos (point))))
  7356. (or (get-text-property pos 'org-category)
  7357. (progn (org-refresh-category-properties)
  7358. (get-text-property pos 'org-category))))))
  7359. ;;; Refresh properties
  7360. (defun org-refresh-properties (dprop tprop)
  7361. "Refresh buffer text properties.
  7362. DPROP is the drawer property and TPROP is either the
  7363. corresponding text property to set, or an alist with each element
  7364. being a text property (as a symbol) and a function to apply to
  7365. the value of the drawer property."
  7366. (let* ((case-fold-search t)
  7367. (inhibit-read-only t)
  7368. (inherit? (org-property-inherit-p dprop))
  7369. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7370. (global (and inherit? (org--property-global-value dprop nil))))
  7371. (with-silent-modifications
  7372. (org-with-point-at 1
  7373. ;; Set global values (e.g., values defined through
  7374. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7375. (when global (put-text-property (point-min) (point-max) tprop global))
  7376. ;; Set local values.
  7377. (while (re-search-forward property-re nil t)
  7378. (when (org-at-property-p)
  7379. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7380. (outline-next-heading))))))
  7381. (defun org-refresh-property (tprop p &optional inherit)
  7382. "Refresh the buffer text property TPROP from the drawer property P.
  7383. The refresh happens only for the current headline, or the whole
  7384. sub-tree if optional argument INHERIT is non-nil."
  7385. (unless (org-before-first-heading-p)
  7386. (save-excursion
  7387. (org-back-to-heading t)
  7388. (let ((start (point))
  7389. (end (save-excursion
  7390. (if inherit (org-end-of-subtree t t)
  7391. (or (outline-next-heading) (point-max))))))
  7392. (if (symbolp tprop)
  7393. ;; TPROP is a text property symbol.
  7394. (put-text-property start end tprop p)
  7395. ;; TPROP is an alist with (property . function) elements.
  7396. (pcase-dolist (`(,prop . ,f) tprop)
  7397. (put-text-property start end prop (funcall f p))))))))
  7398. (defun org-refresh-category-properties ()
  7399. "Refresh category text properties in the buffer."
  7400. (let ((case-fold-search t)
  7401. (inhibit-read-only t)
  7402. (default-category
  7403. (cond ((null org-category)
  7404. (if buffer-file-name
  7405. (file-name-sans-extension
  7406. (file-name-nondirectory buffer-file-name))
  7407. "???"))
  7408. ((symbolp org-category) (symbol-name org-category))
  7409. (t org-category))))
  7410. (with-silent-modifications
  7411. (org-with-wide-buffer
  7412. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7413. ;; This is the default category for the buffer. If none is
  7414. ;; found, fall-back to `org-category' or buffer file name.
  7415. (put-text-property
  7416. (point-min) (point-max)
  7417. 'org-category
  7418. (catch 'buffer-category
  7419. (goto-char (point-max))
  7420. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7421. (let ((element (org-element-at-point)))
  7422. (when (eq (org-element-type element) 'keyword)
  7423. (throw 'buffer-category
  7424. (org-element-property :value element)))))
  7425. default-category))
  7426. ;; Set sub-tree specific categories.
  7427. (goto-char (point-min))
  7428. (let ((regexp (org-re-property "CATEGORY")))
  7429. (while (re-search-forward regexp nil t)
  7430. (let ((value (match-string-no-properties 3)))
  7431. (when (org-at-property-p)
  7432. (put-text-property
  7433. (save-excursion (org-back-to-heading t) (point))
  7434. (save-excursion (org-end-of-subtree t t) (point))
  7435. 'org-category
  7436. value)))))))))
  7437. (defun org-refresh-stats-properties ()
  7438. "Refresh stats text properties in the buffer."
  7439. (with-silent-modifications
  7440. (org-with-point-at 1
  7441. (let ((regexp (concat org-outline-regexp-bol
  7442. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7443. (while (re-search-forward regexp nil t)
  7444. (let* ((numerator (string-to-number (match-string 1)))
  7445. (denominator (and (match-end 2)
  7446. (string-to-number (match-string 2))))
  7447. (stats (cond ((not denominator) numerator) ;percent
  7448. ((= denominator 0) 0)
  7449. (t (/ (* numerator 100) denominator)))))
  7450. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7451. 'org-stats stats)))))))
  7452. (defun org-refresh-effort-properties ()
  7453. "Refresh effort properties."
  7454. (org-refresh-properties
  7455. org-effort-property
  7456. '((effort . identity)
  7457. (effort-minutes . org-duration-to-minutes))))
  7458. (defun org-find-file-at-mouse (ev)
  7459. "Open file link or URL at mouse."
  7460. (interactive "e")
  7461. (mouse-set-point ev)
  7462. (org-open-at-point 'in-emacs))
  7463. (defun org-open-at-mouse (ev)
  7464. "Open file link or URL at mouse.
  7465. See the docstring of `org-open-file' for details."
  7466. (interactive "e")
  7467. (mouse-set-point ev)
  7468. (when (eq major-mode 'org-agenda-mode)
  7469. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7470. (org-open-at-point))
  7471. (defvar org-window-config-before-follow-link nil
  7472. "The window configuration before following a link.
  7473. This is saved in case the need arises to restore it.")
  7474. (defun org--file-default-apps ()
  7475. "Return the default applications for this operating system."
  7476. (pcase system-type
  7477. (`darwin org-file-apps-macos)
  7478. (`windows-nt org-file-apps-windowsnt)
  7479. (_ org-file-apps-gnu)))
  7480. (defun org--file-apps-entry-dlink-p (entry)
  7481. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7482. It assumes that is the case when the entry uses a regular
  7483. expression which has at least one grouping construct and the
  7484. action is either a Lisp form or a command string containing
  7485. \"%1\", i.e., using at least one subexpression match as
  7486. a parameter."
  7487. (pcase entry
  7488. (`(,selector . ,action)
  7489. (and (stringp selector)
  7490. (> (regexp-opt-depth selector) 0)
  7491. (or (and (stringp action)
  7492. (string-match "%[0-9]" action))
  7493. (consp action))))
  7494. (_ nil)))
  7495. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7496. "Convert extensions to regular expressions in the cars of LIST.
  7497. Also, weed out any non-string entries, because the return value
  7498. is used only for regexp matching.
  7499. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7500. point to the symbol `emacs', indicating that the file should be
  7501. opened in Emacs."
  7502. (append
  7503. (delq nil
  7504. (mapcar (lambda (x)
  7505. (unless (not (stringp (car x)))
  7506. (if (string-match "\\W" (car x))
  7507. x
  7508. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7509. list))
  7510. (when add-auto-mode
  7511. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7512. ;;;###autoload
  7513. (defun org-open-file (path &optional in-emacs line search)
  7514. "Open the file at PATH.
  7515. First, this expands any special file name abbreviations. Then the
  7516. configuration variable `org-file-apps' is checked if it contains an
  7517. entry for this file type, and if yes, the corresponding command is launched.
  7518. If no application is found, Emacs simply visits the file.
  7519. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7520. With a double \\[universal-argument] \\[universal-argument] \
  7521. prefix arg, Org tries to avoid opening in Emacs
  7522. and to use an external application to visit the file.
  7523. Optional LINE specifies a line to go to, optional SEARCH a string
  7524. to search for. If LINE or SEARCH is given, the file will be
  7525. opened in Emacs, unless an entry from `org-file-apps' that makes
  7526. use of groups in a regexp matches.
  7527. If you want to change the way frames are used when following a
  7528. link, please customize `org-link-frame-setup'.
  7529. If the file does not exist, throw an error."
  7530. (let* ((file (if (equal path "") buffer-file-name
  7531. (substitute-in-file-name (expand-file-name path))))
  7532. (file-apps (append org-file-apps (org--file-default-apps)))
  7533. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7534. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7535. file-apps))
  7536. (remp (and (assq 'remote apps) (file-remote-p file)))
  7537. (dirp (unless remp (file-directory-p file)))
  7538. (file (if (and dirp org-open-directory-means-index-dot-org)
  7539. (concat (file-name-as-directory file) "index.org")
  7540. file))
  7541. (a-m-a-p (assq 'auto-mode apps))
  7542. (dfile (downcase file))
  7543. ;; Reconstruct the original link from the PATH, LINE and
  7544. ;; SEARCH args.
  7545. (link (cond (line (concat file "::" (number-to-string line)))
  7546. (search (concat file "::" search))
  7547. (t file)))
  7548. (dlink (downcase link))
  7549. (ext
  7550. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7551. (match-string 1 dfile)))
  7552. (save-position-maybe
  7553. (let ((old-buffer (current-buffer))
  7554. (old-pos (point))
  7555. (old-mode major-mode))
  7556. (lambda ()
  7557. (and (derived-mode-p 'org-mode)
  7558. (eq old-mode 'org-mode)
  7559. (or (not (eq old-buffer (current-buffer)))
  7560. (not (eq old-pos (point))))
  7561. (org-mark-ring-push old-pos old-buffer)))))
  7562. cmd link-match-data)
  7563. (cond
  7564. ((member in-emacs '((16) system))
  7565. (setq cmd (cdr (assq 'system apps))))
  7566. (in-emacs (setq cmd 'emacs))
  7567. (t
  7568. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7569. (and dirp (cdr (assq 'directory apps)))
  7570. ;; First, try matching against apps-dlink if we
  7571. ;; get a match here, store the match data for
  7572. ;; later.
  7573. (let ((match (assoc-default dlink apps-dlink
  7574. 'string-match)))
  7575. (if match
  7576. (progn (setq link-match-data (match-data))
  7577. match)
  7578. (progn (setq in-emacs (or in-emacs line search))
  7579. nil))) ; if we have no match in apps-dlink,
  7580. ; always open the file in emacs if line or search
  7581. ; is given (for backwards compatibility)
  7582. (assoc-default dfile
  7583. (org--file-apps-regexp-alist apps a-m-a-p)
  7584. 'string-match)
  7585. (cdr (assoc ext apps))
  7586. (cdr (assq t apps))))))
  7587. (when (eq cmd 'system)
  7588. (setq cmd (cdr (assq 'system apps))))
  7589. (when (eq cmd 'default)
  7590. (setq cmd (cdr (assoc t apps))))
  7591. (when (eq cmd 'mailcap)
  7592. (require 'mailcap)
  7593. (mailcap-parse-mailcaps)
  7594. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7595. (command (mailcap-mime-info mime-type)))
  7596. (if (stringp command)
  7597. (setq cmd command)
  7598. (setq cmd 'emacs))))
  7599. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7600. (not (file-exists-p file))
  7601. (not org-open-non-existing-files))
  7602. (user-error "No such file: %s" file))
  7603. (cond
  7604. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7605. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7606. (while (string-match "['\"]%s['\"]" cmd)
  7607. (setq cmd (replace-match "%s" t t cmd)))
  7608. (setq cmd (replace-regexp-in-string
  7609. "%s"
  7610. (shell-quote-argument (convert-standard-filename file))
  7611. cmd
  7612. nil t))
  7613. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7614. (save-match-data
  7615. (let ((match-index 1)
  7616. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7617. (set-match-data link-match-data)
  7618. (while (<= match-index number-of-groups)
  7619. (let ((regex (concat "%" (number-to-string match-index)))
  7620. (replace-with (match-string match-index dlink)))
  7621. (while (string-match regex cmd)
  7622. (setq cmd (replace-match replace-with t t cmd))))
  7623. (setq match-index (+ match-index 1)))))
  7624. (save-window-excursion
  7625. (message "Running %s...done" cmd)
  7626. (start-process-shell-command cmd nil cmd)
  7627. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7628. ((or (stringp cmd)
  7629. (eq cmd 'emacs))
  7630. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7631. (widen)
  7632. (cond (line (org-goto-line line)
  7633. (when (derived-mode-p 'org-mode) (org-reveal)))
  7634. (search (condition-case err
  7635. (org-link-search search)
  7636. ;; Save position before error-ing out so user
  7637. ;; can easily move back to the original buffer.
  7638. (error (funcall save-position-maybe)
  7639. (error (nth 1 err)))))))
  7640. ((functionp cmd)
  7641. (save-match-data
  7642. (set-match-data link-match-data)
  7643. (condition-case nil
  7644. (funcall cmd file link)
  7645. ;; FIXME: Remove this check when most default installations
  7646. ;; of Emacs have at least Org 9.0.
  7647. ((debug wrong-number-of-arguments wrong-type-argument
  7648. invalid-function)
  7649. (user-error "Please see Org News for version 9.0 about \
  7650. `org-file-apps'--Lisp error: %S" cmd)))))
  7651. ((consp cmd)
  7652. ;; FIXME: Remove this check when most default installations of
  7653. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7654. ;; fall back to `org-link-frame-setup' for an old usage of
  7655. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7656. (user-error "Please see Org News for version 9.0 about \
  7657. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7658. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7659. (funcall save-position-maybe)))
  7660. ;;;###autoload
  7661. (defun org-open-at-point-global ()
  7662. "Follow a link or a time-stamp like Org mode does.
  7663. Also follow links and emails as seen by `thing-at-point'.
  7664. This command can be called in any mode to follow an external
  7665. link or a time-stamp that has Org mode syntax. Its behavior
  7666. is undefined when called on internal links like fuzzy links.
  7667. Raise a user error when there is nothing to follow."
  7668. (interactive)
  7669. (let ((tap-url (thing-at-point 'url))
  7670. (tap-email (thing-at-point 'email)))
  7671. (cond ((org-in-regexp org-link-any-re)
  7672. (org-link-open-from-string (match-string-no-properties 0)))
  7673. ((or (org-in-regexp org-ts-regexp-both nil t)
  7674. (org-in-regexp org-tsr-regexp-both nil t))
  7675. (org-follow-timestamp-link))
  7676. (tap-url (org-link-open-from-string tap-url))
  7677. (tap-email (org-link-open-from-string
  7678. (concat "mailto:" tap-email)))
  7679. (t (user-error "No link found")))))
  7680. (defvar org-open-at-point-functions nil
  7681. "Hook that is run when following a link at point.
  7682. Functions in this hook must return t if they identify and follow
  7683. a link at point. If they don't find anything interesting at point,
  7684. they must return nil.")
  7685. (defun org-open-at-point (&optional arg)
  7686. "Open link, timestamp, footnote or tags at point.
  7687. When point is on a link, follow it. Normally, files will be
  7688. opened by an appropriate application. If the optional prefix
  7689. argument ARG is non-nil, Emacs will visit the file. With
  7690. a double prefix argument, try to open outside of Emacs, in the
  7691. application the system uses for this file type.
  7692. When point is on a timestamp, open the agenda at the day
  7693. specified.
  7694. When point is a footnote definition, move to the first reference
  7695. found. If it is on a reference, move to the associated
  7696. definition.
  7697. When point is on a headline, display a list of every link in the
  7698. entry, so it is possible to pick one, or all, of them. If point
  7699. is on a tag, call `org-tags-view' instead.
  7700. On top of syntactically correct links, this function also tries
  7701. to open links and time-stamps in comments, node properties, and
  7702. keywords if point is on something looking like a timestamp or
  7703. a link."
  7704. (interactive "P")
  7705. (org-load-modules-maybe)
  7706. (setq org-window-config-before-follow-link (current-window-configuration))
  7707. (org-remove-occur-highlights nil nil t)
  7708. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7709. (let* ((context
  7710. ;; Only consider supported types, even if they are not the
  7711. ;; closest one.
  7712. (org-element-lineage
  7713. (org-element-context)
  7714. '(clock comment comment-block footnote-definition
  7715. footnote-reference headline inline-src-block inlinetask
  7716. keyword link node-property planning src-block timestamp)
  7717. t))
  7718. (type (org-element-type context))
  7719. (value (org-element-property :value context)))
  7720. (cond
  7721. ((not type) (user-error "No link found"))
  7722. ;; No valid link at point. For convenience, look if something
  7723. ;; looks like a link under point in some specific places.
  7724. ((memq type '(comment comment-block node-property keyword))
  7725. (call-interactively #'org-open-at-point-global))
  7726. ;; On a headline or an inlinetask, but not on a timestamp,
  7727. ;; a link, a footnote reference.
  7728. ((memq type '(headline inlinetask))
  7729. (org-match-line org-complex-heading-regexp)
  7730. (if (and (match-beginning 5)
  7731. (>= (point) (match-beginning 5))
  7732. (< (point) (match-end 5)))
  7733. ;; On tags.
  7734. (org-tags-view
  7735. arg
  7736. (save-excursion
  7737. (let* ((beg (match-beginning 5))
  7738. (end (match-end 5))
  7739. (beg-tag (or (search-backward ":" beg 'at-limit) (point)))
  7740. (end-tag (search-forward ":" end nil 2)))
  7741. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7742. ;; Not on tags.
  7743. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7744. (`(nil . ,_)
  7745. (require 'org-attach)
  7746. (message "Opening attachment-dir")
  7747. (if (equal arg '(4))
  7748. (org-attach-reveal-in-emacs)
  7749. (org-attach-reveal)))
  7750. (`(,links . ,links-end)
  7751. (dolist (link (if (stringp links) (list links) links))
  7752. (search-forward link nil links-end)
  7753. (goto-char (match-beginning 0))
  7754. (org-open-at-point arg))))))
  7755. ;; On a footnote reference or at definition's label.
  7756. ((or (eq type 'footnote-reference)
  7757. (and (eq type 'footnote-definition)
  7758. (save-excursion
  7759. ;; Do not validate action when point is on the
  7760. ;; spaces right after the footnote label, in order
  7761. ;; to be on par with behavior on links.
  7762. (skip-chars-forward " \t")
  7763. (let ((begin
  7764. (org-element-property :contents-begin context)))
  7765. (if begin (< (point) begin)
  7766. (= (org-element-property :post-affiliated context)
  7767. (line-beginning-position)))))))
  7768. (org-footnote-action))
  7769. ;; On a planning line. Check if we are really on a timestamp.
  7770. ((and (eq type 'planning)
  7771. (org-in-regexp org-ts-regexp-both nil t))
  7772. (org-follow-timestamp-link))
  7773. ;; On a clock line, make sure point is on the timestamp
  7774. ;; before opening it.
  7775. ((and (eq type 'clock)
  7776. value
  7777. (>= (point) (org-element-property :begin value))
  7778. (<= (point) (org-element-property :end value)))
  7779. (org-follow-timestamp-link))
  7780. ((eq type 'src-block) (org-babel-open-src-block-result))
  7781. ;; Do nothing on white spaces after an object.
  7782. ((>= (point)
  7783. (save-excursion
  7784. (goto-char (org-element-property :end context))
  7785. (skip-chars-backward " \t")
  7786. (point)))
  7787. (user-error "No link found"))
  7788. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7789. ((eq type 'timestamp) (org-follow-timestamp-link))
  7790. ((eq type 'link) (org-link-open context arg))
  7791. (t (user-error "No link found")))))
  7792. (run-hook-with-args 'org-follow-link-hook))
  7793. ;;;###autoload
  7794. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7795. "Offer links in the current entry and return the selected link.
  7796. If there is only one link, return it.
  7797. If NTH is an integer, return the NTH link found.
  7798. If ZERO is a string, check also this string for a link, and if
  7799. there is one, return it."
  7800. (with-current-buffer buffer
  7801. (org-with-wide-buffer
  7802. (goto-char marker)
  7803. (let ((cnt ?0)
  7804. have-zero end links link c)
  7805. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7806. (push (match-string 0 zero) links)
  7807. (setq cnt (1- cnt) have-zero t))
  7808. (save-excursion
  7809. (org-back-to-heading t)
  7810. (setq end (save-excursion (outline-next-heading) (point)))
  7811. (while (re-search-forward org-link-any-re end t)
  7812. (push (match-string 0) links))
  7813. (setq links (org-uniquify (reverse links))))
  7814. (cond
  7815. ((null links)
  7816. (message "No links"))
  7817. ((equal (length links) 1)
  7818. (setq link (car links)))
  7819. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7820. (setq link (nth (if have-zero nth (1- nth)) links)))
  7821. (t ; we have to select a link
  7822. (save-excursion
  7823. (save-window-excursion
  7824. (delete-other-windows)
  7825. (with-output-to-temp-buffer "*Select Link*"
  7826. (dolist (l links)
  7827. (cond
  7828. ((not (string-match org-link-bracket-re l))
  7829. (princ (format "[%c] %s\n" (cl-incf cnt)
  7830. (org-unbracket-string "<" ">" l))))
  7831. ((match-end 2)
  7832. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7833. (match-string 2 l) (match-string 1 l))))
  7834. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7835. (match-string 1 l)))))))
  7836. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7837. (message "Select link to open, RET to open all:")
  7838. (setq c (read-char-exclusive))
  7839. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7840. (when (equal c ?q) (user-error "Abort"))
  7841. (if (equal c ?\C-m)
  7842. (setq link links)
  7843. (setq nth (- c ?0))
  7844. (when have-zero (setq nth (1+ nth)))
  7845. (unless (and (integerp nth) (>= (length links) nth))
  7846. (user-error "Invalid link selection"))
  7847. (setq link (nth (1- nth) links)))))
  7848. (cons link end)))))
  7849. ;;; File search
  7850. (defun org-do-occur (regexp &optional cleanup)
  7851. "Call the Emacs command `occur'.
  7852. If CLEANUP is non-nil, remove the printout of the regular expression
  7853. in the *Occur* buffer. This is useful if the regex is long and not useful
  7854. to read."
  7855. (occur regexp)
  7856. (when cleanup
  7857. (let ((cwin (selected-window)) win beg end)
  7858. (when (setq win (get-buffer-window "*Occur*"))
  7859. (select-window win))
  7860. (goto-char (point-min))
  7861. (when (re-search-forward "match[a-z]+" nil t)
  7862. (setq beg (match-end 0))
  7863. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7864. (setq end (1- (match-beginning 0)))))
  7865. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7866. (goto-char (point-min))
  7867. (select-window cwin))))
  7868. ;;; The Mark Ring
  7869. (defvar org-mark-ring nil
  7870. "Mark ring for positions before jumps in Org mode.")
  7871. (defvar org-mark-ring-last-goto nil
  7872. "Last position in the mark ring used to go back.")
  7873. ;; Fill and close the ring
  7874. (setq org-mark-ring nil)
  7875. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7876. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7877. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7878. org-mark-ring)
  7879. (defun org-mark-ring-push (&optional pos buffer)
  7880. "Put the current position into the mark ring and rotate it.
  7881. Also push position into the Emacs mark ring. If optional
  7882. argument POS and BUFFER are not nil, mark this location instead."
  7883. (interactive)
  7884. (let ((pos (or pos (point)))
  7885. (buffer (or buffer (current-buffer))))
  7886. (with-current-buffer buffer
  7887. (org-with-point-at pos (push-mark nil t)))
  7888. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7889. (move-marker (car org-mark-ring) pos buffer))
  7890. (message
  7891. (substitute-command-keys
  7892. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7893. (defun org-mark-ring-goto (&optional n)
  7894. "Jump to the previous position in the mark ring.
  7895. With prefix arg N, jump back that many stored positions. When
  7896. called several times in succession, walk through the entire ring.
  7897. Org mode commands jumping to a different position in the current file,
  7898. or to another Org file, automatically push the old position onto the ring."
  7899. (interactive "p")
  7900. (let (p m)
  7901. (if (eq last-command this-command)
  7902. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7903. (setq p org-mark-ring))
  7904. (setq org-mark-ring-last-goto p)
  7905. (setq m (car p))
  7906. (pop-to-buffer-same-window (marker-buffer m))
  7907. (goto-char m)
  7908. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7909. ;;; Following specific links
  7910. (defvar org-agenda-buffer-tmp-name)
  7911. (defvar org-agenda-start-on-weekday)
  7912. (defun org-follow-timestamp-link ()
  7913. "Open an agenda view for the time-stamp date/range at point."
  7914. (cond
  7915. ((org-at-date-range-p t)
  7916. (let ((org-agenda-start-on-weekday)
  7917. (t1 (match-string 1))
  7918. (t2 (match-string 2)) tt1 tt2)
  7919. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7920. tt2 (time-to-days (org-time-string-to-time t2)))
  7921. (let ((org-agenda-buffer-tmp-name
  7922. (format "*Org Agenda(a:%s)"
  7923. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7924. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7925. ((org-at-timestamp-p 'lax)
  7926. (let ((org-agenda-buffer-tmp-name
  7927. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7928. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7929. (substring (match-string 1) 0 10)))
  7930. 1)))
  7931. (t (error "This should not happen"))))
  7932. ;;; Following file links
  7933. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7934. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7935. (declare-function mailcap-mime-info
  7936. "mailcap" (string &optional request no-decode))
  7937. (defvar org-wait nil)
  7938. ;;;; Refiling
  7939. (defun org-get-org-file ()
  7940. "Read a filename, with default directory `org-directory'."
  7941. (let ((default (or org-default-notes-file remember-data-file)))
  7942. (read-file-name (format "File name [%s]: " default)
  7943. (file-name-as-directory org-directory)
  7944. default)))
  7945. (defun org-notes-order-reversed-p ()
  7946. "Check if the current file should receive notes in reversed order."
  7947. (cond
  7948. ((not org-reverse-note-order) nil)
  7949. ((eq t org-reverse-note-order) t)
  7950. ((not (listp org-reverse-note-order)) nil)
  7951. (t (catch 'exit
  7952. (dolist (entry org-reverse-note-order)
  7953. (when (string-match (car entry) buffer-file-name)
  7954. (throw 'exit (cdr entry))))))))
  7955. (defvar org-refile-target-table nil
  7956. "The list of refile targets, created by `org-refile'.")
  7957. (defvar org-agenda-new-buffers nil
  7958. "Buffers created to visit agenda files.")
  7959. (defvar org-refile-cache nil
  7960. "Cache for refile targets.")
  7961. (defvar org-refile-markers nil
  7962. "All the markers used for caching refile locations.")
  7963. (defun org-refile-marker (pos)
  7964. "Get a new refile marker, but only if caching is in use."
  7965. (if (not org-refile-use-cache)
  7966. pos
  7967. (let ((m (make-marker)))
  7968. (move-marker m pos)
  7969. (push m org-refile-markers)
  7970. m)))
  7971. (defun org-refile-cache-clear ()
  7972. "Clear the refile cache and disable all the markers."
  7973. (dolist (m org-refile-markers) (move-marker m nil))
  7974. (setq org-refile-markers nil)
  7975. (setq org-refile-cache nil)
  7976. (message "Refile cache has been cleared"))
  7977. (defun org-refile-cache-check-set (set)
  7978. "Check if all the markers in the cache still have live buffers."
  7979. (let (marker)
  7980. (catch 'exit
  7981. (while (and set (setq marker (nth 3 (pop set))))
  7982. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  7983. (when (and marker (null (marker-buffer marker)))
  7984. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  7985. (sit-for 3)
  7986. (throw 'exit nil)))
  7987. t)))
  7988. (defun org-refile-cache-put (set &rest identifiers)
  7989. "Push the refile targets SET into the cache, under IDENTIFIERS."
  7990. (let* ((key (sha1 (prin1-to-string identifiers)))
  7991. (entry (assoc key org-refile-cache)))
  7992. (if entry
  7993. (setcdr entry set)
  7994. (push (cons key set) org-refile-cache))))
  7995. (defun org-refile-cache-get (&rest identifiers)
  7996. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  7997. (cond
  7998. ((not org-refile-cache) nil)
  7999. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8000. (t
  8001. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8002. org-refile-cache))))
  8003. (and set (org-refile-cache-check-set set) set)))))
  8004. (defvar org-outline-path-cache nil
  8005. "Alist between buffer positions and outline paths.
  8006. It value is an alist (POSITION . PATH) where POSITION is the
  8007. buffer position at the beginning of an entry and PATH is a list
  8008. of strings describing the outline path for that entry, in reverse
  8009. order.")
  8010. (defun org-refile-get-targets (&optional default-buffer)
  8011. "Produce a table with refile targets."
  8012. (let ((case-fold-search nil)
  8013. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8014. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8015. targets tgs files desc descre)
  8016. (message "Getting targets...")
  8017. (with-current-buffer (or default-buffer (current-buffer))
  8018. (dolist (entry entries)
  8019. (setq files (car entry) desc (cdr entry))
  8020. (cond
  8021. ((null files) (setq files (list (current-buffer))))
  8022. ((eq files 'org-agenda-files)
  8023. (setq files (org-agenda-files 'unrestricted)))
  8024. ((and (symbolp files) (fboundp files))
  8025. (setq files (funcall files)))
  8026. ((and (symbolp files) (boundp files))
  8027. (setq files (symbol-value files))))
  8028. (when (stringp files) (setq files (list files)))
  8029. (cond
  8030. ((eq (car desc) :tag)
  8031. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8032. ((eq (car desc) :todo)
  8033. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8034. ((eq (car desc) :regexp)
  8035. (setq descre (cdr desc)))
  8036. ((eq (car desc) :level)
  8037. (setq descre (concat "^\\*\\{" (number-to-string
  8038. (if org-odd-levels-only
  8039. (1- (* 2 (cdr desc)))
  8040. (cdr desc)))
  8041. "\\}[ \t]")))
  8042. ((eq (car desc) :maxlevel)
  8043. (setq descre (concat "^\\*\\{1," (number-to-string
  8044. (if org-odd-levels-only
  8045. (1- (* 2 (cdr desc)))
  8046. (cdr desc)))
  8047. "\\}[ \t]")))
  8048. (t (error "Bad refiling target description %s" desc)))
  8049. (dolist (f files)
  8050. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8051. (or
  8052. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8053. (progn
  8054. (when (bufferp f)
  8055. (setq f (buffer-file-name (buffer-base-buffer f))))
  8056. (setq f (and f (expand-file-name f)))
  8057. (when (eq org-refile-use-outline-path 'file)
  8058. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8059. (when (eq org-refile-use-outline-path 'buffer-name)
  8060. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8061. (when (eq org-refile-use-outline-path 'full-file-path)
  8062. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8063. (org-with-wide-buffer
  8064. (goto-char (point-min))
  8065. (setq org-outline-path-cache nil)
  8066. (while (re-search-forward descre nil t)
  8067. (beginning-of-line)
  8068. (let ((case-fold-search nil))
  8069. (looking-at org-complex-heading-regexp))
  8070. (let ((begin (point))
  8071. (heading (match-string-no-properties 4)))
  8072. (unless (or (and
  8073. org-refile-target-verify-function
  8074. (not
  8075. (funcall org-refile-target-verify-function)))
  8076. (not heading))
  8077. (let ((re (format org-complex-heading-regexp-format
  8078. (regexp-quote heading)))
  8079. (target
  8080. (if (not org-refile-use-outline-path) heading
  8081. (mapconcat
  8082. #'identity
  8083. (append
  8084. (pcase org-refile-use-outline-path
  8085. (`file (list (file-name-nondirectory
  8086. (buffer-file-name
  8087. (buffer-base-buffer)))))
  8088. (`full-file-path
  8089. (list (buffer-file-name
  8090. (buffer-base-buffer))))
  8091. (`buffer-name
  8092. (list (buffer-name
  8093. (buffer-base-buffer))))
  8094. (_ nil))
  8095. (mapcar (lambda (s) (replace-regexp-in-string
  8096. "/" "\\/" s nil t))
  8097. (org-get-outline-path t t)))
  8098. "/"))))
  8099. (push (list target f re (org-refile-marker (point)))
  8100. tgs)))
  8101. (when (= (point) begin)
  8102. ;; Verification function has not moved point.
  8103. (end-of-line)))))))
  8104. (when org-refile-use-cache
  8105. (org-refile-cache-put tgs (buffer-file-name) descre))
  8106. (setq targets (append tgs targets))))))
  8107. (message "Getting targets...done")
  8108. (delete-dups (nreverse targets))))
  8109. (defun org--get-outline-path-1 (&optional use-cache)
  8110. "Return outline path to current headline.
  8111. Outline path is a list of strings, in reverse order. When
  8112. optional argument USE-CACHE is non-nil, make use of a cache. See
  8113. `org-get-outline-path' for details.
  8114. Assume buffer is widened and point is on a headline."
  8115. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8116. (let ((p (point))
  8117. (heading (let ((case-fold-search nil))
  8118. (looking-at org-complex-heading-regexp)
  8119. (if (not (match-end 4)) ""
  8120. ;; Remove statistics cookies.
  8121. (org-trim
  8122. (org-link-display-format
  8123. (replace-regexp-in-string
  8124. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8125. (match-string-no-properties 4))))))))
  8126. (if (org-up-heading-safe)
  8127. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8128. (when use-cache
  8129. (push (cons p path) org-outline-path-cache))
  8130. path)
  8131. ;; This is a new root node. Since we assume we are moving
  8132. ;; forward, we can drop previous cache so as to limit number
  8133. ;; of associations there.
  8134. (let ((path (list heading)))
  8135. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8136. path)))))
  8137. (defun org-get-outline-path (&optional with-self use-cache)
  8138. "Return the outline path to the current entry.
  8139. An outline path is a list of ancestors for current headline, as
  8140. a list of strings. Statistics cookies are removed and links are
  8141. replaced with their description, if any, or their path otherwise.
  8142. When optional argument WITH-SELF is non-nil, the path also
  8143. includes the current headline.
  8144. When optional argument USE-CACHE is non-nil, cache outline paths
  8145. between calls to this function so as to avoid backtracking. This
  8146. argument is useful when planning to find more than one outline
  8147. path in the same document. In that case, there are two
  8148. conditions to satisfy:
  8149. - `org-outline-path-cache' is set to nil before starting the
  8150. process;
  8151. - outline paths are computed by increasing buffer positions."
  8152. (org-with-wide-buffer
  8153. (and (or (and with-self (org-back-to-heading t))
  8154. (org-up-heading-safe))
  8155. (reverse (org--get-outline-path-1 use-cache)))))
  8156. (defun org-format-outline-path (path &optional width prefix separator)
  8157. "Format the outline path PATH for display.
  8158. WIDTH is the maximum number of characters that is available.
  8159. PREFIX is a prefix to be included in the returned string,
  8160. such as the file name.
  8161. SEPARATOR is inserted between the different parts of the path,
  8162. the default is \"/\"."
  8163. (setq width (or width 79))
  8164. (setq path (delq nil path))
  8165. (unless (> width 0)
  8166. (user-error "Argument `width' must be positive"))
  8167. (setq separator (or separator "/"))
  8168. (let* ((org-odd-levels-only nil)
  8169. (fpath (concat
  8170. prefix (and prefix path separator)
  8171. (mapconcat
  8172. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8173. (cl-loop for head in path
  8174. for n from 0
  8175. collect (org-add-props
  8176. head nil 'face
  8177. (nth (% n org-n-level-faces) org-level-faces)))
  8178. separator))))
  8179. (when (> (length fpath) width)
  8180. (if (< width 7)
  8181. ;; It's unlikely that `width' will be this small, but don't
  8182. ;; waste characters by adding ".." if it is.
  8183. (setq fpath (substring fpath 0 width))
  8184. (setf (substring fpath (- width 2)) "..")))
  8185. fpath))
  8186. (defun org-display-outline-path (&optional file current separator just-return-string)
  8187. "Display the current outline path in the echo area.
  8188. If FILE is non-nil, prepend the output with the file name.
  8189. If CURRENT is non-nil, append the current heading to the output.
  8190. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8191. the different parts of the path and defaults to \"/\".
  8192. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8193. (interactive "P")
  8194. (let* (case-fold-search
  8195. (bfn (buffer-file-name (buffer-base-buffer)))
  8196. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8197. res)
  8198. (when current (setq path (append path
  8199. (save-excursion
  8200. (org-back-to-heading t)
  8201. (when (looking-at org-complex-heading-regexp)
  8202. (list (match-string 4)))))))
  8203. (setq res
  8204. (org-format-outline-path
  8205. path
  8206. (1- (frame-width))
  8207. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8208. separator))
  8209. (if just-return-string
  8210. (org-no-properties res)
  8211. (org-unlogged-message "%s" res))))
  8212. (defvar org-refile-history nil
  8213. "History for refiling operations.")
  8214. (defvar org-after-refile-insert-hook nil
  8215. "Hook run after `org-refile' has inserted its stuff at the new location.
  8216. Note that this is still *before* the stuff will be removed from
  8217. the *old* location.")
  8218. (defvar org-capture-last-stored-marker)
  8219. (defvar org-refile-keep nil
  8220. "Non-nil means `org-refile' will copy instead of refile.")
  8221. (defun org-copy ()
  8222. "Like `org-refile', but copy."
  8223. (interactive)
  8224. (let ((org-refile-keep t))
  8225. (org-refile nil nil nil "Copy")))
  8226. (defun org-refile (&optional arg default-buffer rfloc msg)
  8227. "Move the entry or entries at point to another heading.
  8228. The list of target headings is compiled using the information in
  8229. `org-refile-targets', which see.
  8230. At the target location, the entry is filed as a subitem of the
  8231. target heading. Depending on `org-reverse-note-order', the new
  8232. subitem will either be the first or the last subitem.
  8233. If there is an active region, all entries in that region will be
  8234. refiled. However, the region must fulfill the requirement that
  8235. the first heading sets the top-level of the moved text.
  8236. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8237. location
  8238. and not actually move anything.
  8239. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8240. location where the last
  8241. refiling operation has put the subtree.
  8242. With a numeric prefix argument of `2', refile to the running clock.
  8243. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8244. being set to t and copy to the target location, don't move it.
  8245. Beware that keeping refiled entries may result in duplicated ID
  8246. properties.
  8247. RFLOC can be a refile location obtained in a different way.
  8248. MSG is a string to replace \"Refile\" in the default prompt with
  8249. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8250. See also `org-refile-use-outline-path'.
  8251. If you are using target caching (see `org-refile-use-cache'), you
  8252. have to clear the target cache in order to find new targets.
  8253. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8254. prefix argument (`C-u C-u C-u C-c C-w')."
  8255. (interactive "P")
  8256. (if (member arg '(0 (64)))
  8257. (org-refile-cache-clear)
  8258. (let* ((actionmsg (cond (msg msg)
  8259. ((equal arg 3) "Refile (and keep)")
  8260. (t "Refile")))
  8261. (regionp (org-region-active-p))
  8262. (region-start (and regionp (region-beginning)))
  8263. (region-end (and regionp (region-end)))
  8264. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8265. pos it nbuf file level reversed)
  8266. (setq last-command nil)
  8267. (when regionp
  8268. (goto-char region-start)
  8269. (beginning-of-line)
  8270. (setq region-start (point))
  8271. (unless (or (org-kill-is-subtree-p
  8272. (buffer-substring region-start region-end))
  8273. (prog1 org-refile-active-region-within-subtree
  8274. (let ((s (point-at-eol)))
  8275. (org-toggle-heading)
  8276. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8277. (user-error "The region is not a (sequence of) subtree(s)")))
  8278. (if (equal arg '(16))
  8279. (org-refile-goto-last-stored)
  8280. (when (or
  8281. (and (equal arg 2)
  8282. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8283. (prog1
  8284. (setq it (list (or org-clock-heading "running clock")
  8285. (buffer-file-name
  8286. (marker-buffer org-clock-hd-marker))
  8287. ""
  8288. (marker-position org-clock-hd-marker)))
  8289. (setq arg nil)))
  8290. (setq it
  8291. (or rfloc
  8292. (let (heading-text)
  8293. (save-excursion
  8294. (unless (and arg (listp arg))
  8295. (org-back-to-heading t)
  8296. (setq heading-text
  8297. (replace-regexp-in-string
  8298. org-link-bracket-re
  8299. "\\2"
  8300. (or (nth 4 (org-heading-components))
  8301. ""))))
  8302. (org-refile-get-location
  8303. (cond ((and arg (listp arg)) "Goto")
  8304. (regionp (concat actionmsg " region to"))
  8305. (t (concat actionmsg " subtree \""
  8306. heading-text "\" to")))
  8307. default-buffer
  8308. (and (not (equal '(4) arg))
  8309. org-refile-allow-creating-parent-nodes)))))))
  8310. (setq file (nth 1 it)
  8311. pos (nth 3 it))
  8312. (when (and (not arg)
  8313. pos
  8314. (equal (buffer-file-name) file)
  8315. (if regionp
  8316. (and (>= pos region-start)
  8317. (<= pos region-end))
  8318. (and (>= pos (point))
  8319. (< pos (save-excursion
  8320. (org-end-of-subtree t t))))))
  8321. (error "Cannot refile to position inside the tree or region"))
  8322. (setq nbuf (or (find-buffer-visiting file)
  8323. (find-file-noselect file)))
  8324. (if (and arg (not (equal arg 3)))
  8325. (progn
  8326. (pop-to-buffer-same-window nbuf)
  8327. (goto-char (cond (pos)
  8328. ((org-notes-order-reversed-p) (point-min))
  8329. (t (point-max))))
  8330. (org-show-context 'org-goto))
  8331. (if regionp
  8332. (progn
  8333. (org-kill-new (buffer-substring region-start region-end))
  8334. (org-save-markers-in-region region-start region-end))
  8335. (org-copy-subtree 1 nil t))
  8336. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8337. (find-file-noselect file)))
  8338. (setq reversed (org-notes-order-reversed-p))
  8339. (org-with-wide-buffer
  8340. (if pos
  8341. (progn
  8342. (goto-char pos)
  8343. (setq level (org-get-valid-level (funcall outline-level) 1))
  8344. (goto-char
  8345. (if reversed
  8346. (or (outline-next-heading) (point-max))
  8347. (or (save-excursion (org-get-next-sibling))
  8348. (org-end-of-subtree t t)
  8349. (point-max)))))
  8350. (setq level 1)
  8351. (if (not reversed)
  8352. (goto-char (point-max))
  8353. (goto-char (point-min))
  8354. (or (outline-next-heading) (goto-char (point-max)))))
  8355. (unless (bolp) (newline))
  8356. (org-paste-subtree level nil nil t)
  8357. ;; Record information, according to `org-log-refile'.
  8358. ;; Do not prompt for a note when refiling multiple
  8359. ;; headlines, however. Simply add a time stamp.
  8360. (cond
  8361. ((not org-log-refile))
  8362. (regionp
  8363. (org-map-region
  8364. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8365. (point)
  8366. (+ (point) (- region-end region-start))))
  8367. (t
  8368. (org-add-log-setup 'refile nil nil org-log-refile)))
  8369. (and org-auto-align-tags
  8370. (let ((org-loop-over-headlines-in-active-region nil))
  8371. (org-align-tags)))
  8372. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8373. :last-refile)))
  8374. (when bookmark-name
  8375. (with-demoted-errors
  8376. (bookmark-set bookmark-name))))
  8377. ;; If we are refiling for capture, make sure that the
  8378. ;; last-capture pointers point here
  8379. (when (bound-and-true-p org-capture-is-refiling)
  8380. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8381. :last-capture-marker)))
  8382. (when bookmark-name
  8383. (with-demoted-errors
  8384. (bookmark-set bookmark-name))))
  8385. (move-marker org-capture-last-stored-marker (point)))
  8386. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8387. (run-hooks 'org-after-refile-insert-hook)))
  8388. (unless org-refile-keep
  8389. (if regionp
  8390. (delete-region (point) (+ (point) (- region-end region-start)))
  8391. (org-preserve-local-variables
  8392. (delete-region
  8393. (and (org-back-to-heading t) (point))
  8394. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8395. (when (featurep 'org-inlinetask)
  8396. (org-inlinetask-remove-END-maybe))
  8397. (setq org-markers-to-move nil)
  8398. (message "%s to \"%s\" in file %s: done" actionmsg
  8399. (car it) file)))))))
  8400. (defun org-refile-goto-last-stored ()
  8401. "Go to the location where the last refile was stored."
  8402. (interactive)
  8403. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8404. (message "This is the location of the last refile"))
  8405. (defun org-refile--get-location (refloc tbl)
  8406. "When user refile to REFLOC, find the associated target in TBL.
  8407. Also check `org-refile-target-table'."
  8408. (car (delq
  8409. nil
  8410. (mapcar
  8411. (lambda (r) (or (assoc r tbl)
  8412. (assoc r org-refile-target-table)))
  8413. (list (replace-regexp-in-string "/$" "" refloc)
  8414. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8415. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8416. "Prompt the user for a refile location, using PROMPT.
  8417. PROMPT should not be suffixed with a colon and a space, because
  8418. this function appends the default value from
  8419. `org-refile-history' automatically, if that is not empty."
  8420. (let ((org-refile-targets org-refile-targets)
  8421. (org-refile-use-outline-path org-refile-use-outline-path))
  8422. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8423. (unless org-refile-target-table
  8424. (user-error "No refile targets"))
  8425. (let* ((cbuf (current-buffer))
  8426. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8427. (cfunc (if (and org-refile-use-outline-path
  8428. org-outline-path-complete-in-steps)
  8429. #'org-olpath-completing-read
  8430. #'completing-read))
  8431. (extra (if org-refile-use-outline-path "/" ""))
  8432. (cbnex (concat (buffer-name) extra))
  8433. (filename (and cfn (expand-file-name cfn)))
  8434. (tbl (mapcar
  8435. (lambda (x)
  8436. (if (and (not (member org-refile-use-outline-path
  8437. '(file full-file-path)))
  8438. (not (equal filename (nth 1 x))))
  8439. (cons (concat (car x) extra " ("
  8440. (file-name-nondirectory (nth 1 x)) ")")
  8441. (cdr x))
  8442. (cons (concat (car x) extra) (cdr x))))
  8443. org-refile-target-table))
  8444. (completion-ignore-case t)
  8445. cdef
  8446. (prompt (concat prompt
  8447. (or (and (car org-refile-history)
  8448. (concat " (default " (car org-refile-history) ")"))
  8449. (and (assoc cbnex tbl) (setq cdef cbnex)
  8450. (concat " (default " cbnex ")"))) ": "))
  8451. pa answ parent-target child parent old-hist)
  8452. (setq old-hist org-refile-history)
  8453. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8454. nil 'org-refile-history (or cdef (car org-refile-history))))
  8455. (if (setq pa (org-refile--get-location answ tbl))
  8456. (progn
  8457. (org-refile-check-position pa)
  8458. (when (or (not org-refile-history)
  8459. (not (eq old-hist org-refile-history))
  8460. (not (equal (car pa) (car org-refile-history))))
  8461. (setq org-refile-history
  8462. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8463. org-refile-history
  8464. (cdr org-refile-history))))
  8465. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8466. (pop org-refile-history)))
  8467. pa)
  8468. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8469. (progn
  8470. (setq parent (match-string 1 answ)
  8471. child (match-string 2 answ))
  8472. (setq parent-target (org-refile--get-location parent tbl))
  8473. (when (and parent-target
  8474. (or (eq new-nodes t)
  8475. (and (eq new-nodes 'confirm)
  8476. (y-or-n-p (format "Create new node \"%s\"? "
  8477. child)))))
  8478. (org-refile-new-child parent-target child)))
  8479. (user-error "Invalid target location")))))
  8480. (declare-function org-string-nw-p "org-macs" (s))
  8481. (defun org-refile-check-position (refile-pointer)
  8482. "Check if the refile pointer matches the headline to which it points."
  8483. (let* ((file (nth 1 refile-pointer))
  8484. (re (nth 2 refile-pointer))
  8485. (pos (nth 3 refile-pointer))
  8486. buffer)
  8487. (if (and (not (markerp pos)) (not file))
  8488. (user-error "Please indicate a target file in the refile path")
  8489. (when (org-string-nw-p re)
  8490. (setq buffer (if (markerp pos)
  8491. (marker-buffer pos)
  8492. (or (find-buffer-visiting file)
  8493. (find-file-noselect file))))
  8494. (with-current-buffer buffer
  8495. (org-with-wide-buffer
  8496. (goto-char pos)
  8497. (beginning-of-line 1)
  8498. (unless (looking-at-p re)
  8499. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8500. (defun org-refile-new-child (parent-target child)
  8501. "Use refile target PARENT-TARGET to add new CHILD below it."
  8502. (unless parent-target
  8503. (error "Cannot find parent for new node"))
  8504. (let ((file (nth 1 parent-target))
  8505. (pos (nth 3 parent-target))
  8506. level)
  8507. (with-current-buffer (or (find-buffer-visiting file)
  8508. (find-file-noselect file))
  8509. (org-with-wide-buffer
  8510. (if pos
  8511. (goto-char pos)
  8512. (goto-char (point-max))
  8513. (unless (bolp) (newline)))
  8514. (when (looking-at org-outline-regexp)
  8515. (setq level (funcall outline-level))
  8516. (org-end-of-subtree t t))
  8517. (org-back-over-empty-lines)
  8518. (insert "\n" (make-string
  8519. (if pos (org-get-valid-level level 1) 1) ?*)
  8520. " " child "\n")
  8521. (beginning-of-line 0)
  8522. (list (concat (car parent-target) "/" child) file "" (point))))))
  8523. (defun org-olpath-completing-read (prompt collection &rest args)
  8524. "Read an outline path like a file name."
  8525. (let ((thetable collection))
  8526. (apply #'completing-read
  8527. prompt
  8528. (lambda (string predicate &optional flag)
  8529. (cond
  8530. ((eq flag nil) (try-completion string thetable))
  8531. ((eq flag t)
  8532. (let ((l (length string)))
  8533. (mapcar (lambda (x)
  8534. (let ((r (substring x l))
  8535. (f (if (string-match " ([^)]*)$" x)
  8536. (match-string 0 x)
  8537. "")))
  8538. (if (string-match "/" r)
  8539. (concat string (substring r 0 (match-end 0)) f)
  8540. x)))
  8541. (all-completions string thetable predicate))))
  8542. ;; Exact match?
  8543. ((eq flag 'lambda) (assoc string thetable))))
  8544. args)))
  8545. ;;;; Dynamic blocks
  8546. (defun org-find-dblock (name)
  8547. "Find the first dynamic block with name NAME in the buffer.
  8548. If not found, stay at current position and return nil."
  8549. (let ((case-fold-search t) pos)
  8550. (save-excursion
  8551. (goto-char (point-min))
  8552. (setq pos (and (re-search-forward
  8553. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8554. (match-beginning 0))))
  8555. (when pos (goto-char pos))
  8556. pos))
  8557. (defun org-create-dblock (plist)
  8558. "Create a dynamic block section, with parameters taken from PLIST.
  8559. PLIST must contain a :name entry which is used as the name of the block."
  8560. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8561. (end-of-line 1)
  8562. (newline))
  8563. (let ((col (current-column))
  8564. (name (plist-get plist :name)))
  8565. (insert "#+BEGIN: " name)
  8566. (while plist
  8567. (if (eq (car plist) :name)
  8568. (setq plist (cddr plist))
  8569. (insert " " (prin1-to-string (pop plist)))))
  8570. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8571. (beginning-of-line -2)))
  8572. (defun org-prepare-dblock ()
  8573. "Prepare dynamic block for refresh.
  8574. This empties the block, puts the cursor at the insert position and returns
  8575. the property list including an extra property :name with the block name."
  8576. (unless (looking-at org-dblock-start-re)
  8577. (user-error "Not at a dynamic block"))
  8578. (let* ((begdel (1+ (match-end 0)))
  8579. (name (org-no-properties (match-string 1)))
  8580. (params (append (list :name name)
  8581. (read (concat "(" (match-string 3) ")")))))
  8582. (save-excursion
  8583. (beginning-of-line 1)
  8584. (skip-chars-forward " \t")
  8585. (setq params (plist-put params :indentation-column (current-column))))
  8586. (unless (re-search-forward org-dblock-end-re nil t)
  8587. (error "Dynamic block not terminated"))
  8588. (setq params
  8589. (append params
  8590. (list :content (buffer-substring
  8591. begdel (match-beginning 0)))))
  8592. (delete-region begdel (match-beginning 0))
  8593. (goto-char begdel)
  8594. (open-line 1)
  8595. params))
  8596. (defun org-map-dblocks (&optional command)
  8597. "Apply COMMAND to all dynamic blocks in the current buffer.
  8598. If COMMAND is not given, use `org-update-dblock'."
  8599. (let ((cmd (or command 'org-update-dblock)))
  8600. (save-excursion
  8601. (goto-char (point-min))
  8602. (while (re-search-forward org-dblock-start-re nil t)
  8603. (goto-char (match-beginning 0))
  8604. (save-excursion
  8605. (condition-case nil
  8606. (funcall cmd)
  8607. (error (message "Error during update of dynamic block"))))
  8608. (unless (re-search-forward org-dblock-end-re nil t)
  8609. (error "Dynamic block not terminated"))))))
  8610. (defvar org-dynamic-block-alist nil
  8611. "Alist defining all the Org dynamic blocks.
  8612. The key is the dynamic block type name, as a string. The value
  8613. is the function used to insert the dynamic block.
  8614. Use `org-dynamic-block-define' to populate it.")
  8615. (defun org-dynamic-block-function (type)
  8616. "Return function associated to a given dynamic block type.
  8617. TYPE is the dynamic block type, as a string."
  8618. (cdr (assoc type org-dynamic-block-alist)))
  8619. (defun org-dynamic-block-types ()
  8620. "List all defined dynamic block types."
  8621. (mapcar #'car org-dynamic-block-alist))
  8622. (defun org-dynamic-block-define (type func)
  8623. "Define dynamic block TYPE with FUNC.
  8624. TYPE is a string. FUNC is the function creating the dynamic
  8625. block of such type."
  8626. (pcase (assoc type org-dynamic-block-alist)
  8627. (`nil (push (cons type func) org-dynamic-block-alist))
  8628. (def (setcdr def func))))
  8629. (defun org-dynamic-block-insert-dblock (type)
  8630. "Insert a dynamic block of type TYPE.
  8631. When used interactively, select the dynamic block types among
  8632. defined types, per `org-dynamic-block-define'."
  8633. (interactive (list (completing-read "Dynamic block: "
  8634. (org-dynamic-block-types))))
  8635. (pcase (org-dynamic-block-function type)
  8636. (`nil (error "No such dynamic block: %S" type))
  8637. ((and f (pred functionp)) (funcall f))
  8638. (_ (error "Invalid function for dynamic block %S" type))))
  8639. (defun org-dblock-update (&optional arg)
  8640. "User command for updating dynamic blocks.
  8641. Update the dynamic block at point. With prefix ARG, update all dynamic
  8642. blocks in the buffer."
  8643. (interactive "P")
  8644. (if arg
  8645. (org-update-all-dblocks)
  8646. (or (looking-at org-dblock-start-re)
  8647. (org-beginning-of-dblock))
  8648. (org-update-dblock)))
  8649. (defun org-update-dblock ()
  8650. "Update the dynamic block at point.
  8651. This means to empty the block, parse for parameters and then call
  8652. the correct writing function."
  8653. (interactive)
  8654. (save-excursion
  8655. (let* ((win (selected-window))
  8656. (pos (point))
  8657. (line (org-current-line))
  8658. (params (org-prepare-dblock))
  8659. (name (plist-get params :name))
  8660. (indent (plist-get params :indentation-column))
  8661. (cmd (intern (concat "org-dblock-write:" name))))
  8662. (message "Updating dynamic block `%s' at line %d..." name line)
  8663. (funcall cmd params)
  8664. (message "Updating dynamic block `%s' at line %d...done" name line)
  8665. (goto-char pos)
  8666. (when (and indent (> indent 0))
  8667. (setq indent (make-string indent ?\ ))
  8668. (save-excursion
  8669. (select-window win)
  8670. (org-beginning-of-dblock)
  8671. (forward-line 1)
  8672. (while (not (looking-at org-dblock-end-re))
  8673. (insert indent)
  8674. (beginning-of-line 2))
  8675. (when (looking-at org-dblock-end-re)
  8676. (and (looking-at "[ \t]+")
  8677. (replace-match ""))
  8678. (insert indent)))))))
  8679. (defun org-beginning-of-dblock ()
  8680. "Find the beginning of the dynamic block at point.
  8681. Error if there is no such block at point."
  8682. (let ((pos (point))
  8683. beg)
  8684. (end-of-line 1)
  8685. (if (and (re-search-backward org-dblock-start-re nil t)
  8686. (setq beg (match-beginning 0))
  8687. (re-search-forward org-dblock-end-re nil t)
  8688. (> (match-end 0) pos))
  8689. (goto-char beg)
  8690. (goto-char pos)
  8691. (error "Not in a dynamic block"))))
  8692. (defun org-update-all-dblocks ()
  8693. "Update all dynamic blocks in the buffer.
  8694. This function can be used in a hook."
  8695. (interactive)
  8696. (when (derived-mode-p 'org-mode)
  8697. (org-map-dblocks 'org-update-dblock)))
  8698. ;;;; Completion
  8699. (declare-function org-export-backend-options "ox" (cl-x) t)
  8700. (defun org-get-export-keywords ()
  8701. "Return a list of all currently understood export keywords.
  8702. Export keywords include options, block names, attributes and
  8703. keywords relative to each registered export back-end."
  8704. (let (keywords)
  8705. (dolist (backend
  8706. (bound-and-true-p org-export-registered-backends)
  8707. (delq nil keywords))
  8708. ;; Back-end name (for keywords, like #+LATEX:)
  8709. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8710. (dolist (option-entry (org-export-backend-options backend))
  8711. ;; Back-end options.
  8712. (push (nth 1 option-entry) keywords)))))
  8713. (defconst org-options-keywords
  8714. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8715. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8716. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8717. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8718. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8719. (defcustom org-structure-template-alist
  8720. '(("a" . "export ascii")
  8721. ("c" . "center")
  8722. ("C" . "comment")
  8723. ("e" . "example")
  8724. ("E" . "export")
  8725. ("h" . "export html")
  8726. ("l" . "export latex")
  8727. ("q" . "quote")
  8728. ("s" . "src")
  8729. ("v" . "verse"))
  8730. "An alist of keys and block types.
  8731. `org-insert-structure-template' will display a menu with this
  8732. list of templates to choose from. The block type is inserted,
  8733. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8734. The menu keys are defined by the car of each entry in this alist.
  8735. If two entries have the keys \"a\" and \"aa\" respectively, the
  8736. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8737. latter will be inserted by typing \"aa\". If an entry with the
  8738. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8739. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8740. block can be inserted by pressing TAB after the string \"<KEY\"."
  8741. :group 'org-edit-structure
  8742. :type '(repeat
  8743. (cons (string :tag "Key")
  8744. (string :tag "Template")))
  8745. :package-version '(Org . "9.2"))
  8746. (defun org--check-org-structure-template-alist (&optional checklist)
  8747. "Check whether `org-structure-template-alist' is set up correctly.
  8748. In particular, check if the Org 9.2 format is used as opposed to
  8749. previous format.
  8750. "
  8751. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8752. (or (eval checklist)
  8753. org-structure-template-alist))))
  8754. (when elm
  8755. (org-display-warning
  8756. (format "
  8757. Please update the entries of `%s'.
  8758. In Org 9.2 the format was changed from something like
  8759. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8760. to something like
  8761. (\"s\" . \"src\")
  8762. Please refer to the documentation of `org-structure-template-alist'.
  8763. The following entries must be updated:
  8764. %s"
  8765. (or checklist 'org-structure-template-alist)
  8766. (pp-to-string elm))))))
  8767. (defun org--insert-structure-template-mks ()
  8768. "Present `org-structure-template-alist' with `org-mks'.
  8769. Menus are added if keys require more than one keystroke. Tabs
  8770. are added to single key entries when more than one stroke is
  8771. needed. Keys longer than two characters are reduced to two
  8772. characters."
  8773. (org--check-org-structure-template-alist)
  8774. (let* (case-fold-search
  8775. (templates (append org-structure-template-alist
  8776. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8777. (keys (mapcar #'car templates))
  8778. (start-letters
  8779. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8780. ;; Sort each element of `org-structure-template-alist' into
  8781. ;; sublists according to the first letter.
  8782. (superlist
  8783. (mapcar (lambda (letter)
  8784. (list letter
  8785. (cl-remove-if-not
  8786. (apply-partially #'string-match-p (concat "^" letter))
  8787. templates :key #'car)))
  8788. start-letters)))
  8789. (org-mks
  8790. (apply #'append
  8791. ;; Make an `org-mks' table. If only one element is
  8792. ;; present in a sublist, make it part of the top-menu,
  8793. ;; otherwise make a submenu according to the starting
  8794. ;; letter and populate it.
  8795. (mapcar (lambda (sublist)
  8796. (if (eq 1 (length (cadr sublist)))
  8797. (mapcar (lambda (elm)
  8798. (list (substring (car elm) 0 1)
  8799. (cdr elm) ""))
  8800. (cadr sublist))
  8801. ;; Create submenu.
  8802. (let* ((topkey (car sublist))
  8803. (elms (cadr sublist))
  8804. (keys (mapcar #'car elms))
  8805. (long (> (length elms) 3)))
  8806. (append
  8807. (list
  8808. ;; Make a description of the submenu.
  8809. (list topkey
  8810. (concat
  8811. (mapconcat #'cdr
  8812. (cl-subseq elms 0 (if long 3 (length elms)))
  8813. ", ")
  8814. (when long ", ..."))))
  8815. ;; List of entries in submenu.
  8816. (cl-mapcar #'list
  8817. (org--insert-structure-template-unique-keys keys)
  8818. (mapcar #'cdr elms)
  8819. (make-list (length elms) ""))))))
  8820. superlist))
  8821. "Select a key\n============"
  8822. "Key: ")))
  8823. (defun org--insert-structure-template-unique-keys (keys)
  8824. "Make a list of unique, two characters long elements from KEYS.
  8825. Elements of length one have a tab appended. Elements of length
  8826. two are kept as is. Longer elements are truncated to length two.
  8827. If an element cannot be made unique, an error is raised."
  8828. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8829. menu-keys)
  8830. (dolist (key orderd-keys)
  8831. (let ((potential-key
  8832. (cl-case (length key)
  8833. (1 (concat key "\t"))
  8834. (2 key)
  8835. (otherwise
  8836. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8837. (mapcar (apply-partially #'concat (substring key 0 1))
  8838. (split-string (substring key 1) "" t)))))))
  8839. (if (or (not potential-key) (assoc potential-key menu-keys))
  8840. (user-error "Could not make unique key for %s." key)
  8841. (push (cons potential-key key) menu-keys))))
  8842. (mapcar #'car
  8843. (cl-sort menu-keys #'<
  8844. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8845. (defun org-insert-structure-template (type)
  8846. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8847. Select a block from `org-structure-template-alist' then type
  8848. either RET, TAB or SPC to write the block type. With an active
  8849. region, wrap the region in the block. Otherwise, insert an empty
  8850. block."
  8851. (interactive
  8852. (list (pcase (org--insert-structure-template-mks)
  8853. (`("\t" . ,_) (read-string "Structure type: "))
  8854. (`(,_ ,choice . ,_) choice))))
  8855. (let* ((region? (use-region-p))
  8856. (region-start (and region? (region-beginning)))
  8857. (region-end (and region? (copy-marker (region-end))))
  8858. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8859. (verbatim? (string-match-p
  8860. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8861. type)))
  8862. (when region? (goto-char region-start))
  8863. (let ((column (current-indentation)))
  8864. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8865. (beginning-of-line)
  8866. (insert "\n"))
  8867. (save-excursion
  8868. (indent-to column)
  8869. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8870. (when region?
  8871. (when verbatim? (org-escape-code-in-region (point) region-end))
  8872. (goto-char region-end)
  8873. ;; Ignore empty lines at the end of the region.
  8874. (skip-chars-backward " \r\t\n")
  8875. (end-of-line))
  8876. (unless (bolp) (insert "\n"))
  8877. (indent-to column)
  8878. (insert (format "#+end_%s" (car (split-string type))))
  8879. (if (looking-at "[ \t]*$") (replace-match "")
  8880. (insert "\n"))
  8881. (when (and (eobp) (not (bolp))) (insert "\n")))
  8882. (if extended? (end-of-line)
  8883. (forward-line)
  8884. (skip-chars-forward " \t")))))
  8885. ;;;; TODO, DEADLINE, Comments
  8886. (defun org-toggle-comment ()
  8887. "Change the COMMENT state of an entry."
  8888. (interactive)
  8889. (save-excursion
  8890. (org-back-to-heading)
  8891. (let ((case-fold-search nil))
  8892. (looking-at org-complex-heading-regexp))
  8893. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8894. (skip-chars-forward " \t")
  8895. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8896. (if (org-in-commented-heading-p t)
  8897. (delete-region (point)
  8898. (progn (search-forward " " (line-end-position) 'move)
  8899. (skip-chars-forward " \t")
  8900. (point)))
  8901. (insert org-comment-string)
  8902. (unless (eolp) (insert " ")))))
  8903. (defvar org-last-todo-state-is-todo nil
  8904. "This is non-nil when the last TODO state change led to a TODO state.
  8905. If the last change removed the TODO tag or switched to DONE, then
  8906. this is nil.")
  8907. (defvar org-todo-setup-filter-hook nil
  8908. "Hook for functions that pre-filter todo specs.
  8909. Each function takes a todo spec and returns either nil or the spec
  8910. transformed into canonical form." )
  8911. (defvar org-todo-get-default-hook nil
  8912. "Hook for functions that get a default item for todo.
  8913. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8914. nil or a string to be used for the todo mark." )
  8915. (defvar org-agenda-headline-snapshot-before-repeat)
  8916. (defun org-current-effective-time ()
  8917. "Return current time adjusted for `org-extend-today-until' variable."
  8918. (let* ((ct (org-current-time))
  8919. (dct (decode-time ct))
  8920. (ct1
  8921. (cond
  8922. (org-use-last-clock-out-time-as-effective-time
  8923. (or (org-clock-get-last-clock-out-time) ct))
  8924. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8925. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8926. (t ct))))
  8927. ct1))
  8928. (defun org-todo-yesterday (&optional arg)
  8929. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8930. (interactive "P")
  8931. (if (eq major-mode 'org-agenda-mode)
  8932. (apply 'org-agenda-todo-yesterday arg)
  8933. (let* ((org-use-effective-time t)
  8934. (hour (nth 2 (decode-time (org-current-time))))
  8935. (org-extend-today-until (1+ hour)))
  8936. (org-todo arg))))
  8937. (defvar org-block-entry-blocking ""
  8938. "First entry preventing the TODO state change.")
  8939. (defun org-cancel-repeater ()
  8940. "Cancel a repeater by setting its numeric value to zero."
  8941. (interactive)
  8942. (save-excursion
  8943. (org-back-to-heading t)
  8944. (let ((bound1 (point))
  8945. (bound0 (save-excursion (outline-next-heading) (point))))
  8946. (when (and (re-search-forward
  8947. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8948. org-deadline-time-regexp "\\)\\|\\("
  8949. org-ts-regexp "\\)")
  8950. bound0 t)
  8951. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8952. bound1 t))
  8953. (replace-match "0" t nil nil 1)))))
  8954. (defvar org-state)
  8955. (defvar org-blocked-by-checkboxes)
  8956. (defun org-todo (&optional arg)
  8957. "Change the TODO state of an item.
  8958. The state of an item is given by a keyword at the start of the heading,
  8959. like
  8960. *** TODO Write paper
  8961. *** DONE Call mom
  8962. The different keywords are specified in the variable `org-todo-keywords'.
  8963. By default the available states are \"TODO\" and \"DONE\". So, for this
  8964. example: when the item starts with TODO, it is changed to DONE.
  8965. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8966. DONE are present, add TODO at the beginning of the heading.
  8967. You can set up single-charcter keys to fast-select the new state. See the
  8968. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8969. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8970. and take a
  8971. logging note.
  8972. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8973. next set of TODO \
  8974. keywords (nextset).
  8975. Another way to achieve this is `S-C-<right>'.
  8976. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8977. prefix, circumvent any state blocking.
  8978. With numeric prefix arg, switch to the Nth state.
  8979. With a numeric prefix arg of 0, inhibit note taking for the change.
  8980. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8981. When called through ELisp, arg is also interpreted in the following way:
  8982. `none' -> empty state
  8983. \"\" -> switch to empty state
  8984. `done' -> switch to DONE
  8985. `nextset' -> switch to the next set of keywords
  8986. `previousset' -> switch to the previous set of keywords
  8987. \"WAITING\" -> switch to the specified keyword, but only if it
  8988. really is a member of `org-todo-keywords'."
  8989. (interactive "P")
  8990. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8991. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8992. 'region-start-level 'region))
  8993. org-loop-over-headlines-in-active-region)
  8994. (org-map-entries
  8995. `(org-todo ,arg)
  8996. org-loop-over-headlines-in-active-region
  8997. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8998. (when (equal arg '(16)) (setq arg 'nextset))
  8999. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9000. (let ((org-blocker-hook org-blocker-hook)
  9001. commentp
  9002. case-fold-search)
  9003. (when (equal arg '(64))
  9004. (setq arg nil org-blocker-hook nil))
  9005. (when (and org-blocker-hook
  9006. (or org-inhibit-blocking
  9007. (org-entry-get nil "NOBLOCKING")))
  9008. (setq org-blocker-hook nil))
  9009. (save-excursion
  9010. (catch 'exit
  9011. (org-back-to-heading t)
  9012. (when (org-in-commented-heading-p t)
  9013. (org-toggle-comment)
  9014. (setq commentp t))
  9015. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9016. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9017. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9018. (let* ((match-data (match-data))
  9019. (startpos (copy-marker (line-beginning-position)))
  9020. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9021. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9022. (org-log-done org-log-done)
  9023. (org-log-repeat org-log-repeat)
  9024. (org-todo-log-states org-todo-log-states)
  9025. (org-inhibit-logging
  9026. (if (equal arg 0)
  9027. (progn (setq arg nil) 'note) org-inhibit-logging))
  9028. (this (match-string 1))
  9029. (hl-pos (match-beginning 0))
  9030. (head (org-get-todo-sequence-head this))
  9031. (ass (assoc head org-todo-kwd-alist))
  9032. (interpret (nth 1 ass))
  9033. (done-word (nth 3 ass))
  9034. (final-done-word (nth 4 ass))
  9035. (org-last-state (or this ""))
  9036. (completion-ignore-case t)
  9037. (member (member this org-todo-keywords-1))
  9038. (tail (cdr member))
  9039. (org-state (cond
  9040. ((eq arg 'right)
  9041. ;; Next state
  9042. (if this
  9043. (if tail (car tail) nil)
  9044. (car org-todo-keywords-1)))
  9045. ((eq arg 'left)
  9046. ;; Previous state
  9047. (unless (equal member org-todo-keywords-1)
  9048. (if this
  9049. (nth (- (length org-todo-keywords-1)
  9050. (length tail) 2)
  9051. org-todo-keywords-1)
  9052. (org-last org-todo-keywords-1))))
  9053. (arg
  9054. ;; User or caller requests a specific state.
  9055. (cond
  9056. ((equal arg "") nil)
  9057. ((eq arg 'none) nil)
  9058. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9059. ((eq arg 'nextset)
  9060. (or (car (cdr (member head org-todo-heads)))
  9061. (car org-todo-heads)))
  9062. ((eq arg 'previousset)
  9063. (let ((org-todo-heads (reverse org-todo-heads)))
  9064. (or (car (cdr (member head org-todo-heads)))
  9065. (car org-todo-heads))))
  9066. ((car (member arg org-todo-keywords-1)))
  9067. ((stringp arg)
  9068. (user-error "State `%s' not valid in this file" arg))
  9069. ((nth (1- (prefix-numeric-value arg))
  9070. org-todo-keywords-1))))
  9071. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9072. ;; Use fast selection.
  9073. (org-fast-todo-selection this))
  9074. ((null member) (or head (car org-todo-keywords-1)))
  9075. ((equal this final-done-word) nil) ;-> make empty
  9076. ((null tail) nil) ;-> first entry
  9077. ((memq interpret '(type priority))
  9078. (if (eq this-command last-command)
  9079. (car tail)
  9080. (if (> (length tail) 0)
  9081. (or done-word (car org-done-keywords))
  9082. nil)))
  9083. (t
  9084. (car tail))))
  9085. (org-state (or
  9086. (run-hook-with-args-until-success
  9087. 'org-todo-get-default-hook org-state org-last-state)
  9088. org-state))
  9089. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9090. (change-plist (list :type 'todo-state-change :from this :to org-state
  9091. :position startpos))
  9092. dolog now-done-p)
  9093. (when org-blocker-hook
  9094. (let (org-blocked-by-checkboxes block-reason)
  9095. (setq org-last-todo-state-is-todo
  9096. (not (member this org-done-keywords)))
  9097. (unless (save-excursion
  9098. (save-match-data
  9099. (org-with-wide-buffer
  9100. (run-hook-with-args-until-failure
  9101. 'org-blocker-hook change-plist))))
  9102. (setq block-reason (if org-blocked-by-checkboxes
  9103. "contained checkboxes"
  9104. (format "\"%s\"" org-block-entry-blocking)))
  9105. (if (called-interactively-p 'interactive)
  9106. (user-error "TODO state change from %s to %s blocked (by %s)"
  9107. this org-state block-reason)
  9108. ;; Fail silently.
  9109. (message "TODO state change from %s to %s blocked (by %s)"
  9110. this org-state block-reason)
  9111. (throw 'exit nil)))))
  9112. (store-match-data match-data)
  9113. (replace-match next t t)
  9114. (cond ((equal this org-state)
  9115. (message "TODO state was already %s" (org-trim next)))
  9116. ((not (pos-visible-in-window-p hl-pos))
  9117. (message "TODO state changed to %s" (org-trim next))))
  9118. (unless head
  9119. (setq head (org-get-todo-sequence-head org-state)
  9120. ass (assoc head org-todo-kwd-alist)
  9121. interpret (nth 1 ass)
  9122. done-word (nth 3 ass)
  9123. final-done-word (nth 4 ass)))
  9124. (when (memq arg '(nextset previousset))
  9125. (message "Keyword-Set %d/%d: %s"
  9126. (- (length org-todo-sets) -1
  9127. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9128. (length org-todo-sets)
  9129. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9130. (setq org-last-todo-state-is-todo
  9131. (not (member org-state org-done-keywords)))
  9132. (setq now-done-p (and (member org-state org-done-keywords)
  9133. (not (member this org-done-keywords))))
  9134. (and logging (org-local-logging logging))
  9135. (when (or (and (or org-todo-log-states org-log-done)
  9136. (not (eq org-inhibit-logging t))
  9137. (not (memq arg '(nextset previousset))))
  9138. force-log)
  9139. ;; We need to look at recording a time and note.
  9140. (setq dolog (or (if force-log 'note)
  9141. (nth 1 (assoc org-state org-todo-log-states))
  9142. (nth 2 (assoc this org-todo-log-states))))
  9143. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9144. (setq dolog 'time))
  9145. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9146. (and org-state
  9147. (member org-state org-not-done-keywords)
  9148. (not (member this org-not-done-keywords))))
  9149. ;; This is now a todo state and was not one before
  9150. ;; If there was a CLOSED time stamp, get rid of it.
  9151. (org-add-planning-info nil nil 'closed))
  9152. (when (and now-done-p org-log-done)
  9153. ;; It is now done, and it was not done before.
  9154. (org-add-planning-info 'closed (org-current-effective-time))
  9155. (when (and (not dolog) (eq 'note org-log-done))
  9156. (org-add-log-setup 'done org-state this 'note)))
  9157. (when (and org-state dolog)
  9158. ;; This is a non-nil state, and we need to log it.
  9159. (org-add-log-setup 'state org-state this dolog)))
  9160. ;; Fixup tag positioning.
  9161. (org-todo-trigger-tag-changes org-state)
  9162. (when org-auto-align-tags (org-align-tags))
  9163. (when org-provide-todo-statistics
  9164. (org-update-parent-todo-statistics))
  9165. (when (bound-and-true-p org-clock-out-when-done)
  9166. (org-clock-out-if-current))
  9167. (run-hooks 'org-after-todo-state-change-hook)
  9168. (when (and arg (not (member org-state org-done-keywords)))
  9169. (setq head (org-get-todo-sequence-head org-state)))
  9170. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9171. ;; Do we need to trigger a repeat?
  9172. (when now-done-p
  9173. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9174. ;; This is for the agenda, take a snapshot of the headline.
  9175. (save-match-data
  9176. (setq org-agenda-headline-snapshot-before-repeat
  9177. (org-get-heading))))
  9178. (org-auto-repeat-maybe org-state))
  9179. ;; Fixup cursor location if close to the keyword.
  9180. (when (and (outline-on-heading-p)
  9181. (not (bolp))
  9182. (save-excursion (beginning-of-line 1)
  9183. (looking-at org-todo-line-regexp))
  9184. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9185. (goto-char (or (match-end 2) (match-end 1)))
  9186. (and (looking-at " ")
  9187. (not (looking-at " *:"))
  9188. (just-one-space)))
  9189. (when org-trigger-hook
  9190. (save-excursion
  9191. (run-hook-with-args 'org-trigger-hook change-plist)))
  9192. (when commentp (org-toggle-comment))))))))
  9193. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9194. "Block turning an entry into a TODO, using the hierarchy.
  9195. This checks whether the current task should be blocked from state
  9196. changes. Such blocking occurs when:
  9197. 1. The task has children which are not all in a completed state.
  9198. 2. A task has a parent with the property :ORDERED:, and there
  9199. are siblings prior to the current task with incomplete
  9200. status.
  9201. 3. The parent of the task is blocked because it has siblings that should
  9202. be done first, or is child of a block grandparent TODO entry."
  9203. (if (not org-enforce-todo-dependencies)
  9204. t ; if locally turned off don't block
  9205. (catch 'dont-block
  9206. ;; If this is not a todo state change, or if this entry is already DONE,
  9207. ;; do not block
  9208. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9209. (member (plist-get change-plist :from)
  9210. (cons 'done org-done-keywords))
  9211. (member (plist-get change-plist :to)
  9212. (cons 'todo org-not-done-keywords))
  9213. (not (plist-get change-plist :to)))
  9214. (throw 'dont-block t))
  9215. ;; If this task has children, and any are undone, it's blocked
  9216. (save-excursion
  9217. (org-back-to-heading t)
  9218. (let ((this-level (funcall outline-level)))
  9219. (outline-next-heading)
  9220. (let ((child-level (funcall outline-level)))
  9221. (while (and (not (eobp))
  9222. (> child-level this-level))
  9223. ;; this todo has children, check whether they are all
  9224. ;; completed
  9225. (when (and (not (org-entry-is-done-p))
  9226. (org-entry-is-todo-p))
  9227. (setq org-block-entry-blocking (org-get-heading))
  9228. (throw 'dont-block nil))
  9229. (outline-next-heading)
  9230. (setq child-level (funcall outline-level))))))
  9231. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9232. ;; any previous siblings are undone, it's blocked
  9233. (save-excursion
  9234. (org-back-to-heading t)
  9235. (let* ((pos (point))
  9236. (parent-pos (and (org-up-heading-safe) (point)))
  9237. (case-fold-search nil))
  9238. (unless parent-pos (throw 'dont-block t)) ; no parent
  9239. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9240. (forward-line 1)
  9241. (re-search-forward org-not-done-heading-regexp pos t))
  9242. (setq org-block-entry-blocking (match-string 0))
  9243. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9244. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9245. (while t
  9246. (goto-char parent-pos)
  9247. (unless (looking-at org-not-done-heading-regexp)
  9248. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9249. (setq pos (point))
  9250. (setq parent-pos (and (org-up-heading-safe) (point)))
  9251. (unless parent-pos (throw 'dont-block t)) ; no parent
  9252. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9253. (forward-line 1)
  9254. (re-search-forward org-not-done-heading-regexp pos t)
  9255. (setq org-block-entry-blocking (org-get-heading)))
  9256. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9257. (defcustom org-track-ordered-property-with-tag nil
  9258. "Should the ORDERED property also be shown as a tag?
  9259. The ORDERED property decides if an entry should require subtasks to be
  9260. completed in sequence. Since a property is not very visible, setting
  9261. this option means that toggling the ORDERED property with the command
  9262. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9263. not relevant for the behavior, but it makes things more visible.
  9264. Note that toggling the tag with tags commands will not change the property
  9265. and therefore not influence behavior!
  9266. This can be t, meaning the tag ORDERED should be used. It can also be a
  9267. string to select a different tag for this task."
  9268. :group 'org-todo
  9269. :type '(choice
  9270. (const :tag "No tracking" nil)
  9271. (const :tag "Track with ORDERED tag" t)
  9272. (string :tag "Use other tag")))
  9273. (defun org-toggle-ordered-property ()
  9274. "Toggle the ORDERED property of the current entry.
  9275. For better visibility, you can track the value of this property with a tag.
  9276. See variable `org-track-ordered-property-with-tag'."
  9277. (interactive)
  9278. (let* ((t1 org-track-ordered-property-with-tag)
  9279. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9280. (save-excursion
  9281. (org-back-to-heading)
  9282. (if (org-entry-get nil "ORDERED")
  9283. (progn
  9284. (org-delete-property "ORDERED")
  9285. (and tag (org-toggle-tag tag 'off))
  9286. (message "Subtasks can be completed in arbitrary order"))
  9287. (org-entry-put nil "ORDERED" "t")
  9288. (and tag (org-toggle-tag tag 'on))
  9289. (message "Subtasks must be completed in sequence")))))
  9290. (defun org-block-todo-from-checkboxes (change-plist)
  9291. "Block turning an entry into a TODO, using checkboxes.
  9292. This checks whether the current task should be blocked from state
  9293. changes because there are unchecked boxes in this entry."
  9294. (if (not org-enforce-todo-checkbox-dependencies)
  9295. t ; if locally turned off don't block
  9296. (catch 'dont-block
  9297. ;; If this is not a todo state change, or if this entry is already DONE,
  9298. ;; do not block
  9299. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9300. (member (plist-get change-plist :from)
  9301. (cons 'done org-done-keywords))
  9302. (member (plist-get change-plist :to)
  9303. (cons 'todo org-not-done-keywords))
  9304. (not (plist-get change-plist :to)))
  9305. (throw 'dont-block t))
  9306. ;; If this task has checkboxes that are not checked, it's blocked
  9307. (save-excursion
  9308. (org-back-to-heading t)
  9309. (let ((beg (point)) end)
  9310. (outline-next-heading)
  9311. (setq end (point))
  9312. (goto-char beg)
  9313. (when (org-list-search-forward
  9314. (concat (org-item-beginning-re)
  9315. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9316. "\\[[- ]\\]")
  9317. end t)
  9318. (when (boundp 'org-blocked-by-checkboxes)
  9319. (setq org-blocked-by-checkboxes t))
  9320. (throw 'dont-block nil))))
  9321. t))) ; do not block
  9322. (defun org-entry-blocked-p ()
  9323. "Non-nil if entry at point is blocked."
  9324. (and (not (org-entry-get nil "NOBLOCKING"))
  9325. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9326. (not (run-hook-with-args-until-failure
  9327. 'org-blocker-hook
  9328. (list :type 'todo-state-change
  9329. :position (point)
  9330. :from 'todo
  9331. :to 'done)))))
  9332. (defun org-update-statistics-cookies (all)
  9333. "Update the statistics cookie, either from TODO or from checkboxes.
  9334. This should be called with the cursor in a line with a statistics
  9335. cookie. When called with a \\[universal-argument] prefix, update
  9336. all statistics cookies in the buffer."
  9337. (interactive "P")
  9338. (if all
  9339. (progn
  9340. (org-update-checkbox-count 'all)
  9341. (org-map-entries 'org-update-parent-todo-statistics))
  9342. (if (not (org-at-heading-p))
  9343. (org-update-checkbox-count)
  9344. (let ((pos (point-marker))
  9345. end l1 l2)
  9346. (ignore-errors (org-back-to-heading t))
  9347. (if (not (org-at-heading-p))
  9348. (org-update-checkbox-count)
  9349. (setq l1 (org-outline-level))
  9350. (setq end (save-excursion
  9351. (outline-next-heading)
  9352. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9353. (point)))
  9354. (if (and (save-excursion
  9355. (re-search-forward
  9356. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9357. (not (save-excursion (re-search-forward
  9358. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9359. (org-update-checkbox-count)
  9360. (if (and l2 (> l2 l1))
  9361. (progn
  9362. (goto-char end)
  9363. (org-update-parent-todo-statistics))
  9364. (goto-char pos)
  9365. (beginning-of-line 1)
  9366. (while (re-search-forward
  9367. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9368. (point-at-eol) t)
  9369. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9370. (goto-char pos)
  9371. (move-marker pos nil)))))
  9372. (defvar org-entry-property-inherited-from) ;; defined below
  9373. (defun org-update-parent-todo-statistics ()
  9374. "Update any statistics cookie in the parent of the current headline.
  9375. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9376. the entire subtree and this will travel up the hierarchy and update
  9377. statistics everywhere."
  9378. (let* ((prop (save-excursion (org-up-heading-safe)
  9379. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9380. (recursive (or (not org-hierarchical-todo-statistics)
  9381. (and prop (string-match "\\<recursive\\>" prop))))
  9382. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9383. 0))
  9384. (first t)
  9385. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9386. level ltoggle l1 new ndel
  9387. (cnt-all 0) (cnt-done 0) is-percent kwd
  9388. checkbox-beg cookie-present)
  9389. (catch 'exit
  9390. (save-excursion
  9391. (beginning-of-line 1)
  9392. (setq ltoggle (funcall outline-level))
  9393. ;; Three situations are to consider:
  9394. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9395. ;; to the top-level ancestor on the headline;
  9396. ;; 2. If parent has "recursive" property, repeat up to the
  9397. ;; headline setting that property, taking inheritance into
  9398. ;; account;
  9399. ;; 3. Else, move up to direct parent and proceed only once.
  9400. (while (and (setq level (org-up-heading-safe))
  9401. (or recursive first)
  9402. (>= (point) lim))
  9403. (setq first nil cookie-present nil)
  9404. (unless (and level
  9405. (not (string-match
  9406. "\\<checkbox\\>"
  9407. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9408. "")))))
  9409. (throw 'exit nil))
  9410. (while (re-search-forward box-re (point-at-eol) t)
  9411. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9412. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9413. (save-match-data
  9414. (unless (outline-next-heading) (throw 'exit nil))
  9415. (while (and (looking-at org-complex-heading-regexp)
  9416. (> (setq l1 (length (match-string 1))) level))
  9417. (setq kwd (and (or recursive (= l1 ltoggle))
  9418. (match-string 2)))
  9419. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9420. (and (eq org-provide-todo-statistics t)
  9421. (or (member kwd org-done-keywords)))
  9422. (and (listp org-provide-todo-statistics)
  9423. (stringp (car org-provide-todo-statistics))
  9424. (or (member kwd org-provide-todo-statistics)
  9425. (member kwd org-done-keywords)))
  9426. (and (listp org-provide-todo-statistics)
  9427. (listp (car org-provide-todo-statistics))
  9428. (or (member kwd (car org-provide-todo-statistics))
  9429. (and (member kwd org-done-keywords)
  9430. (member kwd (cadr org-provide-todo-statistics))))))
  9431. (setq cnt-all (1+ cnt-all))
  9432. (and (eq org-provide-todo-statistics t)
  9433. kwd
  9434. (setq cnt-all (1+ cnt-all))))
  9435. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9436. (member kwd org-done-keywords))
  9437. (and (listp org-provide-todo-statistics)
  9438. (listp (car org-provide-todo-statistics))
  9439. (member kwd org-done-keywords)
  9440. (member kwd (cadr org-provide-todo-statistics)))
  9441. (and (listp org-provide-todo-statistics)
  9442. (stringp (car org-provide-todo-statistics))
  9443. (member kwd org-done-keywords)))
  9444. (setq cnt-done (1+ cnt-done)))
  9445. (outline-next-heading)))
  9446. (setq new
  9447. (if is-percent
  9448. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9449. (max 1 cnt-all)))
  9450. (format "[%d/%d]" cnt-done cnt-all))
  9451. ndel (- (match-end 0) checkbox-beg))
  9452. (goto-char checkbox-beg)
  9453. (insert new)
  9454. (delete-region (point) (+ (point) ndel))
  9455. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9456. (when cookie-present
  9457. (run-hook-with-args 'org-after-todo-statistics-hook
  9458. cnt-done (- cnt-all cnt-done))))))
  9459. (run-hooks 'org-todo-statistics-hook)))
  9460. (defvar org-after-todo-statistics-hook nil
  9461. "Hook that is called after a TODO statistics cookie has been updated.
  9462. Each function is called with two arguments: the number of not-done entries
  9463. and the number of done entries.
  9464. For example, the following function, when added to this hook, will switch
  9465. an entry to DONE when all children are done, and back to TODO when new
  9466. entries are set to a TODO status. Note that this hook is only called
  9467. when there is a statistics cookie in the headline!
  9468. (defun org-summary-todo (n-done n-not-done)
  9469. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9470. (let (org-log-done org-log-states) ; turn off logging
  9471. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9472. ")
  9473. (defvar org-todo-statistics-hook nil
  9474. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9475. This hook runs even if there is no statistics cookie present, in which case
  9476. `org-after-todo-statistics-hook' would not run.")
  9477. (defun org-todo-trigger-tag-changes (state)
  9478. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9479. (let ((l org-todo-state-tags-triggers)
  9480. changes)
  9481. (when (or (not state) (equal state ""))
  9482. (setq changes (append changes (cdr (assoc "" l)))))
  9483. (when (and (stringp state) (> (length state) 0))
  9484. (setq changes (append changes (cdr (assoc state l)))))
  9485. (when (member state org-not-done-keywords)
  9486. (setq changes (append changes (cdr (assq 'todo l)))))
  9487. (when (member state org-done-keywords)
  9488. (setq changes (append changes (cdr (assq 'done l)))))
  9489. (dolist (c changes)
  9490. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9491. (defun org-local-logging (value)
  9492. "Get logging settings from a property VALUE."
  9493. ;; Directly set the variables, they are already local.
  9494. (setq org-log-done nil
  9495. org-log-repeat nil
  9496. org-todo-log-states nil)
  9497. (dolist (w (split-string value))
  9498. (let (a)
  9499. (cond
  9500. ((setq a (assoc w org-startup-options))
  9501. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9502. (set (nth 1 a) (nth 2 a))))
  9503. ((setq a (org-extract-log-state-settings w))
  9504. (and (member (car a) org-todo-keywords-1)
  9505. (push a org-todo-log-states)))))))
  9506. (defun org-get-todo-sequence-head (kwd)
  9507. "Return the head of the TODO sequence to which KWD belongs.
  9508. If KWD is not set, check if there is a text property remembering the
  9509. right sequence."
  9510. (let (p)
  9511. (cond
  9512. ((not kwd)
  9513. (or (get-text-property (point-at-bol) 'org-todo-head)
  9514. (progn
  9515. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9516. nil (point-at-eol)))
  9517. (get-text-property p 'org-todo-head))))
  9518. ((not (member kwd org-todo-keywords-1))
  9519. (car org-todo-keywords-1))
  9520. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9521. (defun org-fast-todo-selection (&optional current-state)
  9522. "Fast TODO keyword selection with single keys.
  9523. Returns the new TODO keyword, or nil if no state change should occur.
  9524. When CURRENT-STATE is given and selection letters are not unique globally,
  9525. prefer a state in the current sequence over on in another sequence."
  9526. (let* ((fulltable org-todo-key-alist)
  9527. (head (org-get-todo-sequence-head current-state))
  9528. (done-keywords org-done-keywords) ;; needed for the faces.
  9529. (maxlen (apply 'max (mapcar
  9530. (lambda (x)
  9531. (if (stringp (car x)) (string-width (car x)) 0))
  9532. fulltable)))
  9533. (expert (equal org-use-fast-todo-selection 'expert))
  9534. (prompt "")
  9535. (fwidth (+ maxlen 3 1 3))
  9536. (ncol (/ (- (window-width) 4) fwidth))
  9537. tg cnt e c tbl subtable
  9538. groups ingroup in-current-sequence)
  9539. (save-excursion
  9540. (save-window-excursion
  9541. (if expert
  9542. (set-buffer (get-buffer-create " *Org todo*"))
  9543. (delete-other-windows)
  9544. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9545. (org-switch-to-buffer-other-window " *Org todo*"))
  9546. (erase-buffer)
  9547. (setq-local org-done-keywords done-keywords)
  9548. (setq tbl fulltable cnt 0)
  9549. (while (setq e (pop tbl))
  9550. (cond
  9551. ((equal e '(:startgroup))
  9552. (push '() groups) (setq ingroup t)
  9553. (unless (= cnt 0)
  9554. (setq cnt 0)
  9555. (insert "\n"))
  9556. (setq prompt (concat prompt "{"))
  9557. (insert "{ "))
  9558. ((equal e '(:endgroup))
  9559. (setq ingroup nil cnt 0 in-current-sequence nil)
  9560. (setq prompt (concat prompt "}"))
  9561. (insert "}\n"))
  9562. ((equal e '(:newline))
  9563. (unless (= cnt 0)
  9564. (setq cnt 0)
  9565. (insert "\n")
  9566. (setq e (car tbl))
  9567. (while (equal (car tbl) '(:newline))
  9568. (insert "\n")
  9569. (setq tbl (cdr tbl)))))
  9570. (t
  9571. (setq tg (car e) c (cdr e))
  9572. (if (equal tg head) (setq in-current-sequence t))
  9573. (when ingroup (push tg (car groups)))
  9574. (when in-current-sequence (push e subtable))
  9575. (setq tg (org-add-props tg nil 'face
  9576. (org-get-todo-face tg)))
  9577. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9578. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9579. (insert "[" c "] " tg (make-string
  9580. (- fwidth 4 (length tg)) ?\ ))
  9581. (when (and (= (setq cnt (1+ cnt)) ncol)
  9582. ;; Avoid lines with just a closing delimiter.
  9583. (not (equal (car tbl) '(:endgroup))))
  9584. (insert "\n")
  9585. (when ingroup (insert " "))
  9586. (setq cnt 0)))))
  9587. (insert "\n")
  9588. (goto-char (point-min))
  9589. (unless expert (org-fit-window-to-buffer))
  9590. (message (concat "[a-z..]:Set [SPC]:clear"
  9591. (if expert (concat "\n" prompt) "")))
  9592. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9593. (setq subtable (nreverse subtable))
  9594. (cond
  9595. ((or (= c ?\C-g)
  9596. (and (= c ?q) (not (rassoc c fulltable))))
  9597. (setq quit-flag t))
  9598. ((= c ?\ ) nil)
  9599. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9600. tg (car e))
  9601. tg)
  9602. (t (setq quit-flag t)))))))
  9603. (defun org-entry-is-todo-p ()
  9604. (member (org-get-todo-state) org-not-done-keywords))
  9605. (defun org-entry-is-done-p ()
  9606. (member (org-get-todo-state) org-done-keywords))
  9607. (defun org-get-todo-state ()
  9608. "Return the TODO keyword of the current subtree."
  9609. (save-excursion
  9610. (org-back-to-heading t)
  9611. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9612. (match-end 2)
  9613. (match-string 2))))
  9614. (defun org-at-date-range-p (&optional inactive-ok)
  9615. "Non-nil if point is inside a date range.
  9616. When optional argument INACTIVE-OK is non-nil, also consider
  9617. inactive time ranges.
  9618. When this function returns a non-nil value, match data is set
  9619. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9620. on INACTIVE-OK."
  9621. (interactive)
  9622. (save-excursion
  9623. (catch 'exit
  9624. (let ((pos (point)))
  9625. (skip-chars-backward "^[<\r\n")
  9626. (skip-chars-backward "<[")
  9627. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9628. (>= (match-end 0) pos)
  9629. (throw 'exit t))
  9630. (skip-chars-backward "^<[\r\n")
  9631. (skip-chars-backward "<[")
  9632. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9633. (>= (match-end 0) pos)
  9634. (throw 'exit t)))
  9635. nil)))
  9636. (defun org-get-repeat (&optional timestamp)
  9637. "Check if there is a time-stamp with repeater in this entry.
  9638. Return the repeater, as a string, or nil. Also return nil when
  9639. this function is called before first heading.
  9640. When optional argument TIMESTAMP is a string, extract the
  9641. repeater from there instead."
  9642. (save-match-data
  9643. (cond (timestamp
  9644. (and (string-match org-repeat-re timestamp)
  9645. (match-string-no-properties 1 timestamp)))
  9646. ((org-before-first-heading-p) nil)
  9647. (t
  9648. (save-excursion
  9649. (org-back-to-heading t)
  9650. (let ((end (org-entry-end-position)))
  9651. (catch :repeat
  9652. (while (re-search-forward org-repeat-re end t)
  9653. (when (save-match-data (org-at-timestamp-p 'agenda))
  9654. (throw :repeat (match-string-no-properties 1)))))))))))
  9655. (defvar org-last-changed-timestamp)
  9656. (defvar org-last-inserted-timestamp)
  9657. (defvar org-log-post-message)
  9658. (defvar org-log-note-purpose)
  9659. (defvar org-log-note-how nil)
  9660. (defvar org-log-note-extra)
  9661. (defun org-auto-repeat-maybe (done-word)
  9662. "Check if the current headline contains a repeated time-stamp.
  9663. If yes, set TODO state back to what it was and change the base date
  9664. of repeating deadline/scheduled time stamps to new date.
  9665. This function is run automatically after each state change to a DONE state."
  9666. (let* ((repeat (org-get-repeat))
  9667. (aa (assoc org-last-state org-todo-kwd-alist))
  9668. (interpret (nth 1 aa))
  9669. (head (nth 2 aa))
  9670. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9671. (msg "Entry repeats: ")
  9672. (org-log-done nil)
  9673. (org-todo-log-states nil)
  9674. (end (copy-marker (org-entry-end-position))))
  9675. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9676. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9677. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9678. (and (stringp org-todo-repeat-to-state)
  9679. org-todo-repeat-to-state)
  9680. (and org-todo-repeat-to-state org-last-state))))
  9681. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9682. to-state)
  9683. ((eq interpret 'type) org-last-state)
  9684. (head)
  9685. (t 'none))))
  9686. (org-back-to-heading t)
  9687. (org-add-planning-info nil nil 'closed)
  9688. ;; When `org-log-repeat' is non-nil or entry contains
  9689. ;; a clock, set LAST_REPEAT property.
  9690. (when (or org-log-repeat
  9691. (catch :clock
  9692. (save-excursion
  9693. (while (re-search-forward org-clock-line-re end t)
  9694. (when (org-at-clock-log-p) (throw :clock t))))))
  9695. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9696. (org-time-stamp-format t t))))
  9697. (when org-log-repeat
  9698. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9699. (memq 'org-add-log-note post-command-hook))
  9700. ;; We are already setup for some record.
  9701. (when (eq org-log-repeat 'note)
  9702. ;; Make sure we take a note, not only a time stamp.
  9703. (setq org-log-note-how 'note))
  9704. ;; Set up for taking a record.
  9705. (org-add-log-setup 'state
  9706. (or done-word (car org-done-keywords))
  9707. org-last-state
  9708. org-log-repeat)))
  9709. ;; Time-stamps without a repeater are usually skipped. However,
  9710. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9711. ;; longer relevant.
  9712. (save-excursion
  9713. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9714. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9715. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9716. ;; Update every time-stamp with a repeater in the entry.
  9717. (let ((planning-re (regexp-opt
  9718. (list org-scheduled-string org-deadline-string))))
  9719. (while (re-search-forward org-repeat-re end t)
  9720. (let* ((ts (match-string 0))
  9721. (type (if (not (org-at-planning-p)) "Plain:"
  9722. (save-excursion
  9723. (re-search-backward
  9724. planning-re (line-beginning-position) t)
  9725. (match-string 0)))))
  9726. (when (and (org-at-timestamp-p 'agenda)
  9727. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9728. (let ((n (string-to-number (match-string 2 ts)))
  9729. (what (match-string 3 ts)))
  9730. (when (equal what "w") (setq n (* n 7) what "d"))
  9731. (when (and (equal what "h")
  9732. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9733. ts)))
  9734. (user-error
  9735. "Cannot repeat in %d hour(s) because no hour has been set"
  9736. n))
  9737. ;; Preparation, see if we need to modify the start
  9738. ;; date for the change.
  9739. (when (match-end 1)
  9740. (let ((time (save-match-data (org-time-string-to-time ts)))
  9741. (repeater-type (match-string 1 ts)))
  9742. (cond
  9743. ((equal "." repeater-type)
  9744. ;; Shift starting date to today.
  9745. (org-timestamp-change (- (org-today) (time-to-days time))
  9746. 'day))
  9747. ((equal "+" repeater-type)
  9748. (let ((nshiftmax 10)
  9749. (nshift 0))
  9750. (while (or (= nshift 0)
  9751. (not (org-time-less-p nil time)))
  9752. (when (= nshiftmax (cl-incf nshift))
  9753. (or (y-or-n-p
  9754. (format "%d repeater intervals were not \
  9755. enough to shift date past today. Continue? "
  9756. nshift))
  9757. (user-error "Abort")))
  9758. (org-timestamp-change n (cdr (assoc what whata)))
  9759. (org-in-regexp org-ts-regexp3)
  9760. (setq ts (match-string 1))
  9761. (setq time
  9762. (save-match-data
  9763. (org-time-string-to-time ts)))))
  9764. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9765. ;; Rematch, so that we have everything in place
  9766. ;; for the real shift.
  9767. (org-in-regexp org-ts-regexp3)
  9768. (setq ts (match-string 1))
  9769. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9770. ts)))))
  9771. (save-excursion
  9772. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9773. (setq msg
  9774. (concat msg type " " org-last-changed-timestamp " ")))))))
  9775. (run-hooks 'org-todo-repeat-hook)
  9776. (setq org-log-post-message msg)
  9777. (message msg))))
  9778. (defun org-show-todo-tree (arg)
  9779. "Make a compact tree which shows all headlines marked with TODO.
  9780. The tree will show the lines where the regexp matches, and all higher
  9781. headlines above the match.
  9782. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9783. With a numeric prefix N, construct a sparse tree for the Nth element
  9784. of `org-todo-keywords-1'."
  9785. (interactive "P")
  9786. (let ((case-fold-search nil)
  9787. (kwd-re
  9788. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9789. ((equal arg '(4))
  9790. (let ((kwd
  9791. (completing-read "Keyword (or KWD1|KWD2|...): "
  9792. (mapcar #'list org-todo-keywords-1))))
  9793. (concat "\\("
  9794. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9795. "\\)\\>")))
  9796. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9797. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9798. org-todo-keywords-1)))
  9799. (t (user-error "Invalid prefix argument: %s" arg)))))
  9800. (message "%d TODO entries found"
  9801. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9802. (defun org--deadline-or-schedule (arg type time)
  9803. "Insert DEADLINE or SCHEDULE information in current entry.
  9804. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9805. `org-schedule' for information about ARG and TIME arguments."
  9806. (let* ((deadline? (eq type 'deadline))
  9807. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9808. (log (if deadline? org-log-redeadline org-log-reschedule))
  9809. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9810. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9811. ;; Save repeater cookie from either TIME or current scheduled
  9812. ;; time stamp. We are going to insert it back at the end of
  9813. ;; the process.
  9814. (repeater (or (and (org-string-nw-p time)
  9815. ;; We use `org-repeat-re' because we need
  9816. ;; to tell the difference between a real
  9817. ;; repeater and a time delta, e.g. "+2d".
  9818. (string-match org-repeat-re time)
  9819. (match-string 1 time))
  9820. (and (org-string-nw-p old-date)
  9821. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9822. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9823. old-date)
  9824. (match-string 1 old-date)))))
  9825. (pcase arg
  9826. (`(4)
  9827. (if (not old-date)
  9828. (message (if deadline? "Entry had no deadline to remove"
  9829. "Entry was not scheduled"))
  9830. (when (and old-date log)
  9831. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9832. nil old-date log))
  9833. (org-remove-timestamp-with-keyword keyword)
  9834. (message (if deadline? "Entry no longer has a deadline."
  9835. "Entry is no longer scheduled."))))
  9836. (`(16)
  9837. (save-excursion
  9838. (org-back-to-heading t)
  9839. (let ((regexp (if deadline? org-deadline-time-regexp
  9840. org-scheduled-time-regexp)))
  9841. (if (not (re-search-forward regexp (line-end-position 2) t))
  9842. (user-error (if deadline? "No deadline information to update"
  9843. "No scheduled information to update"))
  9844. (let* ((rpl0 (match-string 1))
  9845. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9846. (msg (if deadline? "Warn starting from" "Delay until")))
  9847. (replace-match
  9848. (concat keyword
  9849. " <" rpl
  9850. (format " -%dd"
  9851. (abs (- (time-to-days
  9852. (save-match-data
  9853. (org-read-date
  9854. nil t nil msg old-date-time)))
  9855. (time-to-days old-date-time))))
  9856. ">") t t))))))
  9857. (_
  9858. (org-add-planning-info type time 'closed)
  9859. (when (and old-date
  9860. log
  9861. (not (equal old-date org-last-inserted-timestamp)))
  9862. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9863. org-last-inserted-timestamp
  9864. old-date
  9865. log))
  9866. (when repeater
  9867. (save-excursion
  9868. (org-back-to-heading t)
  9869. (when (re-search-forward
  9870. (concat keyword " " org-last-inserted-timestamp)
  9871. (line-end-position 2)
  9872. t)
  9873. (goto-char (1- (match-end 0)))
  9874. (insert " " repeater)
  9875. (setq org-last-inserted-timestamp
  9876. (concat (substring org-last-inserted-timestamp 0 -1)
  9877. " " repeater
  9878. (substring org-last-inserted-timestamp -1))))))
  9879. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9880. org-last-inserted-timestamp)))))
  9881. (defun org-deadline (arg &optional time)
  9882. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9883. With one universal prefix argument, remove any deadline from the item.
  9884. With two universal prefix arguments, prompt for a warning delay.
  9885. With argument TIME, set the deadline at the corresponding date. TIME
  9886. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9887. (interactive "P")
  9888. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9889. (org-map-entries
  9890. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9891. nil
  9892. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9893. 'region-start-level
  9894. 'region)
  9895. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9896. (org--deadline-or-schedule arg 'deadline time)))
  9897. (defun org-schedule (arg &optional time)
  9898. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9899. With one universal prefix argument, remove any scheduling date from the item.
  9900. With two universal prefix arguments, prompt for a delay cookie.
  9901. With argument TIME, scheduled at the corresponding date. TIME can
  9902. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9903. (interactive "P")
  9904. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9905. (org-map-entries
  9906. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9907. nil
  9908. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9909. 'region-start-level
  9910. 'region)
  9911. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9912. (org--deadline-or-schedule arg 'scheduled time)))
  9913. (defun org-get-scheduled-time (pom &optional inherit)
  9914. "Get the scheduled time as a time tuple, of a format suitable
  9915. for calling org-schedule with, or if there is no scheduling,
  9916. returns nil."
  9917. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9918. (when time
  9919. (org-time-string-to-time time))))
  9920. (defun org-get-deadline-time (pom &optional inherit)
  9921. "Get the deadline as a time tuple, of a format suitable for
  9922. calling org-deadline with, or if there is no scheduling, returns
  9923. nil."
  9924. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9925. (when time
  9926. (org-time-string-to-time time))))
  9927. (defun org-remove-timestamp-with-keyword (keyword)
  9928. "Remove all time stamps with KEYWORD in the current entry."
  9929. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9930. beg)
  9931. (save-excursion
  9932. (org-back-to-heading t)
  9933. (setq beg (point))
  9934. (outline-next-heading)
  9935. (while (re-search-backward re beg t)
  9936. (replace-match "")
  9937. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9938. (equal (char-before) ?\ ))
  9939. (backward-delete-char 1)
  9940. (when (string-match "^[ \t]*$" (buffer-substring
  9941. (point-at-bol) (point-at-eol)))
  9942. (delete-region (point-at-bol)
  9943. (min (point-max) (1+ (point-at-eol))))))))))
  9944. (defvar org-time-was-given) ; dynamically scoped parameter
  9945. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9946. (defun org-at-planning-p ()
  9947. "Non-nil when point is on a planning info line."
  9948. ;; This is as accurate and faster than `org-element-at-point' since
  9949. ;; planning info location is fixed in the section.
  9950. (org-with-wide-buffer
  9951. (beginning-of-line)
  9952. (and (looking-at-p org-planning-line-re)
  9953. (eq (point)
  9954. (ignore-errors
  9955. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9956. (org-back-to-heading t)
  9957. (org-with-limited-levels (org-back-to-heading t)))
  9958. (line-beginning-position 2))))))
  9959. (defun org-add-planning-info (what &optional time &rest remove)
  9960. "Insert new timestamp with keyword in the planning line.
  9961. WHAT indicates what kind of time stamp to add. It is a symbol
  9962. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9963. the time to use. If none is given, the user is prompted for
  9964. a date. REMOVE indicates what kind of entries to remove. An old
  9965. WHAT entry will also be removed."
  9966. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9967. (catch 'exit
  9968. (when (and (memq what '(scheduled deadline))
  9969. (or (not time)
  9970. (and (stringp time)
  9971. (string-match "^[-+]+[0-9]" time))))
  9972. ;; Try to get a default date/time from existing timestamp
  9973. (save-excursion
  9974. (org-back-to-heading t)
  9975. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9976. (when (re-search-forward (if (eq what 'scheduled)
  9977. org-scheduled-time-regexp
  9978. org-deadline-time-regexp)
  9979. end t)
  9980. (setq ts (match-string 1)
  9981. default-time (org-time-string-to-time ts)
  9982. default-input (and ts (org-get-compact-tod ts)))))))
  9983. (when what
  9984. (setq time
  9985. (if (stringp time)
  9986. ;; This is a string (relative or absolute), set
  9987. ;; proper date.
  9988. (apply #'encode-time
  9989. (org-read-date-analyze
  9990. time default-time (decode-time default-time)))
  9991. ;; If necessary, get the time from the user
  9992. (or time (org-read-date nil 'to-time nil
  9993. (cl-case what
  9994. (deadline "DEADLINE")
  9995. (scheduled "SCHEDULED")
  9996. (otherwise nil))
  9997. default-time default-input)))))
  9998. (org-with-wide-buffer
  9999. (org-back-to-heading t)
  10000. (forward-line)
  10001. (unless (bolp) (insert "\n"))
  10002. (cond ((looking-at-p org-planning-line-re)
  10003. ;; Move to current indentation.
  10004. (skip-chars-forward " \t")
  10005. ;; Check if we have to remove something.
  10006. (dolist (type (if what (cons what remove) remove))
  10007. (save-excursion
  10008. (when (re-search-forward
  10009. (cl-case type
  10010. (closed org-closed-time-regexp)
  10011. (deadline org-deadline-time-regexp)
  10012. (scheduled org-scheduled-time-regexp)
  10013. (otherwise
  10014. (error "Invalid planning type: %s" type)))
  10015. (line-end-position) t)
  10016. ;; Delete until next keyword or end of line.
  10017. (delete-region
  10018. (match-beginning 0)
  10019. (if (re-search-forward org-keyword-time-not-clock-regexp
  10020. (line-end-position)
  10021. t)
  10022. (match-beginning 0)
  10023. (line-end-position))))))
  10024. ;; If there is nothing more to add and no more keyword
  10025. ;; is left, remove the line completely.
  10026. (if (and (looking-at-p "[ \t]*$") (not what))
  10027. (delete-region (line-beginning-position)
  10028. (line-beginning-position 2))
  10029. ;; If we removed last keyword, do not leave trailing
  10030. ;; white space at the end of line.
  10031. (let ((p (point)))
  10032. (save-excursion
  10033. (end-of-line)
  10034. (unless (= (skip-chars-backward " \t" p) 0)
  10035. (delete-region (point) (line-end-position)))))))
  10036. ((not what) (throw 'exit nil)) ; Nothing to do.
  10037. (t (insert-before-markers "\n")
  10038. (backward-char 1)
  10039. (when org-adapt-indentation
  10040. (indent-to-column (1+ (org-outline-level))))))
  10041. (when what
  10042. ;; Insert planning keyword.
  10043. (insert (cl-case what
  10044. (closed org-closed-string)
  10045. (deadline org-deadline-string)
  10046. (scheduled org-scheduled-string)
  10047. (otherwise (error "Invalid planning type: %s" what)))
  10048. " ")
  10049. ;; Insert associated timestamp.
  10050. (let ((ts (org-insert-time-stamp
  10051. time
  10052. (or org-time-was-given
  10053. (and (eq what 'closed) org-log-done-with-time))
  10054. (eq what 'closed)
  10055. nil nil (list org-end-time-was-given))))
  10056. (unless (eolp) (insert " "))
  10057. ts))))))
  10058. (defvar org-log-note-marker (make-marker)
  10059. "Marker pointing at the entry where the note is to be inserted.")
  10060. (defvar org-log-note-purpose nil)
  10061. (defvar org-log-note-state nil)
  10062. (defvar org-log-note-previous-state nil)
  10063. (defvar org-log-note-extra nil)
  10064. (defvar org-log-note-window-configuration nil)
  10065. (defvar org-log-note-return-to (make-marker))
  10066. (defvar org-log-note-effective-time nil
  10067. "Remembered current time so that dynamically scoped
  10068. `org-extend-today-until' affects timestamps in state change log")
  10069. (defvar org-log-post-message nil
  10070. "Message to be displayed after a log note has been stored.
  10071. The auto-repeater uses this.")
  10072. (defun org-add-note ()
  10073. "Add a note to the current entry.
  10074. This is done in the same way as adding a state change note."
  10075. (interactive)
  10076. (org-add-log-setup 'note))
  10077. (defun org-log-beginning (&optional create)
  10078. "Return expected start of log notes in current entry.
  10079. When optional argument CREATE is non-nil, the function creates
  10080. a drawer to store notes, if necessary. Returned position ignores
  10081. narrowing."
  10082. (org-with-wide-buffer
  10083. (let ((drawer (org-log-into-drawer)))
  10084. (cond
  10085. (drawer
  10086. (org-end-of-meta-data)
  10087. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10088. (end (if (org-at-heading-p) (point)
  10089. (save-excursion (outline-next-heading) (point))))
  10090. (case-fold-search t))
  10091. (catch 'exit
  10092. ;; Try to find existing drawer.
  10093. (while (re-search-forward regexp end t)
  10094. (let ((element (org-element-at-point)))
  10095. (when (eq (org-element-type element) 'drawer)
  10096. (let ((cend (org-element-property :contents-end element)))
  10097. (when (and (not org-log-states-order-reversed) cend)
  10098. (goto-char cend)))
  10099. (throw 'exit nil))))
  10100. ;; No drawer found. Create one, if permitted.
  10101. (when create
  10102. (unless (bolp) (insert "\n"))
  10103. (let ((beg (point)))
  10104. (insert ":" drawer ":\n:END:\n")
  10105. (org-indent-region beg (point))
  10106. (org-flag-region
  10107. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10108. (end-of-line -1)))))
  10109. (t
  10110. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10111. (skip-chars-forward " \t\n")
  10112. (beginning-of-line)
  10113. (unless org-log-states-order-reversed
  10114. (org-skip-over-state-notes)
  10115. (skip-chars-backward " \t\n")
  10116. (forward-line)))))
  10117. (if (bolp) (point) (line-beginning-position 2))))
  10118. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10119. "Set up the post command hook to take a note.
  10120. If this is about to TODO state change, the new state is expected in STATE.
  10121. HOW is an indicator what kind of note should be created.
  10122. EXTRA is additional text that will be inserted into the notes buffer."
  10123. (move-marker org-log-note-marker (point))
  10124. (setq org-log-note-purpose purpose
  10125. org-log-note-state state
  10126. org-log-note-previous-state prev-state
  10127. org-log-note-how how
  10128. org-log-note-extra extra
  10129. org-log-note-effective-time (org-current-effective-time))
  10130. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10131. (defun org-skip-over-state-notes ()
  10132. "Skip past the list of State notes in an entry."
  10133. (when (ignore-errors (goto-char (org-in-item-p)))
  10134. (let* ((struct (org-list-struct))
  10135. (prevs (org-list-prevs-alist struct))
  10136. (regexp
  10137. (concat "[ \t]*- +"
  10138. (replace-regexp-in-string
  10139. " +" " +"
  10140. (org-replace-escapes
  10141. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10142. `(("%d" . ,org-ts-regexp-inactive)
  10143. ("%D" . ,org-ts-regexp)
  10144. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10145. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10146. ("%t" . ,org-ts-regexp-inactive)
  10147. ("%T" . ,org-ts-regexp)
  10148. ("%u" . ".*?")
  10149. ("%U" . ".*?")))))))
  10150. (while (looking-at-p regexp)
  10151. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10152. (org-list-get-item-end (point) struct)))))))
  10153. (defun org-add-log-note (&optional _purpose)
  10154. "Pop up a window for taking a note, and add this note later."
  10155. (remove-hook 'post-command-hook 'org-add-log-note)
  10156. (setq org-log-note-window-configuration (current-window-configuration))
  10157. (delete-other-windows)
  10158. (move-marker org-log-note-return-to (point))
  10159. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10160. (goto-char org-log-note-marker)
  10161. (org-switch-to-buffer-other-window "*Org Note*")
  10162. (erase-buffer)
  10163. (if (memq org-log-note-how '(time state))
  10164. (org-store-log-note)
  10165. (let ((org-inhibit-startup t)) (org-mode))
  10166. (insert (format "# Insert note for %s.
  10167. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10168. (cl-case org-log-note-purpose
  10169. (clock-out "stopped clock")
  10170. (done "closed todo item")
  10171. (reschedule "rescheduling")
  10172. (delschedule "no longer scheduled")
  10173. (redeadline "changing deadline")
  10174. (deldeadline "removing deadline")
  10175. (refile "refiling")
  10176. (note "this entry")
  10177. (state
  10178. (format "state change from \"%s\" to \"%s\""
  10179. (or org-log-note-previous-state "")
  10180. (or org-log-note-state "")))
  10181. (t (error "This should not happen")))))
  10182. (when org-log-note-extra (insert org-log-note-extra))
  10183. (setq-local org-finish-function 'org-store-log-note)
  10184. (run-hooks 'org-log-buffer-setup-hook)))
  10185. (defvar org-note-abort nil) ; dynamically scoped
  10186. (defun org-store-log-note ()
  10187. "Finish taking a log note, and insert it to where it belongs."
  10188. (let ((txt (prog1 (buffer-string)
  10189. (kill-buffer)))
  10190. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10191. lines)
  10192. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10193. (setq txt (replace-match "" t t txt)))
  10194. (when (string-match "\\s-+\\'" txt)
  10195. (setq txt (replace-match "" t t txt)))
  10196. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10197. (when (org-string-nw-p note)
  10198. (setq note
  10199. (org-replace-escapes
  10200. note
  10201. (list (cons "%u" (user-login-name))
  10202. (cons "%U" user-full-name)
  10203. (cons "%t" (format-time-string
  10204. (org-time-stamp-format 'long 'inactive)
  10205. org-log-note-effective-time))
  10206. (cons "%T" (format-time-string
  10207. (org-time-stamp-format 'long nil)
  10208. org-log-note-effective-time))
  10209. (cons "%d" (format-time-string
  10210. (org-time-stamp-format nil 'inactive)
  10211. org-log-note-effective-time))
  10212. (cons "%D" (format-time-string
  10213. (org-time-stamp-format nil nil)
  10214. org-log-note-effective-time))
  10215. (cons "%s" (cond
  10216. ((not org-log-note-state) "")
  10217. ((string-match-p org-ts-regexp
  10218. org-log-note-state)
  10219. (format "\"[%s]\""
  10220. (substring org-log-note-state 1 -1)))
  10221. (t (format "\"%s\"" org-log-note-state))))
  10222. (cons "%S"
  10223. (cond
  10224. ((not org-log-note-previous-state) "")
  10225. ((string-match-p org-ts-regexp
  10226. org-log-note-previous-state)
  10227. (format "\"[%s]\""
  10228. (substring
  10229. org-log-note-previous-state 1 -1)))
  10230. (t (format "\"%s\""
  10231. org-log-note-previous-state)))))))
  10232. (when lines (setq note (concat note " \\\\")))
  10233. (push note lines))
  10234. (when (and lines (not org-note-abort))
  10235. (with-current-buffer (marker-buffer org-log-note-marker)
  10236. (org-with-wide-buffer
  10237. ;; Find location for the new note.
  10238. (goto-char org-log-note-marker)
  10239. (set-marker org-log-note-marker nil)
  10240. ;; Note associated to a clock is to be located right after
  10241. ;; the clock. Do not move point.
  10242. (unless (eq org-log-note-purpose 'clock-out)
  10243. (goto-char (org-log-beginning t)))
  10244. ;; Make sure point is at the beginning of an empty line.
  10245. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10246. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10247. ;; In an existing list, add a new item at the top level.
  10248. ;; Otherwise, indent line like a regular one.
  10249. (let ((itemp (org-in-item-p)))
  10250. (if itemp
  10251. (indent-line-to
  10252. (let ((struct (save-excursion
  10253. (goto-char itemp) (org-list-struct))))
  10254. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10255. (org-indent-line)))
  10256. (insert (org-list-bullet-string "-") (pop lines))
  10257. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10258. (dolist (line lines)
  10259. (insert "\n")
  10260. (indent-line-to ind)
  10261. (insert line)))
  10262. (message "Note stored")
  10263. (org-back-to-heading t))
  10264. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10265. ;; from within `org-add-log-note' because `buffer-undo-list'
  10266. ;; is then modified outside of `org-with-remote-undo'.
  10267. (when (eq this-command 'org-agenda-todo)
  10268. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10269. ;; Don't add undo information when called from `org-agenda-todo'.
  10270. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10271. (set-window-configuration org-log-note-window-configuration)
  10272. (with-current-buffer (marker-buffer org-log-note-return-to)
  10273. (goto-char org-log-note-return-to))
  10274. (move-marker org-log-note-return-to nil)
  10275. (when org-log-post-message (message "%s" org-log-post-message))))
  10276. (defun org-remove-empty-drawer-at (pos)
  10277. "Remove an empty drawer at position POS.
  10278. POS may also be a marker."
  10279. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10280. (org-with-wide-buffer
  10281. (goto-char pos)
  10282. (let ((drawer (org-element-at-point)))
  10283. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10284. (not (org-element-property :contents-begin drawer)))
  10285. (delete-region (org-element-property :begin drawer)
  10286. (progn (goto-char (org-element-property :end drawer))
  10287. (skip-chars-backward " \r\t\n")
  10288. (forward-line)
  10289. (point))))))))
  10290. (defvar org-ts-type nil)
  10291. (defun org-sparse-tree (&optional arg type)
  10292. "Create a sparse tree, prompt for the details.
  10293. This command can create sparse trees. You first need to select the type
  10294. of match used to create the tree:
  10295. t Show all TODO entries.
  10296. T Show entries with a specific TODO keyword.
  10297. m Show entries selected by a tags/property match.
  10298. p Enter a property name and its value (both with completion on existing
  10299. names/values) and show entries with that property.
  10300. r Show entries matching a regular expression (`/' can be used as well).
  10301. b Show deadlines and scheduled items before a date.
  10302. a Show deadlines and scheduled items after a date.
  10303. d Show deadlines due within `org-deadline-warning-days'.
  10304. D Show deadlines and scheduled items between a date range."
  10305. (interactive "P")
  10306. (setq type (or type org-sparse-tree-default-date-type))
  10307. (setq org-ts-type type)
  10308. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10309. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10310. \[c]ycle through date types: %s"
  10311. (cl-case type
  10312. (all "all timestamps")
  10313. (scheduled "only scheduled")
  10314. (deadline "only deadline")
  10315. (active "only active timestamps")
  10316. (inactive "only inactive timestamps")
  10317. (closed "with a closed time-stamp")
  10318. (otherwise "scheduled/deadline")))
  10319. (let ((answer (read-char-exclusive)))
  10320. (cl-case answer
  10321. (?c
  10322. (org-sparse-tree
  10323. arg
  10324. (cadr
  10325. (memq type '(nil all scheduled deadline active inactive closed)))))
  10326. (?d (call-interactively 'org-check-deadlines))
  10327. (?b (call-interactively 'org-check-before-date))
  10328. (?a (call-interactively 'org-check-after-date))
  10329. (?D (call-interactively 'org-check-dates-range))
  10330. (?t (call-interactively 'org-show-todo-tree))
  10331. (?T (org-show-todo-tree '(4)))
  10332. (?m (call-interactively 'org-match-sparse-tree))
  10333. ((?p ?P)
  10334. (let* ((kwd (completing-read
  10335. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10336. (value (completing-read
  10337. "Value: " (mapcar #'list (org-property-values kwd)))))
  10338. (unless (string-match "\\`{.*}\\'" value)
  10339. (setq value (concat "\"" value "\"")))
  10340. (org-match-sparse-tree arg (concat kwd "=" value))))
  10341. ((?r ?R ?/) (call-interactively 'org-occur))
  10342. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10343. (defvar-local org-occur-highlights nil
  10344. "List of overlays used for occur matches.")
  10345. (defvar-local org-occur-parameters nil
  10346. "Parameters of the active org-occur calls.
  10347. This is a list, each call to org-occur pushes as cons cell,
  10348. containing the regular expression and the callback, onto the list.
  10349. The list can contain several entries if `org-occur' has been called
  10350. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10351. will only contain one set of parameters. When the highlights are
  10352. removed (for example with `C-c C-c', or with the next edit (depending
  10353. on `org-remove-highlights-with-change'), this variable is emptied
  10354. as well.")
  10355. (defun org-occur (regexp &optional keep-previous callback)
  10356. "Make a compact tree which shows all matches of REGEXP.
  10357. The tree will show the lines where the regexp matches, and any other context
  10358. defined in `org-show-context-detail', which see.
  10359. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10360. done by a previous call to `org-occur' will be kept, to allow stacking of
  10361. calls to this command.
  10362. Optional argument CALLBACK can be a function of no argument. In this case,
  10363. it is called with point at the end of the match, match data being set
  10364. accordingly. Current match is shown only if the return value is non-nil.
  10365. The function must neither move point nor alter narrowing."
  10366. (interactive "sRegexp: \nP")
  10367. (when (equal regexp "")
  10368. (user-error "Regexp cannot be empty"))
  10369. (unless keep-previous
  10370. (org-remove-occur-highlights nil nil t))
  10371. (push (cons regexp callback) org-occur-parameters)
  10372. (let ((cnt 0))
  10373. (save-excursion
  10374. (goto-char (point-min))
  10375. (when (or (not keep-previous) ; do not want to keep
  10376. (not org-occur-highlights)) ; no previous matches
  10377. ;; hide everything
  10378. (org-overview))
  10379. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10380. (isearch-no-upper-case-p regexp t)
  10381. org-occur-case-fold-search)))
  10382. (while (re-search-forward regexp nil t)
  10383. (when (or (not callback)
  10384. (save-match-data (funcall callback)))
  10385. (setq cnt (1+ cnt))
  10386. (when org-highlight-sparse-tree-matches
  10387. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10388. (org-show-context 'occur-tree)))))
  10389. (when org-remove-highlights-with-change
  10390. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10391. nil 'local))
  10392. (unless org-sparse-tree-open-archived-trees
  10393. (org-hide-archived-subtrees (point-min) (point-max)))
  10394. (run-hooks 'org-occur-hook)
  10395. (when (called-interactively-p 'interactive)
  10396. (message "%d match(es) for regexp %s" cnt regexp))
  10397. cnt))
  10398. (defun org-occur-next-match (&optional n _reset)
  10399. "Function for `next-error-function' to find sparse tree matches.
  10400. N is the number of matches to move, when negative move backwards.
  10401. This function always goes back to the starting point when no
  10402. match is found."
  10403. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10404. (search-func (if (< n 0)
  10405. 'previous-single-char-property-change
  10406. 'next-single-char-property-change))
  10407. (n (abs n))
  10408. (pos (point))
  10409. p1)
  10410. (catch 'exit
  10411. (while (setq p1 (funcall search-func (point) 'org-type))
  10412. (when (equal p1 limit)
  10413. (goto-char pos)
  10414. (user-error "No more matches"))
  10415. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10416. (setq n (1- n))
  10417. (when (= n 0)
  10418. (goto-char p1)
  10419. (throw 'exit (point))))
  10420. (goto-char p1))
  10421. (goto-char p1)
  10422. (user-error "No more matches"))))
  10423. (defun org-highlight-new-match (beg end)
  10424. "Highlight from BEG to END and mark the highlight is an occur headline."
  10425. (let ((ov (make-overlay beg end)))
  10426. (overlay-put ov 'face 'secondary-selection)
  10427. (overlay-put ov 'org-type 'org-occur)
  10428. (push ov org-occur-highlights)))
  10429. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10430. "Remove the occur highlights from the buffer.
  10431. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10432. from the `before-change-functions' in the current buffer."
  10433. (interactive)
  10434. (unless org-inhibit-highlight-removal
  10435. (mapc #'delete-overlay org-occur-highlights)
  10436. (setq org-occur-highlights nil)
  10437. (setq org-occur-parameters nil)
  10438. (unless noremove
  10439. (remove-hook 'before-change-functions
  10440. 'org-remove-occur-highlights 'local))))
  10441. ;;;; Priorities
  10442. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10443. "Regular expression matching the priority indicator.")
  10444. (defvar org-remove-priority-next-time nil)
  10445. (defun org-priority-up ()
  10446. "Increase the priority of the current item."
  10447. (interactive)
  10448. (org-priority 'up))
  10449. (defun org-priority-down ()
  10450. "Decrease the priority of the current item."
  10451. (interactive)
  10452. (org-priority 'down))
  10453. (defun org-priority (&optional action show)
  10454. "Change the priority of an item.
  10455. When called interactively with a `\\[universal-argument]' prefix,
  10456. show the priority in the minibuffer instead of changing it.
  10457. When called programmatically, ACTION can be `set', `up', `down',
  10458. or a character."
  10459. (interactive "P")
  10460. (when show
  10461. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10462. ;; passed the SHOW argument should be removed.
  10463. (warn "`org-priority' called with deprecated SHOW argument"))
  10464. (if (equal action '(4))
  10465. (org-show-priority)
  10466. (unless org-enable-priority-commands
  10467. (user-error "Priority commands are disabled"))
  10468. (setq action (or action 'set))
  10469. (let (current new news have remove)
  10470. (save-excursion
  10471. (org-back-to-heading t)
  10472. (when (looking-at org-priority-regexp)
  10473. (setq current (string-to-char (match-string 2))
  10474. have t))
  10475. (cond
  10476. ((eq action 'remove)
  10477. (setq remove t new ?\ ))
  10478. ((or (eq action 'set)
  10479. (integerp action))
  10480. (if (not (eq action 'set))
  10481. (setq new action)
  10482. (message "Priority %c-%c, SPC to remove: "
  10483. org-highest-priority org-lowest-priority)
  10484. (save-match-data
  10485. (setq new (read-char-exclusive))))
  10486. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10487. (= (upcase org-lowest-priority) org-lowest-priority))
  10488. (setq new (upcase new)))
  10489. (cond ((equal new ?\s) (setq remove t))
  10490. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10491. (user-error "Priority must be between `%c' and `%c'"
  10492. org-highest-priority org-lowest-priority))))
  10493. ((eq action 'up)
  10494. (setq new (if have
  10495. (1- current) ; normal cycling
  10496. ;; last priority was empty
  10497. (if (eq last-command this-command)
  10498. org-lowest-priority ; wrap around empty to lowest
  10499. ;; default
  10500. (if org-priority-start-cycle-with-default
  10501. org-default-priority
  10502. (1- org-default-priority))))))
  10503. ((eq action 'down)
  10504. (setq new (if have
  10505. (1+ current) ; normal cycling
  10506. ;; last priority was empty
  10507. (if (eq last-command this-command)
  10508. org-highest-priority ; wrap around empty to highest
  10509. ;; default
  10510. (if org-priority-start-cycle-with-default
  10511. org-default-priority
  10512. (1+ org-default-priority))))))
  10513. (t (user-error "Invalid action")))
  10514. (when (or (< (upcase new) org-highest-priority)
  10515. (> (upcase new) org-lowest-priority))
  10516. (if (and (memq action '(up down))
  10517. (not have) (not (eq last-command this-command)))
  10518. ;; `new' is from default priority
  10519. (error
  10520. "The default can not be set, see `org-default-priority' why")
  10521. ;; normal cycling: `new' is beyond highest/lowest priority
  10522. ;; and is wrapped around to the empty priority
  10523. (setq remove t)))
  10524. (setq news (format "%c" new))
  10525. (if have
  10526. (if remove
  10527. (replace-match "" t t nil 1)
  10528. (replace-match news t t nil 2))
  10529. (if remove
  10530. (user-error "No priority cookie found in line")
  10531. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10532. (if (match-end 2)
  10533. (progn
  10534. (goto-char (match-end 2))
  10535. (insert " [#" news "]"))
  10536. (goto-char (match-beginning 3))
  10537. (insert "[#" news "] "))))
  10538. (org-align-tags))
  10539. (if remove
  10540. (message "Priority removed")
  10541. (message "Priority of current item set to %s" news)))))
  10542. (defun org-show-priority ()
  10543. "Show the priority of the current item.
  10544. This priority is composed of the main priority given with the [#A] cookies,
  10545. and by additional input from the age of a schedules or deadline entry."
  10546. (interactive)
  10547. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10548. (org-get-at-bol 'priority)
  10549. (save-excursion
  10550. (save-match-data
  10551. (beginning-of-line)
  10552. (and (looking-at org-heading-regexp)
  10553. (org-get-priority (match-string 0))))))))
  10554. (message "Priority is %d" (if pri pri -1000))))
  10555. (defun org-get-priority (s)
  10556. "Find priority cookie and return priority."
  10557. (save-match-data
  10558. (if (functionp org-get-priority-function)
  10559. (funcall org-get-priority-function s)
  10560. (if (not (string-match org-priority-regexp s))
  10561. (* 1000 (- org-lowest-priority org-default-priority))
  10562. (* 1000 (- org-lowest-priority
  10563. (string-to-char (match-string 2 s))))))))
  10564. ;;;; Tags
  10565. (defvar org-agenda-archives-mode)
  10566. (defvar org-map-continue-from nil
  10567. "Position from where mapping should continue.
  10568. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10569. (defvar org-scanner-tags nil
  10570. "The current tag list while the tags scanner is running.")
  10571. (defvar org-trust-scanner-tags nil
  10572. "Should `org-get-tags' use the tags for the scanner.
  10573. This is for internal dynamical scoping only.
  10574. When this is non-nil, the function `org-get-tags' will return the value
  10575. of `org-scanner-tags' instead of building the list by itself. This
  10576. can lead to large speed-ups when the tags scanner is used in a file with
  10577. many entries, and when the list of tags is retrieved, for example to
  10578. obtain a list of properties. Building the tags list for each entry in such
  10579. a file becomes an N^2 operation - but with this variable set, it scales
  10580. as N.")
  10581. (defvar org--matcher-tags-todo-only nil)
  10582. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10583. "Scan headline tags with inheritance and produce output ACTION.
  10584. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10585. or `agenda' to produce an entry list for an agenda view. It can also be
  10586. a Lisp form or a function that should be called at each matched headline, in
  10587. this case the return value is a list of all return values from these calls.
  10588. MATCHER is a function accepting three arguments, returning
  10589. a non-nil value whenever a given set of tags qualifies a headline
  10590. for inclusion. See `org-make-tags-matcher' for more information.
  10591. As a special case, it can also be set to t (respectively nil) in
  10592. order to match all (respectively none) headline.
  10593. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10594. included in the output.
  10595. START-LEVEL can be a string with asterisks, reducing the scope to
  10596. headlines matching this string."
  10597. (require 'org-agenda)
  10598. (let* ((re (concat "^"
  10599. (if start-level
  10600. ;; Get the correct level to match
  10601. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10602. org-outline-regexp)
  10603. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10604. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10605. (props (list 'face 'default
  10606. 'done-face 'org-agenda-done
  10607. 'undone-face 'default
  10608. 'mouse-face 'highlight
  10609. 'org-not-done-regexp org-not-done-regexp
  10610. 'org-todo-regexp org-todo-regexp
  10611. 'org-complex-heading-regexp org-complex-heading-regexp
  10612. 'help-echo
  10613. (format "mouse-2 or RET jump to Org file %S"
  10614. (abbreviate-file-name
  10615. (or (buffer-file-name (buffer-base-buffer))
  10616. (buffer-name (buffer-base-buffer)))))))
  10617. (org-map-continue-from nil)
  10618. lspos tags tags-list
  10619. (tags-alist (list (cons 0 org-file-tags)))
  10620. (llast 0) rtn rtn1 level category i txt
  10621. todo marker entry priority
  10622. ts-date ts-date-type ts-date-pair)
  10623. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10624. (setq action (list 'lambda nil action)))
  10625. (save-excursion
  10626. (goto-char (point-min))
  10627. (when (eq action 'sparse-tree)
  10628. (org-overview)
  10629. (org-remove-occur-highlights))
  10630. (while (let (case-fold-search)
  10631. (re-search-forward re nil t))
  10632. (setq org-map-continue-from nil)
  10633. (catch :skip
  10634. ;; Ignore closing parts of inline tasks.
  10635. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10636. (throw :skip t))
  10637. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10638. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10639. (goto-char (setq lspos (match-beginning 0)))
  10640. (setq level (org-reduced-level (org-outline-level))
  10641. category (org-get-category))
  10642. (when (eq action 'agenda)
  10643. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10644. ts-date (car ts-date-pair)
  10645. ts-date-type (cdr ts-date-pair)))
  10646. (setq i llast llast level)
  10647. ;; remove tag lists from same and sublevels
  10648. (while (>= i level)
  10649. (when (setq entry (assoc i tags-alist))
  10650. (setq tags-alist (delete entry tags-alist)))
  10651. (setq i (1- i)))
  10652. ;; add the next tags
  10653. (when tags
  10654. (setq tags (org-split-string tags ":")
  10655. tags-alist
  10656. (cons (cons level tags) tags-alist)))
  10657. ;; compile tags for current headline
  10658. (setq tags-list
  10659. (if org-use-tag-inheritance
  10660. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10661. tags)
  10662. org-scanner-tags tags-list)
  10663. (when org-use-tag-inheritance
  10664. (setcdr (car tags-alist)
  10665. (mapcar (lambda (x)
  10666. (setq x (copy-sequence x))
  10667. (org-add-prop-inherited x))
  10668. (cdar tags-alist))))
  10669. (when (and tags org-use-tag-inheritance
  10670. (or (not (eq t org-use-tag-inheritance))
  10671. org-tags-exclude-from-inheritance))
  10672. ;; Selective inheritance, remove uninherited ones.
  10673. (setcdr (car tags-alist)
  10674. (org-remove-uninherited-tags (cdar tags-alist))))
  10675. (when (and
  10676. ;; eval matcher only when the todo condition is OK
  10677. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10678. (if (functionp matcher)
  10679. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10680. (funcall matcher todo tags-list level))
  10681. matcher))
  10682. ;; Call the skipper, but return t if it does not
  10683. ;; skip, so that the `and' form continues evaluating.
  10684. (progn
  10685. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10686. t)
  10687. ;; Check if timestamps are deselecting this entry
  10688. (or (not todo-only)
  10689. (and (member todo org-todo-keywords-1)
  10690. (or (not org-agenda-tags-todo-honor-ignore-options)
  10691. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10692. ;; select this headline
  10693. (cond
  10694. ((eq action 'sparse-tree)
  10695. (and org-highlight-sparse-tree-matches
  10696. (org-get-heading) (match-end 0)
  10697. (org-highlight-new-match
  10698. (match-beginning 1) (match-end 1)))
  10699. (org-show-context 'tags-tree))
  10700. ((eq action 'agenda)
  10701. (setq txt (org-agenda-format-item
  10702. ""
  10703. (concat
  10704. (if (eq org-tags-match-list-sublevels 'indented)
  10705. (make-string (1- level) ?.) "")
  10706. (org-get-heading))
  10707. (make-string level ?\s)
  10708. category
  10709. tags-list)
  10710. priority (org-get-priority txt))
  10711. (goto-char lspos)
  10712. (setq marker (org-agenda-new-marker))
  10713. (org-add-props txt props
  10714. 'org-marker marker 'org-hd-marker marker 'org-category category
  10715. 'todo-state todo
  10716. 'ts-date ts-date
  10717. 'priority priority
  10718. 'type (concat "tagsmatch" ts-date-type))
  10719. (push txt rtn))
  10720. ((functionp action)
  10721. (setq org-map-continue-from nil)
  10722. (save-excursion
  10723. (setq rtn1 (funcall action))
  10724. (push rtn1 rtn)))
  10725. (t (user-error "Invalid action")))
  10726. ;; if we are to skip sublevels, jump to end of subtree
  10727. (unless org-tags-match-list-sublevels
  10728. (org-end-of-subtree t)
  10729. (backward-char 1))))
  10730. ;; Get the correct position from where to continue
  10731. (if org-map-continue-from
  10732. (goto-char org-map-continue-from)
  10733. (and (= (point) lspos) (end-of-line 1)))))
  10734. (when (and (eq action 'sparse-tree)
  10735. (not org-sparse-tree-open-archived-trees))
  10736. (org-hide-archived-subtrees (point-min) (point-max)))
  10737. (nreverse rtn)))
  10738. (defun org-remove-uninherited-tags (tags)
  10739. "Remove all tags that are not inherited from the list TAGS."
  10740. (cond
  10741. ((eq org-use-tag-inheritance t)
  10742. (if org-tags-exclude-from-inheritance
  10743. (org-delete-all org-tags-exclude-from-inheritance tags)
  10744. tags))
  10745. ((not org-use-tag-inheritance) nil)
  10746. ((stringp org-use-tag-inheritance)
  10747. (delq nil (mapcar
  10748. (lambda (x)
  10749. (if (and (string-match org-use-tag-inheritance x)
  10750. (not (member x org-tags-exclude-from-inheritance)))
  10751. x nil))
  10752. tags)))
  10753. ((listp org-use-tag-inheritance)
  10754. (delq nil (mapcar
  10755. (lambda (x)
  10756. (if (member x org-use-tag-inheritance) x nil))
  10757. tags)))))
  10758. (defun org-match-sparse-tree (&optional todo-only match)
  10759. "Create a sparse tree according to tags string MATCH.
  10760. MATCH is a string with match syntax. It can contain a selection
  10761. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10762. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10763. those. See the manual for details.
  10764. If optional argument TODO-ONLY is non-nil, only select lines that
  10765. are also TODO tasks."
  10766. (interactive "P")
  10767. (org-agenda-prepare-buffers (list (current-buffer)))
  10768. (let ((org--matcher-tags-todo-only todo-only))
  10769. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10770. org--matcher-tags-todo-only)))
  10771. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10772. (defvar org-cached-props nil)
  10773. (defun org-cached-entry-get (pom property)
  10774. (if (or (eq t org-use-property-inheritance)
  10775. (and (stringp org-use-property-inheritance)
  10776. (let ((case-fold-search t))
  10777. (string-match-p org-use-property-inheritance property)))
  10778. (and (listp org-use-property-inheritance)
  10779. (member-ignore-case property org-use-property-inheritance)))
  10780. ;; Caching is not possible, check it directly.
  10781. (org-entry-get pom property 'inherit)
  10782. ;; Get all properties, so we can do complicated checks easily.
  10783. (cdr (assoc-string property
  10784. (or org-cached-props
  10785. (setq org-cached-props (org-entry-properties pom)))
  10786. t))))
  10787. (defun org-global-tags-completion-table (&optional files)
  10788. "Return the list of all tags in all agenda buffer/files.
  10789. Optional FILES argument is a list of files which can be used
  10790. instead of the agenda files."
  10791. (save-excursion
  10792. (org-uniquify
  10793. (delq nil
  10794. (apply #'append
  10795. (mapcar
  10796. (lambda (file)
  10797. (set-buffer (find-file-noselect file))
  10798. (org--tag-add-to-alist
  10799. (org-get-buffer-tags)
  10800. (mapcar (lambda (x)
  10801. (and (stringp (car-safe x))
  10802. (list (car-safe x))))
  10803. org-current-tag-alist)))
  10804. (if (car-safe files) files
  10805. (org-agenda-files))))))))
  10806. (defun org-make-tags-matcher (match)
  10807. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10808. Returns a cons of the selection string MATCH and a function
  10809. implementing the matcher.
  10810. The matcher is to be called at an Org entry, with point on the
  10811. headline, and returns non-nil if the entry matches the selection
  10812. string MATCH. It must be called with three arguments: the TODO
  10813. keyword at the entry (or nil if none), the list of all tags at
  10814. the entry including inherited ones and the reduced level of the
  10815. headline. Additionally, the category of the entry, if any, must
  10816. be specified as the text property `org-category' on the headline.
  10817. This function sets the variable `org--matcher-tags-todo-only' to
  10818. a non-nil value if the matcher restricts matching to TODO
  10819. entries, otherwise it is not touched.
  10820. See also `org-scan-tags'."
  10821. (unless match
  10822. ;; Get a new match request, with completion against the global
  10823. ;; tags table and the local tags in current buffer.
  10824. (let ((org-last-tags-completion-table
  10825. (org--tag-add-to-alist
  10826. (org-get-buffer-tags)
  10827. (org-global-tags-completion-table))))
  10828. (setq match
  10829. (completing-read
  10830. "Match: "
  10831. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10832. (let ((match0 match)
  10833. (re (concat
  10834. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10835. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10836. "\\([<>=]\\{1,2\\}\\)"
  10837. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10838. "\\|" org-tag-re "\\)"))
  10839. (start 0)
  10840. tagsmatch todomatch tagsmatcher todomatcher)
  10841. ;; Expand group tags.
  10842. (setq match (org-tags-expand match))
  10843. ;; Check if there is a TODO part of this match, which would be the
  10844. ;; part after a "/". To make sure that this slash is not part of
  10845. ;; a property value to be matched against, we also check that
  10846. ;; there is no / after that slash. First, find the last slash.
  10847. (let ((s 0))
  10848. (while (string-match "/+" match s)
  10849. (setq start (match-beginning 0))
  10850. (setq s (match-end 0))))
  10851. (if (and (string-match "/+" match start)
  10852. (not (string-match-p "\"" match start)))
  10853. ;; Match contains also a TODO-matching request.
  10854. (progn
  10855. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10856. (setq todomatch (substring match (match-end 0)))
  10857. (when (string-prefix-p "!" todomatch)
  10858. (setq org--matcher-tags-todo-only t)
  10859. (setq todomatch (substring todomatch 1)))
  10860. (when (string-match "\\`\\s-*\\'" todomatch)
  10861. (setq todomatch nil)))
  10862. ;; Only matching tags.
  10863. (setq tagsmatch match)
  10864. (setq todomatch nil))
  10865. ;; Make the tags matcher.
  10866. (when (org-string-nw-p tagsmatch)
  10867. (let ((orlist nil)
  10868. (orterms (org-split-string tagsmatch "|"))
  10869. term)
  10870. (while (setq term (pop orterms))
  10871. (while (and (equal (substring term -1) "\\") orterms)
  10872. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10873. (while (string-match re term)
  10874. (let* ((rest (substring term (match-end 0)))
  10875. (minus (and (match-end 1)
  10876. (equal (match-string 1 term) "-")))
  10877. (tag (save-match-data
  10878. (replace-regexp-in-string
  10879. "\\\\-" "-" (match-string 2 term))))
  10880. (regexp (eq (string-to-char tag) ?{))
  10881. (levelp (match-end 4))
  10882. (propp (match-end 5))
  10883. (mm
  10884. (cond
  10885. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10886. (levelp
  10887. `(,(org-op-to-function (match-string 3 term))
  10888. level
  10889. ,(string-to-number (match-string 4 term))))
  10890. (propp
  10891. (let* ((gv (pcase (upcase (match-string 5 term))
  10892. ("CATEGORY"
  10893. '(get-text-property (point) 'org-category))
  10894. ("TODO" 'todo)
  10895. (p `(org-cached-entry-get nil ,p))))
  10896. (pv (match-string 7 term))
  10897. (regexp (eq (string-to-char pv) ?{))
  10898. (strp (eq (string-to-char pv) ?\"))
  10899. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10900. (po (org-op-to-function (match-string 6 term)
  10901. (if timep 'time strp))))
  10902. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10903. (when timep (setq pv (org-matcher-time pv)))
  10904. (cond ((and regexp (eq po '/=))
  10905. `(not (string-match ,pv (or ,gv ""))))
  10906. (regexp `(string-match ,pv (or ,gv "")))
  10907. (strp `(,po (or ,gv "") ,pv))
  10908. (t
  10909. `(,po
  10910. (string-to-number (or ,gv ""))
  10911. ,(string-to-number pv))))))
  10912. (t `(member ,tag tags-list)))))
  10913. (push (if minus `(not ,mm) mm) tagsmatcher)
  10914. (setq term rest)))
  10915. (push `(and ,@tagsmatcher) orlist)
  10916. (setq tagsmatcher nil))
  10917. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10918. ;; Make the TODO matcher.
  10919. (when (org-string-nw-p todomatch)
  10920. (let ((orlist nil))
  10921. (dolist (term (org-split-string todomatch "|"))
  10922. (while (string-match re term)
  10923. (let* ((minus (and (match-end 1)
  10924. (equal (match-string 1 term) "-")))
  10925. (kwd (match-string 2 term))
  10926. (regexp (eq (string-to-char kwd) ?{))
  10927. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10928. `(equal todo ,kwd))))
  10929. (push (if minus `(not ,mm) mm) todomatcher))
  10930. (setq term (substring term (match-end 0))))
  10931. (push (if (> (length todomatcher) 1)
  10932. (cons 'and todomatcher)
  10933. (car todomatcher))
  10934. orlist)
  10935. (setq todomatcher nil))
  10936. (setq todomatcher (cons 'or orlist))))
  10937. ;; Return the string and function of the matcher. If no
  10938. ;; tags-specific or todo-specific matcher exists, match
  10939. ;; everything.
  10940. (let ((matcher (if (and tagsmatcher todomatcher)
  10941. `(and ,tagsmatcher ,todomatcher)
  10942. (or tagsmatcher todomatcher t))))
  10943. (when org--matcher-tags-todo-only
  10944. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10945. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10946. (defun org--tags-expand-group (group tag-groups expanded)
  10947. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10948. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10949. an accumulator used in recursive calls."
  10950. (dolist (tag group)
  10951. (unless (member tag expanded)
  10952. (let ((group (assoc tag tag-groups)))
  10953. (push tag expanded)
  10954. (when group
  10955. (setq expanded
  10956. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10957. expanded)
  10958. (defun org-tags-expand (match &optional single-as-list downcased)
  10959. "Expand group tags in MATCH.
  10960. This replaces every group tag in MATCH with a regexp tag search.
  10961. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10962. will be replaced like this:
  10963. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10964. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10965. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10966. Replacing by a regexp preserves the structure of the match.
  10967. E.g., this expansion
  10968. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10969. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10970. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10971. A group tag in MATCH can contain regular expressions of its own.
  10972. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10973. will be replaced like this:
  10974. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10975. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10976. assumed to be a single group tag, and the function will return
  10977. the list of tags in this group.
  10978. When DOWNCASED is non-nil, expand downcased TAGS."
  10979. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10980. (let ((tag-groups
  10981. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10982. (if (not downcased) g
  10983. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10984. (cond
  10985. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10986. (org-group-tags
  10987. (let* ((case-fold-search t)
  10988. (tag-syntax org-mode-syntax-table)
  10989. (group-keys (mapcar #'car tag-groups))
  10990. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10991. (return-match (if downcased (downcase match) match)))
  10992. ;; Mark regexp-expressions in the match-expression so that we
  10993. ;; do not replace them later on.
  10994. (let ((s 0))
  10995. (while (string-match "{.+?}" return-match s)
  10996. (setq s (match-end 0))
  10997. (add-text-properties
  10998. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10999. ;; @ and _ are allowed as word-components in tags.
  11000. (modify-syntax-entry ?@ "w" tag-syntax)
  11001. (modify-syntax-entry ?_ "w" tag-syntax)
  11002. ;; For each tag token found in MATCH, compute a regexp and it
  11003. (with-syntax-table tag-syntax
  11004. (replace-regexp-in-string
  11005. key-regexp
  11006. (lambda (m)
  11007. (if (get-text-property (match-beginning 2) 'regexp m)
  11008. m ;regexp tag: ignore
  11009. (let* ((operator (match-string 1 m))
  11010. (tag-token (let ((tag (match-string 2 m)))
  11011. (list (if downcased (downcase tag) tag))))
  11012. regexp-tags regular-tags)
  11013. ;; Partition tags between regexp and regular tags.
  11014. ;; Remove curly bracket syntax from regexp tags.
  11015. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11016. (save-match-data
  11017. (if (string-match "{\\(.+?\\)}" tag)
  11018. (push (match-string 1 tag) regexp-tags)
  11019. (push tag regular-tags))))
  11020. ;; Replace tag token by the appropriate regexp.
  11021. ;; Regular tags need to be regexp-quoted, whereas
  11022. ;; regexp-tags are inserted as-is.
  11023. (let ((regular (regexp-opt regular-tags))
  11024. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11025. (concat operator
  11026. (cond
  11027. ((null regular-tags) (format "{%s}" regexp))
  11028. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11029. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11030. return-match
  11031. t t))))
  11032. (t match))))
  11033. (defun org-op-to-function (op &optional stringp)
  11034. "Turn an operator into the appropriate function."
  11035. (setq op
  11036. (cond
  11037. ((equal op "<" ) '(< org-string< org-time<))
  11038. ((equal op ">" ) '(> org-string> org-time>))
  11039. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11040. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11041. ((member op '("=" "==")) '(= string= org-time=))
  11042. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11043. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11044. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11045. (defvar org-tags-overlay (make-overlay 1 1))
  11046. (delete-overlay org-tags-overlay)
  11047. (defun org-add-prop-inherited (s)
  11048. (add-text-properties 0 (length s) '(inherited t) s)
  11049. s)
  11050. (defun org-toggle-tag (tag &optional onoff)
  11051. "Toggle the tag TAG for the current line.
  11052. If ONOFF is `on' or `off', don't toggle but set to this state."
  11053. (save-excursion
  11054. (org-back-to-heading t)
  11055. (let ((current
  11056. ;; Reverse the tags list so any new tag is appended to the
  11057. ;; current list of tags.
  11058. (nreverse (org-get-tags nil t)))
  11059. res)
  11060. (pcase onoff
  11061. (`off (setq current (delete tag current)))
  11062. ((or `on (guard (not (member tag current))))
  11063. (setq res t)
  11064. (cl-pushnew tag current :test #'equal))
  11065. (_ (setq current (delete tag current))))
  11066. (org-set-tags (nreverse current))
  11067. res)))
  11068. (defun org--align-tags-here (to-col)
  11069. "Align tags on the current headline to TO-COL.
  11070. Assume point is on a headline. Preserve point when aligning
  11071. tags."
  11072. (when (org-match-line org-tag-line-re)
  11073. (let* ((tags-start (match-beginning 1))
  11074. (blank-start (save-excursion
  11075. (goto-char tags-start)
  11076. (skip-chars-backward " \t")
  11077. (point)))
  11078. (new (max (if (>= to-col 0) to-col
  11079. (- (abs to-col) (string-width (match-string 1))))
  11080. ;; Introduce at least one space after the heading
  11081. ;; or the stars.
  11082. (save-excursion
  11083. (goto-char blank-start)
  11084. (1+ (current-column)))))
  11085. (current
  11086. (save-excursion (goto-char tags-start) (current-column)))
  11087. (origin (point-marker))
  11088. (column (current-column))
  11089. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11090. (when (/= new current)
  11091. (delete-region blank-start tags-start)
  11092. (goto-char blank-start)
  11093. (let ((indent-tabs-mode nil)) (indent-to new))
  11094. ;; Try to move back to original position. If point was in the
  11095. ;; blanks before the tags, ORIGIN marker is of no use because
  11096. ;; it now points to BLANK-START. Use COLUMN instead.
  11097. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11098. (defun org-set-tags-command (&optional arg)
  11099. "Set the tags for the current visible entry.
  11100. When called with `\\[universal-argument]' prefix argument ARG, \
  11101. realign all tags
  11102. in the current buffer.
  11103. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11104. unconditionally do not
  11105. offer the fast tag selection interface.
  11106. If a region is active, set tags in the region according to the
  11107. setting of `org-loop-over-headlines-in-active-region'.
  11108. This function is for interactive use only;
  11109. in Lisp code use `org-set-tags' instead."
  11110. (interactive "P")
  11111. (let ((org-use-fast-tag-selection
  11112. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11113. (cond
  11114. ((equal '(4) arg) (org-align-tags t))
  11115. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11116. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11117. (org-map-entries
  11118. #'org-set-tags-command
  11119. nil
  11120. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11121. 'region-start-level
  11122. 'region)
  11123. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11124. (t
  11125. (save-excursion
  11126. (org-back-to-heading)
  11127. (let* ((all-tags (org-get-tags))
  11128. (table (setq org-last-tags-completion-table
  11129. (org--tag-add-to-alist
  11130. (and org-complete-tags-always-offer-all-agenda-tags
  11131. (org-global-tags-completion-table
  11132. (org-agenda-files)))
  11133. (or org-current-tag-alist (org-get-buffer-tags)))))
  11134. (current-tags
  11135. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11136. all-tags))
  11137. (inherited-tags
  11138. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11139. all-tags))
  11140. (tags
  11141. (replace-regexp-in-string
  11142. ;; Ignore all forbidden characters in tags.
  11143. "[^[:alnum:]_@#%]+" ":"
  11144. (if (or (eq t org-use-fast-tag-selection)
  11145. (and org-use-fast-tag-selection
  11146. (delq nil (mapcar #'cdr table))))
  11147. (org-fast-tag-selection
  11148. current-tags
  11149. inherited-tags
  11150. table
  11151. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11152. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11153. (org-trim (completing-read
  11154. "Tags: "
  11155. #'org-tags-completion-function
  11156. nil nil (org-make-tag-string current-tags)
  11157. 'org-tags-history)))))))
  11158. (org-set-tags tags)))))))
  11159. (defun org-align-tags (&optional all)
  11160. "Align tags in current entry.
  11161. When optional argument ALL is non-nil, align all tags in the
  11162. visible part of the buffer."
  11163. (let ((get-indent-column
  11164. (lambda ()
  11165. (let ((offset (if (bound-and-true-p org-indent-mode)
  11166. (* (1- org-indent-indentation-per-level)
  11167. (1- (org-current-level)))
  11168. 0)))
  11169. (+ org-tags-column
  11170. (if (> org-tags-column 0) (- offset) offset))))))
  11171. (if (and (not all) (org-at-heading-p))
  11172. (org--align-tags-here (funcall get-indent-column))
  11173. (save-excursion
  11174. (if all
  11175. (progn
  11176. (goto-char (point-min))
  11177. (while (re-search-forward org-tag-line-re nil t)
  11178. (org--align-tags-here (funcall get-indent-column))))
  11179. (org-back-to-heading t)
  11180. (org--align-tags-here (funcall get-indent-column)))))))
  11181. (defun org-set-tags (tags)
  11182. "Set the tags of the current entry to TAGS, replacing current tags.
  11183. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11184. If TAGS is nil or the empty string, all tags are removed.
  11185. This function assumes point is on a headline."
  11186. (org-with-wide-buffer
  11187. (let ((tags (pcase tags
  11188. ((pred listp) tags)
  11189. ((pred stringp) (split-string (org-trim tags) ":" t))
  11190. (_ (error "Invalid tag specification: %S" tags))))
  11191. (old-tags (org-get-tags nil t))
  11192. (tags-change? nil))
  11193. (when (functionp org-tags-sort-function)
  11194. (setq tags (sort tags org-tags-sort-function)))
  11195. (setq tags-change? (not (equal tags old-tags)))
  11196. (when tags-change?
  11197. ;; Delete previous tags and any trailing white space.
  11198. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11199. (line-end-position)))
  11200. (skip-chars-backward " \t")
  11201. (delete-region (point) (line-end-position))
  11202. ;; Deleting white spaces may break an otherwise empty headline.
  11203. ;; Re-introduce one space in this case.
  11204. (unless (org-at-heading-p) (insert " "))
  11205. (when tags
  11206. (save-excursion (insert " " (org-make-tag-string tags)))
  11207. ;; When text is being inserted on an invisible region
  11208. ;; boundary, it can be inadvertently sucked into
  11209. ;; invisibility.
  11210. (unless (org-invisible-p (line-beginning-position))
  11211. (org-flag-region (point) (line-end-position) nil 'outline))))
  11212. ;; Align tags, if any.
  11213. (when tags (org-align-tags))
  11214. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11215. (defun org-change-tag-in-region (beg end tag off)
  11216. "Add or remove TAG for each entry in the region.
  11217. This works in the agenda, and also in an Org buffer."
  11218. (interactive
  11219. (list (region-beginning) (region-end)
  11220. (let ((org-last-tags-completion-table
  11221. (if (derived-mode-p 'org-mode)
  11222. (org--tag-add-to-alist
  11223. (org-get-buffer-tags)
  11224. (org-global-tags-completion-table))
  11225. (org-global-tags-completion-table))))
  11226. (completing-read
  11227. "Tag: " 'org-tags-completion-function nil nil nil
  11228. 'org-tags-history))
  11229. (progn
  11230. (message "[s]et or [r]emove? ")
  11231. (equal (read-char-exclusive) ?r))))
  11232. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11233. (let ((agendap (equal major-mode 'org-agenda-mode))
  11234. l1 l2 m buf pos newhead (cnt 0))
  11235. (goto-char end)
  11236. (setq l2 (1- (org-current-line)))
  11237. (goto-char beg)
  11238. (setq l1 (org-current-line))
  11239. (cl-loop for l from l1 to l2 do
  11240. (org-goto-line l)
  11241. (setq m (get-text-property (point) 'org-hd-marker))
  11242. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11243. (and agendap m))
  11244. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11245. pos (if agendap m (point)))
  11246. (with-current-buffer buf
  11247. (save-excursion
  11248. (save-restriction
  11249. (goto-char pos)
  11250. (setq cnt (1+ cnt))
  11251. (org-toggle-tag tag (if off 'off 'on))
  11252. (setq newhead (org-get-heading)))))
  11253. (and agendap (org-agenda-change-all-lines newhead m))))
  11254. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11255. (defun org-tags-completion-function (string _predicate &optional flag)
  11256. "Complete tag STRING.
  11257. FLAG specifies the type of completion operation to perform. This
  11258. function is passed as a collection function to `completing-read',
  11259. which see."
  11260. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11261. (confirm (lambda (x) (stringp (car x))))
  11262. (prefix ""))
  11263. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11264. (setq prefix (match-string 1 string))
  11265. (setq string (match-string 2 string)))
  11266. (pcase flag
  11267. (`t (all-completions string org-last-tags-completion-table confirm))
  11268. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11269. (`nil
  11270. (pcase (try-completion string org-last-tags-completion-table confirm)
  11271. ((and completion (pred stringp))
  11272. (concat prefix
  11273. completion
  11274. (if (and org-add-colon-after-tag-completion
  11275. (assoc completion org-last-tags-completion-table))
  11276. ":"
  11277. "")))
  11278. (completion completion)))
  11279. (_ nil))))
  11280. (defun org-fast-tag-insert (kwd tags face &optional end)
  11281. "Insert KWD, and the TAGS, the latter with face FACE.
  11282. Also insert END."
  11283. (insert (format "%-12s" (concat kwd ":"))
  11284. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11285. (or end "")))
  11286. (defun org-fast-tag-show-exit (flag)
  11287. (save-excursion
  11288. (org-goto-line 3)
  11289. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11290. (replace-match ""))
  11291. (when flag
  11292. (end-of-line 1)
  11293. (org-move-to-column (- (window-width) 19) t)
  11294. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11295. (defun org-set-current-tags-overlay (current prefix)
  11296. "Add an overlay to CURRENT tag with PREFIX."
  11297. (let ((s (org-make-tag-string current)))
  11298. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11299. (org-overlay-display org-tags-overlay (concat prefix s))))
  11300. (defvar org-last-tag-selection-key nil)
  11301. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11302. "Fast tag selection with single keys.
  11303. CURRENT is the current list of tags in the headline, INHERITED is the
  11304. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11305. possibly with grouping information. TODO-TABLE is a similar table with
  11306. TODO keywords, should these have keys assigned to them.
  11307. If the keys are nil, a-z are automatically assigned.
  11308. Returns the new tags string, or nil to not change the current settings."
  11309. (let* ((fulltable (append table todo-table))
  11310. (maxlen (if (null fulltable) 0
  11311. (apply #'max
  11312. (mapcar (lambda (x)
  11313. (if (stringp (car x)) (string-width (car x))
  11314. 0))
  11315. fulltable))))
  11316. (buf (current-buffer))
  11317. (expert (eq org-fast-tag-selection-single-key 'expert))
  11318. (buffer-tags nil)
  11319. (fwidth (+ maxlen 3 1 3))
  11320. (ncol (/ (- (window-width) 4) fwidth))
  11321. (i-face 'org-done)
  11322. (c-face 'org-todo)
  11323. tg cnt e c char c1 c2 ntable tbl rtn
  11324. ov-start ov-end ov-prefix
  11325. (exit-after-next org-fast-tag-selection-single-key)
  11326. (done-keywords org-done-keywords)
  11327. groups ingroup intaggroup)
  11328. (save-excursion
  11329. (beginning-of-line)
  11330. (if (looking-at org-tag-line-re)
  11331. (setq ov-start (match-beginning 1)
  11332. ov-end (match-end 1)
  11333. ov-prefix "")
  11334. (setq ov-start (1- (point-at-eol))
  11335. ov-end (1+ ov-start))
  11336. (skip-chars-forward "^\n\r")
  11337. (setq ov-prefix
  11338. (concat
  11339. (buffer-substring (1- (point)) (point))
  11340. (if (> (current-column) org-tags-column)
  11341. " "
  11342. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11343. (move-overlay org-tags-overlay ov-start ov-end)
  11344. (save-excursion
  11345. (save-window-excursion
  11346. (if expert
  11347. (set-buffer (get-buffer-create " *Org tags*"))
  11348. (delete-other-windows)
  11349. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11350. (org-switch-to-buffer-other-window " *Org tags*"))
  11351. (erase-buffer)
  11352. (setq-local org-done-keywords done-keywords)
  11353. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11354. (org-fast-tag-insert "Current" current c-face "\n\n")
  11355. (org-fast-tag-show-exit exit-after-next)
  11356. (org-set-current-tags-overlay current ov-prefix)
  11357. (setq tbl fulltable char ?a cnt 0)
  11358. (while (setq e (pop tbl))
  11359. (cond
  11360. ((eq (car e) :startgroup)
  11361. (push '() groups) (setq ingroup t)
  11362. (unless (zerop cnt)
  11363. (setq cnt 0)
  11364. (insert "\n"))
  11365. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11366. ((eq (car e) :endgroup)
  11367. (setq ingroup nil cnt 0)
  11368. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11369. ((eq (car e) :startgrouptag)
  11370. (setq intaggroup t)
  11371. (unless (zerop cnt)
  11372. (setq cnt 0)
  11373. (insert "\n"))
  11374. (insert "[ "))
  11375. ((eq (car e) :endgrouptag)
  11376. (setq intaggroup nil cnt 0)
  11377. (insert "]\n"))
  11378. ((equal e '(:newline))
  11379. (unless (zerop cnt)
  11380. (setq cnt 0)
  11381. (insert "\n")
  11382. (setq e (car tbl))
  11383. (while (equal (car tbl) '(:newline))
  11384. (insert "\n")
  11385. (setq tbl (cdr tbl)))))
  11386. ((equal e '(:grouptags)) (insert " : "))
  11387. (t
  11388. (setq tg (copy-sequence (car e)) c2 nil)
  11389. (if (cdr e)
  11390. (setq c (cdr e))
  11391. ;; automatically assign a character.
  11392. (setq c1 (string-to-char
  11393. (downcase (substring
  11394. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11395. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11396. (while (or (rassoc char ntable) (rassoc char table))
  11397. (setq char (1+ char)))
  11398. (setq c2 c1))
  11399. (setq c (or c2 char)))
  11400. (when ingroup (push tg (car groups)))
  11401. (setq tg (org-add-props tg nil 'face
  11402. (cond
  11403. ((not (assoc tg table))
  11404. (org-get-todo-face tg))
  11405. ((member tg current) c-face)
  11406. ((member tg inherited) i-face))))
  11407. (when (equal (caar tbl) :grouptags)
  11408. (org-add-props tg nil 'face 'org-tag-group))
  11409. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11410. (insert "[" c "] " tg (make-string
  11411. (- fwidth 4 (length tg)) ?\ ))
  11412. (push (cons tg c) ntable)
  11413. (when (= (cl-incf cnt) ncol)
  11414. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11415. (insert "\n")
  11416. (when (or ingroup intaggroup) (insert " ")))
  11417. (setq cnt 0)))))
  11418. (setq ntable (nreverse ntable))
  11419. (insert "\n")
  11420. (goto-char (point-min))
  11421. (unless expert (org-fit-window-to-buffer))
  11422. (setq rtn
  11423. (catch 'exit
  11424. (while t
  11425. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11426. (if (not groups) "no " "")
  11427. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11428. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11429. (setq org-last-tag-selection-key c)
  11430. (cond
  11431. ((= c ?\r) (throw 'exit t))
  11432. ((= c ?!)
  11433. (setq groups (not groups))
  11434. (goto-char (point-min))
  11435. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11436. ((= c ?\C-c)
  11437. (if (not expert)
  11438. (org-fast-tag-show-exit
  11439. (setq exit-after-next (not exit-after-next)))
  11440. (setq expert nil)
  11441. (delete-other-windows)
  11442. (set-window-buffer (split-window-vertically) " *Org tags*")
  11443. (org-switch-to-buffer-other-window " *Org tags*")
  11444. (org-fit-window-to-buffer)))
  11445. ((or (= c ?\C-g)
  11446. (and (= c ?q) (not (rassoc c ntable))))
  11447. (delete-overlay org-tags-overlay)
  11448. (setq quit-flag t))
  11449. ((= c ?\ )
  11450. (setq current nil)
  11451. (when exit-after-next (setq exit-after-next 'now)))
  11452. ((= c ?\t)
  11453. (condition-case nil
  11454. (setq tg (completing-read
  11455. "Tag: "
  11456. (or buffer-tags
  11457. (with-current-buffer buf
  11458. (setq buffer-tags
  11459. (org-get-buffer-tags))))))
  11460. (quit (setq tg "")))
  11461. (when (string-match "\\S-" tg)
  11462. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11463. (if (member tg current)
  11464. (setq current (delete tg current))
  11465. (push tg current)))
  11466. (when exit-after-next (setq exit-after-next 'now)))
  11467. ((setq e (rassoc c todo-table) tg (car e))
  11468. (with-current-buffer buf
  11469. (save-excursion (org-todo tg)))
  11470. (when exit-after-next (setq exit-after-next 'now)))
  11471. ((setq e (rassoc c ntable) tg (car e))
  11472. (if (member tg current)
  11473. (setq current (delete tg current))
  11474. (cl-loop for g in groups do
  11475. (when (member tg g)
  11476. (dolist (x g) (setq current (delete x current)))))
  11477. (push tg current))
  11478. (when exit-after-next (setq exit-after-next 'now))))
  11479. ;; Create a sorted list
  11480. (setq current
  11481. (sort current
  11482. (lambda (a b)
  11483. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11484. (when (eq exit-after-next 'now) (throw 'exit t))
  11485. (goto-char (point-min))
  11486. (beginning-of-line 2)
  11487. (delete-region (point) (point-at-eol))
  11488. (org-fast-tag-insert "Current" current c-face)
  11489. (org-set-current-tags-overlay current ov-prefix)
  11490. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11491. (while (re-search-forward tag-re nil t)
  11492. (let ((tag (match-string 1)))
  11493. (add-text-properties
  11494. (match-beginning 1) (match-end 1)
  11495. (list 'face
  11496. (cond
  11497. ((member tag current) c-face)
  11498. ((member tag inherited) i-face)
  11499. (t (get-text-property (match-beginning 1) '
  11500. face))))))))
  11501. (goto-char (point-min)))))
  11502. (delete-overlay org-tags-overlay)
  11503. (if rtn
  11504. (mapconcat 'identity current ":")
  11505. nil)))))
  11506. (defun org-make-tag-string (tags)
  11507. "Return string associated to TAGS.
  11508. TAGS is a list of strings."
  11509. (if (null tags) ""
  11510. (format ":%s:" (mapconcat #'identity tags ":"))))
  11511. (defun org--get-local-tags ()
  11512. "Return list of tags for the current headline.
  11513. Assume point is at the beginning of the headline."
  11514. (and (looking-at org-tag-line-re)
  11515. (split-string (match-string-no-properties 2) ":" t)))
  11516. (defun org-get-tags (&optional pos local)
  11517. "Get the list of tags specified in the current headline.
  11518. When argument POS is non-nil, retrieve tags for headline at POS.
  11519. According to `org-use-tag-inheritance', tags may be inherited
  11520. from parent headlines, and from the whole document, through
  11521. `org-file-tags'. In this case, the returned list of tags
  11522. contains tags in this order: file tags, tags inherited from
  11523. parent headlines, local tags.
  11524. However, when optional argument LOCAL is non-nil, only return
  11525. tags specified at the headline.
  11526. Inherited tags have the `inherited' text property."
  11527. (if (and org-trust-scanner-tags
  11528. (or (not pos) (eq pos (point)))
  11529. (not local))
  11530. org-scanner-tags
  11531. (org-with-point-at (or pos (point))
  11532. (unless (org-before-first-heading-p)
  11533. (org-back-to-heading t)
  11534. (let ((ltags (org--get-local-tags)) itags)
  11535. (if (or local (not org-use-tag-inheritance)) ltags
  11536. (while (org-up-heading-safe)
  11537. (setq itags (append (mapcar #'org-add-prop-inherited
  11538. (org--get-local-tags))
  11539. itags)))
  11540. (setq itags (append org-file-tags itags))
  11541. (delete-dups
  11542. (append (org-remove-uninherited-tags itags) ltags))))))))
  11543. (defun org-get-buffer-tags ()
  11544. "Get a table of all tags used in the buffer, for completion."
  11545. (org-with-point-at 1
  11546. (let (tags)
  11547. (while (re-search-forward org-tag-line-re nil t)
  11548. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11549. tags)))
  11550. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11551. ;;;; The mapping API
  11552. (defvar org-agenda-skip-comment-trees)
  11553. (defvar org-agenda-skip-function)
  11554. (defun org-map-entries (func &optional match scope &rest skip)
  11555. "Call FUNC at each headline selected by MATCH in SCOPE.
  11556. FUNC is a function or a lisp form. The function will be called without
  11557. arguments, with the cursor positioned at the beginning of the headline.
  11558. The return values of all calls to the function will be collected and
  11559. returned as a list.
  11560. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11561. does not need to preserve point. After evaluation, the cursor will be
  11562. moved to the end of the line (presumably of the headline of the
  11563. processed entry) and search continues from there. Under some
  11564. circumstances, this may not produce the wanted results. For example,
  11565. if you have removed (e.g. archived) the current (sub)tree it could
  11566. mean that the next entry will be skipped entirely. In such cases, you
  11567. can specify the position from where search should continue by making
  11568. FUNC set the variable `org-map-continue-from' to the desired buffer
  11569. position.
  11570. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11571. Only headlines that are matched by this query will be considered during
  11572. the iteration. When MATCH is nil or t, all headlines will be
  11573. visited by the iteration.
  11574. SCOPE determines the scope of this command. It can be any of:
  11575. nil The current buffer, respecting the restriction if any
  11576. tree The subtree started with the entry at point
  11577. region The entries within the active region, if any
  11578. region-start-level
  11579. The entries within the active region, but only those at
  11580. the same level than the first one.
  11581. file The current buffer, without restriction
  11582. file-with-archives
  11583. The current buffer, and any archives associated with it
  11584. agenda All agenda files
  11585. agenda-with-archives
  11586. All agenda files with any archive files associated with them
  11587. \(file1 file2 ...)
  11588. If this is a list, all files in the list will be scanned
  11589. The remaining args are treated as settings for the skipping facilities of
  11590. the scanner. The following items can be given here:
  11591. archive skip trees with the archive tag
  11592. comment skip trees with the COMMENT keyword
  11593. function or Emacs Lisp form:
  11594. will be used as value for `org-agenda-skip-function', so
  11595. whenever the function returns a position, FUNC will not be
  11596. called for that entry and search will continue from the
  11597. position returned
  11598. If your function needs to retrieve the tags including inherited tags
  11599. at the *current* entry, you can use the value of the variable
  11600. `org-scanner-tags' which will be much faster than getting the value
  11601. with `org-get-tags'. If your function gets properties with
  11602. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11603. to t around the call to `org-entry-properties' to get the same speedup.
  11604. Note that if your function moves around to retrieve tags and properties at
  11605. a *different* entry, you cannot use these techniques."
  11606. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11607. (not (org-region-active-p)))
  11608. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11609. (org-agenda-skip-archived-trees (memq 'archive skip))
  11610. (org-agenda-skip-comment-trees (memq 'comment skip))
  11611. (org-agenda-skip-function
  11612. (car (org-delete-all '(comment archive) skip)))
  11613. (org-tags-match-list-sublevels t)
  11614. (start-level (eq scope 'region-start-level))
  11615. matcher res
  11616. org-todo-keywords-for-agenda
  11617. org-done-keywords-for-agenda
  11618. org-todo-keyword-alist-for-agenda
  11619. org-tag-alist-for-agenda
  11620. org--matcher-tags-todo-only)
  11621. (cond
  11622. ((eq match t) (setq matcher t))
  11623. ((eq match nil) (setq matcher t))
  11624. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11625. (save-excursion
  11626. (save-restriction
  11627. (cond ((eq scope 'tree)
  11628. (org-back-to-heading t)
  11629. (org-narrow-to-subtree)
  11630. (setq scope nil))
  11631. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11632. (org-region-active-p))
  11633. ;; If needed, set start-level to a string like "2"
  11634. (when start-level
  11635. (save-excursion
  11636. (goto-char (region-beginning))
  11637. (unless (org-at-heading-p) (outline-next-heading))
  11638. (setq start-level (org-current-level))))
  11639. (narrow-to-region (region-beginning)
  11640. (save-excursion
  11641. (goto-char (region-end))
  11642. (unless (and (bolp) (org-at-heading-p))
  11643. (outline-next-heading))
  11644. (point)))
  11645. (setq scope nil)))
  11646. (if (not scope)
  11647. (progn
  11648. (org-agenda-prepare-buffers
  11649. (and buffer-file-name (list buffer-file-name)))
  11650. (setq res
  11651. (org-scan-tags
  11652. func matcher org--matcher-tags-todo-only start-level)))
  11653. ;; Get the right scope
  11654. (cond
  11655. ((and scope (listp scope) (symbolp (car scope)))
  11656. (setq scope (eval scope)))
  11657. ((eq scope 'agenda)
  11658. (setq scope (org-agenda-files t)))
  11659. ((eq scope 'agenda-with-archives)
  11660. (setq scope (org-agenda-files t))
  11661. (setq scope (org-add-archive-files scope)))
  11662. ((eq scope 'file)
  11663. (setq scope (and buffer-file-name (list buffer-file-name))))
  11664. ((eq scope 'file-with-archives)
  11665. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11666. (org-agenda-prepare-buffers scope)
  11667. (dolist (file scope)
  11668. (with-current-buffer (org-find-base-buffer-visiting file)
  11669. (org-with-wide-buffer
  11670. (goto-char (point-min))
  11671. (setq res
  11672. (append
  11673. res
  11674. (org-scan-tags
  11675. func matcher org--matcher-tags-todo-only)))))))))
  11676. res)))
  11677. ;;; Properties API
  11678. (defconst org-special-properties
  11679. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11680. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11681. "The special properties valid in Org mode.
  11682. These are properties that are not defined in the property drawer,
  11683. but in some other way.")
  11684. (defconst org-default-properties
  11685. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11686. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11687. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11688. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11689. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11690. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11691. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11692. "Some properties that are used by Org mode for various purposes.
  11693. Being in this list makes sure that they are offered for completion.")
  11694. (defun org--valid-property-p (property)
  11695. "Non-nil when string PROPERTY is a valid property name."
  11696. (not
  11697. (or (equal property "")
  11698. (string-match-p "\\s-" property))))
  11699. (defun org--update-property-plist (key val props)
  11700. "Associate KEY to VAL in alist PROPS.
  11701. Modifications are made by side-effect. Return new alist."
  11702. (let* ((appending (string= (substring key -1) "+"))
  11703. (key (if appending (substring key 0 -1) key))
  11704. (old (assoc-string key props t)))
  11705. (if (not old) (cons (cons key val) props)
  11706. (setcdr old (if appending (concat (cdr old) " " val) val))
  11707. props)))
  11708. (defun org-get-property-block (&optional beg force)
  11709. "Return the (beg . end) range of the body of the property drawer.
  11710. BEG is the beginning of the current subtree, or of the part
  11711. before the first headline. If it is not given, it will be found.
  11712. If the drawer does not exist, create it if FORCE is non-nil, or
  11713. return nil."
  11714. (org-with-wide-buffer
  11715. (when beg (goto-char beg))
  11716. (unless (org-before-first-heading-p)
  11717. (let ((beg (cond (beg)
  11718. ((or (not (featurep 'org-inlinetask))
  11719. (org-inlinetask-in-task-p))
  11720. (org-back-to-heading t))
  11721. (t (org-with-limited-levels (org-back-to-heading t))))))
  11722. (forward-line)
  11723. (when (looking-at-p org-planning-line-re) (forward-line))
  11724. (cond ((looking-at org-property-drawer-re)
  11725. (forward-line)
  11726. (cons (point) (progn (goto-char (match-end 0))
  11727. (line-beginning-position))))
  11728. (force
  11729. (goto-char beg)
  11730. (org-insert-property-drawer)
  11731. (let ((pos (save-excursion (search-forward ":END:")
  11732. (line-beginning-position))))
  11733. (cons pos pos))))))))
  11734. (defun org-at-property-p ()
  11735. "Non-nil when point is inside a property drawer.
  11736. See `org-property-re' for match data, if applicable."
  11737. (save-excursion
  11738. (beginning-of-line)
  11739. (and (looking-at org-property-re)
  11740. (let ((property-drawer (save-match-data (org-get-property-block))))
  11741. (and property-drawer
  11742. (>= (point) (car property-drawer))
  11743. (< (point) (cdr property-drawer)))))))
  11744. (defun org-property-action ()
  11745. "Do an action on properties."
  11746. (interactive)
  11747. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11748. (let ((c (read-char-exclusive)))
  11749. (cl-case c
  11750. (?s (call-interactively #'org-set-property))
  11751. (?d (call-interactively #'org-delete-property))
  11752. (?D (call-interactively #'org-delete-property-globally))
  11753. (?c (call-interactively #'org-compute-property-at-point))
  11754. (otherwise (user-error "No such property action %c" c)))))
  11755. (defun org-inc-effort ()
  11756. "Increment the value of the effort property in the current entry."
  11757. (interactive)
  11758. (org-set-effort t))
  11759. (defvar org-clock-effort) ; Defined in org-clock.el.
  11760. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11761. (defun org-set-effort (&optional increment value)
  11762. "Set the effort property of the current entry.
  11763. If INCREMENT is non-nil, set the property to the next allowed
  11764. value. Otherwise, if optional argument VALUE is provided, use
  11765. it. Eventually, prompt for the new value if none of the previous
  11766. variables is set."
  11767. (interactive "P")
  11768. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11769. (current (org-entry-get nil org-effort-property))
  11770. (value
  11771. (cond
  11772. (increment
  11773. (unless allowed (user-error "Allowed effort values are not set"))
  11774. (or (cl-caadr (member (list current) allowed))
  11775. (user-error "Unknown value %S among allowed values" current)))
  11776. (value
  11777. (if (stringp value) value
  11778. (error "Invalid effort value: %S" value)))
  11779. (t
  11780. (let ((must-match
  11781. (and allowed
  11782. (not (get-text-property 0 'org-unrestricted
  11783. (caar allowed))))))
  11784. (completing-read "Effort: " allowed nil must-match))))))
  11785. (unless (equal current value)
  11786. (org-entry-put nil org-effort-property value))
  11787. (org-refresh-property '((effort . identity)
  11788. (effort-minutes . org-duration-to-minutes))
  11789. value)
  11790. (when (equal (org-get-heading t t t t)
  11791. (bound-and-true-p org-clock-current-task))
  11792. (setq org-clock-effort value)
  11793. (org-clock-update-mode-line))
  11794. (message "%s is now %s" org-effort-property value)))
  11795. (defun org-entry-properties (&optional pom which)
  11796. "Get all properties of the current entry.
  11797. When POM is a buffer position, get all properties from the entry
  11798. there instead.
  11799. This includes the TODO keyword, the tags, time strings for
  11800. deadline, scheduled, and clocking, and any additional properties
  11801. defined in the entry.
  11802. If WHICH is nil or `all', get all properties. If WHICH is
  11803. `special' or `standard', only get that subclass. If WHICH is
  11804. a string, only get that property.
  11805. Return value is an alist. Keys are properties, as upcased
  11806. strings."
  11807. (org-with-point-at pom
  11808. (when (and (derived-mode-p 'org-mode)
  11809. (ignore-errors (org-back-to-heading t)))
  11810. (catch 'exit
  11811. (let* ((beg (point))
  11812. (specific (and (stringp which) (upcase which)))
  11813. (which (cond ((not specific) which)
  11814. ((member specific org-special-properties) 'special)
  11815. (t 'standard)))
  11816. props)
  11817. ;; Get the special properties, like TODO and TAGS.
  11818. (when (memq which '(nil all special))
  11819. (when (or (not specific) (string= specific "CLOCKSUM"))
  11820. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11821. (when clocksum
  11822. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11823. props)))
  11824. (when specific (throw 'exit props)))
  11825. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11826. (let ((clocksumt (get-text-property (point)
  11827. :org-clock-minutes-today)))
  11828. (when clocksumt
  11829. (push (cons "CLOCKSUM_T"
  11830. (org-duration-from-minutes clocksumt))
  11831. props)))
  11832. (when specific (throw 'exit props)))
  11833. (when (or (not specific) (string= specific "ITEM"))
  11834. (let ((case-fold-search nil))
  11835. (when (looking-at org-complex-heading-regexp)
  11836. (push (cons "ITEM"
  11837. (let ((title (match-string-no-properties 4)))
  11838. (if (org-string-nw-p title)
  11839. (org-remove-tabs title)
  11840. "")))
  11841. props)))
  11842. (when specific (throw 'exit props)))
  11843. (when (or (not specific) (string= specific "TODO"))
  11844. (let ((case-fold-search nil))
  11845. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11846. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11847. (when specific (throw 'exit props)))
  11848. (when (or (not specific) (string= specific "PRIORITY"))
  11849. (push (cons "PRIORITY"
  11850. (if (looking-at org-priority-regexp)
  11851. (match-string-no-properties 2)
  11852. (char-to-string org-default-priority)))
  11853. props)
  11854. (when specific (throw 'exit props)))
  11855. (when (or (not specific) (string= specific "FILE"))
  11856. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11857. props)
  11858. (when specific (throw 'exit props)))
  11859. (when (or (not specific) (string= specific "TAGS"))
  11860. (let ((tags (org-get-tags nil t)))
  11861. (when tags
  11862. (push (cons "TAGS" (org-make-tag-string tags))
  11863. props)))
  11864. (when specific (throw 'exit props)))
  11865. (when (or (not specific) (string= specific "ALLTAGS"))
  11866. (let ((tags (org-get-tags)))
  11867. (when tags
  11868. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11869. props)))
  11870. (when specific (throw 'exit props)))
  11871. (when (or (not specific) (string= specific "BLOCKED"))
  11872. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11873. (when specific (throw 'exit props)))
  11874. (when (or (not specific)
  11875. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11876. (forward-line)
  11877. (when (looking-at-p org-planning-line-re)
  11878. (end-of-line)
  11879. (let ((bol (line-beginning-position))
  11880. ;; Backward compatibility: time keywords used to
  11881. ;; be configurable (before 8.3). Make sure we
  11882. ;; get the correct keyword.
  11883. (key-assoc `(("CLOSED" . ,org-closed-string)
  11884. ("DEADLINE" . ,org-deadline-string)
  11885. ("SCHEDULED" . ,org-scheduled-string))))
  11886. (dolist (pair (if specific (list (assoc specific key-assoc))
  11887. key-assoc))
  11888. (save-excursion
  11889. (when (search-backward (cdr pair) bol t)
  11890. (goto-char (match-end 0))
  11891. (skip-chars-forward " \t")
  11892. (and (looking-at org-ts-regexp-both)
  11893. (push (cons (car pair)
  11894. (match-string-no-properties 0))
  11895. props)))))))
  11896. (when specific (throw 'exit props)))
  11897. (when (or (not specific)
  11898. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11899. (let ((find-ts
  11900. (lambda (end ts)
  11901. ;; Fix next time-stamp before END. TS is the
  11902. ;; list of time-stamps found so far.
  11903. (let ((ts ts)
  11904. (regexp (cond
  11905. ((string= specific "TIMESTAMP")
  11906. org-ts-regexp)
  11907. ((string= specific "TIMESTAMP_IA")
  11908. org-ts-regexp-inactive)
  11909. ((assoc "TIMESTAMP_IA" ts)
  11910. org-ts-regexp)
  11911. ((assoc "TIMESTAMP" ts)
  11912. org-ts-regexp-inactive)
  11913. (t org-ts-regexp-both))))
  11914. (catch 'next
  11915. (while (re-search-forward regexp end t)
  11916. (backward-char)
  11917. (let ((object (org-element-context)))
  11918. ;; Accept to match timestamps in node
  11919. ;; properties, too.
  11920. (when (memq (org-element-type object)
  11921. '(node-property timestamp))
  11922. (let ((type
  11923. (org-element-property :type object)))
  11924. (cond
  11925. ((and (memq type '(active active-range))
  11926. (not (equal specific "TIMESTAMP_IA")))
  11927. (unless (assoc "TIMESTAMP" ts)
  11928. (push (cons "TIMESTAMP"
  11929. (org-element-property
  11930. :raw-value object))
  11931. ts)
  11932. (when specific (throw 'exit ts))))
  11933. ((and (memq type '(inactive inactive-range))
  11934. (not (string= specific "TIMESTAMP")))
  11935. (unless (assoc "TIMESTAMP_IA" ts)
  11936. (push (cons "TIMESTAMP_IA"
  11937. (org-element-property
  11938. :raw-value object))
  11939. ts)
  11940. (when specific (throw 'exit ts))))))
  11941. ;; Both timestamp types are found,
  11942. ;; move to next part.
  11943. (when (= (length ts) 2) (throw 'next ts)))))
  11944. ts)))))
  11945. (goto-char beg)
  11946. ;; First look for timestamps within headline.
  11947. (let ((ts (funcall find-ts (line-end-position) nil)))
  11948. (if (= (length ts) 2) (setq props (nconc ts props))
  11949. ;; Then find timestamps in the section, skipping
  11950. ;; planning line.
  11951. (let ((end (save-excursion (outline-next-heading))))
  11952. (forward-line)
  11953. (when (looking-at-p org-planning-line-re) (forward-line))
  11954. (setq props (nconc (funcall find-ts end ts) props))))))))
  11955. ;; Get the standard properties, like :PROP:.
  11956. (when (memq which '(nil all standard))
  11957. ;; If we are looking after a specific property, delegate
  11958. ;; to `org-entry-get', which is faster. However, make an
  11959. ;; exception for "CATEGORY", since it can be also set
  11960. ;; through keywords (i.e. #+CATEGORY).
  11961. (if (and specific (not (equal specific "CATEGORY")))
  11962. (let ((value (org-entry-get beg specific nil t)))
  11963. (throw 'exit (and value (list (cons specific value)))))
  11964. (let ((range (org-get-property-block beg)))
  11965. (when range
  11966. (let ((end (cdr range)) seen-base)
  11967. (goto-char (car range))
  11968. ;; Unlike to `org--update-property-plist', we
  11969. ;; handle the case where base values is found
  11970. ;; after its extension. We also forbid standard
  11971. ;; properties to be named as special properties.
  11972. (while (re-search-forward org-property-re end t)
  11973. (let* ((key (upcase (match-string-no-properties 2)))
  11974. (extendp (string-match-p "\\+\\'" key))
  11975. (key-base (if extendp (substring key 0 -1) key))
  11976. (value (match-string-no-properties 3)))
  11977. (cond
  11978. ((member-ignore-case key-base org-special-properties))
  11979. (extendp
  11980. (setq props
  11981. (org--update-property-plist key value props)))
  11982. ((member key seen-base))
  11983. (t (push key seen-base)
  11984. (let ((p (assoc-string key props t)))
  11985. (if p (setcdr p (concat value " " (cdr p)))
  11986. (push (cons key value) props))))))))))))
  11987. (unless (assoc "CATEGORY" props)
  11988. (push (cons "CATEGORY" (org-get-category beg)) props)
  11989. (when (string= specific "CATEGORY") (throw 'exit props)))
  11990. ;; Return value.
  11991. props)))))
  11992. (defun org--property-local-values (property literal-nil)
  11993. "Return value for PROPERTY in current entry.
  11994. Value is a list whose car is the base value for PROPERTY and cdr
  11995. a list of accumulated values. Return nil if neither is found in
  11996. the entry. Also return nil when PROPERTY is set to \"nil\",
  11997. unless LITERAL-NIL is non-nil."
  11998. (let ((range (org-get-property-block)))
  11999. (when range
  12000. (goto-char (car range))
  12001. (let* ((case-fold-search t)
  12002. (end (cdr range))
  12003. (value
  12004. ;; Base value.
  12005. (save-excursion
  12006. (let ((v (and (re-search-forward
  12007. (org-re-property property nil t) end t)
  12008. (match-string-no-properties 3))))
  12009. (list (if literal-nil v (org-not-nil v)))))))
  12010. ;; Find additional values.
  12011. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12012. (while (re-search-forward property+ end t)
  12013. (push (match-string-no-properties 3) value)))
  12014. ;; Return final values.
  12015. (and (not (equal value '(nil))) (nreverse value))))))
  12016. (defun org--property-global-value (property literal-nil)
  12017. "Return value for PROPERTY in current buffer.
  12018. Return value is a string. Return nil if property is not set
  12019. globally. Also return nil when PROPERTY is set to \"nil\",
  12020. unless LITERAL-NIL is non-nil."
  12021. (let ((global
  12022. (cdr (or (assoc-string property org-file-properties t)
  12023. (assoc-string property org-global-properties t)
  12024. (assoc-string property org-global-properties-fixed t)))))
  12025. (if literal-nil global (org-not-nil global))))
  12026. (defun org-entry-get (pom property &optional inherit literal-nil)
  12027. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12028. If INHERIT is non-nil and the entry does not have the property,
  12029. then also check higher levels of the hierarchy. If INHERIT is
  12030. the symbol `selective', use inheritance only if the setting in
  12031. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12032. If the property is present but empty, the return value is the
  12033. empty string. If the property is not present at all, nil is
  12034. returned. In any other case, return the value as a string.
  12035. Search is case-insensitive.
  12036. If LITERAL-NIL is set, return the string value \"nil\" as
  12037. a string, do not interpret it as the list atom nil. This is used
  12038. for inheritance when a \"nil\" value can supersede a non-nil
  12039. value higher up the hierarchy."
  12040. (org-with-point-at pom
  12041. (cond
  12042. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12043. ;; We need a special property. Use `org-entry-properties' to
  12044. ;; retrieve it, but specify the wanted property.
  12045. (cdr (assoc-string property (org-entry-properties nil property))))
  12046. ((and inherit
  12047. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12048. (org-entry-get-with-inheritance property literal-nil))
  12049. (t
  12050. (let* ((local (org--property-local-values property literal-nil))
  12051. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12052. (if literal-nil value (org-not-nil value)))))))
  12053. (defun org-property-or-variable-value (var &optional inherit)
  12054. "Check if there is a property fixing the value of VAR.
  12055. If yes, return this value. If not, return the current value of the variable."
  12056. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12057. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12058. (read prop)
  12059. (symbol-value var))))
  12060. (defun org-entry-delete (pom property)
  12061. "Delete PROPERTY from entry at point-or-marker POM.
  12062. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12063. non-nil when a property was removed."
  12064. (org-with-point-at pom
  12065. (pcase (org-get-property-block)
  12066. (`(,begin . ,origin)
  12067. (let* ((end (copy-marker origin))
  12068. (re (org-re-property
  12069. (concat (regexp-quote property) "\\+?") t t)))
  12070. (goto-char begin)
  12071. (while (re-search-forward re end t)
  12072. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12073. ;; If drawer is empty, remove it altogether.
  12074. (when (= begin end)
  12075. (delete-region (line-beginning-position 0)
  12076. (line-beginning-position 2)))
  12077. ;; Return non-nil if some property was removed.
  12078. (prog1 (/= end origin) (set-marker end nil))))
  12079. (_ nil))))
  12080. ;; Multi-values properties are properties that contain multiple values
  12081. ;; These values are assumed to be single words, separated by whitespace.
  12082. (defun org-entry-add-to-multivalued-property (pom property value)
  12083. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12084. (let* ((old (org-entry-get pom property))
  12085. (values (and old (split-string old))))
  12086. (setq value (org-entry-protect-space value))
  12087. (unless (member value values)
  12088. (setq values (append values (list value)))
  12089. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12090. (defun org-entry-remove-from-multivalued-property (pom property value)
  12091. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12092. (let* ((old (org-entry-get pom property))
  12093. (values (and old (split-string old))))
  12094. (setq value (org-entry-protect-space value))
  12095. (when (member value values)
  12096. (setq values (delete value values))
  12097. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12098. (defun org-entry-member-in-multivalued-property (pom property value)
  12099. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12100. (let* ((old (org-entry-get pom property))
  12101. (values (and old (split-string old))))
  12102. (setq value (org-entry-protect-space value))
  12103. (member value values)))
  12104. (defun org-entry-get-multivalued-property (pom property)
  12105. "Return a list of values in a multivalued property."
  12106. (let* ((value (org-entry-get pom property))
  12107. (values (and value (split-string value))))
  12108. (mapcar #'org-entry-restore-space values)))
  12109. (defun org-entry-put-multivalued-property (pom property &rest values)
  12110. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12111. VALUES should be a list of strings. Spaces will be protected."
  12112. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12113. (let* ((value (org-entry-get pom property))
  12114. (values (and value (split-string value))))
  12115. (mapcar #'org-entry-restore-space values)))
  12116. (defun org-entry-protect-space (s)
  12117. "Protect spaces and newline in string S."
  12118. (while (string-match " " s)
  12119. (setq s (replace-match "%20" t t s)))
  12120. (while (string-match "\n" s)
  12121. (setq s (replace-match "%0A" t t s)))
  12122. s)
  12123. (defun org-entry-restore-space (s)
  12124. "Restore spaces and newline in string S."
  12125. (while (string-match "%20" s)
  12126. (setq s (replace-match " " t t s)))
  12127. (while (string-match "%0A" s)
  12128. (setq s (replace-match "\n" t t s)))
  12129. s)
  12130. (defvar org-entry-property-inherited-from (make-marker)
  12131. "Marker pointing to the entry from where a property was inherited.
  12132. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12133. location of the entry where the inheritance search matched. If there was
  12134. no match, the marker will point nowhere.
  12135. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12136. is set.")
  12137. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12138. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12139. The search will stop at the first ancestor which has the property defined.
  12140. If the value found is \"nil\", return nil to show that the property
  12141. should be considered as undefined (this is the meaning of nil here).
  12142. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12143. (move-marker org-entry-property-inherited-from nil)
  12144. (org-with-wide-buffer
  12145. (let (value)
  12146. (catch 'exit
  12147. (while t
  12148. (let ((v (org--property-local-values property literal-nil)))
  12149. (when v
  12150. (setq value
  12151. (concat (mapconcat #'identity (delq nil v) " ")
  12152. (and value " ")
  12153. value)))
  12154. (cond
  12155. ((car v)
  12156. (org-back-to-heading t)
  12157. (move-marker org-entry-property-inherited-from (point))
  12158. (throw 'exit nil))
  12159. ((org-up-heading-safe))
  12160. (t
  12161. (let ((global (org--property-global-value property literal-nil)))
  12162. (cond ((not global))
  12163. (value (setq value (concat global " " value)))
  12164. (t (setq value global))))
  12165. (throw 'exit nil))))))
  12166. (if literal-nil value (org-not-nil value)))))
  12167. (defvar org-property-changed-functions nil
  12168. "Hook called when the value of a property has changed.
  12169. Each hook function should accept two arguments, the name of the property
  12170. and the new value.")
  12171. (defun org-entry-put (pom property value)
  12172. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12173. If the value is nil, it is converted to the empty string. If it
  12174. is not a string, an error is raised. Also raise an error on
  12175. invalid property names.
  12176. PROPERTY can be any regular property (see
  12177. `org-special-properties'). It can also be \"TODO\",
  12178. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12179. For the last two properties, VALUE may have any of the special
  12180. values \"earlier\" and \"later\". The function then increases or
  12181. decreases scheduled or deadline date by one day."
  12182. (cond ((null value) (setq value ""))
  12183. ((not (stringp value)) (error "Properties values should be strings"))
  12184. ((not (org--valid-property-p property))
  12185. (user-error "Invalid property name: \"%s\"" property)))
  12186. (org-with-point-at pom
  12187. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12188. (org-back-to-heading t)
  12189. (org-with-limited-levels (org-back-to-heading t)))
  12190. (let ((beg (point)))
  12191. (cond
  12192. ((equal property "TODO")
  12193. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12194. ((not (member value org-todo-keywords-1))
  12195. (user-error "\"%s\" is not a valid TODO state" value)))
  12196. (org-todo value)
  12197. (org-align-tags))
  12198. ((equal property "PRIORITY")
  12199. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12200. (org-align-tags))
  12201. ((equal property "SCHEDULED")
  12202. (forward-line)
  12203. (if (and (looking-at-p org-planning-line-re)
  12204. (re-search-forward
  12205. org-scheduled-time-regexp (line-end-position) t))
  12206. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12207. ((string= value "later") (org-timestamp-change 1 'day))
  12208. ((string= value "") (org-schedule '(4)))
  12209. (t (org-schedule nil value)))
  12210. (if (member value '("earlier" "later" ""))
  12211. (call-interactively #'org-schedule)
  12212. (org-schedule nil value))))
  12213. ((equal property "DEADLINE")
  12214. (forward-line)
  12215. (if (and (looking-at-p org-planning-line-re)
  12216. (re-search-forward
  12217. org-deadline-time-regexp (line-end-position) t))
  12218. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12219. ((string= value "later") (org-timestamp-change 1 'day))
  12220. ((string= value "") (org-deadline '(4)))
  12221. (t (org-deadline nil value)))
  12222. (if (member value '("earlier" "later" ""))
  12223. (call-interactively #'org-deadline)
  12224. (org-deadline nil value))))
  12225. ((member property org-special-properties)
  12226. (error "The %s property cannot be set with `org-entry-put'" property))
  12227. (t
  12228. (let* ((range (org-get-property-block beg 'force))
  12229. (end (cdr range))
  12230. (case-fold-search t))
  12231. (goto-char (car range))
  12232. (if (re-search-forward (org-re-property property nil t) end t)
  12233. (progn (delete-region (match-beginning 0) (match-end 0))
  12234. (goto-char (match-beginning 0)))
  12235. (goto-char end)
  12236. (insert "\n")
  12237. (backward-char))
  12238. (insert ":" property ":")
  12239. (when value (insert " " value))
  12240. (org-indent-line)))))
  12241. (run-hook-with-args 'org-property-changed-functions property value)))
  12242. (defun org-buffer-property-keys (&optional specials defaults columns)
  12243. "Get all property keys in the current buffer.
  12244. When SPECIALS is non-nil, also list the special properties that
  12245. reflect things like tags and TODO state.
  12246. When DEFAULTS is non-nil, also include properties that has
  12247. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12248. DESCRIPTION, LOCATION, and LOGGING and others.
  12249. When COLUMNS in non-nil, also include property names given in
  12250. COLUMN formats in the current buffer."
  12251. (let ((case-fold-search t)
  12252. (props (append
  12253. (and specials org-special-properties)
  12254. (and defaults (cons org-effort-property org-default-properties))
  12255. nil)))
  12256. (org-with-wide-buffer
  12257. (goto-char (point-min))
  12258. (while (re-search-forward org-property-start-re nil t)
  12259. (catch :skip
  12260. (let ((range (org-get-property-block)))
  12261. (unless range (throw :skip nil))
  12262. (goto-char (car range))
  12263. (let ((begin (car range))
  12264. (end (cdr range)))
  12265. ;; Make sure that found property block is not located
  12266. ;; before current point, as it would generate an infloop.
  12267. ;; It can happen, for example, in the following
  12268. ;; situation:
  12269. ;;
  12270. ;; * Headline
  12271. ;; :PROPERTIES:
  12272. ;; ...
  12273. ;; :END:
  12274. ;; *************** Inlinetask
  12275. ;; #+BEGIN_EXAMPLE
  12276. ;; :PROPERTIES:
  12277. ;; #+END_EXAMPLE
  12278. ;;
  12279. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12280. (while (< (point) end)
  12281. (let ((p (progn (looking-at org-property-re)
  12282. (match-string-no-properties 2))))
  12283. ;; Only add true property name, not extension symbol.
  12284. (push (if (not (string-match-p "\\+\\'" p)) p
  12285. (substring p 0 -1))
  12286. props))
  12287. (forward-line))))
  12288. (outline-next-heading)))
  12289. (when columns
  12290. (goto-char (point-min))
  12291. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12292. (let ((element (org-element-at-point)))
  12293. (when (memq (org-element-type element) '(keyword node-property))
  12294. (let ((value (org-element-property :value element))
  12295. (start 0))
  12296. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12297. \\(?:{[^}]+}\\)?"
  12298. value start)
  12299. (setq start (match-end 0))
  12300. (let ((p (match-string-no-properties 1 value)))
  12301. (unless (member-ignore-case p org-special-properties)
  12302. (push p props))))))))))
  12303. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12304. (defun org-property-values (key)
  12305. "List all non-nil values of property KEY in current buffer."
  12306. (org-with-wide-buffer
  12307. (goto-char (point-min))
  12308. (let ((case-fold-search t)
  12309. (re (org-re-property key))
  12310. values)
  12311. (while (re-search-forward re nil t)
  12312. (push (org-entry-get (point) key) values))
  12313. (delete-dups values))))
  12314. (defun org-insert-property-drawer ()
  12315. "Insert a property drawer into the current entry.
  12316. Do nothing if the drawer already exists. The newly created
  12317. drawer is immediately hidden."
  12318. (org-with-wide-buffer
  12319. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12320. (org-back-to-heading t)
  12321. (org-with-limited-levels (org-back-to-heading t)))
  12322. (forward-line)
  12323. (when (looking-at-p org-planning-line-re) (forward-line))
  12324. (unless (looking-at-p org-property-drawer-re)
  12325. ;; Make sure we start editing a line from current entry, not from
  12326. ;; next one. It prevents extending text properties or overlays
  12327. ;; belonging to the latter.
  12328. (when (bolp) (backward-char))
  12329. (let ((begin (1+ (point)))
  12330. (inhibit-read-only t))
  12331. (insert "\n:PROPERTIES:\n:END:")
  12332. (org-flag-drawer t nil (line-end-position 0) (point))
  12333. (when (eobp) (insert "\n"))
  12334. (org-indent-region begin (point))))))
  12335. (defun org-insert-drawer (&optional arg drawer)
  12336. "Insert a drawer at point.
  12337. When optional argument ARG is non-nil, insert a property drawer.
  12338. Optional argument DRAWER, when non-nil, is a string representing
  12339. drawer's name. Otherwise, the user is prompted for a name.
  12340. If a region is active, insert the drawer around that region
  12341. instead.
  12342. Point is left between drawer's boundaries."
  12343. (interactive "P")
  12344. (let* ((drawer (if arg "PROPERTIES"
  12345. (or drawer (read-from-minibuffer "Drawer: ")))))
  12346. (cond
  12347. ;; With C-u, fall back on `org-insert-property-drawer'
  12348. (arg (org-insert-property-drawer))
  12349. ;; Check validity of suggested drawer's name.
  12350. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12351. (user-error "Invalid drawer name"))
  12352. ;; With an active region, insert a drawer at point.
  12353. ((not (org-region-active-p))
  12354. (progn
  12355. (unless (bolp) (insert "\n"))
  12356. (insert (format ":%s:\n\n:END:\n" drawer))
  12357. (forward-line -2)))
  12358. ;; Otherwise, insert the drawer at point
  12359. (t
  12360. (let ((rbeg (region-beginning))
  12361. (rend (copy-marker (region-end))))
  12362. (unwind-protect
  12363. (progn
  12364. (goto-char rbeg)
  12365. (beginning-of-line)
  12366. (when (save-excursion
  12367. (re-search-forward org-outline-regexp-bol rend t))
  12368. (user-error "Drawers cannot contain headlines"))
  12369. ;; Position point at the beginning of the first
  12370. ;; non-blank line in region. Insert drawer's opening
  12371. ;; there, then indent it.
  12372. (org-skip-whitespace)
  12373. (beginning-of-line)
  12374. (insert ":" drawer ":\n")
  12375. (forward-line -1)
  12376. (indent-for-tab-command)
  12377. ;; Move point to the beginning of the first blank line
  12378. ;; after the last non-blank line in region. Insert
  12379. ;; drawer's closing, then indent it.
  12380. (goto-char rend)
  12381. (skip-chars-backward " \r\t\n")
  12382. (insert "\n:END:")
  12383. (deactivate-mark t)
  12384. (indent-for-tab-command)
  12385. (unless (eolp) (insert "\n")))
  12386. ;; Clear marker, whatever the outcome of insertion is.
  12387. (set-marker rend nil)))))))
  12388. (defvar org-property-set-functions-alist nil
  12389. "Property set function alist.
  12390. Each entry should have the following format:
  12391. (PROPERTY . READ-FUNCTION)
  12392. The read function will be called with the same argument as
  12393. `org-completing-read'.")
  12394. (defun org-set-property-function (property)
  12395. "Get the function that should be used to set PROPERTY.
  12396. This is computed according to `org-property-set-functions-alist'."
  12397. (or (cdr (assoc property org-property-set-functions-alist))
  12398. 'org-completing-read))
  12399. (defun org-read-property-value (property &optional pom)
  12400. "Read value for PROPERTY, as a string.
  12401. When optional argument POM is non-nil, completion uses additional
  12402. information, i.e., allowed or existing values at point or marker
  12403. POM."
  12404. (let* ((completion-ignore-case t)
  12405. (allowed
  12406. (or (org-property-get-allowed-values nil property 'table)
  12407. (and pom (org-property-get-allowed-values pom property 'table))))
  12408. (current (org-entry-get nil property))
  12409. (prompt (format "%s value%s: "
  12410. property
  12411. (if (org-string-nw-p current)
  12412. (format " [%s]" current)
  12413. "")))
  12414. (set-function (org-set-property-function property)))
  12415. (org-trim
  12416. (if allowed
  12417. (funcall set-function
  12418. prompt allowed nil
  12419. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12420. (let ((all (mapcar #'list
  12421. (append (org-property-values property)
  12422. (and pom
  12423. (org-with-point-at pom
  12424. (org-property-values property)))))))
  12425. (funcall set-function prompt all nil nil "" nil current))))))
  12426. (defvar org-last-set-property nil)
  12427. (defvar org-last-set-property-value nil)
  12428. (defun org-read-property-name ()
  12429. "Read a property name."
  12430. (let ((completion-ignore-case t)
  12431. (default-prop (or (and (org-at-property-p)
  12432. (match-string-no-properties 2))
  12433. org-last-set-property)))
  12434. (org-completing-read
  12435. (concat "Property"
  12436. (if default-prop (concat " [" default-prop "]") "")
  12437. ": ")
  12438. (mapcar #'list (org-buffer-property-keys nil t t))
  12439. nil nil nil nil default-prop)))
  12440. (defun org-set-property-and-value (use-last)
  12441. "Allow to set [PROPERTY]: [value] direction from prompt.
  12442. When use-default, don't even ask, just use the last
  12443. \"[PROPERTY]: [value]\" string from the history."
  12444. (interactive "P")
  12445. (let* ((completion-ignore-case t)
  12446. (pv (or (and use-last org-last-set-property-value)
  12447. (org-completing-read
  12448. "Enter a \"[Property]: [value]\" pair: "
  12449. nil nil nil nil nil
  12450. org-last-set-property-value)))
  12451. prop val)
  12452. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12453. (setq prop (match-string 1 pv)
  12454. val (match-string 2 pv))
  12455. (org-set-property prop val))))
  12456. (defun org-set-property (property value)
  12457. "In the current entry, set PROPERTY to VALUE.
  12458. When called interactively, this will prompt for a property name, offering
  12459. completion on existing and default properties. And then it will prompt
  12460. for a value, offering completion either on allowed values (via an inherited
  12461. xxx_ALL property) or on existing values in other instances of this property
  12462. in the current file.
  12463. Throw an error when trying to set a property with an invalid name."
  12464. (interactive (list nil nil))
  12465. (let ((property (or property (org-read-property-name))))
  12466. ;; `org-entry-put' also makes the following check, but this one
  12467. ;; avoids polluting `org-last-set-property' and
  12468. ;; `org-last-set-property-value' needlessly.
  12469. (unless (org--valid-property-p property)
  12470. (user-error "Invalid property name: \"%s\"" property))
  12471. (let ((value (or value (org-read-property-value property)))
  12472. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12473. (setq org-last-set-property property)
  12474. (setq org-last-set-property-value (concat property ": " value))
  12475. ;; Possibly postprocess the inserted value:
  12476. (when fn (setq value (funcall fn value)))
  12477. (unless (equal (org-entry-get nil property) value)
  12478. (org-entry-put nil property value)))))
  12479. (defun org-find-property (property &optional value)
  12480. "Find first entry in buffer that sets PROPERTY.
  12481. When optional argument VALUE is non-nil, only consider an entry
  12482. if it contains PROPERTY set to this value. If PROPERTY should be
  12483. explicitly set to nil, use string \"nil\" for VALUE.
  12484. Return position where the entry begins, or nil if there is no
  12485. such entry. If narrowing is in effect, only search the visible
  12486. part of the buffer."
  12487. (save-excursion
  12488. (goto-char (point-min))
  12489. (let ((case-fold-search t)
  12490. (re (org-re-property property nil (not value) value)))
  12491. (catch 'exit
  12492. (while (re-search-forward re nil t)
  12493. (when (if value (org-at-property-p)
  12494. (org-entry-get (point) property nil t))
  12495. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12496. (defun org-delete-property (property)
  12497. "In the current entry, delete PROPERTY."
  12498. (interactive
  12499. (let* ((completion-ignore-case t)
  12500. (cat (org-entry-get (point) "CATEGORY"))
  12501. (props0 (org-entry-properties nil 'standard))
  12502. (props (if cat props0
  12503. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12504. (prop (if (< 1 (length props))
  12505. (completing-read "Property: " props nil t)
  12506. (caar props))))
  12507. (list prop)))
  12508. (if (not property)
  12509. (message "No property to delete in this entry")
  12510. (org-entry-delete nil property)
  12511. (message "Property \"%s\" deleted" property)))
  12512. (defun org-delete-property-globally (property)
  12513. "Remove PROPERTY globally, from all entries.
  12514. This function ignores narrowing, if any."
  12515. (interactive
  12516. (let* ((completion-ignore-case t)
  12517. (prop (completing-read
  12518. "Globally remove property: "
  12519. (mapcar #'list (org-buffer-property-keys)))))
  12520. (list prop)))
  12521. (org-with-wide-buffer
  12522. (goto-char (point-min))
  12523. (let ((count 0)
  12524. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12525. (while (re-search-forward re nil t)
  12526. (when (org-entry-delete (point) property) (cl-incf count)))
  12527. (message "Property \"%s\" removed from %d entries" property count))))
  12528. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12529. (defun org-compute-property-at-point ()
  12530. "Compute the property at point.
  12531. This looks for an enclosing column format, extracts the operator and
  12532. then applies it to the property in the column format's scope."
  12533. (interactive)
  12534. (unless (org-at-property-p)
  12535. (user-error "Not at a property"))
  12536. (let ((prop (match-string-no-properties 2)))
  12537. (org-columns-get-format-and-top-level)
  12538. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12539. (user-error "No operator defined for property %s" prop))
  12540. (org-columns-compute prop)))
  12541. (defvar org-property-allowed-value-functions nil
  12542. "Hook for functions supplying allowed values for a specific property.
  12543. The functions must take a single argument, the name of the property, and
  12544. return a flat list of allowed values. If \":ETC\" is one of
  12545. the values, this means that these values are intended as defaults for
  12546. completion, but that other values should be allowed too.
  12547. The functions must return nil if they are not responsible for this
  12548. property.")
  12549. (defun org-property-get-allowed-values (pom property &optional table)
  12550. "Get allowed values for the property PROPERTY.
  12551. When TABLE is non-nil, return an alist that can directly be used for
  12552. completion."
  12553. (let (vals)
  12554. (cond
  12555. ((equal property "TODO")
  12556. (setq vals (org-with-point-at pom
  12557. (append org-todo-keywords-1 '("")))))
  12558. ((equal property "PRIORITY")
  12559. (let ((n org-lowest-priority))
  12560. (while (>= n org-highest-priority)
  12561. (push (char-to-string n) vals)
  12562. (setq n (1- n)))))
  12563. ((equal property "CATEGORY"))
  12564. ((member property org-special-properties))
  12565. ((setq vals (run-hook-with-args-until-success
  12566. 'org-property-allowed-value-functions property)))
  12567. (t
  12568. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12569. (when (and vals (string-match "\\S-" vals))
  12570. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12571. (setq vals (mapcar (lambda (x)
  12572. (cond ((stringp x) x)
  12573. ((numberp x) (number-to-string x))
  12574. ((symbolp x) (symbol-name x))
  12575. (t "???")))
  12576. vals)))))
  12577. (when (member ":ETC" vals)
  12578. (setq vals (remove ":ETC" vals))
  12579. (org-add-props (car vals) '(org-unrestricted t)))
  12580. (if table (mapcar 'list vals) vals)))
  12581. (defun org-property-previous-allowed-value (&optional _previous)
  12582. "Switch to the next allowed value for this property."
  12583. (interactive)
  12584. (org-property-next-allowed-value t))
  12585. (defun org-property-next-allowed-value (&optional previous)
  12586. "Switch to the next allowed value for this property."
  12587. (interactive)
  12588. (unless (org-at-property-p)
  12589. (user-error "Not at a property"))
  12590. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12591. (key (match-string 2))
  12592. (value (match-string 3))
  12593. (allowed (or (org-property-get-allowed-values (point) key)
  12594. (and (member value '("[ ]" "[-]" "[X]"))
  12595. '("[ ]" "[X]"))))
  12596. (heading (save-match-data (nth 4 (org-heading-components))))
  12597. nval)
  12598. (unless allowed
  12599. (user-error "Allowed values for this property have not been defined"))
  12600. (when previous (setq allowed (reverse allowed)))
  12601. (when (member value allowed)
  12602. (setq nval (car (cdr (member value allowed)))))
  12603. (setq nval (or nval (car allowed)))
  12604. (when (equal nval value)
  12605. (user-error "Only one allowed value for this property"))
  12606. (org-at-property-p)
  12607. (replace-match (concat " :" key ": " nval) t t)
  12608. (org-indent-line)
  12609. (beginning-of-line 1)
  12610. (skip-chars-forward " \t")
  12611. (when (equal prop org-effort-property)
  12612. (org-refresh-property
  12613. '((effort . identity)
  12614. (effort-minutes . org-duration-to-minutes))
  12615. nval)
  12616. (when (string= org-clock-current-task heading)
  12617. (setq org-clock-effort nval)
  12618. (org-clock-update-mode-line)))
  12619. (run-hook-with-args 'org-property-changed-functions key nval)))
  12620. (defun org-find-olp (path &optional this-buffer)
  12621. "Return a marker pointing to the entry at outline path OLP.
  12622. If anything goes wrong, throw an error.
  12623. You can wrap this call to catch the error like this:
  12624. (condition-case msg
  12625. (org-mobile-locate-entry (match-string 4))
  12626. (error (nth 1 msg)))
  12627. The return value will then be either a string with the error message,
  12628. or a marker if everything is OK.
  12629. If THIS-BUFFER is set, the outline path does not contain a file,
  12630. only headings."
  12631. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12632. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12633. (level 1)
  12634. (lmin 1)
  12635. (lmax 1)
  12636. end found flevel)
  12637. (unless buffer (error "File not found :%s" file))
  12638. (with-current-buffer buffer
  12639. (unless (derived-mode-p 'org-mode)
  12640. (error "Buffer %s needs to be in Org mode" buffer))
  12641. (org-with-wide-buffer
  12642. (goto-char (point-min))
  12643. (dolist (heading path)
  12644. (let ((re (format org-complex-heading-regexp-format
  12645. (regexp-quote heading)))
  12646. (cnt 0))
  12647. (while (re-search-forward re end t)
  12648. (setq level (- (match-end 1) (match-beginning 1)))
  12649. (when (and (>= level lmin) (<= level lmax))
  12650. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12651. (when (= cnt 0)
  12652. (error "Heading not found on level %d: %s" lmax heading))
  12653. (when (> cnt 1)
  12654. (error "Heading not unique on level %d: %s" lmax heading))
  12655. (goto-char found)
  12656. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12657. (setq end (save-excursion (org-end-of-subtree t t)))))
  12658. (when (org-at-heading-p)
  12659. (point-marker))))))
  12660. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12661. "Find node HEADING in BUFFER.
  12662. Return a marker to the heading if it was found, or nil if not.
  12663. If POS-ONLY is set, return just the position instead of a marker.
  12664. The heading text must match exact, but it may have a TODO keyword,
  12665. a priority cookie and tags in the standard locations."
  12666. (with-current-buffer (or buffer (current-buffer))
  12667. (org-with-wide-buffer
  12668. (goto-char (point-min))
  12669. (let (case-fold-search)
  12670. (when (re-search-forward
  12671. (format org-complex-heading-regexp-format
  12672. (regexp-quote heading)) nil t)
  12673. (if pos-only
  12674. (match-beginning 0)
  12675. (move-marker (make-marker) (match-beginning 0))))))))
  12676. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12677. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12678. When the target headline is found, return a marker to this location."
  12679. (let ((files (directory-files (or dir default-directory)
  12680. t "\\`[^.#].*\\.org\\'"))
  12681. visiting m buffer)
  12682. (catch 'found
  12683. (dolist (file files)
  12684. (message "trying %s" file)
  12685. (setq visiting (org-find-base-buffer-visiting file))
  12686. (setq buffer (or visiting (find-file-noselect file)))
  12687. (setq m (org-find-exact-headline-in-buffer
  12688. heading buffer))
  12689. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12690. (and m (throw 'found m))))))
  12691. (defun org-find-entry-with-id (ident)
  12692. "Locate the entry that contains the ID property with exact value IDENT.
  12693. IDENT can be a string, a symbol or a number, this function will search for
  12694. the string representation of it.
  12695. Return the position where this entry starts, or nil if there is no such entry."
  12696. (interactive "sID: ")
  12697. (let ((id (cond
  12698. ((stringp ident) ident)
  12699. ((symbolp ident) (symbol-name ident))
  12700. ((numberp ident) (number-to-string ident))
  12701. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12702. (org-with-wide-buffer (org-find-property "ID" id))))
  12703. ;;;; Timestamps
  12704. (defvar org-last-changed-timestamp nil)
  12705. (defvar org-last-inserted-timestamp nil
  12706. "The last time stamp inserted with `org-insert-time-stamp'.")
  12707. (defun org-time-stamp (arg &optional inactive)
  12708. "Prompt for a date/time and insert a time stamp.
  12709. If the user specifies a time like HH:MM or if this command is
  12710. called with at least one prefix argument, the time stamp contains
  12711. the date and the time. Otherwise, only the date is included.
  12712. All parts of a date not specified by the user are filled in from
  12713. the timestamp at point, if any, or the current date/time
  12714. otherwise.
  12715. If there is already a timestamp at the cursor, it is replaced.
  12716. With two universal prefix arguments, insert an active timestamp
  12717. with the current time without prompting the user.
  12718. When called from lisp, the timestamp is inactive if INACTIVE is
  12719. non-nil."
  12720. (interactive "P")
  12721. (let* ((ts (cond
  12722. ((org-at-date-range-p t)
  12723. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12724. ((org-at-timestamp-p 'lax) (match-string 0))))
  12725. ;; Default time is either the timestamp at point or today.
  12726. ;; When entering a range, only the range start is considered.
  12727. (default-time (and ts (org-time-string-to-time ts)))
  12728. (default-input (and ts (org-get-compact-tod ts)))
  12729. (repeater (and ts
  12730. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12731. (match-string 0 ts)))
  12732. org-time-was-given
  12733. org-end-time-was-given
  12734. (time
  12735. (if (equal arg '(16)) (current-time)
  12736. ;; Preserve `this-command' and `last-command'.
  12737. (let ((this-command this-command)
  12738. (last-command last-command))
  12739. (org-read-date
  12740. arg 'totime nil nil default-time default-input
  12741. inactive)))))
  12742. (cond
  12743. ((and ts
  12744. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12745. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12746. (insert "--")
  12747. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12748. (ts
  12749. ;; Make sure we're on a timestamp. When in the middle of a date
  12750. ;; range, move arbitrarily to range end.
  12751. (unless (org-at-timestamp-p 'lax)
  12752. (skip-chars-forward "-")
  12753. (org-at-timestamp-p 'lax))
  12754. (replace-match "")
  12755. (setq org-last-changed-timestamp
  12756. (org-insert-time-stamp
  12757. time (or org-time-was-given arg)
  12758. inactive nil nil (list org-end-time-was-given)))
  12759. (when repeater
  12760. (backward-char)
  12761. (insert " " repeater)
  12762. (setq org-last-changed-timestamp
  12763. (concat (substring org-last-inserted-timestamp 0 -1)
  12764. " " repeater ">")))
  12765. (message "Timestamp updated"))
  12766. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12767. (t (org-insert-time-stamp
  12768. time (or org-time-was-given arg) inactive nil nil
  12769. (list org-end-time-was-given))))))
  12770. ;; FIXME: can we use this for something else, like computing time differences?
  12771. (defun org-get-compact-tod (s)
  12772. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12773. (let* ((t1 (match-string 1 s))
  12774. (h1 (string-to-number (match-string 2 s)))
  12775. (m1 (string-to-number (match-string 3 s)))
  12776. (t2 (and (match-end 4) (match-string 5 s)))
  12777. (h2 (and t2 (string-to-number (match-string 6 s))))
  12778. (m2 (and t2 (string-to-number (match-string 7 s))))
  12779. dh dm)
  12780. (if (not t2)
  12781. t1
  12782. (setq dh (- h2 h1) dm (- m2 m1))
  12783. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12784. (concat t1 "+" (number-to-string dh)
  12785. (and (/= 0 dm) (format ":%02d" dm)))))))
  12786. (defun org-time-stamp-inactive (&optional arg)
  12787. "Insert an inactive time stamp.
  12788. An inactive time stamp is enclosed in square brackets instead of angle
  12789. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12790. does not link to the calendar and cannot be changed with the S-cursor keys.
  12791. So these are more for recording a certain time/date.
  12792. If the user specifies a time like HH:MM or if this command is called with
  12793. at least one prefix argument, the time stamp contains the date and the time.
  12794. Otherwise, only the date is included.
  12795. When called with two universal prefix arguments, insert an active time stamp
  12796. with the current time without prompting the user."
  12797. (interactive "P")
  12798. (org-time-stamp arg 'inactive))
  12799. (defvar org-date-ovl (make-overlay 1 1))
  12800. (overlay-put org-date-ovl 'face 'org-date-selected)
  12801. (delete-overlay org-date-ovl)
  12802. (defvar org-ans1) ; dynamically scoped parameter
  12803. (defvar org-ans2) ; dynamically scoped parameter
  12804. (defvar org-plain-time-of-day-regexp) ; defined below
  12805. (defvar org-overriding-default-time nil) ; dynamically scoped
  12806. (defvar org-read-date-overlay nil)
  12807. (defvar org-dcst nil) ; dynamically scoped
  12808. (defvar org-read-date-history nil)
  12809. (defvar org-read-date-final-answer nil)
  12810. (defvar org-read-date-analyze-futurep nil)
  12811. (defvar org-read-date-analyze-forced-year nil)
  12812. (defvar org-read-date-inactive)
  12813. (defvar org-def)
  12814. (defvar org-defdecode)
  12815. (defvar org-with-time)
  12816. (defvar calendar-setup) ; Dynamically scoped.
  12817. (defun org-read-date (&optional with-time to-time from-string prompt
  12818. default-time default-input inactive)
  12819. "Read a date, possibly a time, and make things smooth for the user.
  12820. The prompt will suggest to enter an ISO date, but you can also enter anything
  12821. which will at least partially be understood by `parse-time-string'.
  12822. Unrecognized parts of the date will default to the current day, month, year,
  12823. hour and minute. If this command is called to replace a timestamp at point,
  12824. or to enter the second timestamp of a range, the default time is taken
  12825. from the existing stamp. Furthermore, the command prefers the future,
  12826. so if you are giving a date where the year is not given, and the day-month
  12827. combination is already past in the current year, it will assume you
  12828. mean next year. For details, see the manual. A few examples:
  12829. 3-2-5 --> 2003-02-05
  12830. feb 15 --> currentyear-02-15
  12831. 2/15 --> currentyear-02-15
  12832. sep 12 9 --> 2009-09-12
  12833. 12:45 --> today 12:45
  12834. 22 sept 0:34 --> currentyear-09-22 0:34
  12835. 12 --> currentyear-currentmonth-12
  12836. Fri --> nearest Friday after today
  12837. -Tue --> last Tuesday
  12838. etc.
  12839. Furthermore you can specify a relative date by giving, as the *first* thing
  12840. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12841. change in days weeks, months, years.
  12842. With a single plus or minus, the date is relative to today. With a double
  12843. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12844. +4d --> four days from today
  12845. +4 --> same as above
  12846. +2w --> two weeks from today
  12847. ++5 --> five days from default date
  12848. The function understands only English month and weekday abbreviations.
  12849. While prompting, a calendar is popped up - you can also select the
  12850. date with the mouse (button 1). The calendar shows a period of three
  12851. months. To scroll it to other months, use the keys `>' and `<'.
  12852. If you don't like the calendar, turn it off with
  12853. (setq org-read-date-popup-calendar nil)
  12854. With optional argument TO-TIME, the date will immediately be converted
  12855. to an internal time.
  12856. With an optional argument WITH-TIME, the prompt will suggest to
  12857. also insert a time. Note that when WITH-TIME is not set, you can
  12858. still enter a time, and this function will inform the calling routine
  12859. about this change. The calling routine may then choose to change the
  12860. format used to insert the time stamp into the buffer to include the time.
  12861. With optional argument FROM-STRING, read from this string instead from
  12862. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12863. the time/date that is used for everything that is not specified by the
  12864. user."
  12865. (require 'parse-time)
  12866. (let* ((org-with-time with-time)
  12867. (org-time-stamp-rounding-minutes
  12868. (if (equal org-with-time '(16))
  12869. '(0 0)
  12870. org-time-stamp-rounding-minutes))
  12871. (org-dcst org-display-custom-times)
  12872. (ct (org-current-time))
  12873. (org-def (or org-overriding-default-time default-time ct))
  12874. (org-defdecode (decode-time org-def))
  12875. (cur-frame (selected-frame))
  12876. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12877. (calendar-setup
  12878. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12879. (calendar-move-hook nil)
  12880. (calendar-view-diary-initially-flag nil)
  12881. (calendar-view-holidays-initially-flag nil)
  12882. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12883. ;; Rationalize `org-def' and `org-defdecode', if required.
  12884. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12885. (setf (nth 2 org-defdecode) -1)
  12886. (setf (nth 1 org-defdecode) 59)
  12887. (setq org-def (apply #'encode-time org-defdecode))
  12888. (setq org-defdecode (decode-time org-def)))
  12889. (let* ((timestr (format-time-string
  12890. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12891. org-def))
  12892. (prompt (concat (if prompt (concat prompt " ") "")
  12893. (format "Date+time [%s]: " timestr))))
  12894. (cond
  12895. (from-string (setq ans from-string))
  12896. (org-read-date-popup-calendar
  12897. (save-excursion
  12898. (save-window-excursion
  12899. (calendar)
  12900. (when (eq calendar-setup 'calendar-only)
  12901. (setq cal-frame
  12902. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12903. (select-frame cal-frame))
  12904. (org-eval-in-calendar '(setq cursor-type nil) t)
  12905. (unwind-protect
  12906. (progn
  12907. (calendar-forward-day (- (time-to-days org-def)
  12908. (calendar-absolute-from-gregorian
  12909. (calendar-current-date))))
  12910. (org-eval-in-calendar nil t)
  12911. (let* ((old-map (current-local-map))
  12912. (map (copy-keymap calendar-mode-map))
  12913. (minibuffer-local-map
  12914. (copy-keymap org-read-date-minibuffer-local-map)))
  12915. (org-defkey map (kbd "RET") 'org-calendar-select)
  12916. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12917. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12918. (unwind-protect
  12919. (progn
  12920. (use-local-map map)
  12921. (setq org-read-date-inactive inactive)
  12922. (add-hook 'post-command-hook 'org-read-date-display)
  12923. (setq org-ans0
  12924. (read-string prompt
  12925. default-input
  12926. 'org-read-date-history
  12927. nil))
  12928. ;; org-ans0: from prompt
  12929. ;; org-ans1: from mouse click
  12930. ;; org-ans2: from calendar motion
  12931. (setq ans
  12932. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12933. (remove-hook 'post-command-hook 'org-read-date-display)
  12934. (use-local-map old-map)
  12935. (when org-read-date-overlay
  12936. (delete-overlay org-read-date-overlay)
  12937. (setq org-read-date-overlay nil)))))
  12938. (bury-buffer "*Calendar*")
  12939. (when cal-frame
  12940. (delete-frame cal-frame)
  12941. (select-frame-set-input-focus cur-frame))))))
  12942. (t ; Naked prompt only
  12943. (unwind-protect
  12944. (setq ans (read-string prompt default-input
  12945. 'org-read-date-history timestr))
  12946. (when org-read-date-overlay
  12947. (delete-overlay org-read-date-overlay)
  12948. (setq org-read-date-overlay nil))))))
  12949. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12950. (when org-read-date-analyze-forced-year
  12951. (message "Year was forced into %s"
  12952. (if org-read-date-force-compatible-dates
  12953. "compatible range (1970-2037)"
  12954. "range representable on this machine"))
  12955. (ding))
  12956. (setq final (apply #'encode-time final))
  12957. (setq org-read-date-final-answer ans)
  12958. (if to-time
  12959. final
  12960. ;; This round-trip gets rid of 34th of August and stuff like that....
  12961. (setq final (decode-time final))
  12962. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12963. (format "%04d-%02d-%02d %02d:%02d"
  12964. (nth 5 final) (nth 4 final) (nth 3 final)
  12965. (nth 2 final) (nth 1 final))
  12966. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12967. (defun org-read-date-display ()
  12968. "Display the current date prompt interpretation in the minibuffer."
  12969. (when org-read-date-display-live
  12970. (when org-read-date-overlay
  12971. (delete-overlay org-read-date-overlay))
  12972. (when (minibufferp (current-buffer))
  12973. (save-excursion
  12974. (end-of-line 1)
  12975. (while (not (equal (buffer-substring
  12976. (max (point-min) (- (point) 4)) (point))
  12977. " "))
  12978. (insert " ")))
  12979. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12980. " " (or org-ans1 org-ans2)))
  12981. (org-end-time-was-given nil)
  12982. (f (org-read-date-analyze ans org-def org-defdecode))
  12983. (fmts (if org-dcst
  12984. org-time-stamp-custom-formats
  12985. org-time-stamp-formats))
  12986. (fmt (if (or org-with-time
  12987. (and (boundp 'org-time-was-given) org-time-was-given))
  12988. (cdr fmts)
  12989. (car fmts)))
  12990. (txt (format-time-string fmt (apply #'encode-time f)))
  12991. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12992. (txt (concat "=> " txt)))
  12993. (when (and org-end-time-was-given
  12994. (string-match org-plain-time-of-day-regexp txt))
  12995. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12996. org-end-time-was-given
  12997. (substring txt (match-end 0)))))
  12998. (when org-read-date-analyze-futurep
  12999. (setq txt (concat txt " (=>F)")))
  13000. (setq org-read-date-overlay
  13001. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13002. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13003. (defun org-read-date-analyze (ans def defdecode)
  13004. "Analyze the combined answer of the date prompt."
  13005. ;; FIXME: cleanup and comment
  13006. (let ((org-def def)
  13007. (org-defdecode defdecode)
  13008. (nowdecode (decode-time))
  13009. delta deltan deltaw deltadef year month day
  13010. hour minute second wday pm h2 m2 tl wday1
  13011. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13012. (setq org-read-date-analyze-futurep nil
  13013. org-read-date-analyze-forced-year nil)
  13014. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13015. (setq ans "+0"))
  13016. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13017. (setq ans (replace-match "" t t ans)
  13018. deltan (car delta)
  13019. deltaw (nth 1 delta)
  13020. deltadef (nth 2 delta)))
  13021. ;; Check if there is an iso week date in there. If yes, store the
  13022. ;; info and postpone interpreting it until the rest of the parsing
  13023. ;; is done.
  13024. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13025. (setq iso-year (when (match-end 1)
  13026. (org-small-year-to-year
  13027. (string-to-number (match-string 1 ans))))
  13028. iso-weekday (when (match-end 3)
  13029. (string-to-number (match-string 3 ans)))
  13030. iso-week (string-to-number (match-string 2 ans)))
  13031. (setq ans (replace-match "" t t ans)))
  13032. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13033. (when (string-match
  13034. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13035. (setq year (if (match-end 2)
  13036. (string-to-number (match-string 2 ans))
  13037. (progn (setq kill-year t)
  13038. (string-to-number (format-time-string "%Y"))))
  13039. month (string-to-number (match-string 3 ans))
  13040. day (string-to-number (match-string 4 ans)))
  13041. (setq year (org-small-year-to-year year))
  13042. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13043. t nil ans)))
  13044. ;; Help matching dotted european dates
  13045. (when (string-match
  13046. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13047. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13048. (setq kill-year t)
  13049. (string-to-number (format-time-string "%Y")))
  13050. day (string-to-number (match-string 1 ans))
  13051. month (string-to-number (match-string 2 ans))
  13052. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13053. t nil ans)))
  13054. ;; Help matching american dates, like 5/30 or 5/30/7
  13055. (when (string-match
  13056. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13057. (setq year (if (match-end 4)
  13058. (string-to-number (match-string 4 ans))
  13059. (progn (setq kill-year t)
  13060. (string-to-number (format-time-string "%Y"))))
  13061. month (string-to-number (match-string 1 ans))
  13062. day (string-to-number (match-string 2 ans)))
  13063. (setq year (org-small-year-to-year year))
  13064. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13065. t nil ans)))
  13066. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13067. ;; If there is a time with am/pm, and *no* time without it, we convert
  13068. ;; so that matching will be successful.
  13069. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13070. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13071. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13072. (setq hour (string-to-number (match-string 1 ans))
  13073. minute (if (match-end 3)
  13074. (string-to-number (match-string 3 ans))
  13075. 0)
  13076. pm (equal ?p
  13077. (string-to-char (downcase (match-string 4 ans)))))
  13078. (if (and (= hour 12) (not pm))
  13079. (setq hour 0)
  13080. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13081. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13082. t t ans))))
  13083. ;; Check if a time range is given as a duration
  13084. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13085. (setq hour (string-to-number (match-string 1 ans))
  13086. h2 (+ hour (string-to-number (match-string 3 ans)))
  13087. minute (string-to-number (match-string 2 ans))
  13088. m2 (+ minute (if (match-end 5) (string-to-number
  13089. (match-string 5 ans))0)))
  13090. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13091. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13092. t t ans)))
  13093. ;; Check if there is a time range
  13094. (when (boundp 'org-end-time-was-given)
  13095. (setq org-time-was-given nil)
  13096. (when (and (string-match org-plain-time-of-day-regexp ans)
  13097. (match-end 8))
  13098. (setq org-end-time-was-given (match-string 8 ans))
  13099. (setq ans (concat (substring ans 0 (match-beginning 7))
  13100. (substring ans (match-end 7))))))
  13101. (setq tl (parse-time-string ans)
  13102. day (or (nth 3 tl) (nth 3 org-defdecode))
  13103. month
  13104. (cond ((nth 4 tl))
  13105. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13106. ;; Day was specified. Make sure DAY+MONTH
  13107. ;; combination happens in the future.
  13108. ((nth 3 tl)
  13109. (setq futurep t)
  13110. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13111. (nth 4 nowdecode)))
  13112. (t (nth 4 org-defdecode)))
  13113. year
  13114. (cond ((and (not kill-year) (nth 5 tl)))
  13115. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13116. ;; Month was guessed in the future and is at least
  13117. ;; equal to NOWDECODE's. Fix year accordingly.
  13118. (futurep
  13119. (if (or (> month (nth 4 nowdecode))
  13120. (>= day (nth 3 nowdecode)))
  13121. (nth 5 nowdecode)
  13122. (1+ (nth 5 nowdecode))))
  13123. ;; Month was specified. Make sure MONTH+YEAR
  13124. ;; combination happens in the future.
  13125. ((nth 4 tl)
  13126. (setq futurep t)
  13127. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13128. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13129. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13130. (t (nth 5 nowdecode))))
  13131. (t (nth 5 org-defdecode)))
  13132. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13133. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13134. second (or (nth 0 tl) 0)
  13135. wday (nth 6 tl))
  13136. (when (and (eq org-read-date-prefer-future 'time)
  13137. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13138. (equal day (nth 3 nowdecode))
  13139. (equal month (nth 4 nowdecode))
  13140. (equal year (nth 5 nowdecode))
  13141. (nth 2 tl)
  13142. (or (< (nth 2 tl) (nth 2 nowdecode))
  13143. (and (= (nth 2 tl) (nth 2 nowdecode))
  13144. (nth 1 tl)
  13145. (< (nth 1 tl) (nth 1 nowdecode)))))
  13146. (setq day (1+ day)
  13147. futurep t))
  13148. ;; Special date definitions below
  13149. (cond
  13150. (iso-week
  13151. ;; There was an iso week
  13152. (require 'cal-iso)
  13153. (setq futurep nil)
  13154. (setq year (or iso-year year)
  13155. day (or iso-weekday wday 1)
  13156. wday nil ; to make sure that the trigger below does not match
  13157. iso-date (calendar-gregorian-from-absolute
  13158. (calendar-iso-to-absolute
  13159. (list iso-week day year))))
  13160. ; FIXME: Should we also push ISO weeks into the future?
  13161. ; (when (and org-read-date-prefer-future
  13162. ; (not iso-year)
  13163. ; (< (calendar-absolute-from-gregorian iso-date)
  13164. ; (time-to-days nil)))
  13165. ; (setq year (1+ year)
  13166. ; iso-date (calendar-gregorian-from-absolute
  13167. ; (calendar-iso-to-absolute
  13168. ; (list iso-week day year)))))
  13169. (setq month (car iso-date)
  13170. year (nth 2 iso-date)
  13171. day (nth 1 iso-date)))
  13172. (deltan
  13173. (setq futurep nil)
  13174. (unless deltadef
  13175. (let ((now (decode-time)))
  13176. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13177. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13178. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13179. ((equal deltaw "m") (setq month (+ month deltan)))
  13180. ((equal deltaw "y") (setq year (+ year deltan)))))
  13181. ((and wday (not (nth 3 tl)))
  13182. ;; Weekday was given, but no day, so pick that day in the week
  13183. ;; on or after the derived date.
  13184. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13185. (unless (equal wday wday1)
  13186. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13187. (when (and (boundp 'org-time-was-given)
  13188. (nth 2 tl))
  13189. (setq org-time-was-given t))
  13190. (when (< year 100) (setq year (+ 2000 year)))
  13191. ;; Check of the date is representable
  13192. (if org-read-date-force-compatible-dates
  13193. (progn
  13194. (when (< year 1970)
  13195. (setq year 1970 org-read-date-analyze-forced-year t))
  13196. (when (> year 2037)
  13197. (setq year 2037 org-read-date-analyze-forced-year t)))
  13198. (condition-case nil
  13199. (ignore (encode-time second minute hour day month year))
  13200. (error
  13201. (setq year (nth 5 org-defdecode))
  13202. (setq org-read-date-analyze-forced-year t))))
  13203. (setq org-read-date-analyze-futurep futurep)
  13204. (list second minute hour day month year)))
  13205. (defvar parse-time-weekdays)
  13206. (defun org-read-date-get-relative (s today default)
  13207. "Check string S for special relative date string.
  13208. TODAY and DEFAULT are internal times, for today and for a default.
  13209. Return shift list (N what def-flag)
  13210. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13211. N is the number of WHATs to shift.
  13212. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13213. the DEFAULT date rather than TODAY."
  13214. (require 'parse-time)
  13215. (when (and
  13216. (string-match
  13217. (concat
  13218. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13219. "\\([0-9]+\\)?"
  13220. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13221. "\\([ \t]\\|$\\)") s)
  13222. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13223. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13224. (string-to-char (substring (match-string 1 s) -1))
  13225. ?+))
  13226. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13227. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13228. (what (if (match-end 3) (match-string 3 s) "d"))
  13229. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13230. (date (if rel default today))
  13231. (wday (nth 6 (decode-time date)))
  13232. delta)
  13233. (if wday1
  13234. (progn
  13235. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13236. (when (= delta 0) (setq delta 7))
  13237. (when (= dir ?-)
  13238. (setq delta (- delta 7))
  13239. (when (= delta 0) (setq delta -7)))
  13240. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13241. (list delta "d" rel))
  13242. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13243. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13244. "Turn a user-specified date into the internal representation.
  13245. The internal representation needed by the calendar is (month day year).
  13246. This is a wrapper to handle the brain-dead convention in calendar that
  13247. user function argument order change dependent on argument order."
  13248. (pcase calendar-date-style
  13249. (`american (list arg1 arg2 arg3))
  13250. (`european (list arg2 arg1 arg3))
  13251. (`iso (list arg2 arg3 arg1))))
  13252. (defun org-eval-in-calendar (form &optional keepdate)
  13253. "Eval FORM in the calendar window and return to current window.
  13254. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13255. (let ((sf (selected-frame))
  13256. (sw (selected-window)))
  13257. (select-window (get-buffer-window "*Calendar*" t))
  13258. (eval form)
  13259. (when (and (not keepdate) (calendar-cursor-to-date))
  13260. (let* ((date (calendar-cursor-to-date))
  13261. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13262. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13263. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13264. (select-window sw)
  13265. (select-frame-set-input-focus sf)))
  13266. (defun org-calendar-select ()
  13267. "Return to `org-read-date' with the date currently selected.
  13268. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13269. (interactive)
  13270. (when (calendar-cursor-to-date)
  13271. (let* ((date (calendar-cursor-to-date))
  13272. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13273. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13274. (when (active-minibuffer-window) (exit-minibuffer))))
  13275. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13276. "Insert a date stamp for the date given by the internal TIME.
  13277. See `format-time-string' for the format of TIME.
  13278. WITH-HM means use the stamp format that includes the time of the day.
  13279. INACTIVE means use square brackets instead of angular ones, so that the
  13280. stamp will not contribute to the agenda.
  13281. PRE and POST are optional strings to be inserted before and after the
  13282. stamp.
  13283. The command returns the inserted time stamp."
  13284. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13285. stamp)
  13286. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13287. (insert-before-markers (or pre ""))
  13288. (when (listp extra)
  13289. (setq extra (car extra))
  13290. (if (and (stringp extra)
  13291. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13292. (setq extra (format "-%02d:%02d"
  13293. (string-to-number (match-string 1 extra))
  13294. (string-to-number (match-string 2 extra))))
  13295. (setq extra nil)))
  13296. (when extra
  13297. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13298. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13299. (insert-before-markers (or post ""))
  13300. (setq org-last-inserted-timestamp stamp)))
  13301. (defun org-toggle-time-stamp-overlays ()
  13302. "Toggle the use of custom time stamp formats."
  13303. (interactive)
  13304. (setq org-display-custom-times (not org-display-custom-times))
  13305. (unless org-display-custom-times
  13306. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13307. (while (setq p (next-single-property-change p 'display))
  13308. (when (and (get-text-property p 'display)
  13309. (eq (get-text-property p 'face) 'org-date))
  13310. (remove-text-properties
  13311. p (setq p (next-single-property-change p 'display))
  13312. '(display t))))
  13313. (set-buffer-modified-p bmp)))
  13314. (org-restart-font-lock)
  13315. (setq org-table-may-need-update t)
  13316. (if org-display-custom-times
  13317. (message "Time stamps are overlaid with custom format")
  13318. (message "Time stamp overlays removed")))
  13319. (defun org-display-custom-time (beg end)
  13320. "Overlay modified time stamp format over timestamp between BEG and END."
  13321. (let* ((ts (buffer-substring beg end))
  13322. t1 with-hm tf time str (off 0))
  13323. (save-match-data
  13324. (setq t1 (org-parse-time-string ts t))
  13325. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13326. (setq off (- (match-end 0) (match-beginning 0)))))
  13327. (setq end (- end off))
  13328. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13329. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13330. time (org-fix-decoded-time t1)
  13331. str (org-add-props
  13332. (format-time-string
  13333. (substring tf 1 -1) (apply 'encode-time time))
  13334. nil 'mouse-face 'highlight))
  13335. (put-text-property beg end 'display str)))
  13336. (defun org-fix-decoded-time (time)
  13337. "Set 0 instead of nil for the first 6 elements of time.
  13338. Don't touch the rest."
  13339. (let ((n 0))
  13340. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13341. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13342. "Difference between TIMESTAMP-STRING and now in days.
  13343. If SECONDS is non-nil, return the difference in seconds."
  13344. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13345. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13346. (funcall fdiff nil))))
  13347. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13348. "Is the time in TIMESTAMP-STRING close to the current date?"
  13349. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13350. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13351. (not (org-entry-is-done-p))))
  13352. (defun org-get-wdays (ts &optional delay zero-delay)
  13353. "Get the deadline lead time appropriate for timestring TS.
  13354. When DELAY is non-nil, get the delay time for scheduled items
  13355. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13356. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13357. don't try to find the delay cookie in the scheduled timestamp."
  13358. (let ((tv (if delay org-scheduled-delay-days
  13359. org-deadline-warning-days)))
  13360. (cond
  13361. ((or (and delay (< tv 0))
  13362. (and delay zero-delay (<= tv 0))
  13363. (and (not delay) (<= tv 0)))
  13364. ;; Enforce this value no matter what
  13365. (- tv))
  13366. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13367. ;; lead time is specified.
  13368. (floor (* (string-to-number (match-string 1 ts))
  13369. (cdr (assoc (match-string 2 ts)
  13370. '(("d" . 1) ("w" . 7)
  13371. ("m" . 30.4) ("y" . 365.25)
  13372. ("h" . 0.041667)))))))
  13373. ;; go for the default.
  13374. (t tv))))
  13375. (defun org-calendar-select-mouse (ev)
  13376. "Return to `org-read-date' with the date currently selected.
  13377. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13378. (interactive "e")
  13379. (mouse-set-point ev)
  13380. (when (calendar-cursor-to-date)
  13381. (let* ((date (calendar-cursor-to-date))
  13382. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13383. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13384. (when (active-minibuffer-window) (exit-minibuffer))))
  13385. (defun org-check-deadlines (ndays)
  13386. "Check if there are any deadlines due or past due.
  13387. A deadline is considered due if it happens within `org-deadline-warning-days'
  13388. days from today's date. If the deadline appears in an entry marked DONE,
  13389. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13390. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13391. are shown."
  13392. (interactive "P")
  13393. (let* ((org-warn-days
  13394. (cond
  13395. ((equal ndays '(4)) 100000)
  13396. (ndays (prefix-numeric-value ndays))
  13397. (t (abs org-deadline-warning-days))))
  13398. (case-fold-search nil)
  13399. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13400. (callback
  13401. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13402. (message "%d deadlines past-due or due within %d days"
  13403. (org-occur regexp nil callback)
  13404. org-warn-days)))
  13405. (defsubst org-re-timestamp (type)
  13406. "Return a regexp for timestamp TYPE.
  13407. Allowed values for TYPE are:
  13408. all: all timestamps
  13409. active: only active timestamps (<...>)
  13410. inactive: only inactive timestamps ([...])
  13411. scheduled: only scheduled timestamps
  13412. deadline: only deadline timestamps
  13413. closed: only closed time-stamps
  13414. When TYPE is nil, fall back on returning a regexp that matches
  13415. both scheduled and deadline timestamps."
  13416. (cl-case type
  13417. (all org-ts-regexp-both)
  13418. (active org-ts-regexp)
  13419. (inactive org-ts-regexp-inactive)
  13420. (scheduled org-scheduled-time-regexp)
  13421. (deadline org-deadline-time-regexp)
  13422. (closed org-closed-time-regexp)
  13423. (otherwise
  13424. (concat "\\<"
  13425. (regexp-opt (list org-deadline-string org-scheduled-string))
  13426. " *<\\([^>]+\\)>"))))
  13427. (defun org-check-before-date (d)
  13428. "Check if there are deadlines or scheduled entries before date D."
  13429. (interactive (list (org-read-date)))
  13430. (let* ((case-fold-search nil)
  13431. (regexp (org-re-timestamp org-ts-type))
  13432. (ts-type org-ts-type)
  13433. (callback
  13434. (lambda ()
  13435. (let ((match (match-string 1)))
  13436. (and (if (memq ts-type '(active inactive all))
  13437. (eq (org-element-type (save-excursion
  13438. (backward-char)
  13439. (org-element-context)))
  13440. 'timestamp)
  13441. (org-at-planning-p))
  13442. (time-less-p
  13443. (org-time-string-to-time match)
  13444. (org-time-string-to-time d)))))))
  13445. (message "%d entries before %s"
  13446. (org-occur regexp nil callback)
  13447. d)))
  13448. (defun org-check-after-date (d)
  13449. "Check if there are deadlines or scheduled entries after date D."
  13450. (interactive (list (org-read-date)))
  13451. (let* ((case-fold-search nil)
  13452. (regexp (org-re-timestamp org-ts-type))
  13453. (ts-type org-ts-type)
  13454. (callback
  13455. (lambda ()
  13456. (let ((match (match-string 1)))
  13457. (and (if (memq ts-type '(active inactive all))
  13458. (eq (org-element-type (save-excursion
  13459. (backward-char)
  13460. (org-element-context)))
  13461. 'timestamp)
  13462. (org-at-planning-p))
  13463. (not (time-less-p
  13464. (org-time-string-to-time match)
  13465. (org-time-string-to-time d))))))))
  13466. (message "%d entries after %s"
  13467. (org-occur regexp nil callback)
  13468. d)))
  13469. (defun org-check-dates-range (start-date end-date)
  13470. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13471. (interactive (list (org-read-date nil nil nil "Range starts")
  13472. (org-read-date nil nil nil "Range end")))
  13473. (let ((case-fold-search nil)
  13474. (regexp (org-re-timestamp org-ts-type))
  13475. (callback
  13476. (let ((type org-ts-type))
  13477. (lambda ()
  13478. (let ((match (match-string 1)))
  13479. (and
  13480. (if (memq type '(active inactive all))
  13481. (eq (org-element-type (save-excursion
  13482. (backward-char)
  13483. (org-element-context)))
  13484. 'timestamp)
  13485. (org-at-planning-p))
  13486. (not (time-less-p
  13487. (org-time-string-to-time match)
  13488. (org-time-string-to-time start-date)))
  13489. (time-less-p
  13490. (org-time-string-to-time match)
  13491. (org-time-string-to-time end-date))))))))
  13492. (message "%d entries between %s and %s"
  13493. (org-occur regexp nil callback) start-date end-date)))
  13494. (defun org-evaluate-time-range (&optional to-buffer)
  13495. "Evaluate a time range by computing the difference between start and end.
  13496. Normally the result is just printed in the echo area, but with prefix arg
  13497. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13498. If the time range is actually in a table, the result is inserted into the
  13499. next column.
  13500. For time difference computation, a year is assumed to be exactly 365
  13501. days in order to avoid rounding problems."
  13502. (interactive "P")
  13503. (or
  13504. (org-clock-update-time-maybe)
  13505. (save-excursion
  13506. (unless (org-at-date-range-p t)
  13507. (goto-char (point-at-bol))
  13508. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13509. (unless (org-at-date-range-p t)
  13510. (user-error "Not at a time-stamp range, and none found in current line")))
  13511. (let* ((ts1 (match-string 1))
  13512. (ts2 (match-string 2))
  13513. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13514. (match-end (match-end 0))
  13515. (time1 (org-time-string-to-time ts1))
  13516. (time2 (org-time-string-to-time ts2))
  13517. (diff (abs (float-time (time-subtract time2 time1))))
  13518. (negative (time-less-p time2 time1))
  13519. ;; (ys (floor (* 365 24 60 60)))
  13520. (ds (* 24 60 60))
  13521. (hs (* 60 60))
  13522. (fy "%dy %dd %02d:%02d")
  13523. (fy1 "%dy %dd")
  13524. (fd "%dd %02d:%02d")
  13525. (fd1 "%dd")
  13526. (fh "%02d:%02d")
  13527. y d h m align)
  13528. (if havetime
  13529. (setq ; y (floor diff ys) diff (mod diff ys)
  13530. y 0
  13531. d (floor diff ds) diff (mod diff ds)
  13532. h (floor diff hs) diff (mod diff hs)
  13533. m (floor diff 60))
  13534. (setq ; y (floor diff ys) diff (mod diff ys)
  13535. y 0
  13536. d (round diff ds)
  13537. h 0 m 0))
  13538. (if (not to-buffer)
  13539. (message "%s" (org-make-tdiff-string y d h m))
  13540. (if (org-at-table-p)
  13541. (progn
  13542. (goto-char match-end)
  13543. (setq align t)
  13544. (and (looking-at " *|") (goto-char (match-end 0))))
  13545. (goto-char match-end))
  13546. (when (looking-at
  13547. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13548. (replace-match ""))
  13549. (when negative (insert " -"))
  13550. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13551. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13552. (insert " " (format fh h m))))
  13553. (when align (org-table-align))
  13554. (message "Time difference inserted")))))
  13555. (defun org-make-tdiff-string (y d h m)
  13556. (let ((fmt "")
  13557. (l nil))
  13558. (when (> y 0)
  13559. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13560. (push y l))
  13561. (when (> d 0)
  13562. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13563. (push d l))
  13564. (when (> h 0)
  13565. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13566. (push h l))
  13567. (when (> m 0)
  13568. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13569. (push m l))
  13570. (apply 'format fmt (nreverse l))))
  13571. (defun org-time-string-to-time (s)
  13572. "Convert timestamp string S into internal time."
  13573. (apply #'encode-time (org-parse-time-string s)))
  13574. (defun org-time-string-to-seconds (s)
  13575. "Convert a timestamp string S into a number of seconds."
  13576. (float-time (org-time-string-to-time s)))
  13577. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13578. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13579. "Convert time stamp S to an absolute day number.
  13580. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13581. stamp, get the closest date to DAYNR. If PREFER is
  13582. `past' (respectively `future') return a date past (respectively
  13583. after) or equal to DAYNR.
  13584. POS is the location of time stamp S, as a buffer position in
  13585. BUFFER.
  13586. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13587. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13588. signaled."
  13589. (cond
  13590. ((string-match "\\`%%\\((.*)\\)" s)
  13591. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13592. ;; only able to match individual dates. If it fails, raise an
  13593. ;; error.
  13594. (if (and daynr
  13595. (org-diary-sexp-entry
  13596. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13597. daynr
  13598. (signal 'org-diary-sexp-no-match (list s))))
  13599. (daynr (org-closest-date s daynr prefer))
  13600. (t (time-to-days
  13601. (condition-case errdata
  13602. (org-time-string-to-time s)
  13603. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13604. s
  13605. (if (not (and buffer pos)) ""
  13606. (format-message " at %d in buffer `%s'" pos buffer))
  13607. (cdr errdata))))))))
  13608. (defun org-days-to-iso-week (days)
  13609. "Return the iso week number."
  13610. (require 'cal-iso)
  13611. (car (calendar-iso-from-absolute days)))
  13612. (defun org-small-year-to-year (year)
  13613. "Convert 2-digit years into 4-digit years.
  13614. YEAR is expanded into one of the 30 next years, if possible, or
  13615. into a past one. Any year larger than 99 is returned unchanged."
  13616. (if (>= year 100) year
  13617. (let* ((current (string-to-number (format-time-string "%Y")))
  13618. (century (/ current 100))
  13619. (offset (- year (% current 100))))
  13620. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13621. ((> offset -70) (+ (* century 100) year))
  13622. (t (+ (* (1+ century) 100) year))))))
  13623. (defun org-time-from-absolute (d)
  13624. "Return the time corresponding to date D.
  13625. D may be an absolute day number, or a calendar-type list (month day year)."
  13626. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13627. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13628. (defvar org-agenda-current-date)
  13629. (defun org-calendar-holiday ()
  13630. "List of holidays, for Diary display in Org mode."
  13631. (require 'holidays)
  13632. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13633. (and hl (mapconcat #'identity hl "; "))))
  13634. (defun org-diary-sexp-entry (sexp entry d)
  13635. "Process a SEXP diary ENTRY for date D."
  13636. (require 'diary-lib)
  13637. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13638. ;; dynamically.
  13639. (let* ((sexp `(let ((entry ,entry)
  13640. (date ',d))
  13641. ,(car (read-from-string sexp))))
  13642. (result (if calendar-debug-sexp (eval sexp)
  13643. (condition-case nil
  13644. (eval sexp)
  13645. (error
  13646. (beep)
  13647. (message "Bad sexp at line %d in %s: %s"
  13648. (org-current-line)
  13649. (buffer-file-name) sexp)
  13650. (sleep-for 2))))))
  13651. (cond ((stringp result) (split-string result "; "))
  13652. ((and (consp result)
  13653. (not (consp (cdr result)))
  13654. (stringp (cdr result))) (cdr result))
  13655. ((and (consp result)
  13656. (stringp (car result))) result)
  13657. (result entry))))
  13658. (defun org-diary-to-ical-string (frombuf)
  13659. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13660. This uses the icalendar.el library."
  13661. (let* ((tmpdir temporary-file-directory)
  13662. (tmpfile (make-temp-name
  13663. (expand-file-name "orgics" tmpdir)))
  13664. buf rtn b e)
  13665. (with-current-buffer frombuf
  13666. (icalendar-export-region (point-min) (point-max) tmpfile)
  13667. (setq buf (find-buffer-visiting tmpfile))
  13668. (set-buffer buf)
  13669. (goto-char (point-min))
  13670. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13671. (setq b (match-beginning 0)))
  13672. (goto-char (point-max))
  13673. (when (re-search-backward "^END:VEVENT" nil t)
  13674. (setq e (match-end 0)))
  13675. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13676. (kill-buffer buf)
  13677. (delete-file tmpfile)
  13678. rtn))
  13679. (defun org-closest-date (start current prefer)
  13680. "Return closest date to CURRENT starting from START.
  13681. CURRENT and START are both time stamps.
  13682. When PREFER is `past', return a date that is either CURRENT or
  13683. past. When PREFER is `future', return a date that is either
  13684. CURRENT or future.
  13685. Only time stamps with a repeater are modified. Any other time
  13686. stamp stay unchanged. In any case, return value is an absolute
  13687. day number."
  13688. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13689. ;; No repeater. Do not shift time stamp.
  13690. (time-to-days (org-time-string-to-time start))
  13691. (let ((value (string-to-number (match-string 1 start)))
  13692. (type (match-string 2 start)))
  13693. (if (= 0 value)
  13694. ;; Repeater with a 0-value is considered as void.
  13695. (time-to-days (org-time-string-to-time start))
  13696. (let* ((base (org-date-to-gregorian start))
  13697. (target (org-date-to-gregorian current))
  13698. (sday (calendar-absolute-from-gregorian base))
  13699. (cday (calendar-absolute-from-gregorian target))
  13700. n1 n2)
  13701. ;; If START is already past CURRENT, just return START.
  13702. (if (<= cday sday) sday
  13703. ;; Compute closest date before (N1) and closest date past
  13704. ;; (N2) CURRENT.
  13705. (pcase type
  13706. ("h"
  13707. (let ((missing-hours
  13708. (mod (+ (- (* 24 (- cday sday))
  13709. (nth 2 (org-parse-time-string start)))
  13710. org-extend-today-until)
  13711. value)))
  13712. (setf n1 (if (= missing-hours 0) cday
  13713. (- cday (1+ (/ missing-hours 24)))))
  13714. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13715. ((or "d" "w")
  13716. (let ((value (if (equal type "w") (* 7 value) value)))
  13717. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13718. (setf n2 (+ n1 value))))
  13719. ("m"
  13720. (let* ((add-months
  13721. (lambda (d n)
  13722. ;; Add N months to gregorian date D, i.e.,
  13723. ;; a list (MONTH DAY YEAR). Return a valid
  13724. ;; gregorian date.
  13725. (let ((m (+ (nth 0 d) n)))
  13726. (list (mod m 12)
  13727. (nth 1 d)
  13728. (+ (/ m 12) (nth 2 d))))))
  13729. (months ; Complete months to TARGET.
  13730. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13731. (- (nth 0 target) (nth 0 base))
  13732. ;; If START's day is greater than
  13733. ;; TARGET's, remove incomplete month.
  13734. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13735. value)
  13736. value))
  13737. (before (funcall add-months base months)))
  13738. (setf n1 (calendar-absolute-from-gregorian before))
  13739. (setf n2
  13740. (calendar-absolute-from-gregorian
  13741. (funcall add-months before value)))))
  13742. (_
  13743. (let* ((d (nth 1 base))
  13744. (m (nth 0 base))
  13745. (y (nth 2 base))
  13746. (years ; Complete years to TARGET.
  13747. (* (/ (- (nth 2 target)
  13748. y
  13749. ;; If START's month and day are
  13750. ;; greater than TARGET's, remove
  13751. ;; incomplete year.
  13752. (if (or (> (nth 0 target) m)
  13753. (and (= (nth 0 target) m)
  13754. (> (nth 1 target) d)))
  13755. 0
  13756. 1))
  13757. value)
  13758. value))
  13759. (before (list m d (+ y years))))
  13760. (setf n1 (calendar-absolute-from-gregorian before))
  13761. (setf n2 (calendar-absolute-from-gregorian
  13762. (list m d (+ (nth 2 before) value)))))))
  13763. ;; Handle PREFER parameter, if any.
  13764. (cond
  13765. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13766. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13767. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13768. (defun org-date-to-gregorian (d)
  13769. "Turn any specification of date D into a Gregorian date for the calendar."
  13770. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13771. ((and (listp d) (= (length d) 3)) d)
  13772. ((stringp d)
  13773. (let ((d (org-parse-time-string d)))
  13774. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13775. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13776. (defun org-timestamp-up (&optional arg)
  13777. "Increase the date item at the cursor by one.
  13778. If the cursor is on the year, change the year. If it is on the month,
  13779. the day or the time, change that. If the cursor is on the enclosing
  13780. bracket, change the timestamp type.
  13781. With prefix ARG, change by that many units."
  13782. (interactive "p")
  13783. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13784. (defun org-timestamp-down (&optional arg)
  13785. "Decrease the date item at the cursor by one.
  13786. If the cursor is on the year, change the year. If it is on the month,
  13787. the day or the time, change that. If the cursor is on the enclosing
  13788. bracket, change the timestamp type.
  13789. With prefix ARG, change by that many units."
  13790. (interactive "p")
  13791. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13792. (defun org-timestamp-up-day (&optional arg)
  13793. "Increase the date in the time stamp by one day.
  13794. With prefix ARG, change that many days."
  13795. (interactive "p")
  13796. (if (and (not (org-at-timestamp-p 'lax))
  13797. (org-at-heading-p))
  13798. (org-todo 'up)
  13799. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13800. (defun org-timestamp-down-day (&optional arg)
  13801. "Decrease the date in the time stamp by one day.
  13802. With prefix ARG, change that many days."
  13803. (interactive "p")
  13804. (if (and (not (org-at-timestamp-p 'lax))
  13805. (org-at-heading-p))
  13806. (org-todo 'down)
  13807. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13808. (defun org-at-timestamp-p (&optional extended)
  13809. "Non-nil if point is inside a timestamp.
  13810. By default, the function only consider syntactically valid active
  13811. timestamps. However, the caller may have a broader definition
  13812. for timestamps. As a consequence, optional argument EXTENDED can
  13813. be set to the following values
  13814. `inactive'
  13815. Include also syntactically valid inactive timestamps.
  13816. `agenda'
  13817. Include timestamps allowed in Agenda, i.e., those in
  13818. properties drawers, planning lines and clock lines.
  13819. `lax'
  13820. Ignore context. The function matches any part of the
  13821. document looking like a timestamp. This includes comments,
  13822. example blocks...
  13823. For backward-compatibility with Org 9.0, every other non-nil
  13824. value is equivalent to `inactive'.
  13825. When at a timestamp, return the position of the point as a symbol
  13826. among `bracket', `after', `year', `month', `hour', `minute',
  13827. `day' or a number of character from the last know part of the
  13828. time stamp.
  13829. When matching, the match groups are the following:
  13830. group 1: year
  13831. group 2: month
  13832. group 3: day number
  13833. group 4: day name
  13834. group 5: hours, if any
  13835. group 6: minutes, if any"
  13836. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13837. (pos (point))
  13838. (match?
  13839. (let ((boundaries (org-in-regexp regexp)))
  13840. (save-match-data
  13841. (cond ((null boundaries) nil)
  13842. ((eq extended 'lax) t)
  13843. (t
  13844. (or (and (eq extended 'agenda)
  13845. (or (org-at-planning-p)
  13846. (org-at-property-p)
  13847. (and (bound-and-true-p
  13848. org-agenda-include-inactive-timestamps)
  13849. (org-at-clock-log-p))))
  13850. (eq 'timestamp
  13851. (save-excursion
  13852. (when (= pos (cdr boundaries)) (forward-char -1))
  13853. (org-element-type (org-element-context)))))))))))
  13854. (cond
  13855. ((not match?) nil)
  13856. ((= pos (match-beginning 0)) 'bracket)
  13857. ;; Distinguish location right before the closing bracket from
  13858. ;; right after it.
  13859. ((= pos (1- (match-end 0))) 'bracket)
  13860. ((= pos (match-end 0)) 'after)
  13861. ((org-pos-in-match-range pos 2) 'year)
  13862. ((org-pos-in-match-range pos 3) 'month)
  13863. ((org-pos-in-match-range pos 7) 'hour)
  13864. ((org-pos-in-match-range pos 8) 'minute)
  13865. ((or (org-pos-in-match-range pos 4)
  13866. (org-pos-in-match-range pos 5)) 'day)
  13867. ((and (> pos (or (match-end 8) (match-end 5)))
  13868. (< pos (match-end 0)))
  13869. (- pos (or (match-end 8) (match-end 5))))
  13870. (t 'day))))
  13871. (defun org-toggle-timestamp-type ()
  13872. "Toggle the type (<active> or [inactive]) of a time stamp."
  13873. (interactive)
  13874. (when (org-at-timestamp-p 'lax)
  13875. (let ((beg (match-beginning 0)) (end (match-end 0))
  13876. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13877. (save-excursion
  13878. (goto-char beg)
  13879. (while (re-search-forward "[][<>]" end t)
  13880. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13881. t t)))
  13882. (message "Timestamp is now %sactive"
  13883. (if (equal (char-after beg) ?<) "" "in")))))
  13884. (defun org-at-clock-log-p ()
  13885. "Non-nil if point is on a clock log line."
  13886. (and (org-match-line org-clock-line-re)
  13887. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13888. (defvar org-clock-history) ; defined in org-clock.el
  13889. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13890. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13891. "Change the date in the time stamp at point.
  13892. The date is changed by N times WHAT. WHAT can be `day', `month',
  13893. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13894. position in the timestamp determines what is changed.
  13895. When optional argument UPDOWN is non-nil, minutes are rounded
  13896. according to `org-time-stamp-rounding-minutes'.
  13897. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13898. \"--2d\"."
  13899. (let ((origin (point))
  13900. (timestamp? (org-at-timestamp-p 'lax))
  13901. origin-cat
  13902. with-hm inactive
  13903. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13904. extra rem
  13905. ts time time0 fixnext clrgx)
  13906. (unless timestamp? (user-error "Not at a timestamp"))
  13907. (if (and (not what) (eq timestamp? 'bracket))
  13908. (org-toggle-timestamp-type)
  13909. ;; Point isn't on brackets. Remember the part of the time-stamp
  13910. ;; the point was in. Indeed, size of time-stamps may change,
  13911. ;; but point must be kept in the same category nonetheless.
  13912. (setq origin-cat timestamp?)
  13913. (when (and (not what) (not (eq timestamp? 'day))
  13914. org-display-custom-times
  13915. (get-text-property (point) 'display)
  13916. (not (get-text-property (1- (point)) 'display)))
  13917. (setq timestamp? 'day))
  13918. (setq timestamp? (or what timestamp?)
  13919. inactive (= (char-after (match-beginning 0)) ?\[)
  13920. ts (match-string 0))
  13921. (replace-match "")
  13922. (when (string-match
  13923. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13924. ts)
  13925. (setq extra (match-string 1 ts))
  13926. (when suppress-tmp-delay
  13927. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13928. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13929. (setq with-hm t))
  13930. (setq time0 (org-parse-time-string ts))
  13931. (when (and updown
  13932. (eq timestamp? 'minute)
  13933. (not current-prefix-arg))
  13934. ;; This looks like s-up and s-down. Change by one rounding step.
  13935. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13936. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13937. (setcar (cdr time0) (+ (nth 1 time0)
  13938. (if (> n 0) (- rem) (- dm rem))))))
  13939. (setq time
  13940. (apply #'encode-time
  13941. (or (car time0) 0)
  13942. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13943. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13944. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13945. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13946. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13947. (nthcdr 6 time0)))
  13948. (when (and (memq timestamp? '(hour minute))
  13949. extra
  13950. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13951. (setq extra (org-modify-ts-extra
  13952. extra
  13953. (if (eq timestamp? 'hour) 2 5)
  13954. n dm)))
  13955. (when (integerp timestamp?)
  13956. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13957. (when (eq what 'calendar)
  13958. (let ((cal-date (org-get-date-from-calendar)))
  13959. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13960. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13961. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13962. (setcar time0 (or (car time0) 0))
  13963. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13964. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13965. (setq time (apply 'encode-time time0))))
  13966. ;; Insert the new time-stamp, and ensure point stays in the same
  13967. ;; category as before (i.e. not after the last position in that
  13968. ;; category).
  13969. (let ((pos (point)))
  13970. ;; Stay before inserted string. `save-excursion' is of no use.
  13971. (setq org-last-changed-timestamp
  13972. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13973. (goto-char pos))
  13974. (save-match-data
  13975. (looking-at org-ts-regexp3)
  13976. (goto-char
  13977. (pcase origin-cat
  13978. ;; `day' category ends before `hour' if any, or at the end
  13979. ;; of the day name.
  13980. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13981. (`hour (min (match-end 7) origin))
  13982. (`minute (min (1- (match-end 8)) origin))
  13983. ((pred integerp) (min (1- (match-end 0)) origin))
  13984. ;; Point was right after the time-stamp. However, the
  13985. ;; time-stamp length might have changed, so refer to
  13986. ;; (match-end 0) instead.
  13987. (`after (match-end 0))
  13988. ;; `year' and `month' have both fixed size: point couldn't
  13989. ;; have moved into another part.
  13990. (_ origin))))
  13991. ;; Update clock if on a CLOCK line.
  13992. (org-clock-update-time-maybe)
  13993. ;; Maybe adjust the closest clock in `org-clock-history'
  13994. (when org-clock-adjust-closest
  13995. (if (not (and (org-at-clock-log-p)
  13996. (< 1 (length (delq nil (mapcar 'marker-position
  13997. org-clock-history))))))
  13998. (message "No clock to adjust")
  13999. (cond ((save-excursion ; fix previous clock?
  14000. (re-search-backward org-ts-regexp0 nil t)
  14001. (looking-back (concat org-clock-string " \\[")
  14002. (line-beginning-position)))
  14003. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14004. ((save-excursion ; fix next clock?
  14005. (re-search-backward org-ts-regexp0 nil t)
  14006. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14007. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14008. (save-window-excursion
  14009. ;; Find closest clock to point, adjust the previous/next one in history
  14010. (let* ((p (save-excursion (org-back-to-heading t)))
  14011. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14012. (clfixnth
  14013. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14014. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14015. (if (not clfixpos)
  14016. (message "No clock to adjust")
  14017. (save-excursion
  14018. (org-goto-marker-or-bmk clfixpos)
  14019. (org-show-subtree)
  14020. (when (re-search-forward clrgx nil t)
  14021. (goto-char (match-beginning 1))
  14022. (let (org-clock-adjust-closest)
  14023. (org-timestamp-change n timestamp? updown))
  14024. (message "Clock adjusted in %s for heading: %s"
  14025. (file-name-nondirectory (buffer-file-name))
  14026. (org-get-heading t t)))))))))
  14027. ;; Try to recenter the calendar window, if any.
  14028. (when (and org-calendar-follow-timestamp-change
  14029. (get-buffer-window "*Calendar*" t)
  14030. (memq timestamp? '(day month year)))
  14031. (org-recenter-calendar (time-to-days time))))))
  14032. (defun org-modify-ts-extra (s pos n dm)
  14033. "Change the different parts of the lead-time and repeat fields in timestamp."
  14034. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14035. ng h m new rem)
  14036. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14037. (cond
  14038. ((or (org-pos-in-match-range pos 2)
  14039. (org-pos-in-match-range pos 3))
  14040. (setq m (string-to-number (match-string 3 s))
  14041. h (string-to-number (match-string 2 s)))
  14042. (if (org-pos-in-match-range pos 2)
  14043. (setq h (+ h n))
  14044. (setq n (* dm (with-no-warnings (cl-signum n))))
  14045. (unless (= 0 (setq rem (% m dm)))
  14046. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14047. (setq m (+ m n)))
  14048. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14049. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14050. (setq h (mod h 24))
  14051. (setq ng 1 new (format "-%02d:%02d" h m)))
  14052. ((org-pos-in-match-range pos 6)
  14053. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14054. ((org-pos-in-match-range pos 5)
  14055. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14056. ((org-pos-in-match-range pos 9)
  14057. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14058. ((org-pos-in-match-range pos 8)
  14059. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14060. (when ng
  14061. (setq s (concat
  14062. (substring s 0 (match-beginning ng))
  14063. new
  14064. (substring s (match-end ng))))))
  14065. s))
  14066. (defun org-recenter-calendar (d)
  14067. "If the calendar is visible, recenter it to date D."
  14068. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14069. (when cwin
  14070. (let ((calendar-move-hook nil))
  14071. (with-selected-window cwin
  14072. (calendar-goto-date
  14073. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14074. (defun org-goto-calendar (&optional arg)
  14075. "Go to the Emacs calendar at the current date.
  14076. If there is a time stamp in the current line, go to that date.
  14077. A prefix ARG can be used to force the current date."
  14078. (interactive "P")
  14079. (let ((calendar-move-hook nil)
  14080. (calendar-view-holidays-initially-flag nil)
  14081. (calendar-view-diary-initially-flag nil)
  14082. diff)
  14083. (when (or (org-at-timestamp-p 'lax)
  14084. (org-match-line (concat ".*" org-ts-regexp)))
  14085. (let ((d1 (time-to-days nil))
  14086. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14087. (setq diff (- d2 d1))))
  14088. (calendar)
  14089. (calendar-goto-today)
  14090. (when (and diff (not arg)) (calendar-forward-day diff))))
  14091. (defun org-get-date-from-calendar ()
  14092. "Return a list (month day year) of date at point in calendar."
  14093. (with-current-buffer "*Calendar*"
  14094. (save-match-data
  14095. (calendar-cursor-to-date))))
  14096. (defun org-date-from-calendar ()
  14097. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14098. If there is already a time stamp at the cursor position, update it."
  14099. (interactive)
  14100. (if (org-at-timestamp-p 'lax)
  14101. (org-timestamp-change 0 'calendar)
  14102. (let ((cal-date (org-get-date-from-calendar)))
  14103. (org-insert-time-stamp
  14104. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14105. (defcustom org-image-actual-width t
  14106. "When non-nil, use the actual width of images when inlining them.
  14107. When set to a number, use imagemagick (when available) to set the
  14108. image's width to this value.
  14109. When set to a number in a list, try to get the width from any
  14110. #+ATTR.* keyword if it matches a width specification like
  14111. #+ATTR_HTML: :width 300px
  14112. and fall back on that number if none is found.
  14113. When set to nil, try to get the width from an #+ATTR.* keyword
  14114. and fall back on the original width if none is found.
  14115. When set to any other non-nil value, always use the image width.
  14116. This requires Emacs >= 24.1, built with imagemagick support."
  14117. :group 'org-appearance
  14118. :version "24.4"
  14119. :package-version '(Org . "8.0")
  14120. :type '(choice
  14121. (const :tag "Use the image width" t)
  14122. (integer :tag "Use a number of pixels")
  14123. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14124. (const :tag "Use #+ATTR* or don't resize" nil)))
  14125. (defcustom org-agenda-inhibit-startup nil
  14126. "Inhibit startup when preparing agenda buffers.
  14127. When this variable is t, the initialization of the Org agenda
  14128. buffers is inhibited: e.g. the visibility state is not set, the
  14129. tables are not re-aligned, etc."
  14130. :type 'boolean
  14131. :version "24.3"
  14132. :group 'org-agenda)
  14133. (defcustom org-agenda-ignore-properties nil
  14134. "Avoid updating text properties when building the agenda.
  14135. Properties are used to prepare buffers for effort estimates,
  14136. appointments, statistics and subtree-local categories.
  14137. If you don't use these in the agenda, you can add them to this
  14138. list and agenda building will be a bit faster.
  14139. The value is a list, with zero or more of the symbols `effort', `appt',
  14140. `stats' or `category'."
  14141. :type '(set :greedy t
  14142. (const effort)
  14143. (const appt)
  14144. (const stats)
  14145. (const category))
  14146. :version "26.1"
  14147. :package-version '(Org . "8.3")
  14148. :group 'org-agenda)
  14149. ;;;; Files
  14150. (defun org-save-all-org-buffers ()
  14151. "Save all Org buffers without user confirmation."
  14152. (interactive)
  14153. (message "Saving all Org buffers...")
  14154. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14155. (when (featurep 'org-id) (org-id-locations-save))
  14156. (message "Saving all Org buffers... done"))
  14157. (defun org-revert-all-org-buffers ()
  14158. "Revert all Org buffers.
  14159. Prompt for confirmation when there are unsaved changes.
  14160. Be sure you know what you are doing before letting this function
  14161. overwrite your changes.
  14162. This function is useful in a setup where one tracks Org files
  14163. with a version control system, to revert on one machine after pulling
  14164. changes from another. I believe the procedure must be like this:
  14165. 1. M-x org-save-all-org-buffers
  14166. 2. Pull changes from the other machine, resolve conflicts
  14167. 3. M-x org-revert-all-org-buffers"
  14168. (interactive)
  14169. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14170. (user-error "Abort"))
  14171. (save-excursion
  14172. (save-window-excursion
  14173. (dolist (b (buffer-list))
  14174. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14175. (with-current-buffer b buffer-file-name))
  14176. (pop-to-buffer-same-window b)
  14177. (revert-buffer t 'no-confirm)))
  14178. (when (and (featurep 'org-id) org-id-track-globally)
  14179. (org-id-locations-load)))))
  14180. ;;;; Agenda files
  14181. ;;;###autoload
  14182. (defun org-switchb (&optional arg)
  14183. "Switch between Org buffers.
  14184. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14185. With `\\[universal-argument] \\[universal-argument]' \
  14186. prefix, restrict available buffers to agenda files."
  14187. (interactive "P")
  14188. (let ((blist (org-buffer-list
  14189. (cond ((equal arg '(4)) 'files)
  14190. ((equal arg '(16)) 'agenda)))))
  14191. (pop-to-buffer-same-window
  14192. (completing-read "Org buffer: "
  14193. (mapcar #'list (mapcar #'buffer-name blist))
  14194. nil t))))
  14195. (defun org-buffer-list (&optional predicate exclude-tmp)
  14196. "Return a list of Org buffers.
  14197. PREDICATE can be `export', `files' or `agenda'.
  14198. export restrict the list to Export buffers.
  14199. files restrict the list to buffers visiting Org files.
  14200. agenda restrict the list to buffers visiting agenda files.
  14201. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14202. (let* ((bfn nil)
  14203. (agenda-files (and (eq predicate 'agenda)
  14204. (mapcar 'file-truename (org-agenda-files t))))
  14205. (filter
  14206. (cond
  14207. ((eq predicate 'files)
  14208. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14209. ((eq predicate 'export)
  14210. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14211. ((eq predicate 'agenda)
  14212. (lambda (b)
  14213. (with-current-buffer b
  14214. (and (derived-mode-p 'org-mode)
  14215. (setq bfn (buffer-file-name b))
  14216. (member (file-truename bfn) agenda-files)))))
  14217. (t (lambda (b) (with-current-buffer b
  14218. (or (derived-mode-p 'org-mode)
  14219. (string-match "\\*Org .*Export"
  14220. (buffer-name b)))))))))
  14221. (delq nil
  14222. (mapcar
  14223. (lambda(b)
  14224. (if (and (funcall filter b)
  14225. (or (not exclude-tmp)
  14226. (not (string-match "tmp" (buffer-name b)))))
  14227. b
  14228. nil))
  14229. (buffer-list)))))
  14230. (defun org-agenda-files (&optional unrestricted archives)
  14231. "Get the list of agenda files.
  14232. Optional UNRESTRICTED means return the full list even if a restriction
  14233. is currently in place.
  14234. When ARCHIVES is t, include all archive files that are really being
  14235. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14236. `org-agenda-archives-mode' is t."
  14237. (let ((files
  14238. (cond
  14239. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14240. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14241. ((listp org-agenda-files) org-agenda-files)
  14242. (t (error "Invalid value of `org-agenda-files'")))))
  14243. (setq files (apply 'append
  14244. (mapcar (lambda (f)
  14245. (if (file-directory-p f)
  14246. (directory-files
  14247. f t org-agenda-file-regexp)
  14248. (list f)))
  14249. files)))
  14250. (when org-agenda-skip-unavailable-files
  14251. (setq files (delq nil
  14252. (mapcar (function
  14253. (lambda (file)
  14254. (and (file-readable-p file) file)))
  14255. files))))
  14256. (when (or (eq archives t)
  14257. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14258. (setq files (org-add-archive-files files)))
  14259. files))
  14260. (defun org-agenda-file-p (&optional file)
  14261. "Return non-nil, if FILE is an agenda file.
  14262. If FILE is omitted, use the file associated with the current
  14263. buffer."
  14264. (let ((fname (or file (buffer-file-name))))
  14265. (and fname
  14266. (member (file-truename fname)
  14267. (mapcar #'file-truename (org-agenda-files t))))))
  14268. (defun org-edit-agenda-file-list ()
  14269. "Edit the list of agenda files.
  14270. Depending on setup, this either uses customize to edit the variable
  14271. `org-agenda-files', or it visits the file that is holding the list. In the
  14272. latter case, the buffer is set up in a way that saving it automatically kills
  14273. the buffer and restores the previous window configuration."
  14274. (interactive)
  14275. (if (stringp org-agenda-files)
  14276. (let ((cw (current-window-configuration)))
  14277. (find-file org-agenda-files)
  14278. (setq-local org-window-configuration cw)
  14279. (add-hook 'after-save-hook
  14280. (lambda ()
  14281. (set-window-configuration
  14282. (prog1 org-window-configuration
  14283. (kill-buffer (current-buffer))))
  14284. (org-install-agenda-files-menu)
  14285. (message "New agenda file list installed"))
  14286. nil 'local)
  14287. (message "%s" (substitute-command-keys
  14288. "Edit list and finish with \\[save-buffer]")))
  14289. (customize-variable 'org-agenda-files)))
  14290. (defun org-store-new-agenda-file-list (list)
  14291. "Set new value for the agenda file list and save it correctly."
  14292. (if (stringp org-agenda-files)
  14293. (let ((fe (org-read-agenda-file-list t)) b u)
  14294. (while (setq b (find-buffer-visiting org-agenda-files))
  14295. (kill-buffer b))
  14296. (with-temp-file org-agenda-files
  14297. (insert
  14298. (mapconcat
  14299. (lambda (f) ;; Keep un-expanded entries.
  14300. (if (setq u (assoc f fe))
  14301. (cdr u)
  14302. f))
  14303. list "\n")
  14304. "\n")))
  14305. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14306. (org-insert-mode-line-in-empty-file nil))
  14307. (setq org-agenda-files list)
  14308. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14309. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14310. "Read the list of agenda files from a file.
  14311. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14312. filenames, used by `org-store-new-agenda-file-list' to write back
  14313. un-expanded file names."
  14314. (when (file-directory-p org-agenda-files)
  14315. (error "`org-agenda-files' cannot be a single directory"))
  14316. (when (stringp org-agenda-files)
  14317. (with-temp-buffer
  14318. (insert-file-contents org-agenda-files)
  14319. (mapcar
  14320. (lambda (f)
  14321. (let ((e (expand-file-name (substitute-in-file-name f)
  14322. org-directory)))
  14323. (if pair-with-expansion
  14324. (cons e f)
  14325. e)))
  14326. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14327. ;;;###autoload
  14328. (defun org-cycle-agenda-files ()
  14329. "Cycle through the files in `org-agenda-files'.
  14330. If the current buffer visits an agenda file, find the next one in the list.
  14331. If the current buffer does not, find the first agenda file."
  14332. (interactive)
  14333. (let* ((fs (or (org-agenda-files t)
  14334. (user-error "No agenda files")))
  14335. (files (copy-sequence fs))
  14336. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14337. file)
  14338. (when tcf
  14339. (while (and (setq file (pop files))
  14340. (not (equal (file-truename file) tcf)))))
  14341. (find-file (car (or files fs)))
  14342. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14343. (defun org-agenda-file-to-front (&optional to-end)
  14344. "Move/add the current file to the top of the agenda file list.
  14345. If the file is not present in the list, it is added to the front. If it is
  14346. present, it is moved there. With optional argument TO-END, add/move to the
  14347. end of the list."
  14348. (interactive "P")
  14349. (let ((org-agenda-skip-unavailable-files nil)
  14350. (file-alist (mapcar (lambda (x)
  14351. (cons (file-truename x) x))
  14352. (org-agenda-files t)))
  14353. (ctf (file-truename
  14354. (or buffer-file-name
  14355. (user-error "Please save the current buffer to a file"))))
  14356. x had)
  14357. (setq x (assoc ctf file-alist) had x)
  14358. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14359. (if to-end
  14360. (setq file-alist (append (delq x file-alist) (list x)))
  14361. (setq file-alist (cons x (delq x file-alist))))
  14362. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14363. (org-install-agenda-files-menu)
  14364. (message "File %s to %s of agenda file list"
  14365. (if had "moved" "added") (if to-end "end" "front"))))
  14366. (defun org-remove-file (&optional file)
  14367. "Remove current file from the list of files in variable `org-agenda-files'.
  14368. These are the files which are being checked for agenda entries.
  14369. Optional argument FILE means use this file instead of the current."
  14370. (interactive)
  14371. (let* ((org-agenda-skip-unavailable-files nil)
  14372. (file (or file buffer-file-name
  14373. (user-error "Current buffer does not visit a file")))
  14374. (true-file (file-truename file))
  14375. (afile (abbreviate-file-name file))
  14376. (files (delq nil (mapcar
  14377. (lambda (x)
  14378. (unless (equal true-file
  14379. (file-truename x))
  14380. x))
  14381. (org-agenda-files t)))))
  14382. (if (not (= (length files) (length (org-agenda-files t))))
  14383. (progn
  14384. (org-store-new-agenda-file-list files)
  14385. (org-install-agenda-files-menu)
  14386. (message "Removed from Org Agenda list: %s" afile))
  14387. (message "File was not in list: %s (not removed)" afile))))
  14388. (defun org-file-menu-entry (file)
  14389. (vector file (list 'find-file file) t))
  14390. (defun org-check-agenda-file (file)
  14391. "Make sure FILE exists. If not, ask user what to do."
  14392. (unless (file-exists-p file)
  14393. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14394. (abbreviate-file-name file))
  14395. (let ((r (downcase (read-char-exclusive))))
  14396. (cond
  14397. ((equal r ?r)
  14398. (org-remove-file file)
  14399. (throw 'nextfile t))
  14400. (t (user-error "Abort"))))))
  14401. (defun org-get-agenda-file-buffer (file)
  14402. "Get an agenda buffer visiting FILE.
  14403. If the buffer needs to be created, add it to the list of buffers
  14404. which might be released later."
  14405. (let ((buf (org-find-base-buffer-visiting file)))
  14406. (if buf
  14407. buf ; just return it
  14408. ;; Make a new buffer and remember it
  14409. (setq buf (find-file-noselect file))
  14410. (when buf (push buf org-agenda-new-buffers))
  14411. buf)))
  14412. (defun org-release-buffers (blist)
  14413. "Release all buffers in list, asking the user for confirmation when needed.
  14414. When a buffer is unmodified, it is just killed. When modified, it is saved
  14415. \(if the user agrees) and then killed."
  14416. (let (file)
  14417. (dolist (buf blist)
  14418. (setq file (buffer-file-name buf))
  14419. (when (and (buffer-modified-p buf)
  14420. file
  14421. (y-or-n-p (format "Save file %s? " file)))
  14422. (with-current-buffer buf (save-buffer)))
  14423. (kill-buffer buf))))
  14424. (defun org-agenda-prepare-buffers (files)
  14425. "Create buffers for all agenda files, protect archived trees and comments."
  14426. (interactive)
  14427. (let ((pa '(:org-archived t))
  14428. (pc '(:org-comment t))
  14429. (pall '(:org-archived t :org-comment t))
  14430. (inhibit-read-only t)
  14431. (org-inhibit-startup org-agenda-inhibit-startup)
  14432. (rea (org-make-tag-string (list org-archive-tag)))
  14433. re pos)
  14434. (setq org-tag-alist-for-agenda nil
  14435. org-tag-groups-alist-for-agenda nil)
  14436. (save-excursion
  14437. (save-restriction
  14438. (dolist (file files)
  14439. (catch 'nextfile
  14440. (if (bufferp file)
  14441. (set-buffer file)
  14442. (org-check-agenda-file file)
  14443. (set-buffer (org-get-agenda-file-buffer file)))
  14444. (widen)
  14445. (org-set-regexps-and-options 'tags-only)
  14446. (setq pos (point))
  14447. (or (memq 'category org-agenda-ignore-properties)
  14448. (org-refresh-category-properties))
  14449. (or (memq 'stats org-agenda-ignore-properties)
  14450. (org-refresh-stats-properties))
  14451. (or (memq 'effort org-agenda-ignore-properties)
  14452. (org-refresh-effort-properties))
  14453. (or (memq 'appt org-agenda-ignore-properties)
  14454. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14455. (setq org-todo-keywords-for-agenda
  14456. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14457. (setq org-done-keywords-for-agenda
  14458. (append org-done-keywords-for-agenda org-done-keywords))
  14459. (setq org-todo-keyword-alist-for-agenda
  14460. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14461. (setq org-tag-alist-for-agenda
  14462. (org--tag-add-to-alist
  14463. org-tag-alist-for-agenda
  14464. org-current-tag-alist))
  14465. ;; Merge current file's tag groups into global
  14466. ;; `org-tag-groups-alist-for-agenda'.
  14467. (when org-group-tags
  14468. (dolist (alist org-tag-groups-alist)
  14469. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14470. (if old
  14471. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14472. (push alist org-tag-groups-alist-for-agenda)))))
  14473. (with-silent-modifications
  14474. (save-excursion
  14475. (remove-text-properties (point-min) (point-max) pall)
  14476. (when org-agenda-skip-archived-trees
  14477. (goto-char (point-min))
  14478. (while (re-search-forward rea nil t)
  14479. (when (org-at-heading-p t)
  14480. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14481. (goto-char (point-min))
  14482. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14483. (while (re-search-forward re nil t)
  14484. (when (save-match-data (org-in-commented-heading-p t))
  14485. (add-text-properties
  14486. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14487. (goto-char pos)))))
  14488. (setq org-todo-keywords-for-agenda
  14489. (org-uniquify org-todo-keywords-for-agenda))
  14490. (setq org-todo-keyword-alist-for-agenda
  14491. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14492. ;;;; CDLaTeX minor mode
  14493. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14494. "Keymap for the minor `org-cdlatex-mode'.")
  14495. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14496. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14497. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14498. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14499. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14500. (defvar org-cdlatex-texmathp-advice-is-done nil
  14501. "Flag remembering if we have applied the advice to texmathp already.")
  14502. (define-minor-mode org-cdlatex-mode
  14503. "Toggle the minor `org-cdlatex-mode'.
  14504. This mode supports entering LaTeX environment and math in LaTeX fragments
  14505. in Org mode.
  14506. \\{org-cdlatex-mode-map}"
  14507. nil " OCDL" nil
  14508. (when org-cdlatex-mode
  14509. (require 'cdlatex)
  14510. (run-hooks 'cdlatex-mode-hook)
  14511. (cdlatex-compute-tables))
  14512. (unless org-cdlatex-texmathp-advice-is-done
  14513. (setq org-cdlatex-texmathp-advice-is-done t)
  14514. (defadvice texmathp (around org-math-always-on activate)
  14515. "Always return t in Org buffers.
  14516. This is because we want to insert math symbols without dollars even outside
  14517. the LaTeX math segments. If Org mode thinks that point is actually inside
  14518. an embedded LaTeX fragment, let `texmathp' do its job.
  14519. `\\[org-cdlatex-mode-map]'"
  14520. (interactive)
  14521. (let (p)
  14522. (cond
  14523. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14524. ((eq this-command 'cdlatex-math-symbol)
  14525. (setq ad-return-value t
  14526. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14527. (t
  14528. (let ((p (org-inside-LaTeX-fragment-p)))
  14529. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14530. (setq ad-return-value t
  14531. texmathp-why '("Org mode embedded math" . 0))
  14532. (when p ad-do-it)))))))))
  14533. (defun turn-on-org-cdlatex ()
  14534. "Unconditionally turn on `org-cdlatex-mode'."
  14535. (org-cdlatex-mode 1))
  14536. (defun org-try-cdlatex-tab ()
  14537. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14538. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14539. - inside a LaTeX fragment, or
  14540. - after the first word in a line, where an abbreviation expansion could
  14541. insert a LaTeX environment."
  14542. (when org-cdlatex-mode
  14543. (cond
  14544. ;; Before any word on the line: No expansion possible.
  14545. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14546. ;; Just after first word on the line: Expand it. Make sure it
  14547. ;; cannot happen on headlines, though.
  14548. ((save-excursion
  14549. (skip-chars-backward "a-zA-Z0-9*")
  14550. (skip-chars-backward " \t")
  14551. (and (bolp) (not (org-at-heading-p))))
  14552. (cdlatex-tab) t)
  14553. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14554. (defun org-cdlatex-underscore-caret (&optional _arg)
  14555. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14556. Revert to the normal definition outside of these fragments."
  14557. (interactive "P")
  14558. (if (org-inside-LaTeX-fragment-p)
  14559. (call-interactively 'cdlatex-sub-superscript)
  14560. (let (org-cdlatex-mode)
  14561. (call-interactively (key-binding (vector last-input-event))))))
  14562. (defun org-cdlatex-math-modify (&optional _arg)
  14563. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14564. Revert to the normal definition outside of these fragments."
  14565. (interactive "P")
  14566. (if (org-inside-LaTeX-fragment-p)
  14567. (call-interactively 'cdlatex-math-modify)
  14568. (let (org-cdlatex-mode)
  14569. (call-interactively (key-binding (vector last-input-event))))))
  14570. (defun org-cdlatex-environment-indent (&optional environment item)
  14571. "Execute `cdlatex-environment' and indent the inserted environment.
  14572. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14573. The inserted environment is indented to current indentation
  14574. unless point is at the beginning of the line, in which the
  14575. environment remains unintended."
  14576. (interactive)
  14577. ;; cdlatex-environment always return nil. Therefore, capture output
  14578. ;; first and determine if an environment was selected.
  14579. (let* ((beg (point-marker))
  14580. (end (copy-marker (point) t))
  14581. (inserted (progn
  14582. (ignore-errors (cdlatex-environment environment item))
  14583. (< beg end)))
  14584. ;; Figure out how many lines to move forward after the
  14585. ;; environment has been inserted.
  14586. (lines (when inserted
  14587. (save-excursion
  14588. (- (cl-loop while (< beg (point))
  14589. with x = 0
  14590. do (forward-line -1)
  14591. (cl-incf x)
  14592. finally return x)
  14593. (if (progn (goto-char beg)
  14594. (and (progn (skip-chars-forward " \t") (eolp))
  14595. (progn (skip-chars-backward " \t") (bolp))))
  14596. 1 0)))))
  14597. (env (org-trim (delete-and-extract-region beg end))))
  14598. (when inserted
  14599. ;; Get indentation of next line unless at column 0.
  14600. (let ((ind (if (bolp) 0
  14601. (save-excursion
  14602. (org-return-indent)
  14603. (prog1 (current-indentation)
  14604. (when (progn (skip-chars-forward " \t") (eolp))
  14605. (delete-region beg (point)))))))
  14606. (bol (progn (skip-chars-backward " \t") (bolp))))
  14607. ;; Insert a newline before environment unless at column zero
  14608. ;; to "escape" the current line. Insert a newline if
  14609. ;; something is one the same line as \end{ENVIRONMENT}.
  14610. (insert
  14611. (concat (unless bol "\n") env
  14612. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14613. (unless (zerop ind)
  14614. (save-excursion
  14615. (goto-char beg)
  14616. (while (< (point) end)
  14617. (unless (eolp) (indent-line-to ind))
  14618. (forward-line))))
  14619. (goto-char beg)
  14620. (forward-line lines)
  14621. (indent-line-to ind)))
  14622. (set-marker beg nil)
  14623. (set-marker end nil)))
  14624. ;;;; LaTeX fragments
  14625. (defun org-inside-LaTeX-fragment-p ()
  14626. "Test if point is inside a LaTeX fragment.
  14627. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14628. sequence appearing also before point.
  14629. Even though the matchers for math are configurable, this function assumes
  14630. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14631. delimiters are skipped when they have been removed by customization.
  14632. The return value is nil, or a cons cell with the delimiter and the
  14633. position of this delimiter.
  14634. This function does a reasonably good job, but can locally be fooled by
  14635. for example currency specifications. For example it will assume being in
  14636. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14637. fragments that are properly closed, but during editing, we have to live
  14638. with the uncertainty caused by missing closing delimiters. This function
  14639. looks only before point, not after."
  14640. (catch 'exit
  14641. (let ((pos (point))
  14642. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14643. (lim (save-excursion (org-backward-paragraph) (point)))
  14644. dd-on str (start 0) m re)
  14645. (goto-char pos)
  14646. (when dodollar
  14647. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14648. re (nth 1 (assoc "$" org-latex-regexps)))
  14649. (while (string-match re str start)
  14650. (cond
  14651. ((= (match-end 0) (length str))
  14652. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14653. ((= (match-end 0) (- (length str) 5))
  14654. (throw 'exit nil))
  14655. (t (setq start (match-end 0))))))
  14656. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14657. (goto-char pos)
  14658. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14659. (and (match-beginning 2) (throw 'exit nil))
  14660. ;; count $$
  14661. (while (re-search-backward "\\$\\$" lim t)
  14662. (setq dd-on (not dd-on)))
  14663. (goto-char pos)
  14664. (when dd-on (cons "$$" m))))))
  14665. (defun org-inside-latex-macro-p ()
  14666. "Is point inside a LaTeX macro or its arguments?"
  14667. (save-match-data
  14668. (org-in-regexp
  14669. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14670. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14671. "Build an overlay between BEG and END using IMAGE file.
  14672. Argument IMAGETYPE is the extension of the displayed image,
  14673. as a string. It defaults to \"png\"."
  14674. (let ((ov (make-overlay beg end))
  14675. (imagetype (or (intern imagetype) 'png)))
  14676. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14677. (overlay-put ov 'evaporate t)
  14678. (overlay-put ov
  14679. 'modification-hooks
  14680. (list (lambda (o _flag _beg _end &optional _l)
  14681. (delete-overlay o))))
  14682. (overlay-put ov
  14683. 'display
  14684. (list 'image :type imagetype :file image :ascent 'center))))
  14685. (defun org-clear-latex-preview (&optional beg end)
  14686. "Remove all overlays with LaTeX fragment images in current buffer.
  14687. When optional arguments BEG and END are non-nil, remove all
  14688. overlays between them instead. Return a non-nil value when some
  14689. overlays were removed, nil otherwise."
  14690. (let ((overlays
  14691. (cl-remove-if-not
  14692. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14693. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14694. (mapc #'delete-overlay overlays)
  14695. overlays))
  14696. (defun org--latex-preview-region (beg end)
  14697. "Preview LaTeX fragments between BEG and END.
  14698. BEG and END are buffer positions."
  14699. (let ((file (buffer-file-name (buffer-base-buffer))))
  14700. (save-excursion
  14701. (org-format-latex
  14702. (concat org-preview-latex-image-directory "org-ltximg")
  14703. beg end
  14704. ;; Emacs cannot overlay images from remote hosts. Create it in
  14705. ;; `temporary-file-directory' instead.
  14706. (if (or (not file) (file-remote-p file))
  14707. temporary-file-directory
  14708. default-directory)
  14709. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14710. (defun org-latex-preview (&optional arg)
  14711. "Toggle preview of the LaTeX fragment at point.
  14712. If the cursor is on a LaTeX fragment, create the image and
  14713. overlay it over the source code, if there is none. Remove it
  14714. otherwise. If there is no fragment at point, display images for
  14715. all fragments in the current section.
  14716. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14717. for all fragments
  14718. in the current section.
  14719. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14720. argument ARG, display image for all
  14721. fragments in the buffer.
  14722. With a `\\[universal-argument] \\[universal-argument] \
  14723. \\[universal-argument]' prefix argument ARG, clear image for all
  14724. fragments in the buffer."
  14725. (interactive "P")
  14726. (cond
  14727. ((not (display-graphic-p)) nil)
  14728. ;; Clear whole buffer.
  14729. ((equal arg '(64))
  14730. (org-clear-latex-preview (point-min) (point-max))
  14731. (message "LaTeX previews removed from buffer"))
  14732. ;; Preview whole buffer.
  14733. ((equal arg '(16))
  14734. (message "Creating LaTeX previews in buffer...")
  14735. (org--latex-preview-region (point-min) (point-max))
  14736. (message "Creating LaTeX previews in buffer... done."))
  14737. ;; Clear current section.
  14738. ((equal arg '(4))
  14739. (org-clear-latex-preview
  14740. (if (org-before-first-heading-p) (point-min)
  14741. (save-excursion
  14742. (org-with-limited-levels (org-back-to-heading t) (point))))
  14743. (org-with-limited-levels (org-entry-end-position))))
  14744. ;; Toggle preview on LaTeX code at point.
  14745. ((let ((datum (org-element-context)))
  14746. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14747. (let ((beg (org-element-property :begin datum))
  14748. (end (org-element-property :end datum)))
  14749. (if (org-clear-latex-preview beg end)
  14750. (message "LaTeX preview removed")
  14751. (message "Creating LaTeX preview...")
  14752. (org--latex-preview-region beg end)
  14753. (message "Creating LaTeX preview... done."))
  14754. t))))
  14755. ;; Preview current section.
  14756. (t
  14757. (let ((beg (if (org-before-first-heading-p) (point-min)
  14758. (save-excursion
  14759. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14760. (end (org-with-limited-levels (org-entry-end-position))))
  14761. (message "Creating LaTeX previews in section...")
  14762. (org--latex-preview-region beg end)
  14763. (message "Creating LaTeX previews in section... done.")))))
  14764. (defun org-format-latex
  14765. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14766. "Replace LaTeX fragments with links to an image.
  14767. The function takes care of creating the replacement image.
  14768. Only consider fragments between BEG and END when those are
  14769. provided.
  14770. When optional argument OVERLAYS is non-nil, display the image on
  14771. top of the fragment instead of replacing it.
  14772. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14773. Some of the options can be changed using the variable
  14774. `org-format-latex-options', which see."
  14775. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14776. (unless (eq processing-type 'verbatim)
  14777. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14778. (cnt 0)
  14779. checkdir-flag)
  14780. (goto-char (or beg (point-min)))
  14781. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14782. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14783. (overlay-recenter (or end (point-max))))
  14784. (while (re-search-forward math-regexp end t)
  14785. (unless (and overlays
  14786. (eq (get-char-property (point) 'org-overlay-type)
  14787. 'org-latex-overlay))
  14788. (let* ((context (org-element-context))
  14789. (type (org-element-type context)))
  14790. (when (memq type '(latex-environment latex-fragment))
  14791. (let ((block-type (eq type 'latex-environment))
  14792. (value (org-element-property :value context))
  14793. (beg (org-element-property :begin context))
  14794. (end (save-excursion
  14795. (goto-char (org-element-property :end context))
  14796. (skip-chars-backward " \r\t\n")
  14797. (point))))
  14798. (cond
  14799. ((eq processing-type 'mathjax)
  14800. ;; Prepare for MathJax processing.
  14801. (if (not (string-match "\\`\\$\\$?" value))
  14802. (goto-char end)
  14803. (delete-region beg end)
  14804. (if (string= (match-string 0 value) "$$")
  14805. (insert "\\[" (substring value 2 -2) "\\]")
  14806. (insert "\\(" (substring value 1 -1) "\\)"))))
  14807. ((assq processing-type org-preview-latex-process-alist)
  14808. ;; Process to an image.
  14809. (cl-incf cnt)
  14810. (goto-char beg)
  14811. (let* ((processing-info
  14812. (cdr (assq processing-type org-preview-latex-process-alist)))
  14813. (face (face-at-point))
  14814. ;; Get the colors from the face at point.
  14815. (fg
  14816. (let ((color (plist-get org-format-latex-options
  14817. :foreground)))
  14818. (if (and forbuffer (eq color 'auto))
  14819. (face-attribute face :foreground nil 'default)
  14820. color)))
  14821. (bg
  14822. (let ((color (plist-get org-format-latex-options
  14823. :background)))
  14824. (if (and forbuffer (eq color 'auto))
  14825. (face-attribute face :background nil 'default)
  14826. color)))
  14827. (hash (sha1 (prin1-to-string
  14828. (list org-format-latex-header
  14829. org-latex-default-packages-alist
  14830. org-latex-packages-alist
  14831. org-format-latex-options
  14832. forbuffer value fg bg))))
  14833. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14834. (absprefix (expand-file-name prefix dir))
  14835. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14836. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14837. (sep (and block-type "\n\n"))
  14838. (link (concat sep "[[file:" linkfile "]]" sep))
  14839. (options
  14840. (org-combine-plists
  14841. org-format-latex-options
  14842. `(:foreground ,fg :background ,bg))))
  14843. (when msg (message msg cnt))
  14844. (unless checkdir-flag ; Ensure the directory exists.
  14845. (setq checkdir-flag t)
  14846. (let ((todir (file-name-directory absprefix)))
  14847. (unless (file-directory-p todir)
  14848. (make-directory todir t))))
  14849. (unless (file-exists-p movefile)
  14850. (org-create-formula-image
  14851. value movefile options forbuffer processing-type))
  14852. (if overlays
  14853. (progn
  14854. (dolist (o (overlays-in beg end))
  14855. (when (eq (overlay-get o 'org-overlay-type)
  14856. 'org-latex-overlay)
  14857. (delete-overlay o)))
  14858. (org--make-preview-overlay beg end movefile imagetype)
  14859. (goto-char end))
  14860. (delete-region beg end)
  14861. (insert
  14862. (org-add-props link
  14863. (list 'org-latex-src
  14864. (replace-regexp-in-string "\"" "" value)
  14865. 'org-latex-src-embed-type
  14866. (if block-type 'paragraph 'character)))))))
  14867. ((eq processing-type 'mathml)
  14868. ;; Process to MathML.
  14869. (unless (org-format-latex-mathml-available-p)
  14870. (user-error "LaTeX to MathML converter not configured"))
  14871. (cl-incf cnt)
  14872. (when msg (message msg cnt))
  14873. (goto-char beg)
  14874. (delete-region beg end)
  14875. (insert (org-format-latex-as-mathml
  14876. value block-type prefix dir)))
  14877. (t
  14878. (error "Unknown conversion process %s for LaTeX fragments"
  14879. processing-type)))))))))))
  14880. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14881. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14882. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14883. successful, return the portion between \"<math...> </math>\"
  14884. elements otherwise return nil. When MATHML-FILE is specified,
  14885. write the results in to that file. When invoked as an
  14886. interactive command, prompt for LATEX-FRAG, with initial value
  14887. set to the current active region and echo the results for user
  14888. inspection."
  14889. (interactive (list (let ((frag (when (org-region-active-p)
  14890. (buffer-substring-no-properties
  14891. (region-beginning) (region-end)))))
  14892. (read-string "LaTeX Fragment: " frag nil frag))))
  14893. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14894. (let* ((tmp-in-file
  14895. (let ((file (file-relative-name
  14896. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14897. (write-region latex-frag nil file)
  14898. file))
  14899. (tmp-out-file (file-relative-name
  14900. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14901. (cmd (format-spec
  14902. org-latex-to-mathml-convert-command
  14903. `((?j . ,(and org-latex-to-mathml-jar-file
  14904. (shell-quote-argument
  14905. (expand-file-name
  14906. org-latex-to-mathml-jar-file))))
  14907. (?I . ,(shell-quote-argument tmp-in-file))
  14908. (?i . ,latex-frag)
  14909. (?o . ,(shell-quote-argument tmp-out-file)))))
  14910. mathml shell-command-output)
  14911. (when (called-interactively-p 'any)
  14912. (unless (org-format-latex-mathml-available-p)
  14913. (user-error "LaTeX to MathML converter not configured")))
  14914. (message "Running %s" cmd)
  14915. (setq shell-command-output (shell-command-to-string cmd))
  14916. (setq mathml
  14917. (when (file-readable-p tmp-out-file)
  14918. (with-current-buffer (find-file-noselect tmp-out-file t)
  14919. (goto-char (point-min))
  14920. (when (re-search-forward
  14921. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14922. (regexp-quote
  14923. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14924. nil t)
  14925. (prog1 (match-string 0) (kill-buffer))))))
  14926. (cond
  14927. (mathml
  14928. (setq mathml
  14929. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14930. (when mathml-file
  14931. (write-region mathml nil mathml-file))
  14932. (when (called-interactively-p 'any)
  14933. (message mathml)))
  14934. ((message "LaTeX to MathML conversion failed")
  14935. (message shell-command-output)))
  14936. (delete-file tmp-in-file)
  14937. (when (file-exists-p tmp-out-file)
  14938. (delete-file tmp-out-file))
  14939. mathml))
  14940. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14941. prefix &optional dir)
  14942. "Use `org-create-math-formula' but check local cache first."
  14943. (let* ((absprefix (expand-file-name prefix dir))
  14944. (print-length nil) (print-level nil)
  14945. (formula-id (concat
  14946. "formula-"
  14947. (sha1
  14948. (prin1-to-string
  14949. (list latex-frag
  14950. org-latex-to-mathml-convert-command)))))
  14951. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14952. (formula-cache-dir (file-name-directory formula-cache)))
  14953. (unless (file-directory-p formula-cache-dir)
  14954. (make-directory formula-cache-dir t))
  14955. (unless (file-exists-p formula-cache)
  14956. (org-create-math-formula latex-frag formula-cache))
  14957. (if (file-exists-p formula-cache)
  14958. ;; Successful conversion. Return the link to MathML file.
  14959. (org-add-props
  14960. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14961. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14962. 'org-latex-src-embed-type (if latex-frag-type
  14963. 'paragraph 'character)))
  14964. ;; Failed conversion. Return the LaTeX fragment verbatim
  14965. latex-frag)))
  14966. (defun org--get-display-dpi ()
  14967. "Get the DPI of the display.
  14968. The function assumes that the display has the same pixel width in
  14969. the horizontal and vertical directions."
  14970. (if (display-graphic-p)
  14971. (round (/ (display-pixel-height)
  14972. (/ (display-mm-height) 25.4)))
  14973. (error "Attempt to calculate the dpi of a non-graphic display")))
  14974. (defun org-create-formula-image
  14975. (string tofile options buffer &optional processing-type)
  14976. "Create an image from LaTeX source using external processes.
  14977. The LaTeX STRING is saved to a temporary LaTeX file, then
  14978. converted to an image file by process PROCESSING-TYPE defined in
  14979. `org-preview-latex-process-alist'. A nil value defaults to
  14980. `org-preview-latex-default-process'.
  14981. The generated image file is eventually moved to TOFILE.
  14982. The OPTIONS argument controls the size, foreground color and
  14983. background color of the generated image.
  14984. When BUFFER non-nil, this function is used for LaTeX previewing.
  14985. Otherwise, it is used to deal with LaTeX snippets showed in
  14986. a HTML file."
  14987. (let* ((processing-type (or processing-type
  14988. org-preview-latex-default-process))
  14989. (processing-info
  14990. (cdr (assq processing-type org-preview-latex-process-alist)))
  14991. (programs (plist-get processing-info :programs))
  14992. (error-message (or (plist-get processing-info :message) ""))
  14993. (image-input-type (plist-get processing-info :image-input-type))
  14994. (image-output-type (plist-get processing-info :image-output-type))
  14995. (post-clean (or (plist-get processing-info :post-clean)
  14996. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14997. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14998. (latex-header
  14999. (or (plist-get processing-info :latex-header)
  15000. (org-latex-make-preamble
  15001. (org-export-get-environment (org-export-get-backend 'latex))
  15002. org-format-latex-header
  15003. 'snippet)))
  15004. (latex-compiler (plist-get processing-info :latex-compiler))
  15005. (image-converter (plist-get processing-info :image-converter))
  15006. (tmpdir temporary-file-directory)
  15007. (texfilebase (make-temp-name
  15008. (expand-file-name "orgtex" tmpdir)))
  15009. (texfile (concat texfilebase ".tex"))
  15010. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15011. '(1.0 . 1.0)))
  15012. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15013. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15014. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15015. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15016. "Black"))
  15017. (bg (or (plist-get options (if buffer :background :html-background))
  15018. "Transparent"))
  15019. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15020. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15021. (dolist (program programs)
  15022. (org-check-external-command program error-message))
  15023. (if (eq fg 'default)
  15024. (setq fg (org-latex-color :foreground))
  15025. (setq fg (org-latex-color-format fg)))
  15026. (if (eq bg 'default)
  15027. (setq bg (org-latex-color :background))
  15028. (setq bg (org-latex-color-format
  15029. (if (string= bg "Transparent") "white" bg))))
  15030. (with-temp-file texfile
  15031. (insert latex-header)
  15032. (insert "\n\\begin{document}\n"
  15033. "\\definecolor{fg}{rgb}{" fg "}\n"
  15034. "\\definecolor{bg}{rgb}{" bg "}\n"
  15035. "\n\\pagecolor{bg}\n"
  15036. "\n{\\color{fg}\n"
  15037. string
  15038. "\n}\n"
  15039. "\n\\end{document}\n"))
  15040. (let* ((err-msg (format "Please adjust `%s' part of \
  15041. `org-preview-latex-process-alist'."
  15042. processing-type))
  15043. (image-input-file
  15044. (org-compile-file
  15045. texfile latex-compiler image-input-type err-msg log-buf))
  15046. (image-output-file
  15047. (org-compile-file
  15048. image-input-file image-converter image-output-type err-msg log-buf
  15049. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15050. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15051. (copy-file image-output-file tofile 'replace)
  15052. (dolist (e post-clean)
  15053. (when (file-exists-p (concat texfilebase e))
  15054. (delete-file (concat texfilebase e))))
  15055. image-output-file)))
  15056. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15057. "Fill a LaTeX header template TPL.
  15058. In the template, the following place holders will be recognized:
  15059. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15060. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15061. [PACKAGES] \\usepackage statements for PKG
  15062. [NO-PACKAGES] do not include PKG
  15063. [EXTRA] the string EXTRA
  15064. [NO-EXTRA] do not include EXTRA
  15065. For backward compatibility, if both the positive and the negative place
  15066. holder is missing, the positive one (without the \"NO-\") will be
  15067. assumed to be present at the end of the template.
  15068. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15069. EXTRA is a string.
  15070. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15071. (let (rpl (end ""))
  15072. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15073. (setq rpl (if (or (match-end 1) (not def-pkg))
  15074. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15075. tpl (replace-match rpl t t tpl))
  15076. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15077. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15078. (setq rpl (if (or (match-end 1) (not pkg))
  15079. "" (org-latex-packages-to-string pkg snippets-p t))
  15080. tpl (replace-match rpl t t tpl))
  15081. (when pkg (setq end
  15082. (concat end "\n"
  15083. (org-latex-packages-to-string pkg snippets-p)))))
  15084. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15085. (setq rpl (if (or (match-end 1) (not extra))
  15086. "" (concat extra "\n"))
  15087. tpl (replace-match rpl t t tpl))
  15088. (when (and extra (string-match "\\S-" extra))
  15089. (setq end (concat end "\n" extra))))
  15090. (if (string-match "\\S-" end)
  15091. (concat tpl "\n" end)
  15092. tpl)))
  15093. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15094. "Turn an alist of packages into a string with the \\usepackage macros."
  15095. (setq pkg (mapconcat (lambda(p)
  15096. (cond
  15097. ((stringp p) p)
  15098. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15099. (format "%% Package %s omitted" (cadr p)))
  15100. ((equal "" (car p))
  15101. (format "\\usepackage{%s}" (cadr p)))
  15102. (t
  15103. (format "\\usepackage[%s]{%s}"
  15104. (car p) (cadr p)))))
  15105. pkg
  15106. "\n"))
  15107. (if newline (concat pkg "\n") pkg))
  15108. (defun org-dvipng-color (attr)
  15109. "Return a RGB color specification for dvipng."
  15110. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15111. (defun org-dvipng-color-format (color-name)
  15112. "Convert COLOR-NAME to a RGB color value for dvipng."
  15113. (apply #'format "rgb %s %s %s"
  15114. (mapcar 'org-normalize-color
  15115. (color-values color-name))))
  15116. (defun org-latex-color (attr)
  15117. "Return a RGB color for the LaTeX color package."
  15118. (org-latex-color-format (face-attribute 'default attr nil)))
  15119. (defun org-latex-color-format (color-name)
  15120. "Convert COLOR-NAME to a RGB color value."
  15121. (apply #'format "%s,%s,%s"
  15122. (mapcar 'org-normalize-color
  15123. (color-values color-name))))
  15124. (defun org-normalize-color (value)
  15125. "Return string to be used as color value for an RGB component."
  15126. (format "%g" (/ value 65535.0)))
  15127. ;; Image display
  15128. (defvar-local org-inline-image-overlays nil)
  15129. (defun org-toggle-inline-images (&optional include-linked)
  15130. "Toggle the display of inline images.
  15131. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15132. (interactive "P")
  15133. (if org-inline-image-overlays
  15134. (progn
  15135. (org-remove-inline-images)
  15136. (when (called-interactively-p 'interactive)
  15137. (message "Inline image display turned off")))
  15138. (org-display-inline-images include-linked)
  15139. (when (called-interactively-p 'interactive)
  15140. (message (if org-inline-image-overlays
  15141. (format "%d images displayed inline"
  15142. (length org-inline-image-overlays))
  15143. "No images to display inline")))))
  15144. (defun org-redisplay-inline-images ()
  15145. "Refresh the display of inline images."
  15146. (interactive)
  15147. (if (not org-inline-image-overlays)
  15148. (org-toggle-inline-images)
  15149. (org-toggle-inline-images)
  15150. (org-toggle-inline-images)))
  15151. ;; For without-x builds.
  15152. (declare-function image-refresh "image" (spec &optional frame))
  15153. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15154. "Display inline images.
  15155. An inline image is a link which follows either of these
  15156. conventions:
  15157. 1. Its path is a file with an extension matching return value
  15158. from `image-file-name-regexp' and it has no contents.
  15159. 2. Its description consists in a single link of the previous
  15160. type. In this case, that link must be a well-formed plain
  15161. or angle link, i.e., it must have an explicit \"file\" type.
  15162. Equip each image with the key-map `image-map'.
  15163. When optional argument INCLUDE-LINKED is non-nil, also links with
  15164. a text description part will be inlined. This can be nice for
  15165. a quick look at those images, but it does not reflect what
  15166. exported files will look like.
  15167. When optional argument REFRESH is non-nil, refresh existing
  15168. images between BEG and END. This will create new image displays
  15169. only if necessary. BEG and END default to the buffer
  15170. boundaries."
  15171. (interactive "P")
  15172. (when (display-graphic-p)
  15173. (unless refresh
  15174. (org-remove-inline-images)
  15175. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15176. (org-with-point-at (or beg 1)
  15177. (let* ((case-fold-search t)
  15178. (file-extension-re (image-file-name-regexp))
  15179. (link-abbrevs (mapcar #'car
  15180. (append org-link-abbrev-alist-local
  15181. org-link-abbrev-alist)))
  15182. ;; Check absolute, relative file names and explicit
  15183. ;; "file:" links. Also check link abbreviations since
  15184. ;; some might expand to "file" links.
  15185. (file-types-re
  15186. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15187. (if (not link-abbrevs) ""
  15188. (concat "\\|" (regexp-opt link-abbrevs))))))
  15189. (while (re-search-forward file-types-re end t)
  15190. (let* ((link (org-element-lineage
  15191. (save-match-data (org-element-context))
  15192. '(link) t))
  15193. (linktype (org-element-property :type link))
  15194. (inner-start (match-beginning 1))
  15195. (path
  15196. (cond
  15197. ;; No link at point; no inline image.
  15198. ((not link) nil)
  15199. ;; File link without a description. Also handle
  15200. ;; INCLUDE-LINKED here since it should have
  15201. ;; precedence over the next case. I.e., if link
  15202. ;; contains filenames in both the path and the
  15203. ;; description, prioritize the path only when
  15204. ;; INCLUDE-LINKED is non-nil.
  15205. ((or (not (org-element-property :contents-begin link))
  15206. include-linked)
  15207. (and (or (equal "file" linktype)
  15208. (equal "attachment" linktype))
  15209. (org-element-property :path link)))
  15210. ;; Link with a description. Check if description
  15211. ;; is a filename. Even if Org doesn't have syntax
  15212. ;; for those -- clickable image -- constructs, fake
  15213. ;; them, as in `org-export-insert-image-links'.
  15214. ((not inner-start) nil)
  15215. (t
  15216. (org-with-point-at inner-start
  15217. (and (looking-at
  15218. (if (char-equal ?< (char-after inner-start))
  15219. org-link-angle-re
  15220. org-link-plain-re))
  15221. ;; File name must fill the whole
  15222. ;; description.
  15223. (= (org-element-property :contents-end link)
  15224. (match-end 0))
  15225. (match-string 2)))))))
  15226. (when (and path (string-match-p file-extension-re path))
  15227. (let ((file (if (equal "attachment" linktype)
  15228. (progn
  15229. (require 'org-attach)
  15230. (ignore-errors (org-attach-expand path)))
  15231. (expand-file-name path))))
  15232. (when (and file (file-exists-p file))
  15233. (let ((width
  15234. ;; Apply `org-image-actual-width' specifications.
  15235. (cond
  15236. ((eq org-image-actual-width t) nil)
  15237. ((listp org-image-actual-width)
  15238. (or
  15239. ;; First try to find a width among
  15240. ;; attributes associated to the paragraph
  15241. ;; containing link.
  15242. (pcase (org-element-lineage link '(paragraph))
  15243. (`nil nil)
  15244. (p
  15245. (let* ((case-fold-search t)
  15246. (end (org-element-property :post-affiliated p))
  15247. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15248. (when (org-with-point-at
  15249. (org-element-property :begin p)
  15250. (re-search-forward re end t))
  15251. (string-to-number (match-string 1))))))
  15252. ;; Otherwise, fall-back to provided number.
  15253. (car org-image-actual-width)))
  15254. ((numberp org-image-actual-width)
  15255. org-image-actual-width)
  15256. (t nil)))
  15257. (old (get-char-property-and-overlay
  15258. (org-element-property :begin link)
  15259. 'org-image-overlay)))
  15260. (if (and (car-safe old) refresh)
  15261. (image-refresh (overlay-get (cdr old) 'display))
  15262. (let ((image (create-image file
  15263. (and (image-type-available-p 'imagemagick) 'imagemagick)
  15264. nil
  15265. :width width)))
  15266. (when image
  15267. (let ((ov (make-overlay
  15268. (org-element-property :begin link)
  15269. (progn
  15270. (goto-char
  15271. (org-element-property :end link))
  15272. (skip-chars-backward " \t")
  15273. (point)))))
  15274. (overlay-put ov 'display image)
  15275. (overlay-put ov 'face 'default)
  15276. (overlay-put ov 'org-image-overlay t)
  15277. (overlay-put
  15278. ov 'modification-hooks
  15279. (list 'org-display-inline-remove-overlay))
  15280. (overlay-put ov 'keymap image-map)
  15281. (push ov org-inline-image-overlays)))))))))))))))
  15282. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15283. "Remove inline-display overlay if a corresponding region is modified."
  15284. (let ((inhibit-modification-hooks t))
  15285. (when (and ov after)
  15286. (delete ov org-inline-image-overlays)
  15287. (delete-overlay ov))))
  15288. (defun org-remove-inline-images ()
  15289. "Remove inline display of images."
  15290. (interactive)
  15291. (mapc #'delete-overlay org-inline-image-overlays)
  15292. (setq org-inline-image-overlays nil))
  15293. (defvar org-self-insert-command-undo-counter 0)
  15294. (defvar org-speed-command nil)
  15295. (defun org-self-insert-command (N)
  15296. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15297. If the cursor is in a table looking at whitespace, the whitespace is
  15298. overwritten, and the table is not marked as requiring realignment."
  15299. (interactive "p")
  15300. (org-check-before-invisible-edit 'insert)
  15301. (cond
  15302. ((and org-use-speed-commands
  15303. (let ((kv (this-command-keys-vector)))
  15304. (setq org-speed-command
  15305. (run-hook-with-args-until-success
  15306. 'org-speed-command-hook
  15307. (make-string 1 (aref kv (1- (length kv))))))))
  15308. (cond
  15309. ((commandp org-speed-command)
  15310. (setq this-command org-speed-command)
  15311. (call-interactively org-speed-command))
  15312. ((functionp org-speed-command)
  15313. (funcall org-speed-command))
  15314. ((and org-speed-command (listp org-speed-command))
  15315. (eval org-speed-command))
  15316. (t (let (org-use-speed-commands)
  15317. (call-interactively 'org-self-insert-command)))))
  15318. ((and
  15319. (= N 1)
  15320. (not (org-region-active-p))
  15321. (org-at-table-p)
  15322. (progn
  15323. ;; Check if we blank the field, and if that triggers align.
  15324. (and (featurep 'org-table)
  15325. org-table-auto-blank-field
  15326. (memq last-command
  15327. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15328. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15329. ;; Got extra space, this field does not determine
  15330. ;; column width.
  15331. (let (org-table-may-need-update) (org-table-blank-field))
  15332. ;; No extra space, this field may determine column
  15333. ;; width.
  15334. (org-table-blank-field)))
  15335. t)
  15336. (looking-at "[^|\n]* |"))
  15337. ;; There is room for insertion without re-aligning the table.
  15338. (self-insert-command N)
  15339. (org-table-with-shrunk-field
  15340. (save-excursion
  15341. (skip-chars-forward "^|")
  15342. ;; Do not delete last space, which is
  15343. ;; `org-table-separator-space', but the regular space before
  15344. ;; it.
  15345. (delete-region (- (point) 2) (1- (point))))))
  15346. (t
  15347. (setq org-table-may-need-update t)
  15348. (self-insert-command N)
  15349. (org-fix-tags-on-the-fly)
  15350. (when org-self-insert-cluster-for-undo
  15351. (if (not (eq last-command 'org-self-insert-command))
  15352. (setq org-self-insert-command-undo-counter 1)
  15353. (if (>= org-self-insert-command-undo-counter 20)
  15354. (setq org-self-insert-command-undo-counter 1)
  15355. (and (> org-self-insert-command-undo-counter 0)
  15356. buffer-undo-list (listp buffer-undo-list)
  15357. (not (cadr buffer-undo-list)) ; remove nil entry
  15358. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15359. (setq org-self-insert-command-undo-counter
  15360. (1+ org-self-insert-command-undo-counter))))))))
  15361. (defun org-check-before-invisible-edit (kind)
  15362. "Check is editing if kind KIND would be dangerous with invisible text around.
  15363. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15364. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15365. (when (and org-catch-invisible-edits
  15366. (or (not (boundp 'visible-mode)) (not visible-mode))
  15367. (or (get-char-property (point) 'invisible)
  15368. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15369. ;; OK, we need to take a closer look. Do not consider
  15370. ;; invisibility obtained through text properties (e.g., link
  15371. ;; fontification), as it cannot be toggled.
  15372. (let* ((invisible-at-point
  15373. (pcase (get-char-property-and-overlay (point) 'invisible)
  15374. (`(,_ . ,(and (pred overlayp) o)) o)))
  15375. ;; Assume that point cannot land in the middle of an
  15376. ;; overlay, or between two overlays.
  15377. (invisible-before-point
  15378. (and (not invisible-at-point)
  15379. (not (bobp))
  15380. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15381. (`(,_ . ,(and (pred overlayp) o)) o))))
  15382. (border-and-ok-direction
  15383. (or
  15384. ;; Check if we are acting predictably before invisible
  15385. ;; text.
  15386. (and invisible-at-point
  15387. (memq kind '(insert delete-backward)))
  15388. ;; Check if we are acting predictably after invisible text
  15389. ;; This works not well, and I have turned it off. It seems
  15390. ;; better to always show and stop after invisible text.
  15391. ;; (and (not invisible-at-point) invisible-before-point
  15392. ;; (memq kind '(insert delete)))
  15393. )))
  15394. (when (or invisible-at-point invisible-before-point)
  15395. (when (eq org-catch-invisible-edits 'error)
  15396. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15397. (if (and org-custom-properties-overlays
  15398. (y-or-n-p "Display invisible properties in this buffer? "))
  15399. (org-toggle-custom-properties-visibility)
  15400. ;; Make the area visible
  15401. (save-excursion
  15402. (when invisible-before-point
  15403. (goto-char
  15404. (previous-single-char-property-change (point) 'invisible)))
  15405. ;; Remove whatever overlay is currently making yet-to-be
  15406. ;; edited text invisible. Also remove nested invisibility
  15407. ;; related overlays.
  15408. (delete-overlay (or invisible-at-point invisible-before-point))
  15409. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15410. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15411. (`(,_ . ,(and (pred overlayp) o))
  15412. (delete-overlay o)
  15413. t)))))
  15414. (cond
  15415. ((eq org-catch-invisible-edits 'show)
  15416. ;; That's it, we do the edit after showing
  15417. (message
  15418. "Unfolding invisible region around point before editing")
  15419. (sit-for 1))
  15420. ((and (eq org-catch-invisible-edits 'smart)
  15421. border-and-ok-direction)
  15422. (message "Unfolding invisible region around point before editing"))
  15423. (t
  15424. ;; Don't do the edit, make the user repeat it in full visibility
  15425. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15426. (defun org-fix-tags-on-the-fly ()
  15427. "Align tags in headline at point.
  15428. Unlike `org-align-tags', this function does nothing if point is
  15429. either not currently on a tagged headline or on a tag."
  15430. (when (and (org-match-line org-tag-line-re)
  15431. (< (point) (match-beginning 1)))
  15432. (org-align-tags)))
  15433. (defun org-delete-backward-char (N)
  15434. "Like `delete-backward-char', insert whitespace at field end in tables.
  15435. When deleting backwards, in tables this function will insert whitespace in
  15436. front of the next \"|\" separator, to keep the table aligned. The table will
  15437. still be marked for re-alignment if the field did fill the entire column,
  15438. because, in this case the deletion might narrow the column."
  15439. (interactive "p")
  15440. (save-match-data
  15441. (org-check-before-invisible-edit 'delete-backward)
  15442. (if (and (= N 1)
  15443. (not overwrite-mode)
  15444. (not (org-region-active-p))
  15445. (not (eq (char-before) ?|))
  15446. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15447. (looking-at-p ".*?|")
  15448. (org-at-table-p))
  15449. (progn (forward-char -1) (org-delete-char 1))
  15450. (backward-delete-char N)
  15451. (org-fix-tags-on-the-fly))))
  15452. (defun org-delete-char (N)
  15453. "Like `delete-char', but insert whitespace at field end in tables.
  15454. When deleting characters, in tables this function will insert whitespace in
  15455. front of the next \"|\" separator, to keep the table aligned. The table will
  15456. still be marked for re-alignment if the field did fill the entire column,
  15457. because, in this case the deletion might narrow the column."
  15458. (interactive "p")
  15459. (save-match-data
  15460. (org-check-before-invisible-edit 'delete)
  15461. (cond
  15462. ((or (/= N 1)
  15463. (eq (char-after) ?|)
  15464. (save-excursion (skip-chars-backward " \t") (bolp))
  15465. (not (org-at-table-p)))
  15466. (delete-char N)
  15467. (org-fix-tags-on-the-fly))
  15468. ((looking-at ".\\(.*?\\)|")
  15469. (let* ((update? org-table-may-need-update)
  15470. (noalign (looking-at-p ".*? |")))
  15471. (delete-char 1)
  15472. (org-table-with-shrunk-field
  15473. (save-excursion
  15474. ;; Last space is `org-table-separator-space', so insert
  15475. ;; a regular one before it instead.
  15476. (goto-char (- (match-end 0) 2))
  15477. (insert " ")))
  15478. ;; If there were two spaces at the end, this field does not
  15479. ;; determine the width of the column.
  15480. (when noalign (setq org-table-may-need-update update?))))
  15481. (t
  15482. (delete-char N)))))
  15483. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15484. (put 'org-self-insert-command 'delete-selection
  15485. (lambda ()
  15486. (not (run-hook-with-args-until-success
  15487. 'self-insert-uses-region-functions))))
  15488. (put 'orgtbl-self-insert-command 'delete-selection
  15489. (lambda ()
  15490. (not (run-hook-with-args-until-success
  15491. 'self-insert-uses-region-functions))))
  15492. (put 'org-delete-char 'delete-selection 'supersede)
  15493. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15494. (put 'org-yank 'delete-selection 'yank)
  15495. ;; Make `flyspell-mode' delay after some commands
  15496. (put 'org-self-insert-command 'flyspell-delayed t)
  15497. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15498. (put 'org-delete-char 'flyspell-delayed t)
  15499. (put 'org-delete-backward-char 'flyspell-delayed t)
  15500. ;; Make pabbrev-mode expand after Org mode commands
  15501. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15502. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15503. (defun org-transpose-words ()
  15504. "Transpose words for Org.
  15505. This uses the `org-mode-transpose-word-syntax-table' syntax
  15506. table, which interprets characters in `org-emphasis-alist' as
  15507. word constituents."
  15508. (interactive)
  15509. (with-syntax-table org-mode-transpose-word-syntax-table
  15510. (call-interactively 'transpose-words)))
  15511. (defvar org-ctrl-c-ctrl-c-hook nil
  15512. "Hook for functions attaching themselves to `C-c C-c'.
  15513. This can be used to add additional functionality to the C-c C-c
  15514. key which executes context-dependent commands. This hook is run
  15515. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15516. run after the last test.
  15517. Each function will be called with no arguments. The function
  15518. must check if the context is appropriate for it to act. If yes,
  15519. it should do its thing and then return a non-nil value. If the
  15520. context is wrong, just do nothing and return nil.")
  15521. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15522. "Hook for functions attaching themselves to `C-c C-c'.
  15523. This can be used to add additional functionality to the C-c C-c
  15524. key which executes context-dependent commands. This hook is run
  15525. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15526. before the first test.
  15527. Each function will be called with no arguments. The function
  15528. must check if the context is appropriate for it to act. If yes,
  15529. it should do its thing and then return a non-nil value. If the
  15530. context is wrong, just do nothing and return nil.")
  15531. (defvar org-tab-first-hook nil
  15532. "Hook for functions to attach themselves to TAB.
  15533. See `org-ctrl-c-ctrl-c-hook' for more information.
  15534. This hook runs as the first action when TAB is pressed, even before
  15535. `org-cycle' messes around with the `outline-regexp' to cater for
  15536. inline tasks and plain list item folding.
  15537. If any function in this hook returns t, any other actions that
  15538. would have been caused by TAB (such as table field motion or visibility
  15539. cycling) will not occur.")
  15540. (defvar org-tab-after-check-for-table-hook nil
  15541. "Hook for functions to attach themselves to TAB.
  15542. See `org-ctrl-c-ctrl-c-hook' for more information.
  15543. This hook runs after it has been established that the cursor is not in a
  15544. table, but before checking if the cursor is in a headline or if global cycling
  15545. should be done.
  15546. If any function in this hook returns t, not other actions like visibility
  15547. cycling will be done.")
  15548. (defvar org-tab-after-check-for-cycling-hook nil
  15549. "Hook for functions to attach themselves to TAB.
  15550. See `org-ctrl-c-ctrl-c-hook' for more information.
  15551. This hook runs after it has been established that not table field motion and
  15552. not visibility should be done because of current context. This is probably
  15553. the place where a package like yasnippets can hook in.")
  15554. (defvar org-tab-before-tab-emulation-hook nil
  15555. "Hook for functions to attach themselves to TAB.
  15556. See `org-ctrl-c-ctrl-c-hook' for more information.
  15557. This hook runs after every other options for TAB have been exhausted, but
  15558. before indentation and \t insertion takes place.")
  15559. (defvar org-metaleft-hook nil
  15560. "Hook for functions attaching themselves to `M-left'.
  15561. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15562. (defvar org-metaright-hook nil
  15563. "Hook for functions attaching themselves to `M-right'.
  15564. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15565. (defvar org-metaup-hook nil
  15566. "Hook for functions attaching themselves to `M-up'.
  15567. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15568. (defvar org-metadown-hook nil
  15569. "Hook for functions attaching themselves to `M-down'.
  15570. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15571. (defvar org-shiftmetaleft-hook nil
  15572. "Hook for functions attaching themselves to `M-S-left'.
  15573. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15574. (defvar org-shiftmetaright-hook nil
  15575. "Hook for functions attaching themselves to `M-S-right'.
  15576. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15577. (defvar org-shiftmetaup-hook nil
  15578. "Hook for functions attaching themselves to `M-S-up'.
  15579. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15580. (defvar org-shiftmetadown-hook nil
  15581. "Hook for functions attaching themselves to `M-S-down'.
  15582. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15583. (defvar org-metareturn-hook nil
  15584. "Hook for functions attaching themselves to `M-RET'.
  15585. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15586. (defvar org-shiftup-hook nil
  15587. "Hook for functions attaching themselves to `S-up'.
  15588. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15589. (defvar org-shiftup-final-hook nil
  15590. "Hook for functions attaching themselves to `S-up'.
  15591. This one runs after all other options except shift-select have been excluded.
  15592. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15593. (defvar org-shiftdown-hook nil
  15594. "Hook for functions attaching themselves to `S-down'.
  15595. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15596. (defvar org-shiftdown-final-hook nil
  15597. "Hook for functions attaching themselves to `S-down'.
  15598. This one runs after all other options except shift-select have been excluded.
  15599. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15600. (defvar org-shiftleft-hook nil
  15601. "Hook for functions attaching themselves to `S-left'.
  15602. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15603. (defvar org-shiftleft-final-hook nil
  15604. "Hook for functions attaching themselves to `S-left'.
  15605. This one runs after all other options except shift-select have been excluded.
  15606. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15607. (defvar org-shiftright-hook nil
  15608. "Hook for functions attaching themselves to `S-right'.
  15609. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15610. (defvar org-shiftright-final-hook nil
  15611. "Hook for functions attaching themselves to `S-right'.
  15612. This one runs after all other options except shift-select have been excluded.
  15613. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15614. (defun org-modifier-cursor-error ()
  15615. "Throw an error, a modified cursor command was applied in wrong context."
  15616. (user-error "This command is active in special context like tables, headlines or items"))
  15617. (defun org-shiftselect-error ()
  15618. "Throw an error because Shift-Cursor command was applied in wrong context."
  15619. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15620. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15621. (user-error "This command works only in special context like headlines or timestamps")))
  15622. (defun org-call-for-shift-select (cmd)
  15623. (let ((this-command-keys-shift-translated t))
  15624. (call-interactively cmd)))
  15625. (defun org-shifttab (&optional arg)
  15626. "Global visibility cycling or move to previous table field.
  15627. Call `org-table-previous-field' within a table.
  15628. When ARG is nil, cycle globally through visibility states.
  15629. When ARG is a numeric prefix, show contents of this level."
  15630. (interactive "P")
  15631. (cond
  15632. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15633. ((integerp arg)
  15634. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15635. (message "Content view to level: %d" arg)
  15636. (org-content (prefix-numeric-value arg2))
  15637. (org-cycle-show-empty-lines t)
  15638. (setq org-cycle-global-status 'overview)))
  15639. (t (call-interactively 'org-global-cycle))))
  15640. (defun org-shiftmetaleft ()
  15641. "Promote subtree or delete table column.
  15642. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15643. `org-table-delete-column', depending on context. See the
  15644. individual commands for more information."
  15645. (interactive)
  15646. (cond
  15647. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15648. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15649. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15650. ((if (not (org-region-active-p)) (org-at-item-p)
  15651. (save-excursion (goto-char (region-beginning))
  15652. (org-at-item-p)))
  15653. (call-interactively 'org-outdent-item-tree))
  15654. (t (org-modifier-cursor-error))))
  15655. (defun org-shiftmetaright ()
  15656. "Demote subtree or insert table column.
  15657. Calls `org-demote-subtree', `org-indent-item-tree', or
  15658. `org-table-insert-column', depending on context. See the
  15659. individual commands for more information."
  15660. (interactive)
  15661. (cond
  15662. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15663. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15664. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15665. ((if (not (org-region-active-p)) (org-at-item-p)
  15666. (save-excursion (goto-char (region-beginning))
  15667. (org-at-item-p)))
  15668. (call-interactively 'org-indent-item-tree))
  15669. (t (org-modifier-cursor-error))))
  15670. (defun org-shiftmetaup (&optional _arg)
  15671. "Drag the line at point up.
  15672. In a table, kill the current row.
  15673. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15674. but also adjust the previous clocked item in the clock history.
  15675. Everywhere else, drag the line at point up."
  15676. (interactive "P")
  15677. (cond
  15678. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15679. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15680. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15681. (call-interactively 'org-timestamp-up)))
  15682. (t (call-interactively 'org-drag-line-backward))))
  15683. (defun org-shiftmetadown (&optional _arg)
  15684. "Drag the line at point down.
  15685. In a table, insert an empty row at the current line.
  15686. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15687. but also adjust the previous clocked item in the clock history.
  15688. Everywhere else, drag the line at point down."
  15689. (interactive "P")
  15690. (cond
  15691. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15692. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15693. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15694. (call-interactively 'org-timestamp-down)))
  15695. (t (call-interactively 'org-drag-line-forward))))
  15696. (defsubst org-hidden-tree-error ()
  15697. (user-error
  15698. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15699. (defun org-metaleft (&optional _arg)
  15700. "Promote heading, list item at point or move table column left.
  15701. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15702. depending on context. With no specific context, calls the Emacs
  15703. default `backward-word'. See the individual commands for more
  15704. information.
  15705. This function runs the hook `org-metaleft-hook' as a first step,
  15706. and returns at first non-nil value."
  15707. (interactive "P")
  15708. (cond
  15709. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15710. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15711. ((org-with-limited-levels
  15712. (or (org-at-heading-p)
  15713. (and (org-region-active-p)
  15714. (save-excursion
  15715. (goto-char (region-beginning))
  15716. (org-at-heading-p)))))
  15717. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15718. (call-interactively 'org-do-promote))
  15719. ;; At an inline task.
  15720. ((org-at-heading-p)
  15721. (call-interactively 'org-inlinetask-promote))
  15722. ((or (org-at-item-p)
  15723. (and (org-region-active-p)
  15724. (save-excursion
  15725. (goto-char (region-beginning))
  15726. (org-at-item-p))))
  15727. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15728. (call-interactively 'org-outdent-item))
  15729. (t (call-interactively 'backward-word))))
  15730. (defun org-metaright (&optional _arg)
  15731. "Demote heading, list item at point or move table column right.
  15732. In front of a drawer or a block keyword, indent it correctly.
  15733. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15734. `org-indent-drawer' or `org-indent-block' depending on context.
  15735. With no specific context, calls the Emacs default `forward-word'.
  15736. See the individual commands for more information.
  15737. This function runs the hook `org-metaright-hook' as a first step,
  15738. and returns at first non-nil value."
  15739. (interactive "P")
  15740. (cond
  15741. ((run-hook-with-args-until-success 'org-metaright-hook))
  15742. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15743. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15744. ((org-at-block-p) (call-interactively 'org-indent-block))
  15745. ((org-with-limited-levels
  15746. (or (org-at-heading-p)
  15747. (and (org-region-active-p)
  15748. (save-excursion
  15749. (goto-char (region-beginning))
  15750. (org-at-heading-p)))))
  15751. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15752. (call-interactively 'org-do-demote))
  15753. ;; At an inline task.
  15754. ((org-at-heading-p)
  15755. (call-interactively 'org-inlinetask-demote))
  15756. ((or (org-at-item-p)
  15757. (and (org-region-active-p)
  15758. (save-excursion
  15759. (goto-char (region-beginning))
  15760. (org-at-item-p))))
  15761. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15762. (call-interactively 'org-indent-item))
  15763. (t (call-interactively 'forward-word))))
  15764. (defun org-check-for-hidden (what)
  15765. "Check if there are hidden headlines/items in the current visual line.
  15766. WHAT can be either `headlines' or `items'. If the current line is
  15767. an outline or item heading and it has a folded subtree below it,
  15768. this function returns t, nil otherwise."
  15769. (let ((re (cond
  15770. ((eq what 'headlines) org-outline-regexp-bol)
  15771. ((eq what 'items) (org-item-beginning-re))
  15772. (t (error "This should not happen"))))
  15773. beg end)
  15774. (save-excursion
  15775. (catch 'exit
  15776. (unless (org-region-active-p)
  15777. (setq beg (point-at-bol))
  15778. (beginning-of-line 2)
  15779. (while (and (not (eobp)) ;; this is like `next-line'
  15780. (get-char-property (1- (point)) 'invisible))
  15781. (beginning-of-line 2))
  15782. (setq end (point))
  15783. (goto-char beg)
  15784. (goto-char (point-at-eol))
  15785. (setq end (max end (point)))
  15786. (while (re-search-forward re end t)
  15787. (when (get-char-property (match-beginning 0) 'invisible)
  15788. (throw 'exit t))))
  15789. nil))))
  15790. (defun org-metaup (&optional _arg)
  15791. "Move subtree up or move table row up.
  15792. Calls `org-move-subtree-up' or `org-table-move-row' or
  15793. `org-move-item-up', depending on context. See the individual commands
  15794. for more information."
  15795. (interactive "P")
  15796. (cond
  15797. ((run-hook-with-args-until-success 'org-metaup-hook))
  15798. ((org-region-active-p)
  15799. (let* ((a (save-excursion
  15800. (goto-char (min (region-beginning) (region-end)))
  15801. (line-beginning-position)))
  15802. (b (save-excursion
  15803. (goto-char (max (region-beginning) (region-end)))
  15804. (if (bolp) (1- (point)) (line-end-position))))
  15805. (c (save-excursion
  15806. (goto-char a)
  15807. (move-beginning-of-line 0)
  15808. (point)))
  15809. (d (save-excursion
  15810. (goto-char a)
  15811. (move-end-of-line 0)
  15812. (point))))
  15813. (transpose-regions a b c d)
  15814. (goto-char c)))
  15815. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15816. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15817. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15818. (t (org-drag-element-backward))))
  15819. (defun org-metadown (&optional _arg)
  15820. "Move subtree down or move table row down.
  15821. Calls `org-move-subtree-down' or `org-table-move-row' or
  15822. `org-move-item-down', depending on context. See the individual
  15823. commands for more information."
  15824. (interactive "P")
  15825. (cond
  15826. ((run-hook-with-args-until-success 'org-metadown-hook))
  15827. ((org-region-active-p)
  15828. (let* ((a (save-excursion
  15829. (goto-char (min (region-beginning) (region-end)))
  15830. (line-beginning-position)))
  15831. (b (save-excursion
  15832. (goto-char (max (region-beginning) (region-end)))
  15833. (if (bolp) (1- (point)) (line-end-position))))
  15834. (c (save-excursion
  15835. (goto-char b)
  15836. (move-beginning-of-line (if (bolp) 1 2))
  15837. (point)))
  15838. (d (save-excursion
  15839. (goto-char b)
  15840. (move-end-of-line (if (bolp) 1 2))
  15841. (point))))
  15842. (transpose-regions a b c d)
  15843. (goto-char d)))
  15844. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15845. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15846. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15847. (t (org-drag-element-forward))))
  15848. (defun org-shiftup (&optional arg)
  15849. "Act on current element according to context.
  15850. Call `org-timestamp-up' or `org-priority-up', or
  15851. `org-previous-item', or `org-table-move-cell-up'. See the
  15852. individual commands for more information."
  15853. (interactive "P")
  15854. (cond
  15855. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15856. ((and org-support-shift-select (org-region-active-p))
  15857. (org-call-for-shift-select 'previous-line))
  15858. ((org-at-timestamp-p 'lax)
  15859. (call-interactively (if org-edit-timestamp-down-means-later
  15860. 'org-timestamp-down 'org-timestamp-up)))
  15861. ((and (not (eq org-support-shift-select 'always))
  15862. org-enable-priority-commands
  15863. (org-at-heading-p))
  15864. (call-interactively 'org-priority-up))
  15865. ((and (not org-support-shift-select) (org-at-item-p))
  15866. (call-interactively 'org-previous-item))
  15867. ((org-clocktable-try-shift 'up arg))
  15868. ((org-at-table-p) (org-table-move-cell-up))
  15869. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15870. (org-support-shift-select
  15871. (org-call-for-shift-select 'previous-line))
  15872. (t (org-shiftselect-error))))
  15873. (defun org-shiftdown (&optional arg)
  15874. "Act on current element according to context.
  15875. Call `org-timestamp-down' or `org-priority-down', or
  15876. `org-next-item', or `org-table-move-cell-down'. See the
  15877. individual commands for more information."
  15878. (interactive "P")
  15879. (cond
  15880. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15881. ((and org-support-shift-select (org-region-active-p))
  15882. (org-call-for-shift-select 'next-line))
  15883. ((org-at-timestamp-p 'lax)
  15884. (call-interactively (if org-edit-timestamp-down-means-later
  15885. 'org-timestamp-up 'org-timestamp-down)))
  15886. ((and (not (eq org-support-shift-select 'always))
  15887. org-enable-priority-commands
  15888. (org-at-heading-p))
  15889. (call-interactively 'org-priority-down))
  15890. ((and (not org-support-shift-select) (org-at-item-p))
  15891. (call-interactively 'org-next-item))
  15892. ((org-clocktable-try-shift 'down arg))
  15893. ((org-at-table-p) (org-table-move-cell-down))
  15894. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15895. (org-support-shift-select
  15896. (org-call-for-shift-select 'next-line))
  15897. (t (org-shiftselect-error))))
  15898. (defun org-shiftright (&optional arg)
  15899. "Act on the current element according to context.
  15900. This does one of the following:
  15901. - switch a timestamp at point one day into the future
  15902. - on a headline, switch to the next TODO keyword
  15903. - on an item, switch entire list to the next bullet type
  15904. - on a property line, switch to the next allowed value
  15905. - on a clocktable definition line, move time block into the future
  15906. - in a table, move a single cell right"
  15907. (interactive "P")
  15908. (cond
  15909. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15910. ((and org-support-shift-select (org-region-active-p))
  15911. (org-call-for-shift-select 'forward-char))
  15912. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15913. ((and (not (eq org-support-shift-select 'always))
  15914. (org-at-heading-p))
  15915. (let ((org-inhibit-logging
  15916. (not org-treat-S-cursor-todo-selection-as-state-change))
  15917. (org-inhibit-blocking
  15918. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15919. (org-call-with-arg 'org-todo 'right)))
  15920. ((or (and org-support-shift-select
  15921. (not (eq org-support-shift-select 'always))
  15922. (org-at-item-bullet-p))
  15923. (and (not org-support-shift-select) (org-at-item-p)))
  15924. (org-call-with-arg 'org-cycle-list-bullet nil))
  15925. ((and (not (eq org-support-shift-select 'always))
  15926. (org-at-property-p))
  15927. (call-interactively 'org-property-next-allowed-value))
  15928. ((org-clocktable-try-shift 'right arg))
  15929. ((org-at-table-p) (org-table-move-cell-right))
  15930. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15931. (org-support-shift-select
  15932. (org-call-for-shift-select 'forward-char))
  15933. (t (org-shiftselect-error))))
  15934. (defun org-shiftleft (&optional arg)
  15935. "Act on current element according to context.
  15936. This does one of the following:
  15937. - switch a timestamp at point one day into the past
  15938. - on a headline, switch to the previous TODO keyword.
  15939. - on an item, switch entire list to the previous bullet type
  15940. - on a property line, switch to the previous allowed value
  15941. - on a clocktable definition line, move time block into the past
  15942. - in a table, move a single cell left"
  15943. (interactive "P")
  15944. (cond
  15945. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15946. ((and org-support-shift-select (org-region-active-p))
  15947. (org-call-for-shift-select 'backward-char))
  15948. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15949. ((and (not (eq org-support-shift-select 'always))
  15950. (org-at-heading-p))
  15951. (let ((org-inhibit-logging
  15952. (not org-treat-S-cursor-todo-selection-as-state-change))
  15953. (org-inhibit-blocking
  15954. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15955. (org-call-with-arg 'org-todo 'left)))
  15956. ((or (and org-support-shift-select
  15957. (not (eq org-support-shift-select 'always))
  15958. (org-at-item-bullet-p))
  15959. (and (not org-support-shift-select) (org-at-item-p)))
  15960. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15961. ((and (not (eq org-support-shift-select 'always))
  15962. (org-at-property-p))
  15963. (call-interactively 'org-property-previous-allowed-value))
  15964. ((org-clocktable-try-shift 'left arg))
  15965. ((org-at-table-p) (org-table-move-cell-left))
  15966. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15967. (org-support-shift-select
  15968. (org-call-for-shift-select 'backward-char))
  15969. (t (org-shiftselect-error))))
  15970. (defun org-shiftcontrolright ()
  15971. "Switch to next TODO set."
  15972. (interactive)
  15973. (cond
  15974. ((and org-support-shift-select (org-region-active-p))
  15975. (org-call-for-shift-select 'forward-word))
  15976. ((and (not (eq org-support-shift-select 'always))
  15977. (org-at-heading-p))
  15978. (org-call-with-arg 'org-todo 'nextset))
  15979. (org-support-shift-select
  15980. (org-call-for-shift-select 'forward-word))
  15981. (t (org-shiftselect-error))))
  15982. (defun org-shiftcontrolleft ()
  15983. "Switch to previous TODO set."
  15984. (interactive)
  15985. (cond
  15986. ((and org-support-shift-select (org-region-active-p))
  15987. (org-call-for-shift-select 'backward-word))
  15988. ((and (not (eq org-support-shift-select 'always))
  15989. (org-at-heading-p))
  15990. (org-call-with-arg 'org-todo 'previousset))
  15991. (org-support-shift-select
  15992. (org-call-for-shift-select 'backward-word))
  15993. (t (org-shiftselect-error))))
  15994. (defun org-shiftcontrolup (&optional n)
  15995. "Change timestamps synchronously up in CLOCK log lines.
  15996. Optional argument N tells to change by that many units."
  15997. (interactive "P")
  15998. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15999. (let (org-support-shift-select)
  16000. (org-clock-timestamps-up n))
  16001. (user-error "Not at a clock log")))
  16002. (defun org-shiftcontroldown (&optional n)
  16003. "Change timestamps synchronously down in CLOCK log lines.
  16004. Optional argument N tells to change by that many units."
  16005. (interactive "P")
  16006. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16007. (let (org-support-shift-select)
  16008. (org-clock-timestamps-down n))
  16009. (user-error "Not at a clock log")))
  16010. (defun org-increase-number-at-point (&optional inc)
  16011. "Increment the number at point.
  16012. With an optional prefix numeric argument INC, increment using
  16013. this numeric value."
  16014. (interactive "p")
  16015. (if (not (number-at-point))
  16016. (user-error "Not on a number")
  16017. (unless inc (setq inc 1))
  16018. (let ((pos (point))
  16019. (beg (skip-chars-backward "-+^/*0-9eE."))
  16020. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16021. (setq nap (buffer-substring-no-properties
  16022. (+ pos beg) (+ pos beg end)))
  16023. (delete-region (+ pos beg) (+ pos beg end))
  16024. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16025. (when (org-at-table-p)
  16026. (org-table-align)
  16027. (org-table-end-of-field 1))))
  16028. (defun org-decrease-number-at-point (&optional inc)
  16029. "Decrement the number at point.
  16030. With an optional prefix numeric argument INC, decrement using
  16031. this numeric value."
  16032. (interactive "p")
  16033. (org-increase-number-at-point (- (or inc 1))))
  16034. (defun org-ctrl-c-ret ()
  16035. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16036. (interactive)
  16037. (cond
  16038. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16039. (t (call-interactively 'org-insert-heading))))
  16040. (defun org-find-visible ()
  16041. (let ((s (point)))
  16042. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16043. (get-char-property s 'invisible)))
  16044. s))
  16045. (defun org-find-invisible ()
  16046. (let ((s (point)))
  16047. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16048. (not (get-char-property s 'invisible))))
  16049. s))
  16050. (defun org-copy-visible (beg end)
  16051. "Copy the visible parts of the region."
  16052. (interactive "r")
  16053. (let ((result ""))
  16054. (while (/= beg end)
  16055. (when (get-char-property beg 'invisible)
  16056. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16057. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16058. (setq result (concat result (buffer-substring beg next)))
  16059. (setq beg next)))
  16060. (setq deactivate-mark t)
  16061. (kill-new result)
  16062. (message "Visible strings have been copied to the kill ring.")))
  16063. (defun org-copy-special ()
  16064. "Copy region in table or copy current subtree.
  16065. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16066. context. See the individual commands for more information."
  16067. (interactive)
  16068. (call-interactively
  16069. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16070. (defun org-cut-special ()
  16071. "Cut region in table or cut current subtree.
  16072. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16073. context. See the individual commands for more information."
  16074. (interactive)
  16075. (call-interactively
  16076. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16077. (defun org-paste-special (arg)
  16078. "Paste rectangular region into table, or past subtree relative to level.
  16079. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16080. See the individual commands for more information."
  16081. (interactive "P")
  16082. (if (org-at-table-p)
  16083. (org-table-paste-rectangle)
  16084. (org-paste-subtree arg)))
  16085. (defun org-edit-special (&optional arg)
  16086. "Call a special editor for the element at point.
  16087. When at a table, call the formula editor with `org-table-edit-formulas'.
  16088. When in a source code block, call `org-edit-src-code'.
  16089. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16090. When in an export block, call `org-edit-export-block'.
  16091. When in a LaTeX environment, call `org-edit-latex-environment'.
  16092. When at an #+INCLUDE keyword, visit the included file.
  16093. When at a footnote reference, call `org-edit-footnote-reference'.
  16094. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16095. When at an active timestamp, call `org-time-stamp'.
  16096. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16097. On a link, call `ffap' to visit the link at point.
  16098. Otherwise, return a user error."
  16099. (interactive "P")
  16100. (let ((element (org-element-at-point)))
  16101. (barf-if-buffer-read-only)
  16102. (pcase (org-element-type element)
  16103. (`src-block
  16104. (if (not arg) (org-edit-src-code)
  16105. (let* ((info (org-babel-get-src-block-info))
  16106. (lang (nth 0 info))
  16107. (params (nth 2 info))
  16108. (session (cdr (assq :session params))))
  16109. (if (not session) (org-edit-src-code)
  16110. ;; At a source block with a session and function called
  16111. ;; with an ARG: switch to the buffer related to the
  16112. ;; inferior process.
  16113. (switch-to-buffer
  16114. (funcall (intern (concat "org-babel-prep-session:" lang))
  16115. session params))))))
  16116. (`keyword
  16117. (unless (member (org-element-property :key element)
  16118. '("INCLUDE" "SETUPFILE"))
  16119. (user-error "No special environment to edit here"))
  16120. (let ((value (org-element-property :value element)))
  16121. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16122. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16123. (or (match-string 1 value)
  16124. (match-string 0 value)))))
  16125. (when (org-file-url-p file)
  16126. (user-error "Files located with a URL cannot be edited"))
  16127. (org-link-open-from-string
  16128. (format "[[%s]]" (expand-file-name file))))))
  16129. (`table
  16130. (if (eq (org-element-property :type element) 'table.el)
  16131. (org-edit-table.el)
  16132. (call-interactively 'org-table-edit-formulas)))
  16133. ;; Only Org tables contain `table-row' type elements.
  16134. (`table-row (call-interactively 'org-table-edit-formulas))
  16135. (`example-block (org-edit-src-code))
  16136. (`export-block (org-edit-export-block))
  16137. (`fixed-width (org-edit-fixed-width-region))
  16138. (`latex-environment (org-edit-latex-environment))
  16139. (`planning
  16140. (let ((proplist (cadr element)))
  16141. (mapc #'call-interactively
  16142. (remq nil
  16143. (list
  16144. (when (plist-get proplist :deadline) #'org-deadline)
  16145. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16146. (_
  16147. ;; No notable element at point. Though, we may be at a link or
  16148. ;; a footnote reference, which are objects. Thus, scan deeper.
  16149. (let ((context (org-element-context element)))
  16150. (pcase (org-element-type context)
  16151. (`footnote-reference (org-edit-footnote-reference))
  16152. (`inline-src-block (org-edit-inline-src-code))
  16153. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16154. (call-interactively #'org-time-stamp-inactive)
  16155. (call-interactively #'org-time-stamp)))
  16156. (`link (call-interactively #'ffap))
  16157. (_ (user-error "No special environment to edit here"))))))))
  16158. (defun org-ctrl-c-ctrl-c (&optional arg)
  16159. "Set tags in headline, or update according to changed information at point.
  16160. This command does many different things, depending on context:
  16161. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16162. this is what we do.
  16163. - If the cursor is on a statistics cookie, update it.
  16164. - If the cursor is in a headline, prompt for tags and insert them
  16165. into the current line, aligned to `org-tags-column'. When called
  16166. with prefix arg, realign all tags in the current buffer.
  16167. - If the cursor is in one of the special #+KEYWORD lines, this
  16168. triggers scanning the buffer for these lines and updating the
  16169. information.
  16170. - If the cursor is inside a table, realign the table. This command
  16171. works even if the automatic table editor has been turned off.
  16172. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16173. the entire table.
  16174. - If the cursor is at a footnote reference or definition, jump to
  16175. the corresponding definition or references, respectively.
  16176. - If the cursor is a the beginning of a dynamic block, update it.
  16177. - If the current buffer is a capture buffer, close note and file it.
  16178. - If the cursor is on a <<<target>>>, update radio targets and
  16179. corresponding links in this buffer.
  16180. - If the cursor is on a numbered item in a plain list, renumber the
  16181. ordered list.
  16182. - If the cursor is on a checkbox, toggle it.
  16183. - If the cursor is on a code block, evaluate it. The variable
  16184. `org-confirm-babel-evaluate' can be used to control prompting
  16185. before code block evaluation, by default every code block
  16186. evaluation requires confirmation. Code block evaluation can be
  16187. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16188. (interactive "P")
  16189. (cond
  16190. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16191. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16192. (org-remove-occur-highlights)
  16193. (message "Temporary highlights/overlays removed from current buffer"))
  16194. ((and (local-variable-p 'org-finish-function)
  16195. (fboundp org-finish-function))
  16196. (funcall org-finish-function))
  16197. ((org-babel-hash-at-point))
  16198. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16199. (t
  16200. (let* ((context
  16201. (org-element-lineage
  16202. (org-element-context)
  16203. ;; Limit to supported contexts.
  16204. '(babel-call clock dynamic-block footnote-definition
  16205. footnote-reference inline-babel-call inline-src-block
  16206. inlinetask item keyword node-property paragraph
  16207. plain-list planning property-drawer radio-target
  16208. src-block statistics-cookie table table-cell table-row
  16209. timestamp)
  16210. t))
  16211. (type (org-element-type context)))
  16212. ;; For convenience: at the first line of a paragraph on the same
  16213. ;; line as an item, apply function on that item instead.
  16214. (when (eq type 'paragraph)
  16215. (let ((parent (org-element-property :parent context)))
  16216. (when (and (eq (org-element-type parent) 'item)
  16217. (= (line-beginning-position)
  16218. (org-element-property :begin parent)))
  16219. (setq context parent)
  16220. (setq type 'item))))
  16221. ;; Act according to type of element or object at point.
  16222. ;;
  16223. ;; Do nothing on a blank line, except if it is contained in
  16224. ;; a source block. Hence, we first check if point is in such
  16225. ;; a block and then if it is at a blank line.
  16226. (pcase type
  16227. ((or `inline-src-block `src-block)
  16228. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16229. (org-babel-eval-wipe-error-buffer)
  16230. (org-babel-execute-src-block
  16231. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16232. ((guard (org-match-line "[ \t]*$"))
  16233. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16234. (user-error
  16235. (substitute-command-keys
  16236. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16237. ((or `babel-call `inline-babel-call)
  16238. (let ((info (org-babel-lob-get-info context)))
  16239. (when info (org-babel-execute-src-block nil info))))
  16240. (`clock (org-clock-update-time-maybe))
  16241. (`dynamic-block
  16242. (save-excursion
  16243. (goto-char (org-element-property :post-affiliated context))
  16244. (org-update-dblock)))
  16245. (`footnote-definition
  16246. (goto-char (org-element-property :post-affiliated context))
  16247. (call-interactively 'org-footnote-action))
  16248. (`footnote-reference (call-interactively #'org-footnote-action))
  16249. ((or `headline `inlinetask)
  16250. (save-excursion (goto-char (org-element-property :begin context))
  16251. (call-interactively #'org-set-tags-command)))
  16252. (`item
  16253. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16254. ;; unconditionally, whereas `C-u' will toggle its presence.
  16255. ;; Without a universal argument, if the item has a checkbox,
  16256. ;; toggle it. Otherwise repair the list.
  16257. (let* ((box (org-element-property :checkbox context))
  16258. (struct (org-element-property :structure context))
  16259. (old-struct (copy-tree struct))
  16260. (parents (org-list-parents-alist struct))
  16261. (prevs (org-list-prevs-alist struct))
  16262. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16263. (org-list-set-checkbox
  16264. (org-element-property :begin context) struct
  16265. (cond ((equal arg '(16)) "[-]")
  16266. ((and (not box) (equal arg '(4))) "[ ]")
  16267. ((or (not box) (equal arg '(4))) nil)
  16268. ((eq box 'on) "[ ]")
  16269. (t "[X]")))
  16270. ;; Mimic `org-list-write-struct' but with grabbing a return
  16271. ;; value from `org-list-struct-fix-box'.
  16272. (org-list-struct-fix-ind struct parents 2)
  16273. (org-list-struct-fix-item-end struct)
  16274. (org-list-struct-fix-bul struct prevs)
  16275. (org-list-struct-fix-ind struct parents)
  16276. (let ((block-item
  16277. (org-list-struct-fix-box struct parents prevs orderedp)))
  16278. (if (and box (equal struct old-struct))
  16279. (if (equal arg '(16))
  16280. (message "Checkboxes already reset")
  16281. (user-error "Cannot toggle this checkbox: %s"
  16282. (if (eq box 'on)
  16283. "all subitems checked"
  16284. "unchecked subitems")))
  16285. (org-list-struct-apply-struct struct old-struct)
  16286. (org-update-checkbox-count-maybe))
  16287. (when block-item
  16288. (message "Checkboxes were removed due to empty box at line %d"
  16289. (org-current-line block-item))))))
  16290. (`keyword
  16291. (let ((org-inhibit-startup-visibility-stuff t)
  16292. (org-startup-align-all-tables nil))
  16293. (when (boundp 'org-table-coordinate-overlays)
  16294. (mapc #'delete-overlay org-table-coordinate-overlays)
  16295. (setq org-table-coordinate-overlays nil))
  16296. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16297. (message "Local setup has been refreshed"))
  16298. (`plain-list
  16299. ;; At a plain list, with a double C-u argument, set
  16300. ;; checkboxes of each item to "[-]", whereas a single one
  16301. ;; will toggle their presence according to the state of the
  16302. ;; first item in the list. Without an argument, repair the
  16303. ;; list.
  16304. (let* ((begin (org-element-property :contents-begin context))
  16305. (struct (org-element-property :structure context))
  16306. (old-struct (copy-tree struct))
  16307. (first-box (save-excursion
  16308. (goto-char begin)
  16309. (looking-at org-list-full-item-re)
  16310. (match-string-no-properties 3)))
  16311. (new-box (cond ((equal arg '(16)) "[-]")
  16312. ((equal arg '(4)) (unless first-box "[ ]"))
  16313. ((equal first-box "[X]") "[ ]")
  16314. (t "[X]"))))
  16315. (cond
  16316. (arg
  16317. (dolist (pos
  16318. (org-list-get-all-items
  16319. begin struct (org-list-prevs-alist struct)))
  16320. (org-list-set-checkbox pos struct new-box)))
  16321. ((and first-box (eq (point) begin))
  16322. ;; For convenience, when point is at bol on the first
  16323. ;; item of the list and no argument is provided, simply
  16324. ;; toggle checkbox of that item, if any.
  16325. (org-list-set-checkbox begin struct new-box)))
  16326. (when (equal
  16327. (org-list-write-struct
  16328. struct (org-list-parents-alist struct) old-struct)
  16329. old-struct)
  16330. (message "Cannot update this checkbox"))
  16331. (org-update-checkbox-count-maybe)))
  16332. ((or `property-drawer `node-property)
  16333. (call-interactively #'org-property-action))
  16334. (`radio-target
  16335. (call-interactively #'org-update-radio-target-regexp))
  16336. (`statistics-cookie
  16337. (call-interactively #'org-update-statistics-cookies))
  16338. ((or `table `table-cell `table-row)
  16339. ;; At a table, recalculate every field and align it. Also
  16340. ;; send the table if necessary. If the table has
  16341. ;; a `table.el' type, just give up. At a table row or cell,
  16342. ;; maybe recalculate line but always align table.
  16343. (if (eq (org-element-property :type context) 'table.el)
  16344. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16345. Use `\\[org-edit-special]' to edit table.el tables"))
  16346. (if (or (eq type 'table)
  16347. ;; Check if point is at a TBLFM line.
  16348. (and (eq type 'table-row)
  16349. (= (point) (org-element-property :end context))))
  16350. (save-excursion
  16351. (if (org-at-TBLFM-p)
  16352. (progn (require 'org-table)
  16353. (org-table-calc-current-TBLFM))
  16354. (goto-char (org-element-property :contents-begin context))
  16355. (org-call-with-arg 'org-table-recalculate (or arg t))
  16356. (orgtbl-send-table 'maybe)))
  16357. (org-table-maybe-eval-formula)
  16358. (cond (arg (call-interactively #'org-table-recalculate))
  16359. ((org-table-maybe-recalculate-line))
  16360. (t (org-table-align))))))
  16361. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16362. (org-timestamp-change 0 'day))
  16363. ((and `nil (guard (org-at-heading-p)))
  16364. ;; When point is on an unsupported object type, we can miss
  16365. ;; the fact that it also is at a heading. Handle it here.
  16366. (call-interactively #'org-set-tags-command))
  16367. ((guard
  16368. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16369. (_
  16370. (user-error
  16371. (substitute-command-keys
  16372. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16373. (defun org-mode-restart ()
  16374. (interactive)
  16375. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16376. (funcall major-mode)
  16377. (hack-local-variables)
  16378. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16379. (org-indent-mode -1))
  16380. (org-reset-file-cache))
  16381. (message "%s restarted" major-mode))
  16382. (defun org-flag-above-first-heading (&optional arg)
  16383. "Hide from bob up to the first heading.
  16384. Move point to the beginning of first heading or end of buffer."
  16385. (goto-char (point-min))
  16386. (unless (org-at-heading-p)
  16387. (outline-next-heading))
  16388. (unless (bobp)
  16389. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16390. (defun org-show-branches-buffer ()
  16391. "Show all branches in the buffer."
  16392. (org-flag-above-first-heading)
  16393. (outline-hide-sublevels 1)
  16394. (unless (eobp)
  16395. (outline-show-branches)
  16396. (while (outline-get-next-sibling)
  16397. (outline-show-branches)))
  16398. (goto-char (point-min)))
  16399. (defun org-kill-note-or-show-branches ()
  16400. "Abort storing current note, or show just branches."
  16401. (interactive)
  16402. (if org-finish-function
  16403. (let ((org-note-abort t))
  16404. (funcall org-finish-function))
  16405. (if (org-before-first-heading-p)
  16406. (org-show-branches-buffer)
  16407. (outline-hide-subtree)
  16408. (outline-show-branches))))
  16409. (defun org-delete-indentation (&optional arg)
  16410. "Join current line to previous and fix whitespace at join.
  16411. If previous line is a headline add to headline title. Otherwise
  16412. the function calls `delete-indentation'.
  16413. With a non-nil optional argument, join it to the following one."
  16414. (interactive "*P")
  16415. (if (save-excursion
  16416. (beginning-of-line (if arg 1 0))
  16417. (let ((case-fold-search nil))
  16418. (looking-at org-complex-heading-regexp)))
  16419. ;; At headline.
  16420. (let ((tags-column (when (match-beginning 5)
  16421. (save-excursion (goto-char (match-beginning 5))
  16422. (current-column))))
  16423. (string (concat " " (progn (when arg (forward-line 1))
  16424. (org-trim (delete-and-extract-region
  16425. (line-beginning-position)
  16426. (line-end-position)))))))
  16427. (unless (bobp) (delete-region (point) (1- (point))))
  16428. (goto-char (or (match-end 4)
  16429. (match-beginning 5)
  16430. (match-end 0)))
  16431. (skip-chars-backward " \t")
  16432. (save-excursion (insert string))
  16433. ;; Adjust alignment of tags.
  16434. (cond
  16435. ((not tags-column)) ;no tags
  16436. (org-auto-align-tags (org-align-tags))
  16437. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16438. (delete-indentation arg)))
  16439. (defun org-open-line (n)
  16440. "Insert a new row in tables, call `open-line' elsewhere.
  16441. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16442. As a special case, when a document starts with a table, allow to
  16443. call `open-line' on the very first character."
  16444. (interactive "*p")
  16445. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16446. (org-table-insert-row)
  16447. (open-line n)))
  16448. (defun org-return (&optional indent)
  16449. "Goto next table row or insert a newline.
  16450. Calls `org-table-next-row' or `newline', depending on context.
  16451. When optional INDENT argument is non-nil, call
  16452. `newline-and-indent' instead of `newline'.
  16453. When `org-return-follows-link' is non-nil and point is on
  16454. a timestamp or a link, call `org-open-at-point'. However, it
  16455. will not happen if point is in a table or on a \"dead\"
  16456. object (e.g., within a comment). In these case, you need to use
  16457. `org-open-at-point' directly."
  16458. (interactive)
  16459. (let ((context (if org-return-follows-link (org-element-context)
  16460. (org-element-at-point))))
  16461. (cond
  16462. ;; In a table, call `org-table-next-row'. However, before first
  16463. ;; column or after last one, split the table.
  16464. ((or (and (eq 'table (org-element-type context))
  16465. (not (eq 'table.el (org-element-property :type context)))
  16466. (>= (point) (org-element-property :contents-begin context))
  16467. (< (point) (org-element-property :contents-end context)))
  16468. (org-element-lineage context '(table-row table-cell) t))
  16469. (if (or (looking-at-p "[ \t]*$")
  16470. (save-excursion (skip-chars-backward " \t") (bolp)))
  16471. (insert "\n")
  16472. (org-table-justify-field-maybe)
  16473. (call-interactively #'org-table-next-row)))
  16474. ;; On a link or a timestamp, call `org-open-at-point' if
  16475. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16476. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16477. ((and org-return-follows-link
  16478. (or (and (eq 'link (org-element-type context))
  16479. ;; Ensure point is not on the white spaces after
  16480. ;; the link.
  16481. (let ((origin (point)))
  16482. (org-with-point-at (org-element-property :end context)
  16483. (skip-chars-backward " \t")
  16484. (> (point) origin))))
  16485. (org-in-regexp org-ts-regexp-both nil t)
  16486. (org-in-regexp org-tsr-regexp-both nil t)
  16487. (org-in-regexp org-link-any-re nil t)))
  16488. (call-interactively #'org-open-at-point))
  16489. ;; Insert newline in heading, but preserve tags.
  16490. ((and (not (bolp))
  16491. (let ((case-fold-search nil))
  16492. (org-match-line org-complex-heading-regexp)))
  16493. ;; At headline. Split line. However, if point is on keyword,
  16494. ;; priority cookie or tags, do not break any of them: add
  16495. ;; a newline after the headline instead.
  16496. (let ((tags-column (and (match-beginning 5)
  16497. (save-excursion (goto-char (match-beginning 5))
  16498. (current-column))))
  16499. (string
  16500. (when (and (match-end 4) (org-point-in-group (point) 4))
  16501. (delete-and-extract-region (point) (match-end 4)))))
  16502. ;; Adjust tag alignment.
  16503. (cond
  16504. ((not (and tags-column string)))
  16505. (org-auto-align-tags (org-align-tags))
  16506. (t (org--align-tags-here tags-column))) ;preserve tags column
  16507. (end-of-line)
  16508. (org-show-entry)
  16509. (if indent (newline-and-indent) (newline))
  16510. (when string (save-excursion (insert (org-trim string))))))
  16511. ;; In a list, make sure indenting keeps trailing text within.
  16512. ((and indent
  16513. (not (eolp))
  16514. (org-element-lineage context '(item)))
  16515. (let ((trailing-data
  16516. (delete-and-extract-region (point) (line-end-position))))
  16517. (newline-and-indent)
  16518. (save-excursion (insert trailing-data))))
  16519. (t
  16520. ;; Do not auto-fill when point is in an Org property drawer.
  16521. (let ((auto-fill-function (and (not (org-at-property-p))
  16522. auto-fill-function)))
  16523. (if indent
  16524. (newline-and-indent)
  16525. (newline)))))))
  16526. (defun org-return-indent ()
  16527. "Goto next table row or insert a newline and indent.
  16528. Calls `org-table-next-row' or `newline-and-indent', depending on
  16529. context. See the individual commands for more information."
  16530. (interactive)
  16531. (org-return t))
  16532. (defun org-ctrl-c-tab (&optional arg)
  16533. "Toggle columns width in a table, or show children.
  16534. Call `org-table-toggle-column-width' if point is in a table.
  16535. Otherwise, call `org-show-children'. ARG is the level to hide."
  16536. (interactive "p")
  16537. (if (org-at-table-p)
  16538. (call-interactively #'org-table-toggle-column-width)
  16539. (if (org-before-first-heading-p)
  16540. (progn
  16541. (org-flag-above-first-heading)
  16542. (outline-hide-sublevels (or arg 1))
  16543. (goto-char (point-min)))
  16544. (outline-hide-subtree)
  16545. (org-show-children arg))))
  16546. (defun org-ctrl-c-star ()
  16547. "Compute table, or change heading status of lines.
  16548. Calls `org-table-recalculate' or `org-toggle-heading',
  16549. depending on context."
  16550. (interactive)
  16551. (cond
  16552. ((org-at-table-p)
  16553. (call-interactively 'org-table-recalculate))
  16554. (t
  16555. ;; Convert all lines in region to list items
  16556. (call-interactively 'org-toggle-heading))))
  16557. (defun org-ctrl-c-minus ()
  16558. "Insert separator line in table or modify bullet status of line.
  16559. Also turns a plain line or a region of lines into list items.
  16560. Calls `org-table-insert-hline', `org-toggle-item', or
  16561. `org-cycle-list-bullet', depending on context."
  16562. (interactive)
  16563. (cond
  16564. ((org-at-table-p)
  16565. (call-interactively 'org-table-insert-hline))
  16566. ((org-region-active-p)
  16567. (call-interactively 'org-toggle-item))
  16568. ((org-in-item-p)
  16569. (call-interactively 'org-cycle-list-bullet))
  16570. (t
  16571. (call-interactively 'org-toggle-item))))
  16572. (defun org-toggle-heading (&optional nstars)
  16573. "Convert headings to normal text, or items or text to headings.
  16574. If there is no active region, only convert the current line.
  16575. With a `\\[universal-argument]' prefix, convert the whole list at
  16576. point into heading.
  16577. In a region:
  16578. - If the first non blank line is a headline, remove the stars
  16579. from all headlines in the region.
  16580. - If it is a normal line, turn each and every normal line (i.e.,
  16581. not an heading or an item) in the region into headings. If you
  16582. want to convert only the first line of this region, use one
  16583. universal prefix argument.
  16584. - If it is a plain list item, turn all plain list items into headings.
  16585. When converting a line into a heading, the number of stars is chosen
  16586. such that the lines become children of the current entry. However,
  16587. when a numeric prefix argument is given, its value determines the
  16588. number of stars to add."
  16589. (interactive "P")
  16590. (let ((skip-blanks
  16591. (function
  16592. ;; Return beginning of first non-blank line, starting from
  16593. ;; line at POS.
  16594. (lambda (pos)
  16595. (save-excursion
  16596. (goto-char pos)
  16597. (while (org-at-comment-p) (forward-line))
  16598. (skip-chars-forward " \r\t\n")
  16599. (point-at-bol)))))
  16600. beg end toggled)
  16601. ;; Determine boundaries of changes. If a universal prefix has
  16602. ;; been given, put the list in a region. If region ends at a bol,
  16603. ;; do not consider the last line to be in the region.
  16604. (when (and current-prefix-arg (org-at-item-p))
  16605. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16606. (org-mark-element))
  16607. (if (org-region-active-p)
  16608. (setq beg (funcall skip-blanks (region-beginning))
  16609. end (copy-marker (save-excursion
  16610. (goto-char (region-end))
  16611. (if (bolp) (point) (point-at-eol)))))
  16612. (setq beg (funcall skip-blanks (point-at-bol))
  16613. end (copy-marker (point-at-eol))))
  16614. ;; Ensure inline tasks don't count as headings.
  16615. (org-with-limited-levels
  16616. (save-excursion
  16617. (goto-char beg)
  16618. (cond
  16619. ;; Case 1. Started at an heading: de-star headings.
  16620. ((org-at-heading-p)
  16621. (while (< (point) end)
  16622. (when (org-at-heading-p t)
  16623. (looking-at org-outline-regexp) (replace-match "")
  16624. (setq toggled t))
  16625. (forward-line)))
  16626. ;; Case 2. Started at an item: change items into headlines.
  16627. ;; One star will be added by `org-list-to-subtree'.
  16628. ((org-at-item-p)
  16629. (while (< (point) end)
  16630. (when (org-at-item-p)
  16631. ;; Pay attention to cases when region ends before list.
  16632. (let* ((struct (org-list-struct))
  16633. (list-end
  16634. (min (org-list-get-bottom-point struct) (1+ end))))
  16635. (save-restriction
  16636. (narrow-to-region (point) list-end)
  16637. (insert (org-list-to-subtree
  16638. (org-list-to-lisp t)
  16639. (pcase (org-current-level)
  16640. (`nil 1)
  16641. (l (1+ (org-reduced-level l)))))
  16642. "\n")))
  16643. (setq toggled t))
  16644. (forward-line)))
  16645. ;; Case 3. Started at normal text: make every line an heading,
  16646. ;; skipping headlines and items.
  16647. (t (let* ((stars
  16648. (make-string
  16649. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16650. (add-stars
  16651. (cond (nstars "") ; stars from prefix only
  16652. ((equal stars "") "*") ; before first heading
  16653. (org-odd-levels-only "**") ; inside heading, odd
  16654. (t "*"))) ; inside heading, oddeven
  16655. (rpl (concat stars add-stars " "))
  16656. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16657. (while (< (point) (if (equal nstars '(4)) lend end))
  16658. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16659. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16660. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16661. (forward-line)))))))
  16662. (unless toggled (message "Cannot toggle heading from here"))))
  16663. (defun org-meta-return (&optional arg)
  16664. "Insert a new heading or wrap a region in a table.
  16665. Calls `org-insert-heading', `org-insert-item' or
  16666. `org-table-wrap-region', depending on context. When called with
  16667. an argument, unconditionally call `org-insert-heading'."
  16668. (interactive "P")
  16669. (org-check-before-invisible-edit 'insert)
  16670. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16671. (call-interactively (cond (arg #'org-insert-heading)
  16672. ((org-at-table-p) #'org-table-wrap-region)
  16673. ((org-in-item-p) #'org-insert-item)
  16674. (t #'org-insert-heading)))))
  16675. ;;; Menu entries
  16676. (defsubst org-in-subtree-not-table-p ()
  16677. "Are we in a subtree and not in a table?"
  16678. (and (not (org-before-first-heading-p))
  16679. (not (org-at-table-p))))
  16680. ;; Define the Org mode menus
  16681. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16682. '("Tbl"
  16683. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16684. ["Next Field" org-cycle (org-at-table-p)]
  16685. ["Previous Field" org-shifttab (org-at-table-p)]
  16686. ["Next Row" org-return (org-at-table-p)]
  16687. "--"
  16688. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16689. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16690. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16691. "--"
  16692. ("Column"
  16693. ["Move Column Left" org-metaleft (org-at-table-p)]
  16694. ["Move Column Right" org-metaright (org-at-table-p)]
  16695. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16696. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16697. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16698. ("Row"
  16699. ["Move Row Up" org-metaup (org-at-table-p)]
  16700. ["Move Row Down" org-metadown (org-at-table-p)]
  16701. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16702. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16703. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16704. "--"
  16705. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16706. ("Rectangle"
  16707. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16708. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16709. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16710. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16711. "--"
  16712. ("Calculate"
  16713. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16714. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16715. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16716. "--"
  16717. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16718. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16719. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16720. "--"
  16721. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16722. "--"
  16723. ["Sum Column/Rectangle" org-table-sum
  16724. (or (org-at-table-p) (org-region-active-p))]
  16725. ["Which Column?" org-table-current-column (org-at-table-p)])
  16726. ["Debug Formulas"
  16727. org-table-toggle-formula-debugger
  16728. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16729. ["Show Col/Row Numbers"
  16730. org-table-toggle-coordinate-overlays
  16731. :style toggle
  16732. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16733. "--"
  16734. ["Create" org-table-create (not (org-at-table-p))]
  16735. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16736. ["Import from File" org-table-import (not (org-at-table-p))]
  16737. ["Export to File" org-table-export (org-at-table-p)]
  16738. "--"
  16739. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16740. "--"
  16741. ("Plot"
  16742. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16743. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16744. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16745. '("Org"
  16746. ("Show/Hide"
  16747. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16748. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16749. ["Sparse Tree..." org-sparse-tree t]
  16750. ["Reveal Context" org-reveal t]
  16751. ["Show All" org-show-all t]
  16752. "--"
  16753. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16754. "--"
  16755. ["New Heading" org-insert-heading t]
  16756. ("Navigate Headings"
  16757. ["Up" outline-up-heading t]
  16758. ["Next" outline-next-visible-heading t]
  16759. ["Previous" outline-previous-visible-heading t]
  16760. ["Next Same Level" outline-forward-same-level t]
  16761. ["Previous Same Level" outline-backward-same-level t]
  16762. "--"
  16763. ["Jump" org-goto t])
  16764. ("Edit Structure"
  16765. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16766. "--"
  16767. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16768. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16769. "--"
  16770. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16771. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16772. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16773. "--"
  16774. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16775. "--"
  16776. ["Copy visible text" org-copy-visible t]
  16777. "--"
  16778. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16779. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16780. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16781. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16782. "--"
  16783. ["Sort Region/Children" org-sort t]
  16784. "--"
  16785. ["Convert to odd levels" org-convert-to-odd-levels t]
  16786. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16787. ("Editing"
  16788. ["Emphasis..." org-emphasize t]
  16789. ["Edit Source Example" org-edit-special t]
  16790. "--"
  16791. ["Footnote new/jump" org-footnote-action t]
  16792. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16793. ("Archive"
  16794. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16795. "--"
  16796. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16797. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16798. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16799. )
  16800. "--"
  16801. ("Hyperlinks"
  16802. ["Store Link (Global)" org-store-link t]
  16803. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16804. ["Insert Link" org-insert-link t]
  16805. ["Follow Link" org-open-at-point t]
  16806. "--"
  16807. ["Next link" org-next-link t]
  16808. ["Previous link" org-previous-link t]
  16809. "--"
  16810. ["Descriptive Links"
  16811. org-toggle-link-display
  16812. :style radio
  16813. :selected org-descriptive-links
  16814. ]
  16815. ["Literal Links"
  16816. org-toggle-link-display
  16817. :style radio
  16818. :selected (not org-descriptive-links)])
  16819. "--"
  16820. ("TODO Lists"
  16821. ["TODO/DONE/-" org-todo t]
  16822. ("Select keyword"
  16823. ["Next keyword" org-shiftright (org-at-heading-p)]
  16824. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16825. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16826. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16827. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16828. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16829. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16830. "--"
  16831. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16832. :selected org-enforce-todo-dependencies :style toggle :active t]
  16833. "Settings for tree at point"
  16834. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16835. :selected (org-entry-get nil "ORDERED")
  16836. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16837. ["Do Children parallel" org-toggle-ordered-property :style radio
  16838. :selected (not (org-entry-get nil "ORDERED"))
  16839. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16840. "--"
  16841. ["Set Priority" org-priority t]
  16842. ["Priority Up" org-shiftup t]
  16843. ["Priority Down" org-shiftdown t]
  16844. "--"
  16845. ["Get news from all feeds" org-feed-update-all t]
  16846. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16847. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16848. ("TAGS and Properties"
  16849. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16850. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16851. "--"
  16852. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16853. ["Column view of properties" org-columns t]
  16854. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16855. ("Dates and Scheduling"
  16856. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16857. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16858. ("Change Date"
  16859. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16860. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16861. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16862. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16863. ["Compute Time Range" org-evaluate-time-range t]
  16864. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16865. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16866. "--"
  16867. ["Custom time format" org-toggle-time-stamp-overlays
  16868. :style radio :selected org-display-custom-times]
  16869. "--"
  16870. ["Goto Calendar" org-goto-calendar t]
  16871. ["Date from Calendar" org-date-from-calendar t]
  16872. "--"
  16873. ["Start/Restart Timer" org-timer-start t]
  16874. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16875. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16876. ["Insert Timer String" org-timer t]
  16877. ["Insert Timer Item" org-timer-item t])
  16878. ("Logging work"
  16879. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16880. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16881. ["Clock out" org-clock-out t]
  16882. ["Clock cancel" org-clock-cancel t]
  16883. "--"
  16884. ["Mark as default task" org-clock-mark-default-task t]
  16885. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16886. ["Goto running clock" org-clock-goto t]
  16887. "--"
  16888. ["Display times" org-clock-display t]
  16889. ["Create clock table" org-clock-report t]
  16890. "--"
  16891. ["Record DONE time"
  16892. (progn (setq org-log-done (not org-log-done))
  16893. (message "Switching to %s will %s record a timestamp"
  16894. (car org-done-keywords)
  16895. (if org-log-done "automatically" "not")))
  16896. :style toggle :selected org-log-done])
  16897. "--"
  16898. ["Agenda Command..." org-agenda t]
  16899. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16900. ("File List for Agenda")
  16901. ("Special views current file"
  16902. ["TODO Tree" org-show-todo-tree t]
  16903. ["Check Deadlines" org-check-deadlines t]
  16904. ["Tags/Property tree" org-match-sparse-tree t])
  16905. "--"
  16906. ["Export/Publish..." org-export-dispatch t]
  16907. ("LaTeX"
  16908. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16909. :style toggle :selected org-cdlatex-mode]
  16910. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16911. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16912. ["Modify math symbol" org-cdlatex-math-modify
  16913. (org-inside-LaTeX-fragment-p)]
  16914. ["Insert citation" org-reftex-citation t])
  16915. "--"
  16916. ("MobileOrg"
  16917. ["Push Files and Views" org-mobile-push t]
  16918. ["Get Captured and Flagged" org-mobile-pull t]
  16919. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16920. "--"
  16921. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16922. "--"
  16923. ("Documentation"
  16924. ["Show Version" org-version t]
  16925. ["Info Documentation" org-info t]
  16926. ["Browse Org News" org-browse-news t])
  16927. ("Customize"
  16928. ["Browse Org Group" org-customize t]
  16929. "--"
  16930. ["Expand This Menu" org-create-customize-menu
  16931. (fboundp 'customize-menu-create)])
  16932. ["Send bug report" org-submit-bug-report t]
  16933. "--"
  16934. ("Refresh/Reload"
  16935. ["Refresh setup current buffer" org-mode-restart t]
  16936. ["Reload Org (after update)" org-reload t]
  16937. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16938. (defun org-info (&optional node)
  16939. "Read documentation for Org in the info system.
  16940. With optional NODE, go directly to that node."
  16941. (interactive)
  16942. (info (format "(org)%s" (or node ""))))
  16943. (defun org-browse-news ()
  16944. "Browse the news for the latest major release."
  16945. (interactive)
  16946. (browse-url "https://orgmode.org/Changes.html"))
  16947. ;;;###autoload
  16948. (defun org-submit-bug-report ()
  16949. "Submit a bug report on Org via mail.
  16950. Don't hesitate to report any problems or inaccurate documentation.
  16951. If you don't have setup sending mail from (X)Emacs, please copy the
  16952. output buffer into your mail program, as it gives us important
  16953. information about your Org version and configuration."
  16954. (interactive)
  16955. (require 'reporter)
  16956. (defvar reporter-prompt-for-summary-p)
  16957. (org-load-modules-maybe)
  16958. (org-require-autoloaded-modules)
  16959. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16960. (reporter-submit-bug-report
  16961. "emacs-orgmode@gnu.org"
  16962. (org-version nil 'full)
  16963. (let (list)
  16964. (save-window-excursion
  16965. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16966. (delete-other-windows)
  16967. (erase-buffer)
  16968. (insert "You are about to submit a bug report to the Org mailing list.
  16969. We would like to add your full Org and Outline configuration to the
  16970. bug report. This greatly simplifies the work of the maintainer and
  16971. other experts on the mailing list.
  16972. HOWEVER, some variables you have customized may contain private
  16973. information. The names of customers, colleagues, or friends, might
  16974. appear in the form of file names, tags, todo states, or search strings.
  16975. If you answer yes to the prompt, you might want to check and remove
  16976. such private information before sending the email.")
  16977. (add-text-properties (point-min) (point-max) '(face org-warning))
  16978. (when (yes-or-no-p "Include your Org configuration ")
  16979. (mapatoms
  16980. (lambda (v)
  16981. (and (boundp v)
  16982. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16983. (or (and (symbol-value v)
  16984. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16985. (and
  16986. (get v 'custom-type) (get v 'standard-value)
  16987. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16988. (push v list)))))
  16989. (kill-buffer (get-buffer "*Warn about privacy*"))
  16990. list))
  16991. nil nil
  16992. "Remember to cover the basics, that is, what you expected to happen and
  16993. what in fact did happen. You don't know how to make a good report? See
  16994. https://orgmode.org/manual/Feedback.html#Feedback
  16995. Your bug report will be posted to the Org mailing list.
  16996. ------------------------------------------------------------------------")
  16997. (save-excursion
  16998. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16999. (replace-match "\\1Bug: \\3 [\\2]")))))
  17000. (defun org-install-agenda-files-menu ()
  17001. (let ((bl (buffer-list)))
  17002. (save-excursion
  17003. (while bl
  17004. (set-buffer (pop bl))
  17005. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17006. (when (derived-mode-p 'org-mode)
  17007. (easy-menu-change
  17008. '("Org") "File List for Agenda"
  17009. (append
  17010. (list
  17011. ["Edit File List" (org-edit-agenda-file-list) t]
  17012. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17013. ["Remove Current File from List" org-remove-file t]
  17014. ["Cycle through agenda files" org-cycle-agenda-files t]
  17015. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17016. "--")
  17017. (mapcar 'org-file-menu-entry
  17018. ;; Prevent initialization from failing.
  17019. (ignore-errors (org-agenda-files t)))))))))
  17020. ;;;; Documentation
  17021. (defun org-require-autoloaded-modules ()
  17022. (interactive)
  17023. (mapc #'require
  17024. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17025. org-table org-timer)))
  17026. ;;;###autoload
  17027. (defun org-reload (&optional uncompiled)
  17028. "Reload all Org Lisp files.
  17029. With prefix arg UNCOMPILED, load the uncompiled versions."
  17030. (interactive "P")
  17031. (require 'loadhist)
  17032. (let* ((org-dir (org-find-library-dir "org"))
  17033. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17034. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17035. (remove-re (format "\\`%s\\'"
  17036. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17037. (feats (delete-dups
  17038. (mapcar 'file-name-sans-extension
  17039. (mapcar 'file-name-nondirectory
  17040. (delq nil
  17041. (mapcar 'feature-file
  17042. features))))))
  17043. (lfeat (append
  17044. (sort
  17045. (setq feats
  17046. (delq nil (mapcar
  17047. (lambda (f)
  17048. (if (and (string-match feature-re f)
  17049. (not (string-match remove-re f)))
  17050. f nil))
  17051. feats)))
  17052. 'string-lessp)
  17053. (list "org-version" "org")))
  17054. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17055. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17056. load-uncore load-misses)
  17057. (setq load-misses
  17058. (delq 't
  17059. (mapcar (lambda (f)
  17060. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17061. (and (string= org-dir contrib-dir)
  17062. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17063. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17064. (add-to-list 'load-uncore f 'append)
  17065. 't)
  17066. f))
  17067. lfeat)))
  17068. (when load-uncore
  17069. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17070. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17071. (if load-misses
  17072. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17073. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17074. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17075. ;;;###autoload
  17076. (defun org-customize ()
  17077. "Call the customize function with org as argument."
  17078. (interactive)
  17079. (org-load-modules-maybe)
  17080. (org-require-autoloaded-modules)
  17081. (customize-browse 'org))
  17082. (defun org-create-customize-menu ()
  17083. "Create a full customization menu for Org mode, insert it into the menu."
  17084. (interactive)
  17085. (org-load-modules-maybe)
  17086. (org-require-autoloaded-modules)
  17087. (if (fboundp 'customize-menu-create)
  17088. (progn
  17089. (easy-menu-change
  17090. '("Org") "Customize"
  17091. `(["Browse Org group" org-customize t]
  17092. "--"
  17093. ,(customize-menu-create 'org)
  17094. ["Set" Custom-set t]
  17095. ["Save" Custom-save t]
  17096. ["Reset to Current" Custom-reset-current t]
  17097. ["Reset to Saved" Custom-reset-saved t]
  17098. ["Reset to Standard Settings" Custom-reset-standard t]))
  17099. (message "\"Org\"-menu now contains full customization menu"))
  17100. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17101. ;;;; Miscellaneous stuff
  17102. ;;; Generally useful functions
  17103. (defun org-in-clocktable-p ()
  17104. "Check if the cursor is in a clocktable."
  17105. (let ((pos (point)) start)
  17106. (save-excursion
  17107. (end-of-line 1)
  17108. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17109. (setq start (match-beginning 0))
  17110. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17111. (>= (match-end 0) pos)
  17112. start))))
  17113. (defun org-in-verbatim-emphasis ()
  17114. (save-match-data
  17115. (and (org-in-regexp org-verbatim-re 2)
  17116. (>= (point) (match-beginning 3))
  17117. (<= (point) (match-end 4)))))
  17118. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17119. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17120. (if (and marker (marker-buffer marker)
  17121. (buffer-live-p (marker-buffer marker)))
  17122. (progn
  17123. (pop-to-buffer-same-window (marker-buffer marker))
  17124. (when (or (> marker (point-max)) (< marker (point-min)))
  17125. (widen))
  17126. (goto-char marker)
  17127. (org-show-context 'org-goto))
  17128. (if bookmark
  17129. (bookmark-jump bookmark)
  17130. (error "Cannot find location"))))
  17131. (defun org-quote-csv-field (s)
  17132. "Quote field for inclusion in CSV material."
  17133. (if (string-match "[\",]" s)
  17134. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17135. s))
  17136. (defun org-force-self-insert (N)
  17137. "Needed to enforce self-insert under remapping."
  17138. (interactive "p")
  17139. (self-insert-command N))
  17140. (defun org-quote-vert (s)
  17141. "Replace \"|\" with \"\\vert\"."
  17142. (while (string-match "|" s)
  17143. (setq s (replace-match "\\vert" t t s)))
  17144. s)
  17145. (defun org-uuidgen-p (s)
  17146. "Is S an ID created by UUIDGEN?"
  17147. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17148. (defun org-in-src-block-p (&optional inside)
  17149. "Whether point is in a code source block.
  17150. When INSIDE is non-nil, don't consider we are within a source
  17151. block when point is at #+BEGIN_SRC or #+END_SRC."
  17152. (let ((case-fold-search t))
  17153. (or (and (eq (get-char-property (point) 'src-block) t))
  17154. (and (not inside)
  17155. (save-match-data
  17156. (save-excursion
  17157. (beginning-of-line)
  17158. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17159. (defun org-context ()
  17160. "Return a list of contexts of the current cursor position.
  17161. If several contexts apply, all are returned.
  17162. Each context entry is a list with a symbol naming the context, and
  17163. two positions indicating start and end of the context. Possible
  17164. contexts are:
  17165. :headline anywhere in a headline
  17166. :headline-stars on the leading stars in a headline
  17167. :todo-keyword on a TODO keyword (including DONE) in a headline
  17168. :tags on the TAGS in a headline
  17169. :priority on the priority cookie in a headline
  17170. :item on the first line of a plain list item
  17171. :item-bullet on the bullet/number of a plain list item
  17172. :checkbox on the checkbox in a plain list item
  17173. :table in an Org table
  17174. :table-special on a special filed in a table
  17175. :table-table in a table.el table
  17176. :clocktable in a clocktable
  17177. :src-block in a source block
  17178. :link on a hyperlink
  17179. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17180. :latex-fragment on a LaTeX fragment
  17181. :latex-preview on a LaTeX fragment with overlaid preview image
  17182. This function expects the position to be visible because it uses font-lock
  17183. faces as a help to recognize the following contexts: :table-special, :link,
  17184. and :keyword."
  17185. (let* ((f (get-text-property (point) 'face))
  17186. (faces (if (listp f) f (list f)))
  17187. (case-fold-search t)
  17188. (p (point)) clist o)
  17189. ;; First the large context
  17190. (cond
  17191. ((org-at-heading-p t)
  17192. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17193. (when (progn
  17194. (beginning-of-line 1)
  17195. (looking-at org-todo-line-tags-regexp))
  17196. (push (org-point-in-group p 1 :headline-stars) clist)
  17197. (push (org-point-in-group p 2 :todo-keyword) clist)
  17198. (push (org-point-in-group p 4 :tags) clist))
  17199. (goto-char p)
  17200. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17201. (when (looking-at "\\[#[A-Z0-9]\\]")
  17202. (push (org-point-in-group p 0 :priority) clist)))
  17203. ((org-at-item-p)
  17204. (push (org-point-in-group p 2 :item-bullet) clist)
  17205. (push (list :item (point-at-bol)
  17206. (save-excursion (org-end-of-item) (point)))
  17207. clist)
  17208. (and (org-at-item-checkbox-p)
  17209. (push (org-point-in-group p 0 :checkbox) clist)))
  17210. ((org-at-table-p)
  17211. (push (list :table (org-table-begin) (org-table-end)) clist)
  17212. (when (memq 'org-formula faces)
  17213. (push (list :table-special
  17214. (previous-single-property-change p 'face)
  17215. (next-single-property-change p 'face)) clist)))
  17216. ((org-at-table-p 'any)
  17217. (push (list :table-table) clist)))
  17218. (goto-char p)
  17219. (let ((case-fold-search t))
  17220. ;; New the "medium" contexts: clocktables, source blocks
  17221. (cond ((org-in-clocktable-p)
  17222. (push (list :clocktable
  17223. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17224. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17225. (match-beginning 1))
  17226. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17227. (match-end 0))) clist))
  17228. ((org-in-src-block-p)
  17229. (push (list :src-block
  17230. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17231. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17232. (match-beginning 1))
  17233. (and (search-forward "#+END_SRC" nil t)
  17234. (match-beginning 0))) clist))))
  17235. (goto-char p)
  17236. ;; Now the small context
  17237. (cond
  17238. ((org-at-timestamp-p)
  17239. (push (org-point-in-group p 0 :timestamp) clist))
  17240. ((memq 'org-link faces)
  17241. (push (list :link
  17242. (previous-single-property-change p 'face)
  17243. (next-single-property-change p 'face)) clist))
  17244. ((memq 'org-special-keyword faces)
  17245. (push (list :keyword
  17246. (previous-single-property-change p 'face)
  17247. (next-single-property-change p 'face)) clist))
  17248. ((setq o (cl-some
  17249. (lambda (o)
  17250. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17251. o))
  17252. (overlays-at (point))))
  17253. (push (list :latex-fragment
  17254. (overlay-start o) (overlay-end o)) clist)
  17255. (push (list :latex-preview
  17256. (overlay-start o) (overlay-end o)) clist))
  17257. ((org-inside-LaTeX-fragment-p)
  17258. ;; FIXME: positions wrong.
  17259. (push (list :latex-fragment (point) (point)) clist)))
  17260. (setq clist (nreverse (delq nil clist)))
  17261. clist))
  17262. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17263. "Non-nil when point is between matches of START-RE and END-RE.
  17264. Also return a non-nil value when point is on one of the matches.
  17265. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17266. buffer positions. Default values are the positions of headlines
  17267. surrounding the point.
  17268. The functions returns a cons cell whose car (resp. cdr) is the
  17269. position before START-RE (resp. after END-RE)."
  17270. (save-match-data
  17271. (let ((pos (point))
  17272. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17273. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17274. beg end)
  17275. (save-excursion
  17276. ;; Point is on a block when on START-RE or if START-RE can be
  17277. ;; found before it...
  17278. (and (or (org-in-regexp start-re)
  17279. (re-search-backward start-re limit-up t))
  17280. (setq beg (match-beginning 0))
  17281. ;; ... and END-RE after it...
  17282. (goto-char (match-end 0))
  17283. (re-search-forward end-re limit-down t)
  17284. (> (setq end (match-end 0)) pos)
  17285. ;; ... without another START-RE in-between.
  17286. (goto-char (match-beginning 0))
  17287. (not (re-search-backward start-re (1+ beg) t))
  17288. ;; Return value.
  17289. (cons beg end))))))
  17290. (defun org-in-block-p (names)
  17291. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17292. NAMES is a list of strings containing names of blocks.
  17293. Return first block name matched, or nil. Beware that in case of
  17294. nested blocks, the returned name may not belong to the closest
  17295. block from point."
  17296. (save-match-data
  17297. (catch 'exit
  17298. (let ((case-fold-search t)
  17299. (lim-up (save-excursion (outline-previous-heading)))
  17300. (lim-down (save-excursion (outline-next-heading))))
  17301. (dolist (name names)
  17302. (let ((n (regexp-quote name)))
  17303. (when (org-between-regexps-p
  17304. (concat "^[ \t]*#\\+begin_" n)
  17305. (concat "^[ \t]*#\\+end_" n)
  17306. lim-up lim-down)
  17307. (throw 'exit n)))))
  17308. nil)))
  17309. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17310. "Call `multi-occur' with buffers for all agenda files."
  17311. (interactive "sOrg-files matching: ")
  17312. (let* ((files (org-agenda-files))
  17313. (tnames (mapcar #'file-truename files))
  17314. (extra org-agenda-text-search-extra-files))
  17315. (when (eq (car extra) 'agenda-archives)
  17316. (setq extra (cdr extra))
  17317. (setq files (org-add-archive-files files)))
  17318. (dolist (f extra)
  17319. (unless (member (file-truename f) tnames)
  17320. (unless (member f files) (setq files (append files (list f))))
  17321. (setq tnames (append tnames (list (file-truename f))))))
  17322. (multi-occur
  17323. (mapcar (lambda (x)
  17324. (with-current-buffer
  17325. ;; FIXME: Why not just (find-file-noselect x)?
  17326. ;; Is it to avoid the "revert buffer" prompt?
  17327. (or (get-file-buffer x) (find-file-noselect x))
  17328. (widen)
  17329. (current-buffer)))
  17330. files)
  17331. regexp)))
  17332. (add-hook 'occur-mode-find-occurrence-hook
  17333. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17334. (defun org-occur-link-in-agenda-files ()
  17335. "Create a link and search for it in the agendas.
  17336. The link is not stored in `org-stored-links', it is just created
  17337. for the search purpose."
  17338. (interactive)
  17339. (let ((link (condition-case nil
  17340. (org-store-link nil)
  17341. (error "Unable to create a link to here"))))
  17342. (org-occur-in-agenda-files (regexp-quote link))))
  17343. (defun org-back-over-empty-lines ()
  17344. "Move backwards over whitespace, to the beginning of the first empty line.
  17345. Returns the number of empty lines passed."
  17346. (let ((pos (point)))
  17347. (if (cdr (assq 'heading org-blank-before-new-entry))
  17348. (skip-chars-backward " \t\n\r")
  17349. (unless (eobp)
  17350. (forward-line -1)))
  17351. (beginning-of-line 2)
  17352. (goto-char (min (point) pos))
  17353. (count-lines (point) pos)))
  17354. ;;; TODO: Only called once, from ox-odt which should probably use
  17355. ;;; org-export-inline-image-p or something.
  17356. (defun org-file-image-p (file)
  17357. "Return non-nil if FILE is an image."
  17358. (save-match-data
  17359. (string-match (image-file-name-regexp) file)))
  17360. (defun org-get-cursor-date (&optional with-time)
  17361. "Return the date at cursor in as a time.
  17362. This works in the calendar and in the agenda, anywhere else it just
  17363. returns the current time.
  17364. If WITH-TIME is non-nil, returns the time of the event at point (in
  17365. the agenda) or the current time of the day; otherwise returns the
  17366. earliest time on the cursor date that Org treats as that date
  17367. (bearing in mind `org-extend-today-until')."
  17368. (let (date day defd tp hod mod)
  17369. (when with-time
  17370. (setq tp (get-text-property (point) 'time))
  17371. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17372. (setq hod (string-to-number (match-string 1 tp))
  17373. mod (string-to-number (match-string 2 tp))))
  17374. (or tp (let ((now (decode-time)))
  17375. (setq hod (nth 2 now)
  17376. mod (nth 1 now)))))
  17377. (cond
  17378. ((eq major-mode 'calendar-mode)
  17379. (setq date (calendar-cursor-to-date)
  17380. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17381. (nth 1 date) (nth 0 date) (nth 2 date))))
  17382. ((eq major-mode 'org-agenda-mode)
  17383. (setq day (get-text-property (point) 'day))
  17384. (when day
  17385. (setq date (calendar-gregorian-from-absolute day)
  17386. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17387. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17388. (or defd (current-time))))
  17389. (defun org-mark-subtree (&optional up)
  17390. "Mark the current subtree.
  17391. This puts point at the start of the current subtree, and mark at
  17392. the end. If a numeric prefix UP is given, move up into the
  17393. hierarchy of headlines by UP levels before marking the subtree."
  17394. (interactive "P")
  17395. (org-with-limited-levels
  17396. (cond ((org-at-heading-p) (beginning-of-line))
  17397. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17398. (t (outline-previous-visible-heading 1))))
  17399. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17400. (if (called-interactively-p 'any)
  17401. (call-interactively 'org-mark-element)
  17402. (org-mark-element)))
  17403. ;;; Indentation
  17404. (defvar org-element-greater-elements)
  17405. (defun org--get-expected-indentation (element contentsp)
  17406. "Expected indentation column for current line, according to ELEMENT.
  17407. ELEMENT is an element containing point. CONTENTSP is non-nil
  17408. when indentation is to be computed according to contents of
  17409. ELEMENT."
  17410. (let ((type (org-element-type element))
  17411. (start (org-element-property :begin element))
  17412. (post-affiliated (org-element-property :post-affiliated element)))
  17413. (org-with-wide-buffer
  17414. (cond
  17415. (contentsp
  17416. (cl-case type
  17417. ((diary-sexp footnote-definition) 0)
  17418. ((headline inlinetask nil)
  17419. (if (not org-adapt-indentation) 0
  17420. (let ((level (org-current-level)))
  17421. (if level (1+ level) 0))))
  17422. ((item plain-list) (org-list-item-body-column post-affiliated))
  17423. (t
  17424. (goto-char start)
  17425. (current-indentation))))
  17426. ((memq type '(headline inlinetask nil))
  17427. (if (org-match-line "[ \t]*$")
  17428. (org--get-expected-indentation element t)
  17429. 0))
  17430. ((memq type '(diary-sexp footnote-definition)) 0)
  17431. ;; First paragraph of a footnote definition or an item.
  17432. ;; Indent like parent.
  17433. ((< (line-beginning-position) start)
  17434. (org--get-expected-indentation
  17435. (org-element-property :parent element) t))
  17436. ;; At first line: indent according to previous sibling, if any,
  17437. ;; ignoring footnote definitions and inline tasks, or parent's
  17438. ;; contents.
  17439. ((= (line-beginning-position) start)
  17440. (catch 'exit
  17441. (while t
  17442. (if (= (point-min) start) (throw 'exit 0)
  17443. (goto-char (1- start))
  17444. (let* ((previous (org-element-at-point))
  17445. (parent previous))
  17446. (while (and parent (<= (org-element-property :end parent) start))
  17447. (setq previous parent
  17448. parent (org-element-property :parent parent)))
  17449. (cond
  17450. ((not previous) (throw 'exit 0))
  17451. ((> (org-element-property :end previous) start)
  17452. (throw 'exit (org--get-expected-indentation previous t)))
  17453. ((memq (org-element-type previous)
  17454. '(footnote-definition inlinetask))
  17455. (setq start (org-element-property :begin previous)))
  17456. (t (goto-char (org-element-property :begin previous))
  17457. (throw 'exit
  17458. (if (bolp) (current-indentation)
  17459. ;; At first paragraph in an item or
  17460. ;; a footnote definition.
  17461. (org--get-expected-indentation
  17462. (org-element-property :parent previous) t))))))))))
  17463. ;; Otherwise, move to the first non-blank line above.
  17464. (t
  17465. (beginning-of-line)
  17466. (let ((pos (point)))
  17467. (skip-chars-backward " \r\t\n")
  17468. (cond
  17469. ;; Two blank lines end a footnote definition or a plain
  17470. ;; list. When we indent an empty line after them, the
  17471. ;; containing list or footnote definition is over, so it
  17472. ;; qualifies as a previous sibling. Therefore, we indent
  17473. ;; like its first line.
  17474. ((and (memq type '(footnote-definition plain-list))
  17475. (> (count-lines (point) pos) 2))
  17476. (goto-char start)
  17477. (current-indentation))
  17478. ;; Line above is the first one of a paragraph at the
  17479. ;; beginning of an item or a footnote definition. Indent
  17480. ;; like parent.
  17481. ((< (line-beginning-position) start)
  17482. (org--get-expected-indentation
  17483. (org-element-property :parent element) t))
  17484. ;; Line above is the beginning of an element, i.e., point
  17485. ;; was originally on the blank lines between element's start
  17486. ;; and contents.
  17487. ((= (line-beginning-position) post-affiliated)
  17488. (org--get-expected-indentation element t))
  17489. ;; POS is after contents in a greater element. Indent like
  17490. ;; the beginning of the element.
  17491. ((and (memq type org-element-greater-elements)
  17492. (let ((cend (org-element-property :contents-end element)))
  17493. (and cend (<= cend pos))))
  17494. ;; As a special case, if point is at the end of a footnote
  17495. ;; definition or an item, indent like the very last element
  17496. ;; within. If that last element is an item, indent like
  17497. ;; its contents.
  17498. (if (memq type '(footnote-definition item plain-list))
  17499. (let ((last (org-element-at-point)))
  17500. (goto-char pos)
  17501. (org--get-expected-indentation
  17502. last (eq (org-element-type last) 'item)))
  17503. (goto-char start)
  17504. (current-indentation)))
  17505. ;; In any other case, indent like the current line.
  17506. (t (current-indentation)))))))))
  17507. (defun org--align-node-property ()
  17508. "Align node property at point.
  17509. Alignment is done according to `org-property-format', which see."
  17510. (when (save-excursion
  17511. (beginning-of-line)
  17512. (looking-at org-property-re))
  17513. (replace-match
  17514. (concat (match-string 4)
  17515. (org-trim
  17516. (format org-property-format (match-string 1) (match-string 3))))
  17517. t t)))
  17518. (defun org-indent-line ()
  17519. "Indent line depending on context.
  17520. Indentation is done according to the following rules:
  17521. - Footnote definitions, diary sexps, headlines and inline tasks
  17522. have to start at column 0.
  17523. - On the very first line of an element, consider, in order, the
  17524. next rules until one matches:
  17525. 1. If there's a sibling element before, ignoring footnote
  17526. definitions and inline tasks, indent like its first line.
  17527. 2. If element has a parent, indent like its contents. More
  17528. precisely, if parent is an item, indent after the bullet.
  17529. Else, indent like parent's first line.
  17530. 3. Otherwise, indent relatively to current level, if
  17531. `org-adapt-indentation' is non-nil, or to left margin.
  17532. - On a blank line at the end of an element, indent according to
  17533. the type of the element. More precisely
  17534. 1. If element is a plain list, an item, or a footnote
  17535. definition, indent like the very last element within.
  17536. 2. If element is a paragraph, indent like its last non blank
  17537. line.
  17538. 3. Otherwise, indent like its very first line.
  17539. - In the code part of a source block, use language major mode
  17540. to indent current line if `org-src-tab-acts-natively' is
  17541. non-nil. If it is nil, do nothing.
  17542. - Otherwise, indent like the first non-blank line above.
  17543. The function doesn't indent an item as it could break the whole
  17544. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17545. `\\[org-shiftmetaright]'.
  17546. Also align node properties according to `org-property-format'."
  17547. (interactive)
  17548. (cond
  17549. ((org-at-heading-p) 'noindent)
  17550. (t
  17551. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17552. (type (org-element-type element)))
  17553. (cond ((and (memq type '(plain-list item))
  17554. (= (line-beginning-position)
  17555. (org-element-property :post-affiliated element)))
  17556. 'noindent)
  17557. ((and (eq type 'latex-environment)
  17558. (>= (point) (org-element-property :post-affiliated element))
  17559. (< (point) (org-with-wide-buffer
  17560. (goto-char (org-element-property :end element))
  17561. (skip-chars-backward " \r\t\n")
  17562. (line-beginning-position 2))))
  17563. 'noindent)
  17564. ((and (eq type 'src-block)
  17565. org-src-tab-acts-natively
  17566. (> (line-beginning-position)
  17567. (org-element-property :post-affiliated element))
  17568. (< (line-beginning-position)
  17569. (org-with-wide-buffer
  17570. (goto-char (org-element-property :end element))
  17571. (skip-chars-backward " \r\t\n")
  17572. (line-beginning-position))))
  17573. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17574. (t
  17575. (let ((column (org--get-expected-indentation element nil)))
  17576. ;; Preserve current column.
  17577. (if (<= (current-column) (current-indentation))
  17578. (indent-line-to column)
  17579. (save-excursion (indent-line-to column))))
  17580. ;; Align node property. Also preserve current column.
  17581. (when (eq type 'node-property)
  17582. (let ((column (current-column)))
  17583. (org--align-node-property)
  17584. (org-move-to-column column)))))))))
  17585. (defun org-indent-region (start end)
  17586. "Indent each non-blank line in the region.
  17587. Called from a program, START and END specify the region to
  17588. indent. The function will not indent contents of example blocks,
  17589. verse blocks and export blocks as leading white spaces are
  17590. assumed to be significant there."
  17591. (interactive "r")
  17592. (save-excursion
  17593. (goto-char start)
  17594. (skip-chars-forward " \r\t\n")
  17595. (unless (eobp) (beginning-of-line))
  17596. (let ((indent-to
  17597. (lambda (ind pos)
  17598. ;; Set IND as indentation for all lines between point and
  17599. ;; POS. Blank lines are ignored. Leave point after POS
  17600. ;; once done.
  17601. (let ((limit (copy-marker pos)))
  17602. (while (< (point) limit)
  17603. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17604. (forward-line))
  17605. (set-marker limit nil))))
  17606. (end (copy-marker end)))
  17607. (while (< (point) end)
  17608. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17609. (let* ((element (org-element-at-point))
  17610. (type (org-element-type element))
  17611. (element-end (copy-marker (org-element-property :end element)))
  17612. (ind (org--get-expected-indentation element nil)))
  17613. (cond
  17614. ;; Element indented as a single block. Example blocks
  17615. ;; preserving indentation are a special case since the
  17616. ;; "contents" must not be indented whereas the block
  17617. ;; boundaries can.
  17618. ((or (memq type '(export-block latex-environment))
  17619. (and (eq type 'example-block)
  17620. (not
  17621. (or org-src-preserve-indentation
  17622. (org-element-property :preserve-indent element)))))
  17623. (let ((offset (- ind (current-indentation))))
  17624. (unless (zerop offset)
  17625. (indent-rigidly (org-element-property :begin element)
  17626. (org-element-property :end element)
  17627. offset)))
  17628. (goto-char element-end))
  17629. ;; Elements indented line wise. Be sure to exclude
  17630. ;; example blocks (preserving indentation) and source
  17631. ;; blocks from this category as they are treated
  17632. ;; specially later.
  17633. ((or (memq type '(paragraph table table-row))
  17634. (not (or (org-element-property :contents-begin element)
  17635. (memq type '(example-block src-block)))))
  17636. (when (eq type 'node-property)
  17637. (org--align-node-property)
  17638. (beginning-of-line))
  17639. (funcall indent-to ind (min element-end end)))
  17640. ;; Elements consisting of three parts: before the
  17641. ;; contents, the contents, and after the contents. The
  17642. ;; contents are treated specially, according to the
  17643. ;; element type, or not indented at all. Other parts are
  17644. ;; indented as a single block.
  17645. (t
  17646. (let* ((post (copy-marker
  17647. (org-element-property :post-affiliated element)))
  17648. (cbeg
  17649. (copy-marker
  17650. (cond
  17651. ((not (org-element-property :contents-begin element))
  17652. ;; Fake contents for source blocks.
  17653. (org-with-wide-buffer
  17654. (goto-char post)
  17655. (line-beginning-position 2)))
  17656. ((memq type '(footnote-definition item plain-list))
  17657. ;; Contents in these elements could start on
  17658. ;; the same line as the beginning of the
  17659. ;; element. Make sure we start indenting
  17660. ;; from the second line.
  17661. (org-with-wide-buffer
  17662. (goto-char post)
  17663. (end-of-line)
  17664. (skip-chars-forward " \r\t\n")
  17665. (if (eobp) (point) (line-beginning-position))))
  17666. (t (org-element-property :contents-begin element)))))
  17667. (cend (copy-marker
  17668. (or (org-element-property :contents-end element)
  17669. ;; Fake contents for source blocks.
  17670. (org-with-wide-buffer
  17671. (goto-char element-end)
  17672. (skip-chars-backward " \r\t\n")
  17673. (line-beginning-position)))
  17674. t)))
  17675. ;; Do not change items indentation individually as it
  17676. ;; might break the list as a whole. On the other
  17677. ;; hand, when at a plain list, indent it as a whole.
  17678. (cond ((eq type 'plain-list)
  17679. (let ((offset (- ind (current-indentation))))
  17680. (unless (zerop offset)
  17681. (indent-rigidly (org-element-property :begin element)
  17682. (org-element-property :end element)
  17683. offset))
  17684. (goto-char cbeg)))
  17685. ((eq type 'item) (goto-char cbeg))
  17686. (t (funcall indent-to ind (min cbeg end))))
  17687. (when (< (point) end)
  17688. (cl-case type
  17689. ((example-block verse-block))
  17690. (src-block
  17691. ;; In a source block, indent source code
  17692. ;; according to language major mode, but only if
  17693. ;; `org-src-tab-acts-natively' is non-nil.
  17694. (when (and (< (point) end) org-src-tab-acts-natively)
  17695. (ignore-errors
  17696. (org-babel-do-in-edit-buffer
  17697. (indent-region (point-min) (point-max))))))
  17698. (t (org-indent-region (point) (min cend end))))
  17699. (goto-char (min cend end))
  17700. (when (< (point) end)
  17701. (funcall indent-to ind (min element-end end))))
  17702. (set-marker post nil)
  17703. (set-marker cbeg nil)
  17704. (set-marker cend nil))))
  17705. (set-marker element-end nil))))
  17706. (set-marker end nil))))
  17707. (defun org-indent-drawer ()
  17708. "Indent the drawer at point."
  17709. (interactive)
  17710. (unless (save-excursion
  17711. (beginning-of-line)
  17712. (looking-at-p org-drawer-regexp))
  17713. (user-error "Not at a drawer"))
  17714. (let ((element (org-element-at-point)))
  17715. (unless (memq (org-element-type element) '(drawer property-drawer))
  17716. (user-error "Not at a drawer"))
  17717. (org-with-wide-buffer
  17718. (org-indent-region (org-element-property :begin element)
  17719. (org-element-property :end element))))
  17720. (message "Drawer at point indented"))
  17721. (defun org-indent-block ()
  17722. "Indent the block at point."
  17723. (interactive)
  17724. (unless (save-excursion
  17725. (beginning-of-line)
  17726. (let ((case-fold-search t))
  17727. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17728. (user-error "Not at a block"))
  17729. (let ((element (org-element-at-point)))
  17730. (unless (memq (org-element-type element)
  17731. '(comment-block center-block dynamic-block example-block
  17732. export-block quote-block special-block
  17733. src-block verse-block))
  17734. (user-error "Not at a block"))
  17735. (org-with-wide-buffer
  17736. (org-indent-region (org-element-property :begin element)
  17737. (org-element-property :end element))))
  17738. (message "Block at point indented"))
  17739. ;;; Filling
  17740. ;; We use our own fill-paragraph and auto-fill functions.
  17741. ;; `org-fill-paragraph' relies on adaptive filling and context
  17742. ;; checking. Appropriate `fill-prefix' is computed with
  17743. ;; `org-adaptive-fill-function'.
  17744. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17745. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17746. ;; `org-adaptive-fill-function' value. Internally,
  17747. ;; `org-comment-line-break-function' breaks the line.
  17748. ;; `org-setup-filling' installs filling and auto-filling related
  17749. ;; variables during `org-mode' initialization.
  17750. (defun org-setup-filling ()
  17751. (require 'org-element)
  17752. ;; Prevent auto-fill from inserting unwanted new items.
  17753. (when (boundp 'fill-nobreak-predicate)
  17754. (setq-local
  17755. fill-nobreak-predicate
  17756. (org-uniquify
  17757. (append fill-nobreak-predicate
  17758. '(org-fill-line-break-nobreak-p
  17759. org-fill-n-macro-as-item-nobreak-p
  17760. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17761. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17762. (setq-local paragraph-start paragraph-ending)
  17763. (setq-local paragraph-separate paragraph-ending))
  17764. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17765. (setq-local auto-fill-inhibit-regexp nil)
  17766. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17767. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17768. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17769. (defun org-fill-line-break-nobreak-p ()
  17770. "Non-nil when a new line at point would create an Org line break."
  17771. (save-excursion
  17772. (skip-chars-backward " \t")
  17773. (skip-chars-backward "\\\\")
  17774. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17775. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17776. "Non-nil when a new line at point would split a timestamp."
  17777. (and (org-at-timestamp-p 'lax)
  17778. (not (looking-at org-ts-regexp-both))))
  17779. (defun org-fill-n-macro-as-item-nobreak-p ()
  17780. "Non-nil when a new line at point would create a new list."
  17781. ;; During export, a "n" macro followed by a dot or a closing
  17782. ;; parenthesis can end up being parsed as a new list item.
  17783. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17784. (defun org-adaptive-fill-function ()
  17785. "Compute a fill prefix for the current line.
  17786. Return fill prefix, as a string, or nil if current line isn't
  17787. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17788. matches in paragraphs or comments, use it."
  17789. (org-with-wide-buffer
  17790. (unless (org-at-heading-p)
  17791. (let* ((p (line-beginning-position))
  17792. (element (save-excursion
  17793. (beginning-of-line)
  17794. (org-element-at-point)))
  17795. (type (org-element-type element))
  17796. (post-affiliated (org-element-property :post-affiliated element)))
  17797. (unless (< p post-affiliated)
  17798. (cl-case type
  17799. (comment
  17800. (save-excursion
  17801. (beginning-of-line)
  17802. (looking-at "[ \t]*")
  17803. (concat (match-string 0) "# ")))
  17804. (footnote-definition "")
  17805. ((item plain-list)
  17806. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17807. (paragraph
  17808. ;; Fill prefix is usually the same as the current line,
  17809. ;; unless the paragraph is at the beginning of an item.
  17810. (let ((parent (org-element-property :parent element)))
  17811. (save-excursion
  17812. (beginning-of-line)
  17813. (cond ((eq (org-element-type parent) 'item)
  17814. (make-string (org-list-item-body-column
  17815. (org-element-property :begin parent))
  17816. ?\s))
  17817. ((and adaptive-fill-regexp
  17818. ;; Locally disable
  17819. ;; `adaptive-fill-function' to let
  17820. ;; `fill-context-prefix' handle
  17821. ;; `adaptive-fill-regexp' variable.
  17822. (let (adaptive-fill-function)
  17823. (fill-context-prefix
  17824. post-affiliated
  17825. (org-element-property :end element)))))
  17826. ((looking-at "[ \t]+") (match-string 0))
  17827. (t "")))))
  17828. (comment-block
  17829. ;; Only fill contents if P is within block boundaries.
  17830. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17831. (forward-line)
  17832. (point)))
  17833. (cend (save-excursion
  17834. (goto-char (org-element-property :end element))
  17835. (skip-chars-backward " \r\t\n")
  17836. (line-beginning-position))))
  17837. (when (and (>= p cbeg) (< p cend))
  17838. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17839. (match-string 0)
  17840. ""))))))))))
  17841. (defun org-fill-element (&optional justify)
  17842. "Fill element at point, when applicable.
  17843. This function only applies to comment blocks, comments, example
  17844. blocks and paragraphs. Also, as a special case, re-align table
  17845. when point is at one.
  17846. If JUSTIFY is non-nil (interactively, with prefix argument),
  17847. justify as well. If `sentence-end-double-space' is non-nil, then
  17848. period followed by one space does not end a sentence, so don't
  17849. break a line there. The variable `fill-column' controls the
  17850. width for filling.
  17851. For convenience, when point is at a plain list, an item or
  17852. a footnote definition, try to fill the first paragraph within."
  17853. (with-syntax-table org-mode-transpose-word-syntax-table
  17854. ;; Move to end of line in order to get the first paragraph within
  17855. ;; a plain list or a footnote definition.
  17856. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17857. ;; First check if point is in a blank line at the beginning of
  17858. ;; the buffer. In that case, ignore filling.
  17859. (cl-case (org-element-type element)
  17860. ;; Use major mode filling function is source blocks.
  17861. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17862. ;; Align Org tables, leave table.el tables as-is.
  17863. (table-row (org-table-align) t)
  17864. (table
  17865. (when (eq (org-element-property :type element) 'org)
  17866. (save-excursion
  17867. (goto-char (org-element-property :post-affiliated element))
  17868. (org-table-align)))
  17869. t)
  17870. (paragraph
  17871. ;; Paragraphs may contain `line-break' type objects.
  17872. (let ((beg (max (point-min)
  17873. (org-element-property :contents-begin element)))
  17874. (end (min (point-max)
  17875. (org-element-property :contents-end element))))
  17876. ;; Do nothing if point is at an affiliated keyword.
  17877. (if (< (line-end-position) beg) t
  17878. ;; Fill paragraph, taking line breaks into account.
  17879. (save-excursion
  17880. (goto-char beg)
  17881. (let ((cuts (list beg)))
  17882. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17883. (when (eq 'line-break
  17884. (org-element-type
  17885. (save-excursion (backward-char)
  17886. (org-element-context))))
  17887. (push (point) cuts)))
  17888. (dolist (c (delq end cuts))
  17889. (fill-region-as-paragraph c end justify)
  17890. (setq end c))))
  17891. t)))
  17892. ;; Contents of `comment-block' type elements should be
  17893. ;; filled as plain text, but only if point is within block
  17894. ;; markers.
  17895. (comment-block
  17896. (let* ((case-fold-search t)
  17897. (beg (save-excursion
  17898. (goto-char (org-element-property :begin element))
  17899. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17900. (forward-line)
  17901. (point)))
  17902. (end (save-excursion
  17903. (goto-char (org-element-property :end element))
  17904. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17905. (line-beginning-position))))
  17906. (if (or (< (point) beg) (> (point) end)) t
  17907. (fill-region-as-paragraph
  17908. (save-excursion (end-of-line)
  17909. (re-search-backward "^[ \t]*$" beg 'move)
  17910. (line-beginning-position))
  17911. (save-excursion (beginning-of-line)
  17912. (re-search-forward "^[ \t]*$" end 'move)
  17913. (line-beginning-position))
  17914. justify))))
  17915. ;; Fill comments.
  17916. (comment
  17917. (let ((begin (org-element-property :post-affiliated element))
  17918. (end (org-element-property :end element)))
  17919. (when (and (>= (point) begin) (<= (point) end))
  17920. (let ((begin (save-excursion
  17921. (end-of-line)
  17922. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17923. (progn (forward-line) (point))
  17924. begin)))
  17925. (end (save-excursion
  17926. (end-of-line)
  17927. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17928. (1- (line-beginning-position))
  17929. (skip-chars-backward " \r\t\n")
  17930. (line-end-position)))))
  17931. ;; Do not fill comments when at a blank line.
  17932. (when (> end begin)
  17933. (let ((fill-prefix
  17934. (save-excursion
  17935. (beginning-of-line)
  17936. (looking-at "[ \t]*#")
  17937. (let ((comment-prefix (match-string 0)))
  17938. (goto-char (match-end 0))
  17939. (if (looking-at adaptive-fill-regexp)
  17940. (concat comment-prefix (match-string 0))
  17941. (concat comment-prefix " "))))))
  17942. (save-excursion
  17943. (fill-region-as-paragraph begin end justify))))))
  17944. t))
  17945. ;; Ignore every other element.
  17946. (otherwise t)))))
  17947. (defun org-fill-paragraph (&optional justify region)
  17948. "Fill element at point, when applicable.
  17949. This function only applies to comment blocks, comments, example
  17950. blocks and paragraphs. Also, as a special case, re-align table
  17951. when point is at one.
  17952. For convenience, when point is at a plain list, an item or
  17953. a footnote definition, try to fill the first paragraph within.
  17954. If JUSTIFY is non-nil (interactively, with prefix argument),
  17955. justify as well. If `sentence-end-double-space' is non-nil, then
  17956. period followed by one space does not end a sentence, so don't
  17957. break a line there. The variable `fill-column' controls the
  17958. width for filling.
  17959. The REGION argument is non-nil if called interactively; in that
  17960. case, if Transient Mark mode is enabled and the mark is active,
  17961. fill each of the elements in the active region, instead of just
  17962. filling the current element."
  17963. (interactive (progn
  17964. (barf-if-buffer-read-only)
  17965. (list (when current-prefix-arg 'full) t)))
  17966. (let ((hash (and (not (buffer-modified-p))
  17967. (org-buffer-hash))))
  17968. (cond
  17969. ((and region transient-mark-mode mark-active
  17970. (not (eq (region-beginning) (region-end))))
  17971. (let ((origin (point-marker))
  17972. (start (region-beginning)))
  17973. (unwind-protect
  17974. (progn
  17975. (goto-char (region-end))
  17976. (while (> (point) start)
  17977. (org-backward-paragraph)
  17978. (org-fill-element justify)))
  17979. (goto-char origin)
  17980. (set-marker origin nil))))
  17981. (t (org-fill-element justify)))
  17982. ;; If we didn't change anything in the buffer (and the buffer was
  17983. ;; previously unmodified), then flip the modification status back
  17984. ;; to "unchanged".
  17985. (when (and hash (equal hash (org-buffer-hash)))
  17986. (set-buffer-modified-p nil))))
  17987. (defun org-auto-fill-function ()
  17988. "Auto-fill function."
  17989. ;; Check if auto-filling is meaningful.
  17990. (let ((fc (current-fill-column)))
  17991. (when (and fc (> (current-column) fc))
  17992. (let* ((fill-prefix (org-adaptive-fill-function))
  17993. ;; Enforce empty fill prefix, if required. Otherwise, it
  17994. ;; will be computed again.
  17995. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17996. (when fill-prefix (do-auto-fill))))))
  17997. (defun org-comment-line-break-function (&optional soft)
  17998. "Break line at point and indent, continuing comment if within one.
  17999. The inserted newline is marked hard if variable
  18000. `use-hard-newlines' is true, unless optional argument SOFT is
  18001. non-nil."
  18002. (if soft (insert-and-inherit ?\n) (newline 1))
  18003. (save-excursion (forward-char -1) (delete-horizontal-space))
  18004. (delete-horizontal-space)
  18005. (indent-to-left-margin)
  18006. (insert-before-markers-and-inherit fill-prefix))
  18007. ;;; Fixed Width Areas
  18008. (defun org-toggle-fixed-width ()
  18009. "Toggle fixed-width markup.
  18010. Add or remove fixed-width markup on current line, whenever it
  18011. makes sense. Return an error otherwise.
  18012. If a region is active and if it contains only fixed-width areas
  18013. or blank lines, remove all fixed-width markup in it. If the
  18014. region contains anything else, convert all non-fixed-width lines
  18015. to fixed-width ones.
  18016. Blank lines at the end of the region are ignored unless the
  18017. region only contains such lines."
  18018. (interactive)
  18019. (if (not (org-region-active-p))
  18020. ;; No region:
  18021. ;;
  18022. ;; Remove fixed width marker only in a fixed-with element.
  18023. ;;
  18024. ;; Add fixed width maker in paragraphs, in blank lines after
  18025. ;; elements or at the beginning of a headline or an inlinetask,
  18026. ;; and before any one-line elements (e.g., a clock).
  18027. (progn
  18028. (beginning-of-line)
  18029. (let* ((element (org-element-at-point))
  18030. (type (org-element-type element)))
  18031. (cond
  18032. ((and (eq type 'fixed-width)
  18033. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18034. (replace-match
  18035. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18036. ((and (memq type '(babel-call clock comment diary-sexp headline
  18037. horizontal-rule keyword paragraph
  18038. planning))
  18039. (<= (org-element-property :post-affiliated element) (point)))
  18040. (skip-chars-forward " \t")
  18041. (insert ": "))
  18042. ((and (looking-at-p "[ \t]*$")
  18043. (or (eq type 'inlinetask)
  18044. (save-excursion
  18045. (skip-chars-forward " \r\t\n")
  18046. (<= (org-element-property :end element) (point)))))
  18047. (delete-region (point) (line-end-position))
  18048. (org-indent-line)
  18049. (insert ": "))
  18050. (t (user-error "Cannot insert a fixed-width line here")))))
  18051. ;; Region active.
  18052. (let* ((begin (save-excursion
  18053. (goto-char (region-beginning))
  18054. (line-beginning-position)))
  18055. (end (copy-marker
  18056. (save-excursion
  18057. (goto-char (region-end))
  18058. (unless (eolp) (beginning-of-line))
  18059. (if (save-excursion (re-search-backward "\\S-" begin t))
  18060. (progn (skip-chars-backward " \r\t\n") (point))
  18061. (point)))))
  18062. (all-fixed-width-p
  18063. (catch 'not-all-p
  18064. (save-excursion
  18065. (goto-char begin)
  18066. (skip-chars-forward " \r\t\n")
  18067. (when (eobp) (throw 'not-all-p nil))
  18068. (while (< (point) end)
  18069. (let ((element (org-element-at-point)))
  18070. (if (eq (org-element-type element) 'fixed-width)
  18071. (goto-char (org-element-property :end element))
  18072. (throw 'not-all-p nil))))
  18073. t))))
  18074. (if all-fixed-width-p
  18075. (save-excursion
  18076. (goto-char begin)
  18077. (while (< (point) end)
  18078. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18079. (replace-match
  18080. "" nil nil nil
  18081. (if (= (line-end-position) (match-end 0)) 0 1)))
  18082. (forward-line)))
  18083. (let ((min-ind (point-max)))
  18084. ;; Find minimum indentation across all lines.
  18085. (save-excursion
  18086. (goto-char begin)
  18087. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18088. (setq min-ind 0)
  18089. (catch 'zerop
  18090. (while (< (point) end)
  18091. (unless (looking-at-p "[ \t]*$")
  18092. (let ((ind (current-indentation)))
  18093. (setq min-ind (min min-ind ind))
  18094. (when (zerop ind) (throw 'zerop t))))
  18095. (forward-line)))))
  18096. ;; Loop over all lines and add fixed-width markup everywhere
  18097. ;; but in fixed-width lines.
  18098. (save-excursion
  18099. (goto-char begin)
  18100. (while (< (point) end)
  18101. (cond
  18102. ((org-at-heading-p)
  18103. (insert ": ")
  18104. (forward-line)
  18105. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18106. (insert ":")
  18107. (forward-line)))
  18108. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18109. (let* ((element (org-element-at-point))
  18110. (element-end (org-element-property :end element)))
  18111. (if (eq (org-element-type element) 'fixed-width)
  18112. (progn (goto-char element-end)
  18113. (skip-chars-backward " \r\t\n")
  18114. (forward-line))
  18115. (let ((limit (min end element-end)))
  18116. (while (< (point) limit)
  18117. (org-move-to-column min-ind t)
  18118. (insert ": ")
  18119. (forward-line))))))
  18120. (t
  18121. (org-move-to-column min-ind t)
  18122. (insert ": ")
  18123. (forward-line)))))))
  18124. (set-marker end nil))))
  18125. ;;; Blocks
  18126. (defun org-block-map (function &optional start end)
  18127. "Call FUNCTION at the head of all source blocks in the current buffer.
  18128. Optional arguments START and END can be used to limit the range."
  18129. (let ((start (or start (point-min)))
  18130. (end (or end (point-max))))
  18131. (save-excursion
  18132. (goto-char start)
  18133. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18134. (save-excursion
  18135. (save-match-data
  18136. (goto-char (match-beginning 0))
  18137. (funcall function)))))))
  18138. (defun org-next-block (arg &optional backward block-regexp)
  18139. "Jump to the next block.
  18140. With a prefix argument ARG, jump forward ARG many blocks.
  18141. When BACKWARD is non-nil, jump to the previous block.
  18142. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18143. Match data is set according to this regexp when the function
  18144. returns.
  18145. Return point at beginning of the opening line of found block.
  18146. Throw an error if no block is found."
  18147. (interactive "p")
  18148. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18149. (case-fold-search t)
  18150. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18151. (count (or arg 1))
  18152. (origin (point))
  18153. last-element)
  18154. (if backward (beginning-of-line) (end-of-line))
  18155. (while (and (> count 0) (funcall search-fn re nil t))
  18156. (let ((element (save-excursion
  18157. (goto-char (match-beginning 0))
  18158. (save-match-data (org-element-at-point)))))
  18159. (when (and (memq (org-element-type element)
  18160. '(center-block comment-block dynamic-block
  18161. example-block export-block quote-block
  18162. special-block src-block verse-block))
  18163. (<= (match-beginning 0)
  18164. (org-element-property :post-affiliated element)))
  18165. (setq last-element element)
  18166. (cl-decf count))))
  18167. (if (= count 0)
  18168. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18169. (save-match-data (org-show-context)))
  18170. (goto-char origin)
  18171. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18172. (defun org-previous-block (arg &optional block-regexp)
  18173. "Jump to the previous block.
  18174. With a prefix argument ARG, jump backward ARG many source blocks.
  18175. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18176. (interactive "p")
  18177. (org-next-block arg t block-regexp))
  18178. ;;; Comments
  18179. ;; Org comments syntax is quite complex. It requires the entire line
  18180. ;; to be just a comment. Also, even with the right syntax at the
  18181. ;; beginning of line, some elements (e.g., verse-block or
  18182. ;; example-block) don't accept comments. Usual Emacs comment commands
  18183. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18184. ;; Org still relies on `comment-dwim', but cannot trust
  18185. ;; `comment-only-p'. So, `comment-region-function' and
  18186. ;; `uncomment-region-function' both point
  18187. ;; to`org-comment-or-uncomment-region'. Eventually,
  18188. ;; `org-insert-comment' takes care of insertion of comments at the
  18189. ;; beginning of line.
  18190. ;; `org-setup-comments-handling' install comments related variables
  18191. ;; during `org-mode' initialization.
  18192. (defun org-setup-comments-handling ()
  18193. (interactive)
  18194. (setq-local comment-use-syntax nil)
  18195. (setq-local comment-start "# ")
  18196. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18197. (setq-local comment-insert-comment-function 'org-insert-comment)
  18198. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18199. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18200. (defun org-insert-comment ()
  18201. "Insert an empty comment above current line.
  18202. If the line is empty, insert comment at its beginning. When
  18203. point is within a source block, comment according to the related
  18204. major mode."
  18205. (if (let ((element (org-element-at-point)))
  18206. (and (eq (org-element-type element) 'src-block)
  18207. (< (save-excursion
  18208. (goto-char (org-element-property :post-affiliated element))
  18209. (line-end-position))
  18210. (point))
  18211. (> (save-excursion
  18212. (goto-char (org-element-property :end element))
  18213. (skip-chars-backward " \r\t\n")
  18214. (line-beginning-position))
  18215. (point))))
  18216. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18217. (beginning-of-line)
  18218. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18219. (open-line 1))
  18220. (org-indent-line)
  18221. (insert "# ")))
  18222. (defvar comment-empty-lines) ; From newcomment.el.
  18223. (defun org-comment-or-uncomment-region (beg end &rest _)
  18224. "Comment or uncomment each non-blank line in the region.
  18225. Uncomment each non-blank line between BEG and END if it only
  18226. contains commented lines. Otherwise, comment them. If region is
  18227. strictly within a source block, use appropriate comment syntax."
  18228. (if (let ((element (org-element-at-point)))
  18229. (and (eq (org-element-type element) 'src-block)
  18230. (< (save-excursion
  18231. (goto-char (org-element-property :post-affiliated element))
  18232. (line-end-position))
  18233. beg)
  18234. (>= (save-excursion
  18235. (goto-char (org-element-property :end element))
  18236. (skip-chars-backward " \r\t\n")
  18237. (line-beginning-position))
  18238. end)))
  18239. ;; Translate region boundaries for the Org buffer to the source
  18240. ;; buffer.
  18241. (let ((offset (- end beg)))
  18242. (save-excursion
  18243. (goto-char beg)
  18244. (org-babel-do-in-edit-buffer
  18245. (comment-or-uncomment-region (point) (+ offset (point))))))
  18246. (save-restriction
  18247. ;; Restrict region
  18248. (narrow-to-region (save-excursion (goto-char beg)
  18249. (skip-chars-forward " \r\t\n" end)
  18250. (line-beginning-position))
  18251. (save-excursion (goto-char end)
  18252. (skip-chars-backward " \r\t\n" beg)
  18253. (line-end-position)))
  18254. (let ((uncommentp
  18255. ;; UNCOMMENTP is non-nil when every non blank line between
  18256. ;; BEG and END is a comment.
  18257. (save-excursion
  18258. (goto-char (point-min))
  18259. (while (and (not (eobp))
  18260. (let ((element (org-element-at-point)))
  18261. (and (eq (org-element-type element) 'comment)
  18262. (goto-char (min (point-max)
  18263. (org-element-property
  18264. :end element)))))))
  18265. (eobp))))
  18266. (if uncommentp
  18267. ;; Only blank lines and comments in region: uncomment it.
  18268. (save-excursion
  18269. (goto-char (point-min))
  18270. (while (not (eobp))
  18271. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18272. (replace-match "" nil nil nil 1))
  18273. (forward-line)))
  18274. ;; Comment each line in region.
  18275. (let ((min-indent (point-max)))
  18276. ;; First find the minimum indentation across all lines.
  18277. (save-excursion
  18278. (goto-char (point-min))
  18279. (while (and (not (eobp)) (not (zerop min-indent)))
  18280. (unless (looking-at "[ \t]*$")
  18281. (setq min-indent (min min-indent (current-indentation))))
  18282. (forward-line)))
  18283. ;; Then loop over all lines.
  18284. (save-excursion
  18285. (goto-char (point-min))
  18286. (while (not (eobp))
  18287. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18288. ;; Don't get fooled by invisible text (e.g. link path)
  18289. ;; when moving to column MIN-INDENT.
  18290. (let ((buffer-invisibility-spec nil))
  18291. (org-move-to-column min-indent t))
  18292. (insert comment-start))
  18293. (forward-line)))))))))
  18294. (defun org-comment-dwim (_arg)
  18295. "Call the comment command you mean.
  18296. Call `org-toggle-comment' if on a heading, otherwise call
  18297. `comment-dwim', within a source edit buffer if needed."
  18298. (interactive "*P")
  18299. (cond ((org-at-heading-p)
  18300. (call-interactively #'org-toggle-comment))
  18301. ((org-in-src-block-p)
  18302. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18303. (t (call-interactively #'comment-dwim))))
  18304. ;;; Timestamps API
  18305. ;; This section contains tools to operate on, or create, timestamp
  18306. ;; objects, as returned by, e.g. `org-element-context'.
  18307. (defun org-timestamp-from-string (s)
  18308. "Convert Org timestamp S, as a string, into a timestamp object.
  18309. Return nil if S is not a valid timestamp string."
  18310. (when (org-string-nw-p s)
  18311. (with-temp-buffer
  18312. (save-excursion (insert s))
  18313. (org-element-timestamp-parser))))
  18314. (defun org-timestamp-from-time (time &optional with-time inactive)
  18315. "Convert a time value into a timestamp object.
  18316. TIME is an Emacs internal time representation, as returned, e.g.,
  18317. by `current-time'.
  18318. When optional argument WITH-TIME is non-nil, return a timestamp
  18319. object with a time part, i.e., with hours and minutes.
  18320. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18321. return an active timestamp."
  18322. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18323. (org-element-create 'timestamp
  18324. (list :type (if inactive 'inactive 'active)
  18325. :year-start year
  18326. :month-start month
  18327. :day-start day
  18328. :hour-start (and with-time hour)
  18329. :minute-start (and with-time minute)))))
  18330. (defun org-timestamp-to-time (timestamp &optional end)
  18331. "Convert TIMESTAMP object into an Emacs internal time value.
  18332. Use end of date range or time range when END is non-nil.
  18333. Otherwise, use its start."
  18334. (apply #'encode-time 0
  18335. (mapcar
  18336. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18337. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18338. '(:minute-start :hour-start :day-start :month-start
  18339. :year-start)))))
  18340. (defun org-timestamp-has-time-p (timestamp)
  18341. "Non-nil when TIMESTAMP has a time specified."
  18342. (org-element-property :hour-start timestamp))
  18343. (defun org-timestamp-format (timestamp format &optional end utc)
  18344. "Format a TIMESTAMP object into a string.
  18345. FORMAT is a format specifier to be passed to
  18346. `format-time-string'.
  18347. When optional argument END is non-nil, use end of date-range or
  18348. time-range, if possible.
  18349. When optional argument UTC is non-nil, time is be expressed as
  18350. Universal Time."
  18351. (format-time-string format (org-timestamp-to-time timestamp end)
  18352. (and utc t)))
  18353. (defun org-timestamp-split-range (timestamp &optional end)
  18354. "Extract a TIMESTAMP object from a date or time range.
  18355. END, when non-nil, means extract the end of the range.
  18356. Otherwise, extract its start.
  18357. Return a new timestamp object."
  18358. (let ((type (org-element-property :type timestamp)))
  18359. (if (memq type '(active inactive diary)) timestamp
  18360. (let ((split-ts (org-element-copy timestamp)))
  18361. ;; Set new type.
  18362. (org-element-put-property
  18363. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18364. ;; Copy start properties over end properties if END is
  18365. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18366. (let ((p-alist '((:minute-start . :minute-end)
  18367. (:hour-start . :hour-end)
  18368. (:day-start . :day-end)
  18369. (:month-start . :month-end)
  18370. (:year-start . :year-end))))
  18371. (dolist (p-cell p-alist)
  18372. (org-element-put-property
  18373. split-ts
  18374. (funcall (if end #'car #'cdr) p-cell)
  18375. (org-element-property
  18376. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18377. ;; Eventually refresh `:raw-value'.
  18378. (org-element-put-property split-ts :raw-value nil)
  18379. (org-element-put-property
  18380. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18381. (defun org-timestamp-translate (timestamp &optional boundary)
  18382. "Translate TIMESTAMP object to custom format.
  18383. Format string is defined in `org-time-stamp-custom-formats',
  18384. which see.
  18385. When optional argument BOUNDARY is non-nil, it is either the
  18386. symbol `start' or `end'. In this case, only translate the
  18387. starting or ending part of TIMESTAMP if it is a date or time
  18388. range. Otherwise, translate both parts.
  18389. Return timestamp as-is if `org-display-custom-times' is nil or if
  18390. it has a `diary' type."
  18391. (let ((type (org-element-property :type timestamp)))
  18392. (if (or (not org-display-custom-times) (eq type 'diary))
  18393. (org-element-interpret-data timestamp)
  18394. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18395. org-time-stamp-custom-formats)))
  18396. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18397. (concat (org-timestamp-format timestamp fmt)
  18398. "--"
  18399. (org-timestamp-format timestamp fmt t))
  18400. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18401. ;;; Other stuff
  18402. (defvar reftex-docstruct-symbol)
  18403. (defvar org--rds)
  18404. (defun org-reftex-citation ()
  18405. "Use reftex-citation to insert a citation into the buffer.
  18406. This looks for a line like
  18407. #+BIBLIOGRAPHY: foo plain option:-d
  18408. and derives from it that foo.bib is the bibliography file relevant
  18409. for this document. It then installs the necessary environment for RefTeX
  18410. to work in this buffer and calls `reftex-citation' to insert a citation
  18411. into the buffer.
  18412. Export of such citations to both LaTeX and HTML is handled by the contributed
  18413. package ox-bibtex by Taru Karttunen."
  18414. (interactive)
  18415. (let ((reftex-docstruct-symbol 'org--rds)
  18416. org--rds bib)
  18417. (org-with-wide-buffer
  18418. (let ((case-fold-search t)
  18419. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18420. (if (not (save-excursion
  18421. (or (re-search-forward re nil t)
  18422. (re-search-backward re nil t))))
  18423. (user-error "No bibliography defined in file")
  18424. (setq bib (concat (match-string 1) ".bib")
  18425. org--rds (list (list 'bib bib))))))
  18426. (call-interactively 'reftex-citation)))
  18427. ;;;; Functions extending outline functionality
  18428. (defun org-beginning-of-line (&optional n)
  18429. "Go to the beginning of the current visible line.
  18430. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18431. symbol `reversed', on the first attempt move to where the
  18432. headline text starts, and only move to beginning of line when the
  18433. cursor is already before the start of the text of the headline.
  18434. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18435. start of the text on the second attempt.
  18436. With argument N not nil or 1, move forward N - 1 lines first."
  18437. (interactive "^p")
  18438. (let ((origin (point))
  18439. (special (pcase org-special-ctrl-a/e
  18440. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18441. deactivate-mark)
  18442. ;; First move to a visible line.
  18443. (if (bound-and-true-p visual-line-mode)
  18444. (beginning-of-visual-line n)
  18445. (move-beginning-of-line n)
  18446. ;; `move-beginning-of-line' may leave point after invisible
  18447. ;; characters if line starts with such of these (e.g., with
  18448. ;; a link at column 0). Really move to the beginning of the
  18449. ;; current visible line.
  18450. (beginning-of-line))
  18451. (cond
  18452. ;; No special behavior. Point is already at the beginning of
  18453. ;; a line, logical or visual.
  18454. ((not special))
  18455. ;; `beginning-of-visual-line' left point before logical beginning
  18456. ;; of line: point is at the beginning of a visual line. Bail
  18457. ;; out.
  18458. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18459. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18460. ;; At a headline, special position is before the title, but
  18461. ;; after any TODO keyword or priority cookie.
  18462. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18463. (line-end-position)))
  18464. (bol (point)))
  18465. (if (eq special 'reversed)
  18466. (when (and (= origin bol) (eq last-command this-command))
  18467. (goto-char refpos))
  18468. (when (or (> origin refpos) (= origin bol))
  18469. (goto-char refpos)))))
  18470. ((and (looking-at org-list-full-item-re)
  18471. (memq (org-element-type (save-match-data (org-element-at-point)))
  18472. '(item plain-list)))
  18473. ;; Set special position at first white space character after
  18474. ;; bullet, and check-box, if any.
  18475. (let ((after-bullet
  18476. (let ((box (match-end 3)))
  18477. (cond ((not box) (match-end 1))
  18478. ((eq (char-after box) ?\s) (1+ box))
  18479. (t box)))))
  18480. (if (eq special 'reversed)
  18481. (when (and (= (point) origin) (eq last-command this-command))
  18482. (goto-char after-bullet))
  18483. (when (or (> origin after-bullet) (= (point) origin))
  18484. (goto-char after-bullet)))))
  18485. ;; No special context. Point is already at beginning of line.
  18486. (t nil))))
  18487. (defun org-end-of-line (&optional n)
  18488. "Go to the end of the line, but before ellipsis, if any.
  18489. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18490. symbol `reversed', ignore tags on the first attempt, and only
  18491. move to after the tags when the cursor is already beyond the end
  18492. of the headline.
  18493. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18494. on the second attempt.
  18495. With argument N not nil or 1, move forward N - 1 lines first."
  18496. (interactive "^p")
  18497. (let ((origin (point))
  18498. (special (pcase org-special-ctrl-a/e
  18499. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18500. deactivate-mark)
  18501. ;; First move to a visible line.
  18502. (if (bound-and-true-p visual-line-mode)
  18503. (beginning-of-visual-line n)
  18504. (move-beginning-of-line n))
  18505. (cond
  18506. ;; At a headline, with tags.
  18507. ((and special
  18508. (save-excursion
  18509. (beginning-of-line)
  18510. (let ((case-fold-search nil))
  18511. (looking-at org-complex-heading-regexp)))
  18512. (match-end 5))
  18513. (let ((tags (save-excursion
  18514. (goto-char (match-beginning 5))
  18515. (skip-chars-backward " \t")
  18516. (point)))
  18517. (visual-end (and (bound-and-true-p visual-line-mode)
  18518. (save-excursion
  18519. (end-of-visual-line)
  18520. (point)))))
  18521. ;; If `end-of-visual-line' brings us before end of line or
  18522. ;; even tags, i.e., the headline spans over multiple visual
  18523. ;; lines, move there.
  18524. (cond ((and visual-end
  18525. (< visual-end tags)
  18526. (<= origin visual-end))
  18527. (goto-char visual-end))
  18528. ((eq special 'reversed)
  18529. (if (and (= origin (line-end-position))
  18530. (eq this-command last-command))
  18531. (goto-char tags)
  18532. (end-of-line)))
  18533. (t
  18534. (if (or (< origin tags) (= origin (line-end-position)))
  18535. (goto-char tags)
  18536. (end-of-line))))))
  18537. ((bound-and-true-p visual-line-mode)
  18538. (let ((bol (line-beginning-position)))
  18539. (end-of-visual-line)
  18540. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18541. ;; end of a line, backtrack and use `end-of-line' instead.
  18542. (when (/= bol (line-beginning-position))
  18543. (goto-char bol)
  18544. (end-of-line))))
  18545. (t (end-of-line)))))
  18546. (defun org-backward-sentence (&optional _arg)
  18547. "Go to beginning of sentence, or beginning of table field.
  18548. This will call `backward-sentence' or `org-table-beginning-of-field',
  18549. depending on context."
  18550. (interactive)
  18551. (let* ((element (org-element-at-point))
  18552. (contents-begin (org-element-property :contents-begin element))
  18553. (table (org-element-lineage element '(table) t)))
  18554. (if (and table
  18555. (> (point) contents-begin)
  18556. (<= (point) (org-element-property :contents-end table)))
  18557. (call-interactively #'org-table-beginning-of-field)
  18558. (save-restriction
  18559. (when (and contents-begin
  18560. (< (point-min) contents-begin)
  18561. (> (point) contents-begin))
  18562. (narrow-to-region contents-begin
  18563. (org-element-property :contents-end element)))
  18564. (call-interactively #'backward-sentence)))))
  18565. (defun org-forward-sentence (&optional _arg)
  18566. "Go to end of sentence, or end of table field.
  18567. This will call `forward-sentence' or `org-table-end-of-field',
  18568. depending on context."
  18569. (interactive)
  18570. (if (and (org-at-heading-p)
  18571. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18572. (save-restriction
  18573. (narrow-to-region (line-beginning-position) (line-end-position))
  18574. (call-interactively #'forward-sentence))
  18575. (let* ((element (org-element-at-point))
  18576. (contents-end (org-element-property :contents-end element))
  18577. (table (org-element-lineage element '(table) t)))
  18578. (if (and table
  18579. (>= (point) (org-element-property :contents-begin table))
  18580. (< (point) contents-end))
  18581. (call-interactively #'org-table-end-of-field)
  18582. (save-restriction
  18583. (when (and contents-end
  18584. (> (point-max) contents-end)
  18585. ;; Skip blank lines between elements.
  18586. (< (org-element-property :end element)
  18587. (save-excursion (goto-char contents-end)
  18588. (skip-chars-forward " \r\t\n"))))
  18589. (narrow-to-region (org-element-property :contents-begin element)
  18590. contents-end))
  18591. ;; End of heading is considered as the end of a sentence.
  18592. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18593. (call-interactively #'forward-sentence)))))))
  18594. (defun org-kill-line (&optional _arg)
  18595. "Kill line, to tags or end of line."
  18596. (interactive)
  18597. (cond
  18598. ((or (not org-special-ctrl-k)
  18599. (bolp)
  18600. (not (org-at-heading-p)))
  18601. (when (and (get-char-property (line-end-position) 'invisible)
  18602. org-ctrl-k-protect-subtree
  18603. (or (eq org-ctrl-k-protect-subtree 'error)
  18604. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18605. (user-error
  18606. (substitute-command-keys
  18607. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18608. (call-interactively
  18609. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18610. ((org-match-line org-tag-line-re)
  18611. (let ((end (save-excursion
  18612. (goto-char (match-beginning 1))
  18613. (skip-chars-backward " \t")
  18614. (point))))
  18615. (if (<= end (point)) ;on tags part
  18616. (kill-region (point) (line-end-position))
  18617. (kill-region (point) end)))
  18618. (org-align-tags))
  18619. (t (kill-region (point) (line-end-position)))))
  18620. (defun org-yank (&optional arg)
  18621. "Yank. If the kill is a subtree, treat it specially.
  18622. This command will look at the current kill and check if is a single
  18623. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18624. cursor is at the beginning of a line or after the stars of a currently
  18625. empty headline, then the yank is handled specially. How exactly depends
  18626. on the value of the following variables.
  18627. `org-yank-folded-subtrees'
  18628. By default, this variable is non-nil, which results in
  18629. subtree(s) being folded after insertion, except if doing so
  18630. would swallow text after the yanked text.
  18631. `org-yank-adjusted-subtrees'
  18632. When non-nil (the default value is nil), the subtree will be
  18633. promoted or demoted in order to fit into the local outline tree
  18634. structure, which means that the level will be adjusted so that it
  18635. becomes the smaller one of the two *visible* surrounding headings.
  18636. Any prefix to this command will cause `yank' to be called directly with
  18637. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18638. will just
  18639. plainly yank the text as it is.
  18640. \[1] The test checks if the first non-white line is a heading
  18641. and if there are no other headings with fewer stars."
  18642. (interactive "P")
  18643. (org-yank-generic 'yank arg))
  18644. (defun org-yank-generic (command arg)
  18645. "Perform some yank-like command.
  18646. This function implements the behavior described in the `org-yank'
  18647. documentation. However, it has been generalized to work for any
  18648. interactive command with similar behavior."
  18649. ;; pretend to be command COMMAND
  18650. (setq this-command command)
  18651. (if arg
  18652. (call-interactively command)
  18653. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18654. (and (org-kill-is-subtree-p)
  18655. (or (bolp)
  18656. (and (looking-at "[ \t]*$")
  18657. (string-match
  18658. "\\`\\*+\\'"
  18659. (buffer-substring (point-at-bol) (point)))))))
  18660. swallowp)
  18661. (cond
  18662. ((and subtreep org-yank-folded-subtrees)
  18663. (let ((beg (point))
  18664. end)
  18665. (if (and subtreep org-yank-adjusted-subtrees)
  18666. (org-paste-subtree nil nil 'for-yank)
  18667. (call-interactively command))
  18668. (setq end (point))
  18669. (goto-char beg)
  18670. (when (and (bolp) subtreep
  18671. (not (setq swallowp
  18672. (org-yank-folding-would-swallow-text beg end))))
  18673. (org-with-limited-levels
  18674. (or (looking-at org-outline-regexp)
  18675. (re-search-forward org-outline-regexp-bol end t))
  18676. (while (and (< (point) end) (looking-at org-outline-regexp))
  18677. (org-flag-subtree t)
  18678. (org-cycle-show-empty-lines 'folded)
  18679. (condition-case nil
  18680. (outline-forward-same-level 1)
  18681. (error (goto-char end))))))
  18682. (when swallowp
  18683. (message
  18684. "Inserted text not folded because that would swallow text"))
  18685. (goto-char end)
  18686. (skip-chars-forward " \t\n\r")
  18687. (beginning-of-line 1)
  18688. (push-mark beg 'nomsg)))
  18689. ((and subtreep org-yank-adjusted-subtrees)
  18690. (let ((beg (point-at-bol)))
  18691. (org-paste-subtree nil nil 'for-yank)
  18692. (push-mark beg 'nomsg)))
  18693. (t
  18694. (call-interactively command))))))
  18695. (defun org-yank-folding-would-swallow-text (beg end)
  18696. "Would hide-subtree at BEG swallow any text after END?"
  18697. (let (level)
  18698. (org-with-limited-levels
  18699. (save-excursion
  18700. (goto-char beg)
  18701. (when (or (looking-at org-outline-regexp)
  18702. (re-search-forward org-outline-regexp-bol end t))
  18703. (setq level (org-outline-level)))
  18704. (goto-char end)
  18705. (skip-chars-forward " \t\r\n\v\f")
  18706. (not (or (eobp)
  18707. (and (bolp) (looking-at-p org-outline-regexp)
  18708. (<= (org-outline-level) level))))))))
  18709. (defun org-back-to-heading (&optional invisible-ok)
  18710. "Call `outline-back-to-heading', but provide a better error message."
  18711. (condition-case nil
  18712. (outline-back-to-heading invisible-ok)
  18713. (error (error "Before first headline at position %d in buffer %s"
  18714. (point) (current-buffer)))))
  18715. (defun org-before-first-heading-p ()
  18716. "Before first heading?"
  18717. (org-with-limited-levels
  18718. (save-excursion
  18719. (end-of-line)
  18720. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18721. (defun org-at-heading-p (&optional _)
  18722. "Non-nil when on a headline."
  18723. (outline-on-heading-p t))
  18724. (defun org-in-commented-heading-p (&optional no-inheritance)
  18725. "Non-nil if point is under a commented heading.
  18726. This function also checks ancestors of the current headline,
  18727. unless optional argument NO-INHERITANCE is non-nil."
  18728. (cond
  18729. ((org-before-first-heading-p) nil)
  18730. ((let ((headline (nth 4 (org-heading-components))))
  18731. (and headline
  18732. (let ((case-fold-search nil))
  18733. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18734. headline)))))
  18735. (no-inheritance nil)
  18736. (t
  18737. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18738. (defun org-at-comment-p nil
  18739. "Return t if cursor is in a commented line."
  18740. (save-excursion
  18741. (save-match-data
  18742. (beginning-of-line)
  18743. (looking-at "^[ \t]*# "))))
  18744. (defun org-at-drawer-p nil
  18745. "Return t if cursor is at a drawer keyword."
  18746. (save-excursion
  18747. (move-beginning-of-line 1)
  18748. (looking-at org-drawer-regexp)))
  18749. (defun org-at-block-p nil
  18750. "Return t if cursor is at a block keyword."
  18751. (save-excursion
  18752. (move-beginning-of-line 1)
  18753. (looking-at org-block-regexp)))
  18754. (defun org-point-at-end-of-empty-headline ()
  18755. "If point is at the end of an empty headline, return t, else nil.
  18756. If the heading only contains a TODO keyword, it is still still considered
  18757. empty."
  18758. (let ((case-fold-search nil))
  18759. (and (looking-at "[ \t]*$")
  18760. org-todo-line-regexp
  18761. (save-excursion
  18762. (beginning-of-line)
  18763. (looking-at org-todo-line-regexp)
  18764. (string= (match-string 3) "")))))
  18765. (defun org-at-heading-or-item-p ()
  18766. (or (org-at-heading-p) (org-at-item-p)))
  18767. (defun org-up-heading-all (arg)
  18768. "Move to the heading line of which the present line is a subheading.
  18769. This function considers both visible and invisible heading lines.
  18770. With argument, move up ARG levels."
  18771. (outline-up-heading arg t))
  18772. (defun org-up-heading-safe ()
  18773. "Move to the heading line of which the present line is a subheading.
  18774. This version will not throw an error. It will return the level of the
  18775. headline found, or nil if no higher level is found.
  18776. Also, this function will be a lot faster than `outline-up-heading',
  18777. because it relies on stars being the outline starters. This can really
  18778. make a significant difference in outlines with very many siblings."
  18779. (when (ignore-errors (org-back-to-heading t))
  18780. (let ((level-up (1- (funcall outline-level))))
  18781. (and (> level-up 0)
  18782. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18783. (funcall outline-level)))))
  18784. (defun org-first-sibling-p ()
  18785. "Is this heading the first child of its parents?"
  18786. (interactive)
  18787. (let ((re org-outline-regexp-bol)
  18788. level l)
  18789. (unless (org-at-heading-p t)
  18790. (user-error "Not at a heading"))
  18791. (setq level (funcall outline-level))
  18792. (save-excursion
  18793. (if (not (re-search-backward re nil t))
  18794. t
  18795. (setq l (funcall outline-level))
  18796. (< l level)))))
  18797. (defun org-goto-sibling (&optional previous)
  18798. "Goto the next sibling, even if it is invisible.
  18799. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18800. when a sibling was found. When none is found, return nil and don't
  18801. move point."
  18802. (let ((fun (if previous 're-search-backward 're-search-forward))
  18803. (pos (point))
  18804. (re org-outline-regexp-bol)
  18805. level l)
  18806. (when (ignore-errors (org-back-to-heading t))
  18807. (setq level (funcall outline-level))
  18808. (catch 'exit
  18809. (or previous (forward-char 1))
  18810. (while (funcall fun re nil t)
  18811. (setq l (funcall outline-level))
  18812. (when (< l level) (goto-char pos) (throw 'exit nil))
  18813. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18814. (goto-char pos)
  18815. nil))))
  18816. (defun org-show-siblings ()
  18817. "Show all siblings of the current headline."
  18818. (save-excursion
  18819. (while (org-goto-sibling) (org-flag-heading nil)))
  18820. (save-excursion
  18821. (while (org-goto-sibling 'previous)
  18822. (org-flag-heading nil))))
  18823. (defun org-goto-first-child ()
  18824. "Goto the first child, even if it is invisible.
  18825. Return t when a child was found. Otherwise don't move point and
  18826. return nil."
  18827. (let (level (pos (point)) (re org-outline-regexp-bol))
  18828. (when (ignore-errors (org-back-to-heading t))
  18829. (setq level (outline-level))
  18830. (forward-char 1)
  18831. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18832. (progn (goto-char (match-beginning 0)) t)
  18833. (goto-char pos) nil))))
  18834. (defun org-show-hidden-entry ()
  18835. "Show an entry where even the heading is hidden."
  18836. (save-excursion
  18837. (org-show-entry)))
  18838. (defun org-flag-heading (flag &optional entry)
  18839. "Flag the current heading. FLAG non-nil means make invisible.
  18840. When ENTRY is non-nil, show the entire entry."
  18841. (save-excursion
  18842. (org-back-to-heading t)
  18843. ;; Check if we should show the entire entry
  18844. (if (not entry)
  18845. (org-flag-region
  18846. (line-end-position 0) (line-end-position) flag 'outline)
  18847. (org-show-entry)
  18848. (save-excursion
  18849. (and (outline-next-heading)
  18850. (org-flag-heading nil))))))
  18851. (defun org-get-next-sibling ()
  18852. "Move to next heading of the same level, and return point.
  18853. If there is no such heading, return nil.
  18854. This is like outline-next-sibling, but invisible headings are ok."
  18855. (let ((level (funcall outline-level)))
  18856. (outline-next-heading)
  18857. (while (and (not (eobp)) (> (funcall outline-level) level))
  18858. (outline-next-heading))
  18859. (unless (or (eobp) (< (funcall outline-level) level))
  18860. (point))))
  18861. (defun org-get-last-sibling ()
  18862. "Move to previous heading of the same level, and return point.
  18863. If there is no such heading, return nil."
  18864. (let ((opoint (point))
  18865. (level (funcall outline-level)))
  18866. (outline-previous-heading)
  18867. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18868. (while (and (> (funcall outline-level) level)
  18869. (not (bobp)))
  18870. (outline-previous-heading))
  18871. (unless (< (funcall outline-level) level)
  18872. (point)))))
  18873. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18874. "Goto to the end of a subtree."
  18875. ;; This contains an exact copy of the original function, but it uses
  18876. ;; `org-back-to-heading', to make it work also in invisible
  18877. ;; trees. And is uses an invisible-ok argument.
  18878. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18879. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18880. ;; with many children and grandchildren etc, this can be much faster
  18881. ;; than the outline version.
  18882. (org-back-to-heading invisible-ok)
  18883. (let ((first t)
  18884. (level (funcall outline-level)))
  18885. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18886. ;; A true heading (not a plain list item), in Org
  18887. ;; This means we can easily find the end by looking
  18888. ;; only for the right number of stars. Using a regexp to do
  18889. ;; this is so much faster than using a Lisp loop.
  18890. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18891. (forward-char 1)
  18892. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18893. ;; something else, do it the slow way
  18894. (while (and (not (eobp))
  18895. (or first (> (funcall outline-level) level)))
  18896. (setq first nil)
  18897. (outline-next-heading)))
  18898. (unless to-heading
  18899. (when (memq (preceding-char) '(?\n ?\^M))
  18900. ;; Go to end of line before heading
  18901. (forward-char -1)
  18902. (when (memq (preceding-char) '(?\n ?\^M))
  18903. ;; leave blank line before heading
  18904. (forward-char -1)))))
  18905. (point))
  18906. (defun org-end-of-meta-data (&optional full)
  18907. "Skip planning line and properties drawer in current entry.
  18908. When optional argument FULL is non-nil, also skip empty lines,
  18909. clocking lines and regular drawers at the beginning of the
  18910. entry."
  18911. (org-back-to-heading t)
  18912. (forward-line)
  18913. (when (looking-at-p org-planning-line-re) (forward-line))
  18914. (when (looking-at org-property-drawer-re)
  18915. (goto-char (match-end 0))
  18916. (forward-line))
  18917. (when (and full (not (org-at-heading-p)))
  18918. (catch 'exit
  18919. (let ((end (save-excursion (outline-next-heading) (point)))
  18920. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18921. (while (not (eobp))
  18922. (cond ((looking-at-p org-drawer-regexp)
  18923. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18924. (forward-line)
  18925. (throw 'exit t)))
  18926. ((looking-at-p re) (forward-line))
  18927. (t (throw 'exit t))))))))
  18928. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18929. "Move forward to the ARG'th subheading at same level as this one.
  18930. Stop at the first and last subheadings of a superior heading.
  18931. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18932. non-nil it will also look at invisible ones."
  18933. (interactive "p")
  18934. (let ((backward? (and arg (< arg 0))))
  18935. (if (org-before-first-heading-p)
  18936. (if backward? (goto-char (point-min)) (outline-next-heading))
  18937. (org-back-to-heading invisible-ok)
  18938. (unless backward? (end-of-line)) ;do not match current headline
  18939. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18940. (f (if backward? #'re-search-backward #'re-search-forward))
  18941. (count (if arg (abs arg) 1))
  18942. (result (point)))
  18943. (while (and (> count 0)
  18944. (funcall f org-outline-regexp-bol nil 'move))
  18945. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18946. (cond ((< l level) (setq count 0))
  18947. ((and (= l level)
  18948. (or invisible-ok
  18949. (not (org-invisible-p
  18950. (line-beginning-position)))))
  18951. (cl-decf count)
  18952. (when (= l level) (setq result (point)))))))
  18953. (goto-char result))
  18954. (beginning-of-line))))
  18955. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18956. "Move backward to the ARG'th subheading at same level as this one.
  18957. Stop at the first and last subheadings of a superior heading."
  18958. (interactive "p")
  18959. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18960. (defun org-next-visible-heading (arg)
  18961. "Move to the next visible heading.
  18962. This function wraps `outline-next-visible-heading' with
  18963. `org-with-limited-levels' in order to skip over inline tasks and
  18964. respect customization of `org-odd-levels-only'."
  18965. (interactive "p")
  18966. (org-with-limited-levels
  18967. (outline-next-visible-heading arg)))
  18968. (defun org-previous-visible-heading (arg)
  18969. "Move to the previous visible heading.
  18970. This function wraps `outline-previous-visible-heading' with
  18971. `org-with-limited-levels' in order to skip over inline tasks and
  18972. respect customization of `org-odd-levels-only'."
  18973. (interactive "p")
  18974. (org-with-limited-levels
  18975. (outline-previous-visible-heading arg)))
  18976. (defun org-forward-paragraph ()
  18977. "Move forward to beginning of next paragraph or equivalent.
  18978. The function moves point to the beginning of the next visible
  18979. structural element, which can be a paragraph, a table, a list
  18980. item, etc. It also provides some special moves for convenience:
  18981. - On an affiliated keyword, jump to the beginning of the
  18982. relative element.
  18983. - On an item or a footnote definition, move to the second
  18984. element inside, if any.
  18985. - On a table or a property drawer, jump after it.
  18986. - On a verse or source block, stop after blank lines."
  18987. (interactive)
  18988. (unless (eobp)
  18989. (let* ((deactivate-mark nil)
  18990. (element (org-element-at-point))
  18991. (type (org-element-type element))
  18992. (post-affiliated (org-element-property :post-affiliated element))
  18993. (contents-begin (org-element-property :contents-begin element))
  18994. (contents-end (org-element-property :contents-end element))
  18995. (end (let ((end (org-element-property :end element)) (parent element))
  18996. (while (and (setq parent (org-element-property :parent parent))
  18997. (= (org-element-property :contents-end parent) end))
  18998. (setq end (org-element-property :end parent)))
  18999. end)))
  19000. (cond ((not element)
  19001. (skip-chars-forward " \r\t\n")
  19002. (or (eobp) (beginning-of-line)))
  19003. ;; On affiliated keywords, move to element's beginning.
  19004. ((< (point) post-affiliated)
  19005. (goto-char post-affiliated))
  19006. ;; At a table row, move to the end of the table. Similarly,
  19007. ;; at a node property, move to the end of the property
  19008. ;; drawer.
  19009. ((memq type '(node-property table-row))
  19010. (goto-char (org-element-property
  19011. :end (org-element-property :parent element))))
  19012. ((memq type '(property-drawer table)) (goto-char end))
  19013. ;; Consider blank lines as separators in verse and source
  19014. ;; blocks to ease editing.
  19015. ((memq type '(src-block verse-block))
  19016. (when (eq type 'src-block)
  19017. (setq contents-end
  19018. (save-excursion (goto-char end)
  19019. (skip-chars-backward " \r\t\n")
  19020. (line-beginning-position))))
  19021. (beginning-of-line)
  19022. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19023. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19024. (goto-char end)
  19025. (skip-chars-forward " \r\t\n")
  19026. (if (= (point) contents-end) (goto-char end)
  19027. (beginning-of-line))))
  19028. ;; With no contents, just skip element.
  19029. ((not contents-begin) (goto-char end))
  19030. ;; If contents are invisible, skip the element altogether.
  19031. ((org-invisible-p (line-end-position))
  19032. (cl-case type
  19033. (headline
  19034. (org-with-limited-levels (outline-next-visible-heading 1)))
  19035. ;; At a plain list, make sure we move to the next item
  19036. ;; instead of skipping the whole list.
  19037. (plain-list (forward-char)
  19038. (org-forward-paragraph))
  19039. (otherwise (goto-char end))))
  19040. ((>= (point) contents-end) (goto-char end))
  19041. ((>= (point) contents-begin)
  19042. ;; This can only happen on paragraphs and plain lists.
  19043. (cl-case type
  19044. (paragraph (goto-char end))
  19045. ;; At a plain list, try to move to second element in
  19046. ;; first item, if possible.
  19047. (plain-list (end-of-line)
  19048. (org-forward-paragraph))))
  19049. ;; When contents start on the middle of a line (e.g. in
  19050. ;; items and footnote definitions), try to reach first
  19051. ;; element starting after current line.
  19052. ((> (line-end-position) contents-begin)
  19053. (end-of-line)
  19054. (org-forward-paragraph))
  19055. (t (goto-char contents-begin))))))
  19056. (defun org-backward-paragraph ()
  19057. "Move backward to start of previous paragraph or equivalent.
  19058. The function moves point to the beginning of the current
  19059. structural element, which can be a paragraph, a table, a list
  19060. item, etc., or to the beginning of the previous visible one if
  19061. point is already there. It also provides some special moves for
  19062. convenience:
  19063. - On an affiliated keyword, jump to the first one.
  19064. - On a table or a property drawer, move to its beginning.
  19065. - On comment, example, export, src and verse blocks, stop
  19066. before blank lines."
  19067. (interactive)
  19068. (unless (bobp)
  19069. (let* ((deactivate-mark nil)
  19070. (element (org-element-at-point))
  19071. (type (org-element-type element))
  19072. (contents-end (org-element-property :contents-end element))
  19073. (post-affiliated (org-element-property :post-affiliated element))
  19074. (begin (org-element-property :begin element))
  19075. (special? ;blocks handled specially
  19076. (memq type '(comment-block example-block export-block src-block
  19077. verse-block)))
  19078. (contents-begin
  19079. (if special?
  19080. ;; These types have no proper contents. Fake line
  19081. ;; below the block opening line as contents beginning.
  19082. (save-excursion (goto-char begin) (line-beginning-position 2))
  19083. (org-element-property :contents-begin element))))
  19084. (cond
  19085. ((not element) (goto-char (point-min)))
  19086. ((= (point) begin)
  19087. (backward-char)
  19088. (org-backward-paragraph))
  19089. ((<= (point) post-affiliated) (goto-char begin))
  19090. ;; Special behavior: on a table or a property drawer, move to
  19091. ;; its beginning.
  19092. ((memq type '(node-property table-row))
  19093. (goto-char (org-element-property
  19094. :post-affiliated (org-element-property :parent element))))
  19095. (special?
  19096. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19097. ;; Inside a verse block, see blank lines as paragraph
  19098. ;; separators.
  19099. (let ((origin (point)))
  19100. (skip-chars-backward " \r\t\n" contents-begin)
  19101. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19102. (skip-chars-forward " \r\t\n" origin)
  19103. (if (= (point) origin) (goto-char contents-begin)
  19104. (beginning-of-line))))))
  19105. ((eq type 'paragraph) (goto-char contents-begin)
  19106. ;; When at first paragraph in an item or a footnote definition,
  19107. ;; move directly to beginning of line.
  19108. (let ((parent-contents
  19109. (org-element-property
  19110. :contents-begin (org-element-property :parent element))))
  19111. (when (and parent-contents (= parent-contents contents-begin))
  19112. (beginning-of-line))))
  19113. ;; At the end of a greater element, move to the beginning of
  19114. ;; the last element within.
  19115. ((and contents-end (>= (point) contents-end))
  19116. (goto-char (1- contents-end))
  19117. (org-backward-paragraph))
  19118. (t (goto-char (or post-affiliated begin))))
  19119. ;; Ensure we never leave point invisible.
  19120. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19121. (defun org-forward-element ()
  19122. "Move forward by one element.
  19123. Move to the next element at the same level, when possible."
  19124. (interactive)
  19125. (cond ((eobp) (user-error "Cannot move further down"))
  19126. ((org-with-limited-levels (org-at-heading-p))
  19127. (let ((origin (point)))
  19128. (goto-char (org-end-of-subtree nil t))
  19129. (unless (org-with-limited-levels (org-at-heading-p))
  19130. (goto-char origin)
  19131. (user-error "Cannot move further down"))))
  19132. (t
  19133. (let* ((elem (org-element-at-point))
  19134. (end (org-element-property :end elem))
  19135. (parent (org-element-property :parent elem)))
  19136. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19137. (goto-char (org-element-property :end parent)))
  19138. ((integer-or-marker-p end) (goto-char end))
  19139. (t (message "No element at point")))))))
  19140. (defun org-backward-element ()
  19141. "Move backward by one element.
  19142. Move to the previous element at the same level, when possible."
  19143. (interactive)
  19144. (cond ((bobp) (user-error "Cannot move further up"))
  19145. ((org-with-limited-levels (org-at-heading-p))
  19146. ;; At a headline, move to the previous one, if any, or stay
  19147. ;; here.
  19148. (let ((origin (point)))
  19149. (org-with-limited-levels (org-backward-heading-same-level 1))
  19150. ;; When current headline has no sibling above, move to its
  19151. ;; parent.
  19152. (when (= (point) origin)
  19153. (or (org-with-limited-levels (org-up-heading-safe))
  19154. (progn (goto-char origin)
  19155. (user-error "Cannot move further up"))))))
  19156. (t
  19157. (let* ((elem (org-element-at-point))
  19158. (beg (org-element-property :begin elem)))
  19159. (cond
  19160. ;; Move to beginning of current element if point isn't
  19161. ;; there already.
  19162. ((null beg) (message "No element at point"))
  19163. ((/= (point) beg) (goto-char beg))
  19164. (t (goto-char beg)
  19165. (skip-chars-backward " \r\t\n")
  19166. (unless (bobp)
  19167. (let ((prev (org-element-at-point)))
  19168. (goto-char (org-element-property :begin prev))
  19169. (while (and (setq prev (org-element-property :parent prev))
  19170. (<= (org-element-property :end prev) beg))
  19171. (goto-char (org-element-property :begin prev)))))))))))
  19172. (defun org-up-element ()
  19173. "Move to upper element."
  19174. (interactive)
  19175. (if (org-with-limited-levels (org-at-heading-p))
  19176. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19177. (let* ((elem (org-element-at-point))
  19178. (parent (org-element-property :parent elem)))
  19179. (if parent (goto-char (org-element-property :begin parent))
  19180. (if (org-with-limited-levels (org-before-first-heading-p))
  19181. (user-error "No surrounding element")
  19182. (org-with-limited-levels (org-back-to-heading)))))))
  19183. (defun org-down-element ()
  19184. "Move to inner element."
  19185. (interactive)
  19186. (let ((element (org-element-at-point)))
  19187. (cond
  19188. ((memq (org-element-type element) '(plain-list table))
  19189. (goto-char (org-element-property :contents-begin element))
  19190. (forward-char))
  19191. ((memq (org-element-type element) org-element-greater-elements)
  19192. ;; If contents are hidden, first disclose them.
  19193. (when (org-invisible-p (line-end-position)) (org-cycle))
  19194. (goto-char (or (org-element-property :contents-begin element)
  19195. (user-error "No content for this element"))))
  19196. (t (user-error "No inner element")))))
  19197. (defun org-drag-element-backward ()
  19198. "Move backward element at point."
  19199. (interactive)
  19200. (let ((elem (or (org-element-at-point)
  19201. (user-error "No element at point"))))
  19202. (if (eq (org-element-type elem) 'headline)
  19203. ;; Preserve point when moving a whole tree, even if point was
  19204. ;; on blank lines below the headline.
  19205. (let ((offset (skip-chars-backward " \t\n")))
  19206. (unwind-protect (org-move-subtree-up)
  19207. (forward-char (- offset))))
  19208. (let ((prev-elem
  19209. (save-excursion
  19210. (goto-char (org-element-property :begin elem))
  19211. (skip-chars-backward " \r\t\n")
  19212. (unless (bobp)
  19213. (let* ((beg (org-element-property :begin elem))
  19214. (prev (org-element-at-point))
  19215. (up prev))
  19216. (while (and (setq up (org-element-property :parent up))
  19217. (<= (org-element-property :end up) beg))
  19218. (setq prev up))
  19219. prev)))))
  19220. ;; Error out if no previous element or previous element is
  19221. ;; a parent of the current one.
  19222. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19223. (user-error "Cannot drag element backward")
  19224. (let ((pos (point)))
  19225. (org-element-swap-A-B prev-elem elem)
  19226. (goto-char (+ (org-element-property :begin prev-elem)
  19227. (- pos (org-element-property :begin elem))))))))))
  19228. (defun org-drag-element-forward ()
  19229. "Move forward element at point."
  19230. (interactive)
  19231. (let* ((pos (point))
  19232. (elem (or (org-element-at-point)
  19233. (user-error "No element at point"))))
  19234. (when (= (point-max) (org-element-property :end elem))
  19235. (user-error "Cannot drag element forward"))
  19236. (goto-char (org-element-property :end elem))
  19237. (let ((next-elem (org-element-at-point)))
  19238. (when (or (org-element-nested-p elem next-elem)
  19239. (and (eq (org-element-type next-elem) 'headline)
  19240. (not (eq (org-element-type elem) 'headline))))
  19241. (goto-char pos)
  19242. (user-error "Cannot drag element forward"))
  19243. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19244. ;; body's length (without final blanks) and by the length of
  19245. ;; blanks between ELEM and NEXT-ELEM.
  19246. (let ((size-next (- (save-excursion
  19247. (goto-char (org-element-property :end next-elem))
  19248. (skip-chars-backward " \r\t\n")
  19249. (forward-line)
  19250. ;; Small correction if buffer doesn't end
  19251. ;; with a newline character.
  19252. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19253. (org-element-property :begin next-elem)))
  19254. (size-blank (- (org-element-property :end elem)
  19255. (save-excursion
  19256. (goto-char (org-element-property :end elem))
  19257. (skip-chars-backward " \r\t\n")
  19258. (forward-line)
  19259. (point)))))
  19260. (org-element-swap-A-B elem next-elem)
  19261. (goto-char (+ pos size-next size-blank))))))
  19262. (defun org-drag-line-forward (arg)
  19263. "Drag the line at point ARG lines forward."
  19264. (interactive "p")
  19265. (dotimes (_ (abs arg))
  19266. (let ((c (current-column)))
  19267. (if (< 0 arg)
  19268. (progn
  19269. (beginning-of-line 2)
  19270. (transpose-lines 1)
  19271. (beginning-of-line 0))
  19272. (transpose-lines 1)
  19273. (beginning-of-line -1))
  19274. (org-move-to-column c))))
  19275. (defun org-drag-line-backward (arg)
  19276. "Drag the line at point ARG lines backward."
  19277. (interactive "p")
  19278. (org-drag-line-forward (- arg)))
  19279. (defun org-mark-element ()
  19280. "Put point at beginning of this element, mark at end.
  19281. Interactively, if this command is repeated or (in Transient Mark
  19282. mode) if the mark is active, it marks the next element after the
  19283. ones already marked."
  19284. (interactive)
  19285. (let (deactivate-mark)
  19286. (if (and (called-interactively-p 'any)
  19287. (or (and (eq last-command this-command) (mark t))
  19288. (and transient-mark-mode mark-active)))
  19289. (set-mark
  19290. (save-excursion
  19291. (goto-char (mark))
  19292. (goto-char (org-element-property :end (org-element-at-point)))))
  19293. (let ((element (org-element-at-point)))
  19294. (end-of-line)
  19295. (push-mark (org-element-property :end element) t t)
  19296. (goto-char (org-element-property :begin element))))))
  19297. (defun org-narrow-to-element ()
  19298. "Narrow buffer to current element."
  19299. (interactive)
  19300. (let ((elem (org-element-at-point)))
  19301. (cond
  19302. ((eq (car elem) 'headline)
  19303. (narrow-to-region
  19304. (org-element-property :begin elem)
  19305. (org-element-property :end elem)))
  19306. ((memq (car elem) org-element-greater-elements)
  19307. (narrow-to-region
  19308. (org-element-property :contents-begin elem)
  19309. (org-element-property :contents-end elem)))
  19310. (t
  19311. (narrow-to-region
  19312. (org-element-property :begin elem)
  19313. (org-element-property :end elem))))))
  19314. (defun org-transpose-element ()
  19315. "Transpose current and previous elements, keeping blank lines between.
  19316. Point is moved after both elements."
  19317. (interactive)
  19318. (org-skip-whitespace)
  19319. (let ((end (org-element-property :end (org-element-at-point))))
  19320. (org-drag-element-backward)
  19321. (goto-char end)))
  19322. (defun org-unindent-buffer ()
  19323. "Un-indent the visible part of the buffer.
  19324. Relative indentation (between items, inside blocks, etc.) isn't
  19325. modified."
  19326. (interactive)
  19327. (unless (eq major-mode 'org-mode)
  19328. (user-error "Cannot un-indent a buffer not in Org mode"))
  19329. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19330. (unindent-tree
  19331. (lambda (contents)
  19332. (dolist (element (reverse contents))
  19333. (if (memq (org-element-type element) '(headline section))
  19334. (funcall unindent-tree (org-element-contents element))
  19335. (save-excursion
  19336. (save-restriction
  19337. (narrow-to-region
  19338. (org-element-property :begin element)
  19339. (org-element-property :end element))
  19340. (org-do-remove-indentation))))))))
  19341. (funcall unindent-tree (org-element-contents parse-tree))))
  19342. (defun org-make-options-regexp (kwds &optional extra)
  19343. "Make a regular expression for keyword lines.
  19344. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19345. when non-nil, is a regexp matching keywords names."
  19346. (concat "^[ \t]*#\\+\\("
  19347. (regexp-opt kwds)
  19348. (and extra (concat (and kwds "\\|") extra))
  19349. "\\):[ \t]*\\(.*\\)"))
  19350. ;;; Conveniently switch to Info nodes
  19351. (defun org-info-find-node (&optional nodename)
  19352. "Find Info documentation NODENAME or Org documentation according context.
  19353. Started from `gnus-info-find-node'."
  19354. (interactive)
  19355. (Info-goto-node
  19356. (or nodename
  19357. (let ((default-org-info-node "(org) Top"))
  19358. (cond
  19359. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19360. ((eq 'org-mode major-mode)
  19361. (let* ((context (org-element-at-point))
  19362. (element-info-nodes ; compare to `org-element-all-elements'.
  19363. `((babel-call . "(org) Evaluating Code Blocks")
  19364. (center-block . "(org) Paragraphs")
  19365. (clock . ,default-org-info-node)
  19366. (comment . "(org) Comment Lines")
  19367. (comment-block . "(org) Comment Lines")
  19368. (diary-sexp . ,default-org-info-node)
  19369. (drawer . "(org) Drawers")
  19370. (dynamic-block . "(org) Dynamic Blocks")
  19371. (example-block . "(org) Literal Examples")
  19372. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19373. (fixed-width . ,default-org-info-node)
  19374. (footnote-definition . "(org) Creating Footnotes")
  19375. (headline . "(org) Document Structure")
  19376. (horizontal-rule . "(org) Built-in Table Editor")
  19377. (inlinetask . ,default-org-info-node)
  19378. (item . "(org) Plain Lists")
  19379. (keyword . "(org) Per-file keywords")
  19380. (latex-environment . "(org) LaTeX Export")
  19381. (node-property . "(org) Properties and Columns")
  19382. (paragraph . "(org) Paragraphs")
  19383. (plain-list . "(org) Plain Lists")
  19384. (planning . "(org) Deadlines and Scheduling")
  19385. (property-drawer . "(org) Properties and Columns")
  19386. (quote-block . "(org) Paragraphs")
  19387. (section . ,default-org-info-node)
  19388. (special-block . ,default-org-info-node)
  19389. (src-block . "(org) Working with Source Code")
  19390. (table . "(org) Tables")
  19391. (table-row . "(org) Tables")
  19392. (verse-block . "(org) Paragraphs"))))
  19393. (or (cdr (assoc (car context) element-info-nodes))
  19394. default-org-info-node)))
  19395. (t default-org-info-node))))))
  19396. ;;; Finish up
  19397. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19398. (lambda () (add-hook 'change-major-mode-hook
  19399. 'org-show-all 'append 'local)))
  19400. (provide 'org)
  19401. (run-hooks 'org-load-hook)
  19402. ;;; org.el ends here