org.el 802 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.5-dev
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-attach-dir "org-attach"
  111. (&optional create-if-not-exists-p no-fs-check))
  112. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  113. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  114. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  115. (declare-function org-clock-auto-clockout "org-clock" ())
  116. (declare-function org-clock-cancel "org-clock" ())
  117. (declare-function org-clock-display "org-clock" (&optional arg))
  118. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  119. (declare-function org-clock-goto "org-clock" (&optional select))
  120. (declare-function org-clock-in "org-clock" (&optional select start-time))
  121. (declare-function org-clock-in-last "org-clock" (&optional arg))
  122. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  123. (declare-function org-clock-out-if-current "org-clock" ())
  124. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  125. (declare-function org-clock-report "org-clock" (&optional arg))
  126. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  127. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  128. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  129. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  130. (declare-function org-clock-update-time-maybe "org-clock" ())
  131. (declare-function org-clocking-buffer "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-element-at-point "org-element" ())
  137. (declare-function org-element-cache-refresh "org-element" (pos))
  138. (declare-function org-element-cache-reset "org-element" (&optional all))
  139. (declare-function org-element-contents "org-element" (element))
  140. (declare-function org-element-context "org-element" (&optional element))
  141. (declare-function org-element-copy "org-element" (datum))
  142. (declare-function org-element-create "org-element" (type &optional props &rest children))
  143. (declare-function org-element-interpret-data "org-element" (data))
  144. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  145. (declare-function org-element-link-parser "org-element" ())
  146. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  147. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  148. (declare-function org-element-property "org-element" (property element))
  149. (declare-function org-element-put-property "org-element" (element property value))
  150. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  151. (declare-function org-element-timestamp-parser "org-element" ())
  152. (declare-function org-element-type "org-element" (element))
  153. (declare-function org-export-dispatch "ox" (&optional arg))
  154. (declare-function org-export-get-backend "ox" (name))
  155. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  156. (declare-function org-feed-goto-inbox "org-feed" (feed))
  157. (declare-function org-feed-update-all "org-feed" ())
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-num-mode "org-num" (&optional arg))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  168. (declare-function org-timer "org-timer" (&optional restart no-insert))
  169. (declare-function org-timer-item "org-timer" (&optional arg))
  170. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  171. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  172. (declare-function org-timer-start "org-timer" (&optional offset))
  173. (declare-function org-timer-stop "org-timer" ())
  174. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  175. (declare-function org-update-radio-target-regexp "ol" ())
  176. (defvar ffap-url-regexp)
  177. (defvar org-element-paragraph-separate)
  178. (defvar org-indent-indentation-per-level)
  179. (defvar org-radio-target-regexp)
  180. (defvar org-target-link-regexp)
  181. (defvar org-target-regexp)
  182. (defvar org-id-overriding-file-name)
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With
  202. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  203. byte-compiled before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  206. ;; Tangle only if the Org file is newer than the Elisp file.
  207. (unless (org-file-newer-than-p
  208. tangled-file
  209. (file-attribute-modification-time
  210. (file-attributes (file-truename file))))
  211. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  212. (if compile
  213. (progn
  214. (byte-compile-file tangled-file)
  215. (load tangled-file)
  216. (message "Compiled and loaded %s" tangled-file))
  217. (load-file tangled-file)
  218. (message "Loaded %s" tangled-file))))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. \\<org-mode-map>
  222. This list can be used to load support for any of the languages
  223. below. Each language will depend on a different set of system
  224. executables and/or Emacs modes.
  225. When a language is \"loaded\", code blocks in that language can
  226. be evaluated with `org-babel-execute-src-block', which is bound
  227. by default to \\[org-ctrl-c-ctrl-c].
  228. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  229. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  230. default, only Emacs Lisp is loaded, since it has no specific
  231. requirement."
  232. :group 'org-babel
  233. :set 'org-babel-do-load-languages
  234. :version "24.1"
  235. :type '(alist :tag "Babel Languages"
  236. :key-type
  237. (choice
  238. (const :tag "Awk" awk)
  239. (const :tag "C" C)
  240. (const :tag "R" R)
  241. (const :tag "Asymptote" asymptote)
  242. (const :tag "Calc" calc)
  243. (const :tag "Clojure" clojure)
  244. (const :tag "CSS" css)
  245. (const :tag "Ditaa" ditaa)
  246. (const :tag "Dot" dot)
  247. (const :tag "Ebnf2ps" ebnf2ps)
  248. (const :tag "Emacs Lisp" emacs-lisp)
  249. (const :tag "Forth" forth)
  250. (const :tag "Fortran" fortran)
  251. (const :tag "Gnuplot" gnuplot)
  252. (const :tag "Haskell" haskell)
  253. (const :tag "hledger" hledger)
  254. (const :tag "IO" io)
  255. (const :tag "J" J)
  256. (const :tag "Java" java)
  257. (const :tag "Javascript" js)
  258. (const :tag "LaTeX" latex)
  259. (const :tag "Ledger" ledger)
  260. (const :tag "Lilypond" lilypond)
  261. (const :tag "Lisp" lisp)
  262. (const :tag "Makefile" makefile)
  263. (const :tag "Maxima" maxima)
  264. (const :tag "Matlab" matlab)
  265. (const :tag "Mscgen" mscgen)
  266. (const :tag "Ocaml" ocaml)
  267. (const :tag "Octave" octave)
  268. (const :tag "Org" org)
  269. (const :tag "Perl" perl)
  270. (const :tag "Pico Lisp" picolisp)
  271. (const :tag "PlantUML" plantuml)
  272. (const :tag "Python" python)
  273. (const :tag "Ruby" ruby)
  274. (const :tag "Sass" sass)
  275. (const :tag "Scala" scala)
  276. (const :tag "Scheme" scheme)
  277. (const :tag "Screen" screen)
  278. (const :tag "Shell Script" shell)
  279. (const :tag "Shen" shen)
  280. (const :tag "Sql" sql)
  281. (const :tag "Sqlite" sqlite)
  282. (const :tag "Stan" stan)
  283. (const :tag "Vala" vala))
  284. :value-type (boolean :tag "Activate" :value t)))
  285. ;;;; Customization variables
  286. (defcustom org-clone-delete-id nil
  287. "Remove ID property of clones of a subtree.
  288. When non-nil, clones of a subtree don't inherit the ID property.
  289. Otherwise they inherit the ID property with a new unique
  290. identifier."
  291. :type 'boolean
  292. :version "24.1"
  293. :group 'org-id)
  294. ;;; Version
  295. (org-check-version)
  296. ;;;###autoload
  297. (defun org-version (&optional here full message)
  298. "Show the Org version.
  299. Interactively, or when MESSAGE is non-nil, show it in echo area.
  300. With prefix argument, or when HERE is non-nil, insert it at point.
  301. In non-interactive uses, a reduced version string is output unless
  302. FULL is given."
  303. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  304. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  305. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  306. (load-suffixes (list ".el"))
  307. (org-install-dir
  308. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  309. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  310. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  311. (let* ((load-suffixes save-load-suffixes)
  312. (release (org-release))
  313. (git-version (org-git-version))
  314. (version (format "Org mode version %s (%s @ %s)"
  315. release
  316. git-version
  317. (if org-install-dir
  318. (if (string= org-dir org-install-dir)
  319. org-install-dir
  320. (concat "mixed installation! "
  321. org-install-dir
  322. " and "
  323. org-dir))
  324. "org-loaddefs.el can not be found!")))
  325. (version1 (if full version release)))
  326. (when here (insert version1))
  327. (when message (message "%s" version1))
  328. version1)))
  329. (defconst org-version (org-version))
  330. ;;; Syntax Constants
  331. ;;;; Comments
  332. (defconst org-comment-regexp
  333. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  334. "Regular expression for comment lines.")
  335. ;;;; Keyword
  336. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  337. "Regular expression for keyword-lines.")
  338. ;;;; Block
  339. (defconst org-block-regexp
  340. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  341. "Regular expression for hiding blocks.")
  342. (defconst org-dblock-start-re
  343. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  344. "Matches the start line of a dynamic block, with parameters.")
  345. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  346. "Matches the end of a dynamic block.")
  347. ;;;; Timestamp
  348. (defconst org-ts--internal-regexp
  349. (rx (seq
  350. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  351. (optional " " (*? nonl))))
  352. "Regular expression matching the innards of a time stamp.")
  353. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  354. "Regular expression for fast time stamp matching.")
  355. (defconst org-ts-regexp-inactive
  356. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  357. "Regular expression for fast inactive time stamp matching.")
  358. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  359. "Regular expression for fast time stamp matching.")
  360. (defconst org-ts-regexp0
  361. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  362. "Regular expression matching time strings for analysis.
  363. This one does not require the space after the date, so it can be used
  364. on a string that terminates immediately after the date.")
  365. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  366. "Regular expression matching time strings for analysis.")
  367. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  368. "Regular expression matching time stamps, with groups.")
  369. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  370. "Regular expression matching time stamps (also [..]), with groups.")
  371. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  372. "Regular expression matching a time stamp range.")
  373. (defconst org-tr-regexp-both
  374. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  375. "Regular expression matching a time stamp range.")
  376. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  377. org-ts-regexp "\\)?")
  378. "Regular expression matching a time stamp or time stamp range.")
  379. (defconst org-tsr-regexp-both
  380. (concat org-ts-regexp-both "\\(--?-?"
  381. org-ts-regexp-both "\\)?")
  382. "Regular expression matching a time stamp or time stamp range.
  383. The time stamps may be either active or inactive.")
  384. (defconst org-repeat-re
  385. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  386. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  387. "Regular expression for specifying repeated events.
  388. After a match, group 1 contains the repeat expression.")
  389. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  390. "Formats for `format-time-string' which are used for time stamps.")
  391. ;;;; Clock and Planning
  392. (defconst org-clock-string "CLOCK:"
  393. "String used as prefix for timestamps clocking work hours on an item.")
  394. (defvar org-closed-string "CLOSED:"
  395. "String used as the prefix for timestamps logging closing a TODO entry.")
  396. (defvar org-deadline-string "DEADLINE:"
  397. "String to mark deadline entries.
  398. \\<org-mode-map>
  399. A deadline is this string, followed by a time stamp. It must be
  400. a word, terminated by a colon. You can insert a schedule keyword
  401. and a timestamp with `\\[org-deadline]'.")
  402. (defvar org-scheduled-string "SCHEDULED:"
  403. "String to mark scheduled TODO entries.
  404. \\<org-mode-map>
  405. A schedule is this string, followed by a time stamp. It must be
  406. a word, terminated by a colon. You can insert a schedule keyword
  407. and a timestamp with `\\[org-schedule]'.")
  408. (defconst org-ds-keyword-length
  409. (+ 2
  410. (apply #'max
  411. (mapcar #'length
  412. (list org-deadline-string org-scheduled-string
  413. org-clock-string org-closed-string))))
  414. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  415. (defconst org-planning-line-re
  416. (concat "^[ \t]*"
  417. (regexp-opt
  418. (list org-closed-string org-deadline-string org-scheduled-string)
  419. t))
  420. "Matches a line with planning info.
  421. Matched keyword is in group 1.")
  422. (defconst org-clock-line-re
  423. (concat "^[ \t]*" org-clock-string)
  424. "Matches a line with clock info.")
  425. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  426. "Matches the DEADLINE keyword.")
  427. (defconst org-deadline-time-regexp
  428. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  429. "Matches the DEADLINE keyword together with a time stamp.")
  430. (defconst org-deadline-time-hour-regexp
  431. (concat "\\<" org-deadline-string
  432. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  433. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  434. (defconst org-deadline-line-regexp
  435. (concat "\\<\\(" org-deadline-string "\\).*")
  436. "Matches the DEADLINE keyword and the rest of the line.")
  437. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  438. "Matches the SCHEDULED keyword.")
  439. (defconst org-scheduled-time-regexp
  440. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  441. "Matches the SCHEDULED keyword together with a time stamp.")
  442. (defconst org-scheduled-time-hour-regexp
  443. (concat "\\<" org-scheduled-string
  444. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  445. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  446. (defconst org-closed-time-regexp
  447. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  448. "Matches the CLOSED keyword together with a time stamp.")
  449. (defconst org-keyword-time-regexp
  450. (concat "\\<"
  451. (regexp-opt
  452. (list org-scheduled-string org-deadline-string org-closed-string
  453. org-clock-string)
  454. t)
  455. " *[[<]\\([^]>]+\\)[]>]")
  456. "Matches any of the 4 keywords, together with the time stamp.")
  457. (defconst org-keyword-time-not-clock-regexp
  458. (concat
  459. "\\<"
  460. (regexp-opt
  461. (list org-scheduled-string org-deadline-string org-closed-string) t)
  462. " *[[<]\\([^]>]+\\)[]>]")
  463. "Matches any of the 3 keywords, together with the time stamp.")
  464. (defconst org-all-time-keywords
  465. (mapcar (lambda (w) (substring w 0 -1))
  466. (list org-scheduled-string org-deadline-string
  467. org-clock-string org-closed-string))
  468. "List of time keywords.")
  469. ;;;; Drawer
  470. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  471. "Matches first or last line of a hidden block.
  472. Group 1 contains drawer's name or \"END\".")
  473. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  474. "Regular expression matching the first line of a property drawer.")
  475. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  476. "Regular expression matching the last line of a property drawer.")
  477. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  478. "Regular expression matching the first line of a clock drawer.")
  479. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  480. "Regular expression matching the last line of a clock drawer.")
  481. (defconst org-logbook-drawer-re
  482. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  483. (*? (0+ nonl) "\n")
  484. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  485. "Matches an entire LOGBOOK drawer.")
  486. (defconst org-property-drawer-re
  487. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  488. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  489. "[ \t]*:END:[ \t]*$")
  490. "Matches an entire property drawer.")
  491. (defconst org-clock-drawer-re
  492. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  493. org-clock-drawer-end-re "\\)\n?")
  494. "Matches an entire clock drawer.")
  495. ;;;; Headline
  496. (defconst org-heading-keyword-regexp-format
  497. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  498. "Printf format for a regexp matching a headline with some keyword.
  499. This regexp will match the headline of any node which has the
  500. exact keyword that is put into the format. The keyword isn't in
  501. any group by default, but the stars and the body are.")
  502. (defconst org-heading-keyword-maybe-regexp-format
  503. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  504. "Printf format for a regexp matching a headline, possibly with some keyword.
  505. This regexp can match any headline with the specified keyword, or
  506. without a keyword. The keyword isn't in any group by default,
  507. but the stars and the body are.")
  508. (defconst org-archive-tag "ARCHIVE"
  509. "The tag that marks a subtree as archived.
  510. An archived subtree does not open during visibility cycling, and does
  511. not contribute to the agenda listings.")
  512. (defconst org-tag-re "[[:alnum:]_@#%]+"
  513. "Regexp matching a single tag.")
  514. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  515. "Regexp matching the tag group at the end of a line, with leading spaces.
  516. Tags are stored in match group 1. Match group 2 stores the tags
  517. without the enclosing colons.")
  518. (defconst org-tag-line-re
  519. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  520. "Regexp matching tags in a headline.
  521. Tags are stored in match group 1. Match group 2 stores the tags
  522. without the enclosing colons.")
  523. (eval-and-compile
  524. (defconst org-comment-string "COMMENT"
  525. "Entries starting with this keyword will never be exported.
  526. \\<org-mode-map>
  527. An entry can be toggled between COMMENT and normal with
  528. `\\[org-toggle-comment]'."))
  529. ;;;; LaTeX Environments and Fragments
  530. (defconst org-latex-regexps
  531. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  532. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  533. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  534. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  535. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  536. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  537. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  538. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  539. "Regular expressions for matching embedded LaTeX.")
  540. ;;;; Node Property
  541. (defconst org-effort-property "Effort"
  542. "The property that is being used to keep track of effort estimates.
  543. Effort estimates given in this property need to be in the format
  544. defined in org-duration.el.")
  545. ;;; The custom variables
  546. (defgroup org nil
  547. "Outline-based notes management and organizer."
  548. :tag "Org"
  549. :group 'outlines
  550. :group 'calendar)
  551. (defcustom org-mode-hook nil
  552. "Mode hook for Org mode, run after the mode was turned on."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-load-hook nil
  556. "Hook that is run after org.el has been loaded."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-log-buffer-setup-hook nil
  560. "Hook that is run after an Org log buffer is created."
  561. :group 'org
  562. :version "24.1"
  563. :type 'hook)
  564. (defvar org-modules) ; defined below
  565. (defvar org-modules-loaded nil
  566. "Have the modules been loaded already?")
  567. ;;;###autoload
  568. (defun org-load-modules-maybe (&optional force)
  569. "Load all extensions listed in `org-modules'."
  570. (when (or force (not org-modules-loaded))
  571. (dolist (ext org-modules)
  572. (condition-case nil (require ext)
  573. (error (message "Problems while trying to load feature `%s'" ext))))
  574. (setq org-modules-loaded t)))
  575. (defun org-set-modules (var value)
  576. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  577. (set var value)
  578. (when (featurep 'org)
  579. (org-load-modules-maybe 'force)
  580. (org-element-cache-reset 'all)))
  581. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  582. "Modules that should always be loaded together with org.el.
  583. If a description starts with <C>, the file is not part of Emacs
  584. and loading it will require that you have downloaded and properly
  585. installed the Org mode distribution.
  586. You can also use this system to load external packages (i.e. neither Org
  587. core modules, nor modules from the CONTRIB directory). Just add symbols
  588. to the end of the list. If the package is called org-xyz.el, then you need
  589. to add the symbol `xyz', and the package must have a call to:
  590. (provide \\='org-xyz)
  591. For export specific modules, see also `org-export-backends'."
  592. :group 'org
  593. :set 'org-set-modules
  594. :version "26.1"
  595. :package-version '(Org . "9.2")
  596. :type
  597. '(set :greedy t
  598. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  599. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  600. (const :tag " crypt: Encryption of subtrees" org-crypt)
  601. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  602. (const :tag " docview: Links to Docview buffers" ol-docview)
  603. (const :tag " eww: Store link to URL of Eww" ol-eww)
  604. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  605. (const :tag " habit: Track your consistency with habits" org-habit)
  606. (const :tag " id: Global IDs for identifying entries" org-id)
  607. (const :tag " info: Links to Info nodes" ol-info)
  608. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  609. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  610. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  611. (const :tag " mouse: Additional mouse support" org-mouse)
  612. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  613. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  614. (const :tag " tempo: Fast completion for structures" org-tempo)
  615. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  616. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  617. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  618. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  619. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  620. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  621. (const :tag "C collector: Collect properties into tables" org-collector)
  622. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  623. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  624. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  625. (const :tag "C eval: Include command output as text" org-eval)
  626. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  627. (const :tag "C git-link: Links to specific file version" ol-git-link)
  628. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  629. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  630. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  631. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  632. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  633. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  634. (const :tag "C man: Links to man pages in Org mode" ol-man)
  635. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  636. (const :tag "C notify: Notifications for Org mode" org-notify)
  637. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  638. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  639. (const :tag "C registry: A registry for Org links" org-registry)
  640. (const :tag "C screen: Visit screen sessions through links" org-screen)
  641. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  642. (const :tag "C secretary: Team management with Org" org-secretary)
  643. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  644. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  645. (const :tag "C track: Keep up with Org mode development" org-track)
  646. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  647. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  648. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  649. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  650. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  651. (defvar org-export-registered-backends) ; From ox.el.
  652. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  653. (declare-function org-export-backend-name "ox" (backend) t)
  654. (defcustom org-export-backends '(ascii html icalendar latex odt)
  655. "List of export back-ends that should be always available.
  656. If a description starts with <C>, the file is not part of Emacs
  657. and loading it will require that you have downloaded and properly
  658. installed the Org mode distribution.
  659. Unlike to `org-modules', libraries in this list will not be
  660. loaded along with Org, but only once the export framework is
  661. needed.
  662. This variable needs to be set before org.el is loaded. If you
  663. need to make a change while Emacs is running, use the customize
  664. interface or run the following code, where VAL stands for the new
  665. value of the variable, after updating it:
  666. (progn
  667. (setq org-export-registered-backends
  668. (cl-remove-if-not
  669. (lambda (backend)
  670. (let ((name (org-export-backend-name backend)))
  671. (or (memq name val)
  672. (catch \\='parentp
  673. (dolist (b val)
  674. (and (org-export-derived-backend-p b name)
  675. (throw \\='parentp t)))))))
  676. org-export-registered-backends))
  677. (let ((new-list (mapcar #\\='org-export-backend-name
  678. org-export-registered-backends)))
  679. (dolist (backend val)
  680. (cond
  681. ((not (load (format \"ox-%s\" backend) t t))
  682. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  683. backend))
  684. ((not (memq backend new-list)) (push backend new-list))))
  685. (set-default \\='org-export-backends new-list)))
  686. Adding a back-end to this list will also pull the back-end it
  687. depends on, if any."
  688. :group 'org
  689. :group 'org-export
  690. :version "26.1"
  691. :package-version '(Org . "9.0")
  692. :initialize 'custom-initialize-set
  693. :set (lambda (var val)
  694. (if (not (featurep 'ox)) (set-default var val)
  695. ;; Any back-end not required anymore (not present in VAL and not
  696. ;; a parent of any back-end in the new value) is removed from the
  697. ;; list of registered back-ends.
  698. (setq org-export-registered-backends
  699. (cl-remove-if-not
  700. (lambda (backend)
  701. (let ((name (org-export-backend-name backend)))
  702. (or (memq name val)
  703. (catch 'parentp
  704. (dolist (b val)
  705. (and (org-export-derived-backend-p b name)
  706. (throw 'parentp t)))))))
  707. org-export-registered-backends))
  708. ;; Now build NEW-LIST of both new back-ends and required
  709. ;; parents.
  710. (let ((new-list (mapcar #'org-export-backend-name
  711. org-export-registered-backends)))
  712. (dolist (backend val)
  713. (cond
  714. ((not (load (format "ox-%s" backend) t t))
  715. (message "Problems while trying to load export back-end `%s'"
  716. backend))
  717. ((not (memq backend new-list)) (push backend new-list))))
  718. ;; Set VAR to that list with fixed dependencies.
  719. (set-default var new-list))))
  720. :type '(set :greedy t
  721. (const :tag " ascii Export buffer to ASCII format" ascii)
  722. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  723. (const :tag " html Export buffer to HTML format" html)
  724. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  725. (const :tag " latex Export buffer to LaTeX format" latex)
  726. (const :tag " man Export buffer to MAN format" man)
  727. (const :tag " md Export buffer to Markdown format" md)
  728. (const :tag " odt Export buffer to ODT format" odt)
  729. (const :tag " org Export buffer to Org format" org)
  730. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  731. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  732. (const :tag "C deck Export buffer to deck.js presentations" deck)
  733. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  734. (const :tag "C groff Export buffer to Groff format" groff)
  735. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  736. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  737. (const :tag "C s5 Export buffer to s5 presentations" s5)
  738. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  739. (eval-after-load 'ox
  740. '(dolist (backend org-export-backends)
  741. (condition-case nil (require (intern (format "ox-%s" backend)))
  742. (error (message "Problems while trying to load export back-end `%s'"
  743. backend)))))
  744. (defcustom org-support-shift-select nil
  745. "Non-nil means make shift-cursor commands select text when possible.
  746. \\<org-mode-map>
  747. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  748. start selecting a region, or enlarge regions started in this way.
  749. In Org mode, in special contexts, these same keys are used for
  750. other purposes, important enough to compete with shift selection.
  751. Org tries to balance these needs by supporting `shift-select-mode'
  752. outside these special contexts, under control of this variable.
  753. The default of this variable is nil, to avoid confusing behavior. Shifted
  754. cursor keys will then execute Org commands in the following contexts:
  755. - on a headline, changing TODO state (left/right) and priority (up/down)
  756. - on a time stamp, changing the time
  757. - in a plain list item, changing the bullet type
  758. - in a property definition line, switching between allowed values
  759. - in the BEGIN line of a clock table (changing the time block).
  760. - in a table, moving the cell in the specified direction.
  761. Outside these contexts, the commands will throw an error.
  762. When this variable is t and the cursor is not in a special
  763. context, Org mode will support shift-selection for making and
  764. enlarging regions. To make this more effective, the bullet
  765. cycling will no longer happen anywhere in an item line, but only
  766. if the cursor is exactly on the bullet.
  767. If you set this variable to the symbol `always', then the keys
  768. will not be special in headlines, property lines, item lines, and
  769. table cells, to make shift selection work there as well. If this is
  770. what you want, you can use the following alternative commands:
  771. `\\[org-todo]' and `\\[org-priority]' \
  772. to change TODO state and priority,
  773. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  774. can be used to switch TODO sets,
  775. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  776. and properties can be edited by hand or in column view.
  777. However, when the cursor is on a timestamp, shift-cursor commands
  778. will still edit the time stamp - this is just too good to give up."
  779. :group 'org
  780. :type '(choice
  781. (const :tag "Never" nil)
  782. (const :tag "When outside special context" t)
  783. (const :tag "Everywhere except timestamps" always)))
  784. (defcustom org-loop-over-headlines-in-active-region t
  785. "Shall some commands act upon headlines in the active region?
  786. When set to t, some commands will be performed in all headlines
  787. within the active region.
  788. When set to `start-level', some commands will be performed in all
  789. headlines within the active region, provided that these headlines
  790. are of the same level than the first one.
  791. When set to a string, those commands will be performed on the
  792. matching headlines within the active region. Such string must be
  793. a tags/property/todo match as it is used in the agenda tags view.
  794. The list of commands is: `org-schedule', `org-deadline',
  795. `org-todo', `org-set-tags-command', `org-archive-subtree',
  796. `org-archive-set-tag', `org-toggle-archive-tag' and
  797. `org-archive-to-archive-sibling'. The archiving commands skip
  798. already archived entries.
  799. See `org-agenda-loop-over-headlines-in-active-region' for the
  800. equivalent option for agenda views."
  801. :type '(choice (const :tag "Don't loop" nil)
  802. (const :tag "All headlines in active region" t)
  803. (const :tag "In active region, headlines at the same level than the first one" start-level)
  804. (string :tag "Tags/Property/Todo matcher"))
  805. :package-version '(Org . "9.4")
  806. :group 'org-todo
  807. :group 'org-archive)
  808. (defcustom org-startup-folded 'showeverything
  809. "Non-nil means entering Org mode will switch to OVERVIEW.
  810. This can also be configured on a per-file basis by adding one of
  811. the following lines anywhere in the buffer:
  812. #+STARTUP: fold (or `overview', this is equivalent)
  813. #+STARTUP: nofold (or `showall', this is equivalent)
  814. #+STARTUP: content
  815. #+STARTUP: show<n>levels (<n> = 2..5)
  816. #+STARTUP: showeverything
  817. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  818. to ignore this option when Org opens agenda files for the first
  819. time."
  820. :group 'org-startup
  821. :package-version '(Org . "9.4")
  822. :type '(choice
  823. (const :tag "nofold: show all" nil)
  824. (const :tag "fold: overview" t)
  825. (const :tag "fold: show two levels" show2levels)
  826. (const :tag "fold: show three levels" show3levels)
  827. (const :tag "fold: show four levels" show4evels)
  828. (const :tag "fold: show five levels" show5levels)
  829. (const :tag "content: all headlines" content)
  830. (const :tag "show everything, even drawers" showeverything)))
  831. (defcustom org-startup-truncated t
  832. "Non-nil means entering Org mode will set `truncate-lines'.
  833. This is useful since some lines containing links can be very long and
  834. uninteresting. Also tables look terrible when wrapped.
  835. The variable `org-startup-truncated' allows to configure
  836. truncation for Org mode different to the other modes that use the
  837. variable `truncate-lines' and as a shortcut instead of putting
  838. the variable `truncate-lines' into the `org-mode-hook'. If one
  839. wants to configure truncation for Org mode not statically but
  840. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  841. the variable `truncate-lines' has to be used because in such a
  842. case it is too late to set the variable `org-startup-truncated'."
  843. :group 'org-startup
  844. :type 'boolean)
  845. (defcustom org-startup-indented nil
  846. "Non-nil means turn on `org-indent-mode' on startup.
  847. This can also be configured on a per-file basis by adding one of
  848. the following lines anywhere in the buffer:
  849. #+STARTUP: indent
  850. #+STARTUP: noindent"
  851. :group 'org-structure
  852. :type '(choice
  853. (const :tag "Not" nil)
  854. (const :tag "Globally (slow on startup in large files)" t)))
  855. (defcustom org-startup-numerated nil
  856. "Non-nil means turn on `org-num-mode' on startup.
  857. This can also be configured on a per-file basis by adding one of
  858. the following lines anywhere in the buffer:
  859. #+STARTUP: num
  860. #+STARTUP: nonum"
  861. :group 'org-structure
  862. :package-version '(Org . "9.4")
  863. :type '(choice
  864. (const :tag "Not" nil)
  865. (const :tag "Globally" t)))
  866. (defcustom org-use-sub-superscripts t
  867. "Non-nil means interpret \"_\" and \"^\" for display.
  868. If you want to control how Org exports those characters, see
  869. `org-export-with-sub-superscripts'.
  870. When this option is turned on, you can use TeX-like syntax for
  871. sub- and superscripts within the buffer. Several characters after
  872. \"_\" or \"^\" will be considered as a single item - so grouping
  873. with {} is normally not needed. For example, the following things
  874. will be parsed as single sub- or superscripts:
  875. 10^24 or 10^tau several digits will be considered 1 item.
  876. 10^-12 or 10^-tau a leading sign with digits or a word
  877. x^2-y^3 will be read as x^2 - y^3, because items are
  878. terminated by almost any nonword/nondigit char.
  879. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  880. Still, ambiguity is possible. So when in doubt, use {} to enclose
  881. the sub/superscript. If you set this variable to the symbol `{}',
  882. the braces are *required* in order to trigger interpretations as
  883. sub/superscript. This can be helpful in documents that need \"_\"
  884. frequently in plain text."
  885. :group 'org-startup
  886. :version "24.4"
  887. :package-version '(Org . "8.0")
  888. :type '(choice
  889. (const :tag "Always interpret" t)
  890. (const :tag "Only with braces" {})
  891. (const :tag "Never interpret" nil)))
  892. (defcustom org-startup-with-beamer-mode nil
  893. "Non-nil means turn on `org-beamer-mode' on startup.
  894. This can also be configured on a per-file basis by adding one of
  895. the following lines anywhere in the buffer:
  896. #+STARTUP: beamer"
  897. :group 'org-startup
  898. :version "24.1"
  899. :type 'boolean)
  900. (defcustom org-startup-align-all-tables nil
  901. "Non-nil means align all tables when visiting a file.
  902. This can also be configured on a per-file basis by adding one of
  903. the following lines anywhere in the buffer:
  904. #+STARTUP: align
  905. #+STARTUP: noalign"
  906. :group 'org-startup
  907. :type 'boolean)
  908. (defcustom org-startup-shrink-all-tables nil
  909. "Non-nil means shrink all table columns with a width cookie.
  910. This can also be configured on a per-file basis by adding one of
  911. the following lines anywhere in the buffer:
  912. #+STARTUP: shrink"
  913. :group 'org-startup
  914. :type 'boolean
  915. :version "27.1"
  916. :package-version '(Org . "9.2")
  917. :safe #'booleanp)
  918. (defcustom org-startup-with-inline-images nil
  919. "Non-nil means show inline images when loading a new Org file.
  920. This can also be configured on a per-file basis by adding one of
  921. the following lines anywhere in the buffer:
  922. #+STARTUP: inlineimages
  923. #+STARTUP: noinlineimages"
  924. :group 'org-startup
  925. :version "24.1"
  926. :type 'boolean)
  927. (defcustom org-startup-with-latex-preview nil
  928. "Non-nil means preview LaTeX fragments when loading a new Org file.
  929. This can also be configured on a per-file basis by adding one of
  930. the following lines anywhere in the buffer:
  931. #+STARTUP: latexpreview
  932. #+STARTUP: nolatexpreview"
  933. :group 'org-startup
  934. :version "24.4"
  935. :package-version '(Org . "8.0")
  936. :type 'boolean)
  937. (defcustom org-insert-mode-line-in-empty-file nil
  938. "Non-nil means insert the first line setting Org mode in empty files.
  939. When the function `org-mode' is called interactively in an empty file, this
  940. normally means that the file name does not automatically trigger Org mode.
  941. To ensure that the file will always be in Org mode in the future, a
  942. line enforcing Org mode will be inserted into the buffer, if this option
  943. has been set."
  944. :group 'org-startup
  945. :type 'boolean)
  946. (defcustom org-ellipsis nil
  947. "The ellipsis to use in the Org mode outline.
  948. When nil, just use the standard three dots. When a non-empty string,
  949. use that string instead.
  950. The change affects only Org mode (which will then use its own display table).
  951. Changing this requires executing `\\[org-mode]' in a buffer to become
  952. effective. It cannot be set as a local variable."
  953. :group 'org-startup
  954. :type '(choice (const :tag "Default" nil)
  955. (string :tag "String" :value "...#")))
  956. (defvar org-display-table nil
  957. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  958. (defcustom org-directory "~/org"
  959. "Directory with Org files.
  960. This is just a default location to look for Org files. There is no need
  961. at all to put your files into this directory. It is used in the
  962. following situations:
  963. 1. When a capture template specifies a target file that is not an
  964. absolute path. The path will then be interpreted relative to
  965. `org-directory'
  966. 2. When the value of variable `org-agenda-files' is a single file, any
  967. relative paths in this file will be taken as relative to
  968. `org-directory'."
  969. :group 'org-refile
  970. :group 'org-capture
  971. :type 'directory)
  972. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  973. "Default target for storing notes.
  974. Used as a fall back file for org-capture.el, for templates that
  975. do not specify a target file."
  976. :group 'org-refile
  977. :group 'org-capture
  978. :type 'file)
  979. (defcustom org-reverse-note-order nil
  980. "Non-nil means store new notes at the beginning of a file or entry.
  981. When nil, new notes will be filed to the end of a file or entry.
  982. This can also be a list with cons cells of regular expressions that
  983. are matched against file names, and values."
  984. :group 'org-capture
  985. :group 'org-refile
  986. :type '(choice
  987. (const :tag "Reverse always" t)
  988. (const :tag "Reverse never" nil)
  989. (repeat :tag "By file name regexp"
  990. (cons regexp boolean))))
  991. (defgroup org-keywords nil
  992. "Keywords in Org mode."
  993. :tag "Org Keywords"
  994. :group 'org)
  995. (defcustom org-closed-keep-when-no-todo nil
  996. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  997. :group 'org-todo
  998. :group 'org-keywords
  999. :version "24.4"
  1000. :package-version '(Org . "8.0")
  1001. :type 'boolean)
  1002. (defgroup org-structure nil
  1003. "Options concerning the general structure of Org files."
  1004. :tag "Org Structure"
  1005. :group 'org)
  1006. (defgroup org-reveal-location nil
  1007. "Options about how to make context of a location visible."
  1008. :tag "Org Reveal Location"
  1009. :group 'org-structure)
  1010. (defcustom org-show-context-detail '((agenda . local)
  1011. (bookmark-jump . lineage)
  1012. (isearch . lineage)
  1013. (default . ancestors))
  1014. "Alist between context and visibility span when revealing a location.
  1015. \\<org-mode-map>Some actions may move point into invisible
  1016. locations. As a consequence, Org always exposes a neighborhood
  1017. around point. How much is shown depends on the initial action,
  1018. or context. Valid contexts are
  1019. agenda when exposing an entry from the agenda
  1020. org-goto when using the command `org-goto' (`\\[org-goto]')
  1021. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1022. tags-tree when constructing a sparse tree based on tags matches
  1023. link-search when exposing search matches associated with a link
  1024. mark-goto when exposing the jump goal of a mark
  1025. bookmark-jump when exposing a bookmark location
  1026. isearch when exiting from an incremental search
  1027. default default for all contexts not set explicitly
  1028. Allowed visibility spans are
  1029. minimal show current headline; if point is not on headline,
  1030. also show entry
  1031. local show current headline, entry and next headline
  1032. ancestors show current headline and its direct ancestors; if
  1033. point is not on headline, also show entry
  1034. lineage show current headline, its direct ancestors and all
  1035. their children; if point is not on headline, also show
  1036. entry and first child
  1037. tree show current headline, its direct ancestors and all
  1038. their children; if point is not on headline, also show
  1039. entry and all children
  1040. canonical show current headline, its direct ancestors along with
  1041. their entries and children; if point is not located on
  1042. the headline, also show current entry and all children
  1043. As special cases, a nil or t value means show all contexts in
  1044. `minimal' or `canonical' view, respectively.
  1045. Some views can make displayed information very compact, but also
  1046. make it harder to edit the location of the match. In such
  1047. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1048. more context."
  1049. :group 'org-reveal-location
  1050. :version "26.1"
  1051. :package-version '(Org . "9.0")
  1052. :type '(choice
  1053. (const :tag "Canonical" t)
  1054. (const :tag "Minimal" nil)
  1055. (repeat :greedy t :tag "Individual contexts"
  1056. (cons
  1057. (choice :tag "Context"
  1058. (const agenda)
  1059. (const org-goto)
  1060. (const occur-tree)
  1061. (const tags-tree)
  1062. (const link-search)
  1063. (const mark-goto)
  1064. (const bookmark-jump)
  1065. (const isearch)
  1066. (const default))
  1067. (choice :tag "Detail level"
  1068. (const minimal)
  1069. (const local)
  1070. (const ancestors)
  1071. (const lineage)
  1072. (const tree)
  1073. (const canonical))))))
  1074. (defcustom org-indirect-buffer-display 'other-window
  1075. "How should indirect tree buffers be displayed?
  1076. This applies to indirect buffers created with the commands
  1077. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1078. Valid values are:
  1079. current-window Display in the current window
  1080. other-window Just display in another window.
  1081. dedicated-frame Create one new frame, and re-use it each time.
  1082. new-frame Make a new frame each time. Note that in this case
  1083. previously-made indirect buffers are kept, and you need to
  1084. kill these buffers yourself."
  1085. :group 'org-structure
  1086. :group 'org-agenda-windows
  1087. :type '(choice
  1088. (const :tag "In current window" current-window)
  1089. (const :tag "In current frame, other window" other-window)
  1090. (const :tag "Each time a new frame" new-frame)
  1091. (const :tag "One dedicated frame" dedicated-frame)))
  1092. (defconst org-file-apps-gnu
  1093. '((remote . emacs)
  1094. (system . mailcap)
  1095. (t . mailcap))
  1096. "Default file applications on a UNIX or GNU/Linux system.
  1097. See `org-file-apps'.")
  1098. (defconst org-file-apps-macos
  1099. '((remote . emacs)
  1100. (system . "open %s")
  1101. ("ps.gz" . "gv %s")
  1102. ("eps.gz" . "gv %s")
  1103. ("dvi" . "xdvi %s")
  1104. ("fig" . "xfig %s")
  1105. (t . "open %s"))
  1106. "Default file applications on a macOS system.
  1107. The system \"open\" is known as a default, but we use X11 applications
  1108. for some files for which the OS does not have a good default.
  1109. See `org-file-apps'.")
  1110. (defconst org-file-apps-windowsnt
  1111. (list '(remote . emacs)
  1112. (cons 'system (lambda (file _path)
  1113. (with-no-warnings (w32-shell-execute "open" file))))
  1114. (cons t (lambda (file _path)
  1115. (with-no-warnings (w32-shell-execute "open" file)))))
  1116. "Default file applications on a Windows NT system.
  1117. The system \"open\" is used for most files.
  1118. See `org-file-apps'.")
  1119. (defcustom org-file-apps
  1120. '((auto-mode . emacs)
  1121. (directory . emacs)
  1122. ("\\.mm\\'" . default)
  1123. ("\\.x?html?\\'" . default)
  1124. ("\\.pdf\\'" . default))
  1125. "Applications for opening `file:path' items in a document.
  1126. \\<org-mode-map>
  1127. Org mode uses system defaults for different file types, but you
  1128. can use this variable to set the application for a given file
  1129. extension. The entries in this list are cons cells where the car
  1130. identifies files and the cdr the corresponding command.
  1131. Possible values for the file identifier are:
  1132. \"string\" A string as a file identifier can be interpreted in different
  1133. ways, depending on its contents:
  1134. - Alphanumeric characters only:
  1135. Match links with this file extension.
  1136. Example: (\"pdf\" . \"evince %s\")
  1137. to open PDFs with evince.
  1138. - Regular expression: Match links where the
  1139. filename matches the regexp. If you want to
  1140. use groups here, use shy groups.
  1141. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1142. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1143. to open *.html and *.xhtml with firefox.
  1144. - Regular expression which contains (non-shy) groups:
  1145. Match links where the whole link, including \"::\", and
  1146. anything after that, matches the regexp.
  1147. In a custom command string, %1, %2, etc. are replaced with
  1148. the parts of the link that were matched by the groups.
  1149. For backwards compatibility, if a command string is given
  1150. that does not use any of the group matches, this case is
  1151. handled identically to the second one (i.e. match against
  1152. file name only).
  1153. In a custom function, you can access the group matches with
  1154. (match-string n link).
  1155. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1156. \"evince -p %1 %s\")
  1157. to open [[file:document.pdf::5]] with evince at page 5.
  1158. `directory' Matches a directory
  1159. `remote' Matches a remote file, accessible through tramp or efs.
  1160. Remote files most likely should be visited through Emacs
  1161. because external applications cannot handle such paths.
  1162. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1163. so all files Emacs knows how to handle. Using this with
  1164. command `emacs' will open most files in Emacs. Beware that this
  1165. will also open html files inside Emacs, unless you add
  1166. (\"html\" . default) to the list as well.
  1167. `system' The system command to open files, like `open' on Windows
  1168. and macOS, and mailcap under GNU/Linux. This is the command
  1169. that will be selected if you call `org-open-at-point' with a
  1170. double prefix argument (`\\[universal-argument] \
  1171. \\[universal-argument] \\[org-open-at-point]').
  1172. t Default for files not matched by any of the other options.
  1173. Possible values for the command are:
  1174. `emacs' The file will be visited by the current Emacs process.
  1175. `default' Use the default application for this file type, which is the
  1176. association for t in the list, most likely in the system-specific
  1177. part. This can be used to overrule an unwanted setting in the
  1178. system-specific variable.
  1179. `system' Use the system command for opening files, like \"open\".
  1180. This command is specified by the entry whose car is `system'.
  1181. Most likely, the system-specific version of this variable
  1182. does define this command, but you can overrule/replace it
  1183. here.
  1184. `mailcap' Use command specified in the mailcaps.
  1185. string A command to be executed by a shell; %s will be replaced
  1186. by the path to the file.
  1187. function A Lisp function, which will be called with two arguments:
  1188. the file path and the original link string, without the
  1189. \"file:\" prefix.
  1190. For more examples, see the system specific constants
  1191. `org-file-apps-macos'
  1192. `org-file-apps-windowsnt'
  1193. `org-file-apps-gnu'."
  1194. :group 'org
  1195. :package-version '(Org . "9.4")
  1196. :type '(repeat
  1197. (cons (choice :value ""
  1198. (string :tag "Extension")
  1199. (const :tag "System command to open files" system)
  1200. (const :tag "Default for unrecognized files" t)
  1201. (const :tag "Remote file" remote)
  1202. (const :tag "Links to a directory" directory)
  1203. (const :tag "Any files that have Emacs modes"
  1204. auto-mode))
  1205. (choice :value ""
  1206. (const :tag "Visit with Emacs" emacs)
  1207. (const :tag "Use default" default)
  1208. (const :tag "Use the system command" system)
  1209. (string :tag "Command")
  1210. (function :tag "Function")))))
  1211. (defcustom org-open-non-existing-files nil
  1212. "Non-nil means `org-open-file' opens non-existing files.
  1213. When nil, an error is thrown.
  1214. This variable applies only to external applications because they
  1215. might choke on non-existing files. If the link is to a file that
  1216. will be opened in Emacs, the variable is ignored."
  1217. :group 'org
  1218. :type 'boolean
  1219. :safe #'booleanp)
  1220. (defcustom org-open-directory-means-index-dot-org nil
  1221. "When non-nil a link to a directory really means to \"index.org\".
  1222. When nil, following a directory link runs Dired or opens
  1223. a finder/explorer window on that directory."
  1224. :group 'org
  1225. :type 'boolean
  1226. :safe #'booleanp)
  1227. (defcustom org-bookmark-names-plist
  1228. '(:last-capture "org-capture-last-stored"
  1229. :last-refile "org-refile-last-stored"
  1230. :last-capture-marker "org-capture-last-stored-marker")
  1231. "Names for bookmarks automatically set by some Org commands.
  1232. This can provide strings as names for a number of bookmarks Org sets
  1233. automatically. The following keys are currently implemented:
  1234. :last-capture
  1235. :last-capture-marker
  1236. :last-refile
  1237. When a key does not show up in the property list, the corresponding bookmark
  1238. is not set."
  1239. :group 'org-structure
  1240. :type 'plist)
  1241. (defgroup org-cycle nil
  1242. "Options concerning visibility cycling in Org mode."
  1243. :tag "Org Cycle"
  1244. :group 'org-structure)
  1245. (defcustom org-cycle-skip-children-state-if-no-children t
  1246. "Non-nil means skip CHILDREN state in entries that don't have any."
  1247. :group 'org-cycle
  1248. :type 'boolean)
  1249. (defcustom org-cycle-max-level nil
  1250. "Maximum level which should still be subject to visibility cycling.
  1251. Levels higher than this will, for cycling, be treated as text, not a headline.
  1252. When `org-odd-levels-only' is set, a value of N in this variable actually
  1253. means 2N-1 stars as the limiting headline.
  1254. When nil, cycle all levels.
  1255. Note that the limiting level of cycling is also influenced by
  1256. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1257. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1258. than its value."
  1259. :group 'org-cycle
  1260. :type '(choice
  1261. (const :tag "No limit" nil)
  1262. (integer :tag "Maximum level")))
  1263. (defcustom org-hide-block-startup nil
  1264. "Non-nil means entering Org mode will fold all blocks.
  1265. This can also be set in on a per-file basis with
  1266. #+STARTUP: hideblocks
  1267. #+STARTUP: showblocks"
  1268. :group 'org-startup
  1269. :group 'org-cycle
  1270. :type 'boolean)
  1271. (defcustom org-cycle-global-at-bob nil
  1272. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1273. This makes it possible to do global cycling without having to use `S-TAB'
  1274. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1275. line of the buffer
  1276. must not be a headline -- it may be empty or some other text.
  1277. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1278. sure the cursor stays at the beginning of the buffer.
  1279. When this option is nil, don't do anything special at the beginning of
  1280. the buffer."
  1281. :group 'org-cycle
  1282. :type 'boolean)
  1283. (defcustom org-cycle-level-after-item/entry-creation t
  1284. "Non-nil means cycle entry level or item indentation in new empty entries.
  1285. When the cursor is at the end of an empty headline, i.e., with only stars
  1286. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1287. and then all possible ancestor states, before returning to the original state.
  1288. This makes data entry extremely fast: M-RET to create a new headline,
  1289. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1290. When the cursor is at the end of an empty plain list item, one TAB will
  1291. make it a subitem, two or more tabs will back up to make this an item
  1292. higher up in the item hierarchy."
  1293. :group 'org-cycle
  1294. :type 'boolean)
  1295. (defcustom org-cycle-emulate-tab t
  1296. "Where should `org-cycle' emulate TAB.
  1297. nil Never
  1298. white Only in completely white lines
  1299. whitestart Only at the beginning of lines, before the first non-white char
  1300. t Everywhere except in headlines
  1301. exc-hl-bol Everywhere except at the start of a headline
  1302. If TAB is used in a place where it does not emulate TAB, the current subtree
  1303. visibility is cycled."
  1304. :group 'org-cycle
  1305. :type '(choice (const :tag "Never" nil)
  1306. (const :tag "Only in completely white lines" white)
  1307. (const :tag "Before first char in a line" whitestart)
  1308. (const :tag "Everywhere except in headlines" t)
  1309. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1310. (defcustom org-cycle-separator-lines 2
  1311. "Number of empty lines needed to keep an empty line between collapsed trees.
  1312. If you leave an empty line between the end of a subtree and the following
  1313. headline, this empty line is hidden when the subtree is folded.
  1314. Org mode will leave (exactly) one empty line visible if the number of
  1315. empty lines is equal or larger to the number given in this variable.
  1316. So the default 2 means at least 2 empty lines after the end of a subtree
  1317. are needed to produce free space between a collapsed subtree and the
  1318. following headline.
  1319. If the number is negative, and the number of empty lines is at least -N,
  1320. all empty lines are shown.
  1321. Special case: when 0, never leave empty lines in collapsed view."
  1322. :group 'org-cycle
  1323. :type 'integer)
  1324. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1325. (defcustom org-pre-cycle-hook nil
  1326. "Hook that is run before visibility cycling is happening.
  1327. The function(s) in this hook must accept a single argument which indicates
  1328. the new state that will be set right after running this hook. The
  1329. argument is a symbol. Before a global state change, it can have the values
  1330. `overview', `content', or `all'. Before a local state change, it can have
  1331. the values `folded', `children', or `subtree'."
  1332. :group 'org-cycle
  1333. :type 'hook)
  1334. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1335. org-cycle-hide-drawers
  1336. org-cycle-show-empty-lines
  1337. org-optimize-window-after-visibility-change)
  1338. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1339. The function(s) in this hook must accept a single argument which indicates
  1340. the new state that was set by the most recent `org-cycle' command. The
  1341. argument is a symbol. After a global state change, it can have the values
  1342. `overview', `contents', or `all'. After a local state change, it can have
  1343. the values `folded', `children', or `subtree'."
  1344. :group 'org-cycle
  1345. :package-version '(Org . "9.4")
  1346. :type 'hook)
  1347. (defgroup org-edit-structure nil
  1348. "Options concerning structure editing in Org mode."
  1349. :tag "Org Edit Structure"
  1350. :group 'org-structure)
  1351. (defcustom org-odd-levels-only nil
  1352. "Non-nil means skip even levels and only use odd levels for the outline.
  1353. This has the effect that two stars are being added/taken away in
  1354. promotion/demotion commands. It also influences how levels are
  1355. handled by the exporters.
  1356. Changing it requires restart of `font-lock-mode' to become effective
  1357. for fontification also in regions already fontified.
  1358. You may also set this on a per-file basis by adding one of the following
  1359. lines to the buffer:
  1360. #+STARTUP: odd
  1361. #+STARTUP: oddeven"
  1362. :group 'org-edit-structure
  1363. :group 'org-appearance
  1364. :type 'boolean)
  1365. (defcustom org-adapt-indentation t
  1366. "Non-nil means adapt indentation to outline node level.
  1367. When this variable is set to t, Org assumes that you write
  1368. outlines by indenting text in each node to align with the
  1369. headline (after the stars).
  1370. When this variable is set to 'headline-data, only adapt the
  1371. indentation of the data lines right below the headline, such as
  1372. planning/clock lines and property/logbook drawers.
  1373. The following issues are influenced by this variable:
  1374. - The indentation is increased by one space in a demotion
  1375. command, and decreased by one in a promotion command. However,
  1376. in the latter case, if shifting some line in the entry body
  1377. would alter document structure (e.g., insert a new headline),
  1378. indentation is not changed at all.
  1379. - Property drawers and planning information is inserted indented
  1380. when this variable is set. When nil, they will not be indented.
  1381. - TAB indents a line relative to current level. The lines below
  1382. a headline will be indented when this variable is set to t.
  1383. Note that this is all about true indentation, by adding and
  1384. removing space characters. See also \"org-indent.el\" which does
  1385. level-dependent indentation in a virtual way, i.e. at display
  1386. time in Emacs."
  1387. :group 'org-edit-structure
  1388. :type '(choice
  1389. (const :tag "Adapt indentation for all lines" t)
  1390. (const :tag "Adapt indentation for headline data lines"
  1391. 'headline-data)
  1392. (const :tag "Do not adapt indentation at all" nil))
  1393. :safe #'booleanp)
  1394. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1395. (defcustom org-special-ctrl-a/e nil
  1396. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1397. When t, `C-a' will bring back the cursor to the beginning of the
  1398. headline text, i.e. after the stars and after a possible TODO
  1399. keyword. In an item, this will be the position after bullet and
  1400. check-box, if any. When the cursor is already at that position,
  1401. another `C-a' will bring it to the beginning of the line.
  1402. `C-e' will jump to the end of the headline, ignoring the presence
  1403. of tags in the headline. A second `C-e' will then jump to the
  1404. true end of the line, after any tags. This also means that, when
  1405. this variable is non-nil, `C-e' also will never jump beyond the
  1406. end of the heading of a folded section, i.e. not after the
  1407. ellipses.
  1408. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1409. normally, going to the true line boundary first. Only a directly
  1410. following, identical keypress will bring the cursor to the
  1411. special positions.
  1412. This may also be a cons cell where the behavior for `C-a' and
  1413. `C-e' is set separately."
  1414. :group 'org-edit-structure
  1415. :type '(choice
  1416. (const :tag "off" nil)
  1417. (const :tag "on: after stars/bullet and before tags first" t)
  1418. (const :tag "reversed: true line boundary first" reversed)
  1419. (cons :tag "Set C-a and C-e separately"
  1420. (choice :tag "Special C-a"
  1421. (const :tag "off" nil)
  1422. (const :tag "on: after stars/bullet first" t)
  1423. (const :tag "reversed: before stars/bullet first" reversed))
  1424. (choice :tag "Special C-e"
  1425. (const :tag "off" nil)
  1426. (const :tag "on: before tags first" t)
  1427. (const :tag "reversed: after tags first" reversed)))))
  1428. (defcustom org-special-ctrl-k nil
  1429. "Non-nil means `C-k' will behave specially in headlines.
  1430. When nil, `C-k' will call the default `kill-line' command.
  1431. When t, the following will happen while the cursor is in the headline:
  1432. - When at the beginning of a headline, kill the entire subtree.
  1433. - When in the middle of the headline text, kill the text up to the tags.
  1434. - When after the headline text and before the tags, kill all the tags."
  1435. :group 'org-edit-structure
  1436. :type 'boolean)
  1437. (defcustom org-ctrl-k-protect-subtree nil
  1438. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1439. When set to the symbol `error', simply throw an error when `C-k' is
  1440. used to kill (part-of) a headline that has hidden text behind it.
  1441. Any other non-nil value will result in a query to the user, if it is
  1442. OK to kill that hidden subtree. When nil, kill without remorse."
  1443. :group 'org-edit-structure
  1444. :version "24.1"
  1445. :type '(choice
  1446. (const :tag "Do not protect hidden subtrees" nil)
  1447. (const :tag "Protect hidden subtrees with a security query" t)
  1448. (const :tag "Never kill a hidden subtree with C-k" error)))
  1449. (defcustom org-special-ctrl-o t
  1450. "Non-nil means, make `C-o' insert a row in tables."
  1451. :group 'org-edit-structure
  1452. :type 'boolean)
  1453. (defcustom org-catch-invisible-edits nil
  1454. "Check if in invisible region before inserting or deleting a character.
  1455. Valid values are:
  1456. nil Do not check, so just do invisible edits.
  1457. error Throw an error and do nothing.
  1458. show Make point visible, and do the requested edit.
  1459. show-and-error Make point visible, then throw an error and abort the edit.
  1460. smart Make point visible, and do insertion/deletion if it is
  1461. adjacent to visible text and the change feels predictable.
  1462. Never delete a previously invisible character or add in the
  1463. middle or right after an invisible region. Basically, this
  1464. allows insertion and backward-delete right before ellipses.
  1465. FIXME: maybe in this case we should not even show?"
  1466. :group 'org-edit-structure
  1467. :version "24.1"
  1468. :type '(choice
  1469. (const :tag "Do not check" nil)
  1470. (const :tag "Throw error when trying to edit" error)
  1471. (const :tag "Unhide, but do not do the edit" show-and-error)
  1472. (const :tag "Show invisible part and do the edit" show)
  1473. (const :tag "Be smart and do the right thing" smart)))
  1474. (defcustom org-yank-folded-subtrees t
  1475. "Non-nil means when yanking subtrees, fold them.
  1476. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1477. it starts with a heading and all other headings in it are either children
  1478. or siblings, then fold all the subtrees. However, do this only if no
  1479. text after the yank would be swallowed into a folded tree by this action."
  1480. :group 'org-edit-structure
  1481. :type 'boolean)
  1482. (defcustom org-yank-adjusted-subtrees nil
  1483. "Non-nil means when yanking subtrees, adjust the level.
  1484. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1485. this function for details."
  1486. :group 'org-edit-structure
  1487. :type 'boolean)
  1488. (defcustom org-M-RET-may-split-line '((default . t))
  1489. "Non-nil means M-RET will split the line at the cursor position.
  1490. When nil, it will go to the end of the line before making a
  1491. new line.
  1492. You may also set this option in a different way for different
  1493. contexts. Valid contexts are:
  1494. headline when creating a new headline
  1495. item when creating a new item
  1496. table in a table field
  1497. default the value to be used for all contexts not explicitly
  1498. customized"
  1499. :group 'org-structure
  1500. :group 'org-table
  1501. :type '(choice
  1502. (const :tag "Always" t)
  1503. (const :tag "Never" nil)
  1504. (repeat :greedy t :tag "Individual contexts"
  1505. (cons
  1506. (choice :tag "Context"
  1507. (const headline)
  1508. (const item)
  1509. (const table)
  1510. (const default))
  1511. (boolean)))))
  1512. (defcustom org-insert-heading-respect-content nil
  1513. "Non-nil means insert new headings after the current subtree.
  1514. \\<org-mode-map>
  1515. When nil, the new heading is created directly after the current line.
  1516. The commands `\\[org-insert-heading-respect-content]' and \
  1517. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1518. for the duration of the command."
  1519. :group 'org-structure
  1520. :type 'boolean)
  1521. (defcustom org-blank-before-new-entry '((heading . auto)
  1522. (plain-list-item . auto))
  1523. "Should `org-insert-heading' leave a blank line before new heading/item?
  1524. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1525. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1526. which case Org will look at the surrounding headings/items and try to
  1527. make an intelligent decision whether to insert a blank line or not."
  1528. :group 'org-edit-structure
  1529. :type '(list
  1530. (cons (const heading)
  1531. (choice (const :tag "Never" nil)
  1532. (const :tag "Always" t)
  1533. (const :tag "Auto" auto)))
  1534. (cons (const plain-list-item)
  1535. (choice (const :tag "Never" nil)
  1536. (const :tag "Always" t)
  1537. (const :tag "Auto" auto)))))
  1538. (defcustom org-insert-heading-hook nil
  1539. "Hook being run after inserting a new heading."
  1540. :group 'org-edit-structure
  1541. :type 'hook)
  1542. (defgroup org-sparse-trees nil
  1543. "Options concerning sparse trees in Org mode."
  1544. :tag "Org Sparse Trees"
  1545. :group 'org-structure)
  1546. (defcustom org-highlight-sparse-tree-matches t
  1547. "Non-nil means highlight all matches that define a sparse tree.
  1548. The highlights will automatically disappear the next time the buffer is
  1549. changed by an edit command."
  1550. :group 'org-sparse-trees
  1551. :type 'boolean)
  1552. (defcustom org-remove-highlights-with-change t
  1553. "Non-nil means any change to the buffer will remove temporary highlights.
  1554. \\<org-mode-map>\
  1555. Such highlights are created by `org-occur' and `org-clock-display'.
  1556. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1557. to get rid of the highlights.
  1558. The highlights created by `org-latex-preview' always need
  1559. `\\[org-latex-preview]' to be removed."
  1560. :group 'org-sparse-trees
  1561. :group 'org-time
  1562. :type 'boolean)
  1563. (defcustom org-occur-case-fold-search t
  1564. "Non-nil means `org-occur' should be case-insensitive.
  1565. If set to `smart' the search will be case-insensitive only if it
  1566. doesn't specify any upper case character."
  1567. :group 'org-sparse-trees
  1568. :version "26.1"
  1569. :type '(choice
  1570. (const :tag "Case-sensitive" nil)
  1571. (const :tag "Case-insensitive" t)
  1572. (const :tag "Case-insensitive for lower case searches only" smart)))
  1573. (defcustom org-occur-hook '(org-first-headline-recenter)
  1574. "Hook that is run after `org-occur' has constructed a sparse tree.
  1575. This can be used to recenter the window to show as much of the structure
  1576. as possible."
  1577. :group 'org-sparse-trees
  1578. :type 'hook)
  1579. (defcustom org-self-insert-cluster-for-undo nil
  1580. "Non-nil means cluster self-insert commands for undo when possible.
  1581. If this is set, then, like in the Emacs command loop, 20 consecutive
  1582. characters will be undone together.
  1583. This is configurable, because there is some impact on typing performance."
  1584. :group 'org-table
  1585. :type 'boolean)
  1586. (defvaralias 'org-activate-links 'org-highlight-links)
  1587. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1588. "Types of links that should be highlighted in Org files.
  1589. This is a list of symbols, each one of them leading to the
  1590. highlighting of a certain link type.
  1591. You can still open links that are not highlighted.
  1592. In principle, it does not hurt to turn on highlighting for all
  1593. link types. There may be a small gain when turning off unused
  1594. link types. The types are:
  1595. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1596. angle Links in angular brackets that may contain whitespace like
  1597. <bbdb:Carsten Dominik>.
  1598. plain Plain links in normal text, no whitespace, like http://google.com.
  1599. radio Text that is matched by a radio target, see manual for details.
  1600. tag Tag settings in a headline (link to tag search).
  1601. date Time stamps (link to calendar).
  1602. footnote Footnote labels.
  1603. If you set this variable during an Emacs session, use `org-mode-restart'
  1604. in the Org buffer so that the change takes effect."
  1605. :group 'org-appearance
  1606. :type '(set :greedy t
  1607. (const :tag "Double bracket links" bracket)
  1608. (const :tag "Angular bracket links" angle)
  1609. (const :tag "Plain text links" plain)
  1610. (const :tag "Radio target matches" radio)
  1611. (const :tag "Tags" tag)
  1612. (const :tag "Timestamps" date)
  1613. (const :tag "Footnotes" footnote)))
  1614. (defcustom org-mark-ring-length 4
  1615. "Number of different positions to be recorded in the ring.
  1616. Changing this requires a restart of Emacs to work correctly."
  1617. :group 'org-link-follow
  1618. :type 'integer)
  1619. (defgroup org-todo nil
  1620. "Options concerning TODO items in Org mode."
  1621. :tag "Org TODO"
  1622. :group 'org)
  1623. (defgroup org-progress nil
  1624. "Options concerning Progress logging in Org mode."
  1625. :tag "Org Progress"
  1626. :group 'org-time)
  1627. (defvar org-todo-interpretation-widgets
  1628. '((:tag "Sequence (cycling hits every state)" sequence)
  1629. (:tag "Type (cycling directly to DONE)" type))
  1630. "The available interpretation symbols for customizing `org-todo-keywords'.
  1631. Interested libraries should add to this list.")
  1632. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1633. "List of TODO entry keyword sequences and their interpretation.
  1634. \\<org-mode-map>This is a list of sequences.
  1635. Each sequence starts with a symbol, either `sequence' or `type',
  1636. indicating if the keywords should be interpreted as a sequence of
  1637. action steps, or as different types of TODO items. The first
  1638. keywords are states requiring action - these states will select a headline
  1639. for inclusion into the global TODO list Org produces. If one of the
  1640. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1641. signify that no further action is necessary. If \"|\" is not found,
  1642. the last keyword is treated as the only DONE state of the sequence.
  1643. The command `\\[org-todo]' cycles an entry through these states, and one
  1644. additional state where no keyword is present. For details about this
  1645. cycling, see the manual.
  1646. TODO keywords and interpretation can also be set on a per-file basis with
  1647. the special #+SEQ_TODO and #+TYP_TODO lines.
  1648. Each keyword can optionally specify a character for fast state selection
  1649. \(in combination with the variable `org-use-fast-todo-selection')
  1650. and specifiers for state change logging, using the same syntax that
  1651. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1652. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1653. indicates to record a time stamp each time this state is selected.
  1654. Each keyword may also specify if a timestamp or a note should be
  1655. recorded when entering or leaving the state, by adding additional
  1656. characters in the parenthesis after the keyword. This looks like this:
  1657. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1658. record only the time of the state change. With X and Y being either
  1659. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1660. Y when leaving the state if and only if the *target* state does not
  1661. define X. You may omit any of the fast-selection key or X or /Y,
  1662. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1663. For backward compatibility, this variable may also be just a list
  1664. of keywords. In this case the interpretation (sequence or type) will be
  1665. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1666. :group 'org-todo
  1667. :group 'org-keywords
  1668. :type '(choice
  1669. (repeat :tag "Old syntax, just keywords"
  1670. (string :tag "Keyword"))
  1671. (repeat :tag "New syntax"
  1672. (cons
  1673. (choice
  1674. :tag "Interpretation"
  1675. ;;Quick and dirty way to see
  1676. ;;`org-todo-interpretation'. This takes the
  1677. ;;place of item arguments
  1678. :convert-widget
  1679. (lambda (widget)
  1680. (widget-put widget
  1681. :args (mapcar
  1682. (lambda (x)
  1683. (widget-convert
  1684. (cons 'const x)))
  1685. org-todo-interpretation-widgets))
  1686. widget))
  1687. (repeat
  1688. (string :tag "Keyword"))))))
  1689. (defvar-local org-todo-keywords-1 nil
  1690. "All TODO and DONE keywords active in a buffer.")
  1691. (defvar org-todo-keywords-for-agenda nil)
  1692. (defvar org-done-keywords-for-agenda nil)
  1693. (defvar org-todo-keyword-alist-for-agenda nil)
  1694. (defvar org-tag-alist-for-agenda nil
  1695. "Alist of all tags from all agenda files.")
  1696. (defvar org-tag-groups-alist-for-agenda nil
  1697. "Alist of all groups tags from all current agenda files.")
  1698. (defvar-local org-tag-groups-alist nil)
  1699. (defvar org-agenda-contributing-files nil)
  1700. (defvar-local org-current-tag-alist nil
  1701. "Alist of all tag groups in current buffer.
  1702. This variable takes into consideration `org-tag-alist',
  1703. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1704. (defvar-local org-not-done-keywords nil)
  1705. (defvar-local org-done-keywords nil)
  1706. (defvar-local org-todo-heads nil)
  1707. (defvar-local org-todo-sets nil)
  1708. (defvar-local org-todo-log-states nil)
  1709. (defvar-local org-todo-kwd-alist nil)
  1710. (defvar-local org-todo-key-alist nil)
  1711. (defvar-local org-todo-key-trigger nil)
  1712. (defcustom org-todo-interpretation 'sequence
  1713. "Controls how TODO keywords are interpreted.
  1714. This variable is in principle obsolete and is only used for
  1715. backward compatibility, if the interpretation of todo keywords is
  1716. not given already in `org-todo-keywords'. See that variable for
  1717. more information."
  1718. :group 'org-todo
  1719. :group 'org-keywords
  1720. :type '(choice (const sequence)
  1721. (const type)))
  1722. (defcustom org-use-fast-todo-selection 'auto
  1723. "\\<org-mode-map>\
  1724. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1725. This variable describes if and under what circumstances the cycling
  1726. mechanism for TODO keywords will be replaced by a single-key, direct
  1727. selection scheme, where the choices are displayed in a little window.
  1728. When nil, fast selection is never used. This means that the command
  1729. will always switch to the next state.
  1730. When it is the symbol `auto', fast selection is whenever selection
  1731. keys have been defined.
  1732. `expert' is like `auto', but no special window with the keyword
  1733. will be shown, choices will only be listed in the prompt.
  1734. In all cases, the special interface is only used if access keys have
  1735. actually been assigned by the user, i.e. if keywords in the configuration
  1736. are followed by a letter in parenthesis, like TODO(t)."
  1737. :group 'org-todo
  1738. :set (lambda (var val)
  1739. (cond
  1740. ((eq var t) (set var 'auto))
  1741. ((eq var 'prefix) (set var nil))
  1742. (t (set var val))))
  1743. :type '(choice
  1744. (const :tag "Never" nil)
  1745. (const :tag "Automatically, when key letter have been defined" auto)
  1746. (const :tag "Automatically, but don't show the selection window" expert)))
  1747. (defcustom org-provide-todo-statistics t
  1748. "Non-nil means update todo statistics after insert and toggle.
  1749. ALL-HEADLINES means update todo statistics by including headlines
  1750. with no TODO keyword as well, counting them as not done.
  1751. A list of TODO keywords means the same, but skip keywords that are
  1752. not in this list.
  1753. When set to a list of two lists, the first list contains keywords
  1754. to consider as TODO keywords, the second list contains keywords
  1755. to consider as DONE keywords.
  1756. When this is set, todo statistics is updated in the parent of the
  1757. current entry each time a todo state is changed."
  1758. :group 'org-todo
  1759. :type '(choice
  1760. (const :tag "Yes, only for TODO entries" t)
  1761. (const :tag "Yes, including all entries" all-headlines)
  1762. (repeat :tag "Yes, for TODOs in this list"
  1763. (string :tag "TODO keyword"))
  1764. (list :tag "Yes, for TODOs and DONEs in these lists"
  1765. (repeat (string :tag "TODO keyword"))
  1766. (repeat (string :tag "DONE keyword")))
  1767. (other :tag "No TODO statistics" nil)))
  1768. (defcustom org-hierarchical-todo-statistics t
  1769. "Non-nil means TODO statistics covers just direct children.
  1770. When nil, all entries in the subtree are considered.
  1771. This has only an effect if `org-provide-todo-statistics' is set.
  1772. To set this to nil for only a single subtree, use a COOKIE_DATA
  1773. property and include the word \"recursive\" into the value."
  1774. :group 'org-todo
  1775. :type 'boolean)
  1776. (defcustom org-after-todo-state-change-hook nil
  1777. "Hook which is run after the state of a TODO item was changed.
  1778. The new state (a string with a TODO keyword, or nil) is available in the
  1779. Lisp variable `org-state'."
  1780. :group 'org-todo
  1781. :type 'hook)
  1782. (defvar org-blocker-hook nil
  1783. "Hook for functions that are allowed to block a state change.
  1784. Functions in this hook should not modify the buffer.
  1785. Each function gets as its single argument a property list,
  1786. see `org-trigger-hook' for more information about this list.
  1787. If any of the functions in this hook returns nil, the state change
  1788. is blocked.")
  1789. (defvar org-trigger-hook nil
  1790. "Hook for functions that are triggered by a state change.
  1791. Each function gets as its single argument a property list with at
  1792. least the following elements:
  1793. (:type type-of-change :position pos-at-entry-start
  1794. :from old-state :to new-state)
  1795. Depending on the type, more properties may be present.
  1796. This mechanism is currently implemented for:
  1797. TODO state changes
  1798. ------------------
  1799. :type todo-state-change
  1800. :from previous state (keyword as a string), or nil, or a symbol
  1801. `todo' or `done', to indicate the general type of state.
  1802. :to new state, like in :from")
  1803. (defcustom org-enforce-todo-dependencies nil
  1804. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1805. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1806. be blocked if any prior sibling is not yet done.
  1807. Finally, if the parent is blocked because of ordered siblings of its own,
  1808. the child will also be blocked."
  1809. :set (lambda (var val)
  1810. (set var val)
  1811. (if val
  1812. (add-hook 'org-blocker-hook
  1813. 'org-block-todo-from-children-or-siblings-or-parent)
  1814. (remove-hook 'org-blocker-hook
  1815. 'org-block-todo-from-children-or-siblings-or-parent)))
  1816. :group 'org-todo
  1817. :type 'boolean)
  1818. (defcustom org-enforce-todo-checkbox-dependencies nil
  1819. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1820. When this is nil, checkboxes have no influence on switching TODO states.
  1821. When non-nil, you first need to check off all check boxes before the TODO
  1822. entry can be switched to DONE.
  1823. This variable needs to be set before org.el is loaded, and you need to
  1824. restart Emacs after a change to make the change effective. The only way
  1825. to change it while Emacs is running is through the customize interface."
  1826. :set (lambda (var val)
  1827. (set var val)
  1828. (if val
  1829. (add-hook 'org-blocker-hook
  1830. 'org-block-todo-from-checkboxes)
  1831. (remove-hook 'org-blocker-hook
  1832. 'org-block-todo-from-checkboxes)))
  1833. :group 'org-todo
  1834. :type 'boolean)
  1835. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1836. "Non-nil means inserting a TODO heading is treated as state change.
  1837. So when the command `\\[org-insert-todo-heading]' is used, state change
  1838. logging will apply if appropriate. When nil, the new TODO item will
  1839. be inserted directly, and no logging will take place."
  1840. :group 'org-todo
  1841. :type 'boolean)
  1842. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1843. "Non-nil means switching TODO states with S-cursor counts as state change.
  1844. This is the default behavior. However, setting this to nil allows a
  1845. convenient way to select a TODO state and bypass any logging associated
  1846. with that."
  1847. :group 'org-todo
  1848. :type 'boolean)
  1849. (defcustom org-todo-state-tags-triggers nil
  1850. "Tag changes that should be triggered by TODO state changes.
  1851. This is a list. Each entry is
  1852. (state-change (tag . flag) .......)
  1853. State-change can be a string with a state, and empty string to indicate the
  1854. state that has no TODO keyword, or it can be one of the symbols `todo'
  1855. or `done', meaning any not-done or done state, respectively."
  1856. :group 'org-todo
  1857. :group 'org-tags
  1858. :type '(repeat
  1859. (cons (choice :tag "When changing to"
  1860. (const :tag "Not-done state" todo)
  1861. (const :tag "Done state" done)
  1862. (string :tag "State"))
  1863. (repeat
  1864. (cons :tag "Tag action"
  1865. (string :tag "Tag")
  1866. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1867. (defcustom org-log-done nil
  1868. "Information to record when a task moves to the DONE state.
  1869. Possible values are:
  1870. nil Don't add anything, just change the keyword
  1871. time Add a time stamp to the task
  1872. note Prompt for a note and add it with template `org-log-note-headings'
  1873. This option can also be set with on a per-file-basis with
  1874. #+STARTUP: nologdone
  1875. #+STARTUP: logdone
  1876. #+STARTUP: lognotedone
  1877. You can have local logging settings for a subtree by setting the LOGGING
  1878. property to one or more of these keywords."
  1879. :group 'org-todo
  1880. :group 'org-progress
  1881. :type '(choice
  1882. (const :tag "No logging" nil)
  1883. (const :tag "Record CLOSED timestamp" time)
  1884. (const :tag "Record CLOSED timestamp with note." note)))
  1885. ;; Normalize old uses of org-log-done.
  1886. (cond
  1887. ((eq org-log-done t) (setq org-log-done 'time))
  1888. ((and (listp org-log-done) (memq 'done org-log-done))
  1889. (setq org-log-done 'note)))
  1890. (defcustom org-log-reschedule nil
  1891. "Information to record when the scheduling date of a task is modified.
  1892. Possible values are:
  1893. nil Don't add anything, just change the date
  1894. time Add a time stamp to the task
  1895. note Prompt for a note and add it with template `org-log-note-headings'
  1896. This option can also be set with on a per-file-basis with
  1897. #+STARTUP: nologreschedule
  1898. #+STARTUP: logreschedule
  1899. #+STARTUP: lognotereschedule
  1900. You can have local logging settings for a subtree by setting the LOGGING
  1901. property to one or more of these keywords.
  1902. This variable has an effect when calling `org-schedule' or
  1903. `org-agenda-schedule' only."
  1904. :group 'org-todo
  1905. :group 'org-progress
  1906. :type '(choice
  1907. (const :tag "No logging" nil)
  1908. (const :tag "Record timestamp" time)
  1909. (const :tag "Record timestamp with note" note)))
  1910. (defcustom org-log-redeadline nil
  1911. "Information to record when the deadline date of a task is modified.
  1912. Possible values are:
  1913. nil Don't add anything, just change the date
  1914. time Add a time stamp to the task
  1915. note Prompt for a note and add it with template `org-log-note-headings'
  1916. This option can also be set with on a per-file-basis with
  1917. #+STARTUP: nologredeadline
  1918. #+STARTUP: logredeadline
  1919. #+STARTUP: lognoteredeadline
  1920. You can have local logging settings for a subtree by setting the LOGGING
  1921. property to one or more of these keywords.
  1922. This variable has an effect when calling `org-deadline' or
  1923. `org-agenda-deadline' only."
  1924. :group 'org-todo
  1925. :group 'org-progress
  1926. :type '(choice
  1927. (const :tag "No logging" nil)
  1928. (const :tag "Record timestamp" time)
  1929. (const :tag "Record timestamp with note." note)))
  1930. (defcustom org-log-note-clock-out nil
  1931. "Non-nil means record a note when clocking out of an item.
  1932. This can also be configured on a per-file basis by adding one of
  1933. the following lines anywhere in the buffer:
  1934. #+STARTUP: lognoteclock-out
  1935. #+STARTUP: nolognoteclock-out"
  1936. :group 'org-todo
  1937. :group 'org-progress
  1938. :type 'boolean)
  1939. (defcustom org-log-done-with-time t
  1940. "Non-nil means the CLOSED time stamp will contain date and time.
  1941. When nil, only the date will be recorded."
  1942. :group 'org-progress
  1943. :type 'boolean)
  1944. (defcustom org-log-note-headings
  1945. '((done . "CLOSING NOTE %t")
  1946. (state . "State %-12s from %-12S %t")
  1947. (note . "Note taken on %t")
  1948. (reschedule . "Rescheduled from %S on %t")
  1949. (delschedule . "Not scheduled, was %S on %t")
  1950. (redeadline . "New deadline from %S on %t")
  1951. (deldeadline . "Removed deadline, was %S on %t")
  1952. (refile . "Refiled on %t")
  1953. (clock-out . ""))
  1954. "Headings for notes added to entries.
  1955. The value is an alist, with the car being a symbol indicating the
  1956. note context, and the cdr is the heading to be used. The heading
  1957. may also be the empty string. The following placeholders can be
  1958. used:
  1959. %t a time stamp.
  1960. %T an active time stamp instead the default inactive one
  1961. %d a short-format time stamp.
  1962. %D an active short-format time stamp.
  1963. %s the new TODO state or time stamp (inactive), in double quotes.
  1964. %S the old TODO state or time stamp (inactive), in double quotes.
  1965. %u the user name.
  1966. %U full user name.
  1967. In fact, it is not a good idea to change the `state' entry,
  1968. because Agenda Log mode depends on the format of these entries."
  1969. :group 'org-todo
  1970. :group 'org-progress
  1971. :type '(list :greedy t
  1972. (cons (const :tag "Heading when closing an item" done) string)
  1973. (cons (const :tag
  1974. "Heading when changing todo state (todo sequence only)"
  1975. state) string)
  1976. (cons (const :tag "Heading when just taking a note" note) string)
  1977. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1978. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1979. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1980. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1981. (cons (const :tag "Heading when refiling" refile) string)
  1982. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1983. (unless (assq 'note org-log-note-headings)
  1984. (push '(note . "%t") org-log-note-headings))
  1985. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1986. (defcustom org-log-into-drawer nil
  1987. "Non-nil means insert state change notes and time stamps into a drawer.
  1988. When nil, state changes notes will be inserted after the headline and
  1989. any scheduling and clock lines, but not inside a drawer.
  1990. The value of this variable should be the name of the drawer to use.
  1991. LOGBOOK is proposed as the default drawer for this purpose, you can
  1992. also set this to a string to define the drawer of your choice.
  1993. A value of t is also allowed, representing \"LOGBOOK\".
  1994. A value of t or nil can also be set with on a per-file-basis with
  1995. #+STARTUP: logdrawer
  1996. #+STARTUP: nologdrawer
  1997. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1998. will be ignored.
  1999. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2000. a subtree.
  2001. Do not check directly this variable in a Lisp program. Call
  2002. function `org-log-into-drawer' instead."
  2003. :group 'org-todo
  2004. :group 'org-progress
  2005. :type '(choice
  2006. (const :tag "Not into a drawer" nil)
  2007. (const :tag "LOGBOOK" t)
  2008. (string :tag "Other")))
  2009. (defun org-log-into-drawer ()
  2010. "Name of the log drawer, as a string, or nil.
  2011. This is the value of `org-log-into-drawer'. However, if the
  2012. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2013. be used instead of the default value."
  2014. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2015. (cond ((equal p "nil") nil)
  2016. ((equal p "t") "LOGBOOK")
  2017. ((stringp p) p)
  2018. (p "LOGBOOK")
  2019. ((stringp org-log-into-drawer) org-log-into-drawer)
  2020. (org-log-into-drawer "LOGBOOK"))))
  2021. (defcustom org-log-state-notes-insert-after-drawers nil
  2022. "Non-nil means insert state change notes after any drawers in entry.
  2023. Only the drawers that *immediately* follow the headline and the
  2024. deadline/scheduled line are skipped.
  2025. When nil, insert notes right after the heading and perhaps the line
  2026. with deadline/scheduling if present.
  2027. This variable will have no effect if `org-log-into-drawer' is
  2028. set."
  2029. :group 'org-todo
  2030. :group 'org-progress
  2031. :type 'boolean)
  2032. (defcustom org-log-states-order-reversed t
  2033. "Non-nil means the latest state note will be directly after heading.
  2034. When nil, the state change notes will be ordered according to time.
  2035. This option can also be set with on a per-file-basis with
  2036. #+STARTUP: logstatesreversed
  2037. #+STARTUP: nologstatesreversed"
  2038. :group 'org-todo
  2039. :group 'org-progress
  2040. :type 'boolean)
  2041. (defcustom org-todo-repeat-to-state nil
  2042. "The TODO state to which a repeater should return the repeating task.
  2043. By default this is the first task of a TODO sequence or the
  2044. previous state of a TYPE_TODO set. But you can specify to use
  2045. the previous state in a TODO sequence or a string.
  2046. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2047. entry, which has precedence over this option."
  2048. :group 'org-todo
  2049. :version "24.1"
  2050. :type '(choice (const :tag "Use the previous TODO state" t)
  2051. (const :tag "Use the head of the TODO sequence" nil)
  2052. (string :tag "Use a specific TODO state")))
  2053. (defcustom org-log-repeat 'time
  2054. "Non-nil means record moving through the DONE state when triggering repeat.
  2055. An auto-repeating task is immediately switched back to TODO when
  2056. marked DONE. If you are not logging state changes (by adding \"@\"
  2057. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2058. record a closing note, there will be no record of the task moving
  2059. through DONE. This variable forces taking a note anyway.
  2060. nil Don't force a record
  2061. time Record a time stamp
  2062. note Prompt for a note and add it with template `org-log-note-headings'
  2063. This option can also be set with on a per-file-basis with
  2064. #+STARTUP: nologrepeat
  2065. #+STARTUP: logrepeat
  2066. #+STARTUP: lognoterepeat
  2067. You can have local logging settings for a subtree by setting the LOGGING
  2068. property to one or more of these keywords."
  2069. :group 'org-todo
  2070. :group 'org-progress
  2071. :type '(choice
  2072. (const :tag "Don't force a record" nil)
  2073. (const :tag "Force recording the DONE state" time)
  2074. (const :tag "Force recording a note with the DONE state" note)))
  2075. (defcustom org-todo-repeat-hook nil
  2076. "Hook that is run after a task has been repeated."
  2077. :package-version '(Org . "9.2")
  2078. :group 'org-todo
  2079. :type 'hook)
  2080. (defgroup org-priorities nil
  2081. "Priorities in Org mode."
  2082. :tag "Org Priorities"
  2083. :group 'org-todo)
  2084. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2085. (defcustom org-priority-enable-commands t
  2086. "Non-nil means priority commands are active.
  2087. When nil, these commands will be disabled, so that you never accidentally
  2088. set a priority."
  2089. :group 'org-priorities
  2090. :type 'boolean)
  2091. (defvaralias 'org-highest-priority 'org-priority-highest)
  2092. (defcustom org-priority-highest ?A
  2093. "The highest priority of TODO items.
  2094. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2095. Must be smaller than `org-priority-lowest'."
  2096. :group 'org-priorities
  2097. :type '(choice
  2098. (character :tag "Character")
  2099. (integer :tag "Integer (< 65)")))
  2100. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2101. (defcustom org-priority-lowest ?C
  2102. "The lowest priority of TODO items.
  2103. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2104. Must be higher than `org-priority-highest'."
  2105. :group 'org-priorities
  2106. :type '(choice
  2107. (character :tag "Character")
  2108. (integer :tag "Integer (< 65)")))
  2109. (defvaralias 'org-default-priority 'org-priority-default)
  2110. (defcustom org-priority-default ?B
  2111. "The default priority of TODO items.
  2112. This is the priority an item gets if no explicit priority is given.
  2113. When starting to cycle on an empty priority the first step in the cycle
  2114. depends on `org-priority-start-cycle-with-default'. The resulting first
  2115. step priority must not exceed the range from `org-priority-highest' to
  2116. `org-priority-lowest' which means that `org-priority-default' has to be
  2117. in this range exclusive or inclusive to the range boundaries. Else the
  2118. first step refuses to set the default and the second will fall back on
  2119. \(depending on the command used) the highest or lowest priority."
  2120. :group 'org-priorities
  2121. :type '(choice
  2122. (character :tag "Character")
  2123. (integer :tag "Integer (< 65)")))
  2124. (defcustom org-priority-start-cycle-with-default t
  2125. "Non-nil means start with default priority when starting to cycle.
  2126. When this is nil, the first step in the cycle will be (depending on the
  2127. command used) one higher or lower than the default priority.
  2128. See also `org-priority-default'."
  2129. :group 'org-priorities
  2130. :type 'boolean)
  2131. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2132. (defcustom org-priority-get-priority-function nil
  2133. "Function to extract the priority from a string.
  2134. The string is normally the headline. If this is nil, Org
  2135. computes the priority from the priority cookie like [#A] in the
  2136. headline. It returns an integer, increasing by 1000 for each
  2137. priority level.
  2138. The user can set a different function here, which should take a
  2139. string as an argument and return the numeric priority."
  2140. :group 'org-priorities
  2141. :version "24.1"
  2142. :type '(choice
  2143. (const nil)
  2144. (function)))
  2145. (defgroup org-time nil
  2146. "Options concerning time stamps and deadlines in Org mode."
  2147. :tag "Org Time"
  2148. :group 'org)
  2149. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2150. "Number of minutes to round time stamps to.
  2151. \\<org-mode-map>\
  2152. These are two values, the first applies when first creating a time stamp.
  2153. The second applies when changing it with the commands `S-up' and `S-down'.
  2154. When changing the time stamp, this means that it will change in steps
  2155. of N minutes, as given by the second value.
  2156. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2157. numbers should be factors of 60, so for example 5, 10, 15.
  2158. When this is larger than 1, you can still force an exact time stamp by using
  2159. a double prefix argument to a time stamp command like \
  2160. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2161. and by using a prefix arg to `S-up/down' to specify the exact number
  2162. of minutes to shift."
  2163. :group 'org-time
  2164. :get (lambda (var) ; Make sure both elements are there
  2165. (if (integerp (default-value var))
  2166. (list (default-value var) 5)
  2167. (default-value var)))
  2168. :type '(list
  2169. (integer :tag "when inserting times")
  2170. (integer :tag "when modifying times")))
  2171. ;; Normalize old customizations of this variable.
  2172. (when (integerp org-time-stamp-rounding-minutes)
  2173. (setq org-time-stamp-rounding-minutes
  2174. (list org-time-stamp-rounding-minutes
  2175. org-time-stamp-rounding-minutes)))
  2176. (defcustom org-display-custom-times nil
  2177. "Non-nil means overlay custom formats over all time stamps.
  2178. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2179. To turn this on on a per-file basis, insert anywhere in the file:
  2180. #+STARTUP: customtime"
  2181. :group 'org-time
  2182. :set 'set-default
  2183. :type 'sexp)
  2184. (make-variable-buffer-local 'org-display-custom-times)
  2185. (defcustom org-time-stamp-custom-formats
  2186. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2187. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2188. These are overlaid over the default ISO format if the variable
  2189. `org-display-custom-times' is set. Time like %H:%M should be at the
  2190. end of the second format. The custom formats are also honored by export
  2191. commands, if custom time display is turned on at the time of export."
  2192. :group 'org-time
  2193. :type 'sexp)
  2194. (defun org-time-stamp-format (&optional long inactive)
  2195. "Get the right format for a time string."
  2196. (let ((f (if long (cdr org-time-stamp-formats)
  2197. (car org-time-stamp-formats))))
  2198. (if inactive
  2199. (concat "[" (substring f 1 -1) "]")
  2200. f)))
  2201. (defcustom org-deadline-warning-days 14
  2202. "Number of days before expiration during which a deadline becomes active.
  2203. This variable governs the display in sparse trees and in the agenda.
  2204. When 0 or negative, it means use this number (the absolute value of it)
  2205. even if a deadline has a different individual lead time specified.
  2206. Custom commands can set this variable in the options section."
  2207. :group 'org-time
  2208. :group 'org-agenda-daily/weekly
  2209. :type 'integer)
  2210. (defcustom org-scheduled-delay-days 0
  2211. "Number of days before a scheduled item becomes active.
  2212. This variable governs the display in sparse trees and in the agenda.
  2213. The default value (i.e. 0) means: don't delay scheduled item.
  2214. When negative, it means use this number (the absolute value of it)
  2215. even if a scheduled item has a different individual delay time
  2216. specified.
  2217. Custom commands can set this variable in the options section."
  2218. :group 'org-time
  2219. :group 'org-agenda-daily/weekly
  2220. :version "24.4"
  2221. :package-version '(Org . "8.0")
  2222. :type 'integer)
  2223. (defcustom org-read-date-prefer-future t
  2224. "Non-nil means assume future for incomplete date input from user.
  2225. This affects the following situations:
  2226. 1. The user gives a month but not a year.
  2227. For example, if it is April and you enter \"feb 2\", this will be read
  2228. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2229. 2. The user gives a day, but no month.
  2230. For example, if today is the 15th, and you enter \"3\", Org will read
  2231. this as the third of *next* month. However, if you enter \"17\",
  2232. it will be considered as *this* month.
  2233. If you set this variable to the symbol `time', then also the following
  2234. will work:
  2235. 3. If the user gives a time.
  2236. If the time is before now, it will be interpreted as tomorrow.
  2237. Currently none of this works for ISO week specifications.
  2238. When this option is nil, the current day, month and year will always be
  2239. used as defaults.
  2240. See also `org-agenda-jump-prefer-future'."
  2241. :group 'org-time
  2242. :type '(choice
  2243. (const :tag "Never" nil)
  2244. (const :tag "Check month and day" t)
  2245. (const :tag "Check month, day, and time" time)))
  2246. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2247. "Should the agenda jump command prefer the future for incomplete dates?
  2248. The default is to do the same as configured in `org-read-date-prefer-future'.
  2249. But you can also set a deviating value here.
  2250. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2251. :group 'org-agenda
  2252. :group 'org-time
  2253. :version "24.1"
  2254. :type '(choice
  2255. (const :tag "Use org-read-date-prefer-future"
  2256. org-read-date-prefer-future)
  2257. (const :tag "Never" nil)
  2258. (const :tag "Always" t)))
  2259. (defcustom org-read-date-force-compatible-dates t
  2260. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2261. Depending on the system Emacs is running on, certain dates cannot
  2262. be represented with the type used internally to represent time.
  2263. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2264. correctly. Some systems allow for earlier dates, some for later,
  2265. some for both. One way to find out is to insert any date into an
  2266. Org buffer, putting the cursor on the year and hitting S-up and
  2267. S-down to test the range.
  2268. When this variable is set to t, the date/time prompt will not let
  2269. you specify dates outside the 1970-2037 range, so it is certain that
  2270. these dates will work in whatever version of Emacs you are
  2271. running, and also that you can move a file from one Emacs implementation
  2272. to another. Whenever Org is forcing the year for you, it will display
  2273. a message and beep.
  2274. When this variable is nil, Org will check if the date is
  2275. representable in the specific Emacs implementation you are using.
  2276. If not, it will force a year, usually the current year, and beep
  2277. to remind you. Currently this setting is not recommended because
  2278. the likelihood that you will open your Org files in an Emacs that
  2279. has limited date range is not negligible.
  2280. A workaround for this problem is to use diary sexp dates for time
  2281. stamps outside of this range."
  2282. :group 'org-time
  2283. :version "24.1"
  2284. :type 'boolean)
  2285. (defcustom org-read-date-display-live t
  2286. "Non-nil means display current interpretation of date prompt live.
  2287. This display will be in an overlay, in the minibuffer. Note that
  2288. live display is only active when `org-read-date-popup-calendar'
  2289. is non-nil."
  2290. :group 'org-time
  2291. :type 'boolean)
  2292. (defvaralias 'org-popup-calendar-for-date-prompt
  2293. 'org-read-date-popup-calendar)
  2294. (defcustom org-read-date-popup-calendar t
  2295. "Non-nil means pop up a calendar when prompting for a date.
  2296. In the calendar, the date can be selected with mouse-1. However, the
  2297. minibuffer will also be active, and you can simply enter the date as well.
  2298. When nil, only the minibuffer will be available."
  2299. :group 'org-time
  2300. :type 'boolean)
  2301. (defcustom org-extend-today-until 0
  2302. "The hour when your day really ends. Must be an integer.
  2303. This has influence for the following applications:
  2304. - When switching the agenda to \"today\". If it is still earlier than
  2305. the time given here, the day recognized as TODAY is actually yesterday.
  2306. - When a date is read from the user and it is still before the time given
  2307. here, the current date and time will be assumed to be yesterday, 23:59.
  2308. Also, timestamps inserted in capture templates follow this rule.
  2309. IMPORTANT: This is a feature whose implementation is and likely will
  2310. remain incomplete. Really, it is only here because past midnight seems to
  2311. be the favorite working time of John Wiegley :-)"
  2312. :group 'org-time
  2313. :type 'integer)
  2314. (defcustom org-use-effective-time nil
  2315. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2316. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2317. \"effective time\" of any timestamps between midnight and 8am will be
  2318. 23:59 of the previous day."
  2319. :group 'org-time
  2320. :version "24.1"
  2321. :type 'boolean)
  2322. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2323. "When non-nil, use the last clock out time for `org-todo'.
  2324. Note that this option has precedence over the combined use of
  2325. `org-use-effective-time' and `org-extend-today-until'."
  2326. :group 'org-time
  2327. :version "24.4"
  2328. :package-version '(Org . "8.0")
  2329. :type 'boolean)
  2330. (defcustom org-edit-timestamp-down-means-later nil
  2331. "Non-nil means S-down will increase the time in a time stamp.
  2332. When nil, S-up will increase."
  2333. :group 'org-time
  2334. :type 'boolean)
  2335. (defcustom org-calendar-follow-timestamp-change t
  2336. "Non-nil means make the calendar window follow timestamp changes.
  2337. When a timestamp is modified and the calendar window is visible, it will be
  2338. moved to the new date."
  2339. :group 'org-time
  2340. :type 'boolean)
  2341. (defgroup org-tags nil
  2342. "Options concerning tags in Org mode."
  2343. :tag "Org Tags"
  2344. :group 'org)
  2345. (defcustom org-tag-alist nil
  2346. "Default tags available in Org files.
  2347. The value of this variable is an alist. Associations either:
  2348. (TAG)
  2349. (TAG . SELECT)
  2350. (SPECIAL)
  2351. where TAG is a tag as a string, SELECT is character, used to
  2352. select that tag through the fast tag selection interface, and
  2353. SPECIAL is one of the following keywords: `:startgroup',
  2354. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2355. `:newline'. These keywords are used to define a hierarchy of
  2356. tags. See manual for details.
  2357. When this variable is nil, Org mode bases tag input on what is
  2358. already in the buffer. The value can be overridden locally by
  2359. using a TAGS keyword, e.g.,
  2360. #+TAGS: tag1 tag2
  2361. See also `org-tag-persistent-alist' to sidestep this behavior."
  2362. :group 'org-tags
  2363. :type '(repeat
  2364. (choice
  2365. (cons :tag "Tag with key"
  2366. (string :tag "Tag name")
  2367. (character :tag "Access char"))
  2368. (list :tag "Tag" (string :tag "Tag name"))
  2369. (const :tag "Start radio group" (:startgroup))
  2370. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2371. (const :tag "Group tags delimiter" (:grouptags))
  2372. (const :tag "End radio group" (:endgroup))
  2373. (const :tag "End tag group, non distinct" (:endgrouptag))
  2374. (const :tag "New line" (:newline)))))
  2375. (defcustom org-tag-persistent-alist nil
  2376. "Tags always available in Org files.
  2377. The value of this variable is an alist. Associations either:
  2378. (TAG)
  2379. (TAG . SELECT)
  2380. (SPECIAL)
  2381. where TAG is a tag as a string, SELECT is a character, used to
  2382. select that tag through the fast tag selection interface, and
  2383. SPECIAL is one of the following keywords: `:startgroup',
  2384. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2385. `:newline'. These keywords are used to define a hierarchy of
  2386. tags. See manual for details.
  2387. Unlike to `org-tag-alist', tags defined in this variable do not
  2388. depend on a local TAGS keyword. Instead, to disable these tags
  2389. on a per-file basis, insert anywhere in the file:
  2390. #+STARTUP: noptag"
  2391. :group 'org-tags
  2392. :type '(repeat
  2393. (choice
  2394. (cons :tag "Tag with key"
  2395. (string :tag "Tag name")
  2396. (character :tag "Access char"))
  2397. (list :tag "Tag" (string :tag "Tag name"))
  2398. (const :tag "Start radio group" (:startgroup))
  2399. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2400. (const :tag "Group tags delimiter" (:grouptags))
  2401. (const :tag "End radio group" (:endgroup))
  2402. (const :tag "End tag group, non distinct" (:endgrouptag))
  2403. (const :tag "New line" (:newline)))))
  2404. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2405. "If non-nil, always offer completion for all tags of all agenda files.
  2406. Setting this variable locally allows for dynamic generation of tag
  2407. completions in capture buffers.
  2408. (add-hook \\='org-capture-mode-hook
  2409. (lambda ()
  2410. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2411. :group 'org-tags
  2412. :version "24.1"
  2413. :type 'boolean)
  2414. (defvar org-file-tags nil
  2415. "List of tags that can be inherited by all entries in the file.
  2416. The tags will be inherited if the variable `org-use-tag-inheritance'
  2417. says they should be.
  2418. This variable is populated from #+FILETAGS lines.")
  2419. (defcustom org-use-fast-tag-selection 'auto
  2420. "Non-nil means use fast tag selection scheme.
  2421. This is a special interface to select and deselect tags with single keys.
  2422. When nil, fast selection is never used.
  2423. When the symbol `auto', fast selection is used if and only if selection
  2424. characters for tags have been configured, either through the variable
  2425. `org-tag-alist' or through a #+TAGS line in the buffer.
  2426. When t, fast selection is always used and selection keys are assigned
  2427. automatically if necessary."
  2428. :group 'org-tags
  2429. :type '(choice
  2430. (const :tag "Always" t)
  2431. (const :tag "Never" nil)
  2432. (const :tag "When selection characters are configured" auto)))
  2433. (defcustom org-fast-tag-selection-single-key nil
  2434. "Non-nil means fast tag selection exits after first change.
  2435. When nil, you have to press RET to exit it.
  2436. During fast tag selection, you can toggle this flag with `C-c'.
  2437. This variable can also have the value `expert'. In this case, the window
  2438. displaying the tags menu is not even shown, until you press `C-c' again."
  2439. :group 'org-tags
  2440. :type '(choice
  2441. (const :tag "No" nil)
  2442. (const :tag "Yes" t)
  2443. (const :tag "Expert" expert)))
  2444. (defvar org-fast-tag-selection-include-todo nil
  2445. "Non-nil means fast tags selection interface will also offer TODO states.
  2446. This is an undocumented feature, you should not rely on it.")
  2447. (defcustom org-tags-column -77
  2448. "The column to which tags should be indented in a headline.
  2449. If this number is positive, it specifies the column. If it is negative,
  2450. it means that the tags should be flushright to that column. For example,
  2451. -80 works well for a normal 80 character screen.
  2452. When 0, place tags directly after headline text, with only one space in
  2453. between."
  2454. :group 'org-tags
  2455. :type 'integer)
  2456. (defcustom org-auto-align-tags t
  2457. "Non-nil keeps tags aligned when modifying headlines.
  2458. Some operations (i.e. demoting) change the length of a headline and
  2459. therefore shift the tags around. With this option turned on, after
  2460. each such operation the tags are again aligned to `org-tags-column'."
  2461. :group 'org-tags
  2462. :type 'boolean)
  2463. (defcustom org-use-tag-inheritance t
  2464. "Non-nil means tags in levels apply also for sublevels.
  2465. When nil, only the tags directly given in a specific line apply there.
  2466. This may also be a list of tags that should be inherited, or a regexp that
  2467. matches tags that should be inherited. Additional control is possible
  2468. with the variable `org-tags-exclude-from-inheritance' which gives an
  2469. explicit list of tags to be excluded from inheritance, even if the value of
  2470. `org-use-tag-inheritance' would select it for inheritance.
  2471. If this option is t, a match early-on in a tree can lead to a large
  2472. number of matches in the subtree when constructing the agenda or creating
  2473. a sparse tree. If you only want to see the first match in a tree during
  2474. a search, check out the variable `org-tags-match-list-sublevels'."
  2475. :group 'org-tags
  2476. :type '(choice
  2477. (const :tag "Not" nil)
  2478. (const :tag "Always" t)
  2479. (repeat :tag "Specific tags" (string :tag "Tag"))
  2480. (regexp :tag "Tags matched by regexp")))
  2481. (defcustom org-tags-exclude-from-inheritance nil
  2482. "List of tags that should never be inherited.
  2483. This is a way to exclude a few tags from inheritance. For way to do
  2484. the opposite, to actively allow inheritance for selected tags,
  2485. see the variable `org-use-tag-inheritance'."
  2486. :group 'org-tags
  2487. :type '(repeat (string :tag "Tag")))
  2488. (defun org-tag-inherit-p (tag)
  2489. "Check if TAG is one that should be inherited."
  2490. (cond
  2491. ((member tag org-tags-exclude-from-inheritance) nil)
  2492. ((eq org-use-tag-inheritance t) t)
  2493. ((not org-use-tag-inheritance) nil)
  2494. ((stringp org-use-tag-inheritance)
  2495. (string-match org-use-tag-inheritance tag))
  2496. ((listp org-use-tag-inheritance)
  2497. (member tag org-use-tag-inheritance))
  2498. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2499. (defcustom org-tags-match-list-sublevels t
  2500. "Non-nil means list also sublevels of headlines matching a search.
  2501. This variable applies to tags/property searches, and also to stuck
  2502. projects because this search is based on a tags match as well.
  2503. When set to the symbol `indented', sublevels are indented with
  2504. leading dots.
  2505. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2506. the sublevels of a headline matching a tag search often also match
  2507. the same search. Listing all of them can create very long lists.
  2508. Setting this variable to nil causes subtrees of a match to be skipped.
  2509. This variable is semi-obsolete and probably should always be true. It
  2510. is better to limit inheritance to certain tags using the variables
  2511. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2512. :group 'org-tags
  2513. :type '(choice
  2514. (const :tag "No, don't list them" nil)
  2515. (const :tag "Yes, do list them" t)
  2516. (const :tag "List them, indented with leading dots" indented)))
  2517. (defcustom org-tags-sort-function nil
  2518. "When set, tags are sorted using this function as a comparator."
  2519. :group 'org-tags
  2520. :type '(choice
  2521. (const :tag "No sorting" nil)
  2522. (const :tag "Alphabetical" org-string-collate-lessp)
  2523. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2524. (function :tag "Custom function" nil)))
  2525. (defvar org-tags-history nil
  2526. "History of minibuffer reads for tags.")
  2527. (defvar org-last-tags-completion-table nil
  2528. "The last used completion table for tags.")
  2529. (defvar org-after-tags-change-hook nil
  2530. "Hook that is run after the tags in a line have changed.")
  2531. (defgroup org-properties nil
  2532. "Options concerning properties in Org mode."
  2533. :tag "Org Properties"
  2534. :group 'org)
  2535. (defcustom org-property-format "%-10s %s"
  2536. "How property key/value pairs should be formatted by `indent-line'.
  2537. When `indent-line' hits a property definition, it will format the line
  2538. according to this format, mainly to make sure that the values are
  2539. lined-up with respect to each other."
  2540. :group 'org-properties
  2541. :type 'string)
  2542. (defcustom org-properties-postprocess-alist nil
  2543. "Alist of properties and functions to adjust inserted values.
  2544. Elements of this alist must be of the form
  2545. ([string] [function])
  2546. where [string] must be a property name and [function] must be a
  2547. lambda expression: this lambda expression must take one argument,
  2548. the value to adjust, and return the new value as a string.
  2549. For example, this element will allow the property \"Remaining\"
  2550. to be updated wrt the relation between the \"Effort\" property
  2551. and the clock summary:
  2552. ((\"Remaining\" (lambda(value)
  2553. (let ((clocksum (org-clock-sum-current-item))
  2554. (effort (org-duration-to-minutes
  2555. (org-entry-get (point) \"Effort\"))))
  2556. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2557. :group 'org-properties
  2558. :version "24.1"
  2559. :type '(alist :key-type (string :tag "Property")
  2560. :value-type (function :tag "Function")))
  2561. (defcustom org-use-property-inheritance nil
  2562. "Non-nil means properties apply also for sublevels.
  2563. This setting is chiefly used during property searches. Turning it on can
  2564. cause significant overhead when doing a search, which is why it is not
  2565. on by default.
  2566. When nil, only the properties directly given in the current entry count.
  2567. When t, every property is inherited. The value may also be a list of
  2568. properties that should have inheritance, or a regular expression matching
  2569. properties that should be inherited.
  2570. However, note that some special properties use inheritance under special
  2571. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2572. and the properties ending in \"_ALL\" when they are used as descriptor
  2573. for valid values of a property.
  2574. Note for programmers:
  2575. When querying an entry with `org-entry-get', you can control if inheritance
  2576. should be used. By default, `org-entry-get' looks only at the local
  2577. properties. You can request inheritance by setting the inherit argument
  2578. to t (to force inheritance) or to `selective' (to respect the setting
  2579. in this variable)."
  2580. :group 'org-properties
  2581. :type '(choice
  2582. (const :tag "Not" nil)
  2583. (const :tag "Always" t)
  2584. (repeat :tag "Specific properties" (string :tag "Property"))
  2585. (regexp :tag "Properties matched by regexp")))
  2586. (defun org-property-inherit-p (property)
  2587. "Return a non-nil value if PROPERTY should be inherited."
  2588. (cond
  2589. ((eq org-use-property-inheritance t) t)
  2590. ((not org-use-property-inheritance) nil)
  2591. ((stringp org-use-property-inheritance)
  2592. (string-match org-use-property-inheritance property))
  2593. ((listp org-use-property-inheritance)
  2594. (member-ignore-case property org-use-property-inheritance))
  2595. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2596. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2597. "The default column format, if no other format has been defined.
  2598. This variable can be set on the per-file basis by inserting a line
  2599. #+COLUMNS: %25ITEM ....."
  2600. :group 'org-properties
  2601. :type 'string)
  2602. (defcustom org-columns-default-format-for-agenda nil
  2603. "The default column format in an agenda buffer.
  2604. This will be used for column view in the agenda unless a format has
  2605. been set by adding `org-overriding-columns-format' to the local
  2606. settings list of a custom agenda view. When nil, the columns format
  2607. for the first item in the agenda list will be used, or as a fall-back,
  2608. `org-columns-default-format'."
  2609. :group 'org-properties
  2610. :type '(choice
  2611. (const :tag "No default" nil)
  2612. (string :tag "Format string")))
  2613. (defcustom org-columns-ellipses ".."
  2614. "The ellipses to be used when a field in column view is truncated.
  2615. When this is the empty string, as many characters as possible are shown,
  2616. but then there will be no visual indication that the field has been truncated.
  2617. When this is a string of length N, the last N characters of a truncated
  2618. field are replaced by this string. If the column is narrower than the
  2619. ellipses string, only part of the ellipses string will be shown."
  2620. :group 'org-properties
  2621. :type 'string)
  2622. (defconst org-global-properties-fixed
  2623. '(("VISIBILITY_ALL" . "folded children content all")
  2624. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2625. "List of property/value pairs that can be inherited by any entry.
  2626. These are fixed values, for the preset properties. The user variable
  2627. that can be used to add to this list is `org-global-properties'.
  2628. The entries in this list are cons cells where the car is a property
  2629. name and cdr is a string with the value. If the value represents
  2630. multiple items like an \"_ALL\" property, separate the items by
  2631. spaces.")
  2632. (defcustom org-global-properties nil
  2633. "List of property/value pairs that can be inherited by any entry.
  2634. This list will be combined with the constant `org-global-properties-fixed'.
  2635. The entries in this list are cons cells where the car is a property
  2636. name and cdr is a string with the value.
  2637. Buffer local properties are added either by a document property drawer
  2638. :PROPERTIES:
  2639. :NAME: VALUE
  2640. :END:
  2641. or by adding lines like
  2642. #+PROPERTY: NAME VALUE"
  2643. :group 'org-properties
  2644. :type '(repeat
  2645. (cons (string :tag "Property")
  2646. (string :tag "Value"))))
  2647. (defvar-local org-keyword-properties nil
  2648. "List of property/value pairs inherited by any entry.
  2649. Valid for the current buffer. This variable is populated from
  2650. PROPERTY keywords.
  2651. Note that properties are defined also in property drawers.
  2652. Properties defined there take precedence over properties defined
  2653. as keywords.")
  2654. (defgroup org-agenda nil
  2655. "Options concerning agenda views in Org mode."
  2656. :tag "Org Agenda"
  2657. :group 'org)
  2658. (defvar-local org-category nil
  2659. "Variable used by Org files to set a category for agenda display.
  2660. There are multiple ways to set the category. One way is to set
  2661. it in the document property drawer. For example:
  2662. :PROPERTIES:
  2663. :CATEGORY: ELisp
  2664. :END:
  2665. Other ways to define it is as an emacs file variable, for example
  2666. # -*- mode: org; org-category: \"ELisp\"
  2667. or for the file to contain a special line:
  2668. #+CATEGORY: ELisp
  2669. If the file does not specify a category, then file's base name
  2670. is used instead.")
  2671. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2672. (defcustom org-agenda-files nil
  2673. "The files to be used for agenda display.
  2674. If an entry is a directory, all files in that directory that are matched
  2675. by `org-agenda-file-regexp' will be part of the file list.
  2676. If the value of the variable is not a list but a single file name, then
  2677. the list of agenda files is actually stored and maintained in that file,
  2678. one agenda file per line. In this file paths can be given relative to
  2679. `org-directory'. Tilde expansion and environment variable substitution
  2680. are also made.
  2681. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2682. and removed with `\\[org-remove-file]'."
  2683. :group 'org-agenda
  2684. :type '(choice
  2685. (repeat :tag "List of files and directories" file)
  2686. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2687. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2688. "Regular expression to match files for `org-agenda-files'.
  2689. If any element in the list in that variable contains a directory instead
  2690. of a normal file, all files in that directory that are matched by this
  2691. regular expression will be included."
  2692. :group 'org-agenda
  2693. :type 'regexp)
  2694. (defvaralias 'org-agenda-multi-occur-extra-files
  2695. 'org-agenda-text-search-extra-files)
  2696. (defcustom org-agenda-text-search-extra-files nil
  2697. "List of extra files to be searched by text search commands.
  2698. These files will be searched in addition to the agenda files by the
  2699. commands `org-search-view' (`\\[org-agenda] s') \
  2700. and `org-occur-in-agenda-files'.
  2701. Note that these files will only be searched for text search commands,
  2702. not for the other agenda views like todo lists, tag searches or the weekly
  2703. agenda. This variable is intended to list notes and possibly archive files
  2704. that should also be searched by these two commands.
  2705. In fact, if the first element in the list is the symbol `agenda-archives',
  2706. then all archive files of all agenda files will be added to the search
  2707. scope."
  2708. :group 'org-agenda
  2709. :type '(set :greedy t
  2710. (const :tag "Agenda Archives" agenda-archives)
  2711. (repeat :inline t (file))))
  2712. (defcustom org-agenda-skip-unavailable-files nil
  2713. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2714. A nil value means to remove them, after a query, from the list."
  2715. :group 'org-agenda
  2716. :type 'boolean)
  2717. (defgroup org-latex nil
  2718. "Options for embedding LaTeX code into Org mode."
  2719. :tag "Org LaTeX"
  2720. :group 'org)
  2721. (defcustom org-format-latex-options
  2722. '(:foreground default :background default :scale 1.0
  2723. :html-foreground "Black" :html-background "Transparent"
  2724. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2725. "Options for creating images from LaTeX fragments.
  2726. This is a property list with the following properties:
  2727. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2728. `default' means use the foreground of the default face.
  2729. `auto' means use the foreground from the text face.
  2730. :background the background color, or \"Transparent\".
  2731. `default' means use the background of the default face.
  2732. `auto' means use the background from the text face.
  2733. :scale a scaling factor for the size of the images, to get more pixels
  2734. :html-foreground, :html-background, :html-scale
  2735. the same numbers for HTML export.
  2736. :matchers a list indicating which matchers should be used to
  2737. find LaTeX fragments. Valid members of this list are:
  2738. \"begin\" find environments
  2739. \"$1\" find single characters surrounded by $.$
  2740. \"$\" find math expressions surrounded by $...$
  2741. \"$$\" find math expressions surrounded by $$....$$
  2742. \"\\(\" find math expressions surrounded by \\(...\\)
  2743. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2744. :group 'org-latex
  2745. :type 'plist)
  2746. (defcustom org-format-latex-signal-error t
  2747. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2748. When nil, just push out a message."
  2749. :group 'org-latex
  2750. :version "24.1"
  2751. :type 'boolean)
  2752. (defcustom org-latex-to-mathml-jar-file nil
  2753. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2754. Use this to specify additional executable file say a jar file.
  2755. When using MathToWeb as the converter, specify the full-path to
  2756. your mathtoweb.jar file."
  2757. :group 'org-latex
  2758. :version "24.1"
  2759. :type '(choice
  2760. (const :tag "None" nil)
  2761. (file :tag "JAR file" :must-match t)))
  2762. (defcustom org-latex-to-mathml-convert-command nil
  2763. "Command to convert LaTeX fragments to MathML.
  2764. Replace format-specifiers in the command as noted below and use
  2765. `shell-command' to convert LaTeX to MathML.
  2766. %j: Executable file in fully expanded form as specified by
  2767. `org-latex-to-mathml-jar-file'.
  2768. %I: Input LaTeX file in fully expanded form.
  2769. %i: The latex fragment to be converted.
  2770. %o: Output MathML file.
  2771. This command is used by `org-create-math-formula'.
  2772. When using MathToWeb as the converter, set this option to
  2773. \"java -jar %j -unicode -force -df %o %I\".
  2774. When using LaTeXML set this option to
  2775. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2776. :group 'org-latex
  2777. :version "24.1"
  2778. :type '(choice
  2779. (const :tag "None" nil)
  2780. (string :tag "\nShell command")))
  2781. (defcustom org-latex-to-html-convert-command nil
  2782. "Command to convert LaTeX fragments to HTML.
  2783. This command is very open-ended: the output of the command will
  2784. directly replace the LaTeX fragment in the resulting HTML.
  2785. Replace format-specifiers in the command as noted below and use
  2786. `shell-command' to convert LaTeX to HTML.
  2787. %i: The LaTeX fragment to be converted.
  2788. For example, this could be used with LaTeXML as
  2789. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2790. :group 'org-latex
  2791. :package-version '(Org . "9.4")
  2792. :type '(choice
  2793. (const :tag "None" nil)
  2794. (string :tag "Shell command")))
  2795. (defcustom org-preview-latex-default-process 'dvipng
  2796. "The default process to convert LaTeX fragments to image files.
  2797. All available processes and theirs documents can be found in
  2798. `org-preview-latex-process-alist', which see."
  2799. :group 'org-latex
  2800. :version "26.1"
  2801. :package-version '(Org . "9.0")
  2802. :type 'symbol)
  2803. (defcustom org-preview-latex-process-alist
  2804. '((dvipng
  2805. :programs ("latex" "dvipng")
  2806. :description "dvi > png"
  2807. :message "you need to install the programs: latex and dvipng."
  2808. :image-input-type "dvi"
  2809. :image-output-type "png"
  2810. :image-size-adjust (1.0 . 1.0)
  2811. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2812. :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2813. (dvisvgm
  2814. :programs ("latex" "dvisvgm")
  2815. :description "dvi > svg"
  2816. :message "you need to install the programs: latex and dvisvgm."
  2817. :image-input-type "dvi"
  2818. :image-output-type "svg"
  2819. :image-size-adjust (1.7 . 1.5)
  2820. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2821. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2822. (imagemagick
  2823. :programs ("latex" "convert")
  2824. :description "pdf > png"
  2825. :message "you need to install the programs: latex and imagemagick."
  2826. :image-input-type "pdf"
  2827. :image-output-type "png"
  2828. :image-size-adjust (1.0 . 1.0)
  2829. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2830. :image-converter
  2831. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2832. "Definitions of external processes for LaTeX previewing.
  2833. Org mode can use some external commands to generate TeX snippet's images for
  2834. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2835. `org-create-formula-image' how to call them.
  2836. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2837. PROPERTIES accepts the following attributes:
  2838. :programs list of strings, required programs.
  2839. :description string, describe the process.
  2840. :message string, message it when required programs cannot be found.
  2841. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2842. :image-output-type string, output file type of image converter (e.g., \"png\").
  2843. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2844. image size showed in buffer and the cdr element is for
  2845. HTML file. This option is only useful for process
  2846. developers, users should use variable
  2847. `org-format-latex-options' instead.
  2848. :post-clean list of strings, files matched are to be cleaned up once
  2849. the image is generated. When nil, the files with \".dvi\",
  2850. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2851. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2852. be cleaned up.
  2853. :latex-header list of strings, the LaTeX header of the snippet file.
  2854. When nil, the fallback value is used instead, which is
  2855. controlled by `org-format-latex-header',
  2856. `org-latex-default-packages-alist' and
  2857. `org-latex-packages-alist', which see.
  2858. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2859. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2860. replaced with values defined below.
  2861. :image-converter list of image converter commands strings. Each of them is
  2862. given to the shell and supports any of the following
  2863. place-holders defined below.
  2864. Place-holders used by `:image-converter' and `:latex-compiler':
  2865. %f input file name
  2866. %b base name of input file
  2867. %o base directory of input file
  2868. %O absolute output file name
  2869. Place-holders only used by `:image-converter':
  2870. %D dpi, which is used to adjust image size by some processing commands.
  2871. %S the image size scale ratio, which is used to adjust image size by some
  2872. processing commands."
  2873. :group 'org-latex
  2874. :version "26.1"
  2875. :package-version '(Org . "9.0")
  2876. :type '(alist :tag "LaTeX to image backends"
  2877. :value-type (plist)))
  2878. (defcustom org-preview-latex-image-directory "ltximg/"
  2879. "Path to store latex preview images.
  2880. A relative path here creates many directories relative to the
  2881. processed Org files paths. An absolute path puts all preview
  2882. images at the same place."
  2883. :group 'org-latex
  2884. :version "26.1"
  2885. :package-version '(Org . "9.0")
  2886. :type 'string)
  2887. (defun org-format-latex-mathml-available-p ()
  2888. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2889. (save-match-data
  2890. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2891. org-latex-to-mathml-convert-command)
  2892. (let ((executable (car (split-string
  2893. org-latex-to-mathml-convert-command))))
  2894. (when (executable-find executable)
  2895. (if (string-match
  2896. "%j" org-latex-to-mathml-convert-command)
  2897. (file-readable-p org-latex-to-mathml-jar-file)
  2898. t))))))
  2899. (defcustom org-format-latex-header "\\documentclass{article}
  2900. \\usepackage[usenames]{color}
  2901. \[PACKAGES]
  2902. \[DEFAULT-PACKAGES]
  2903. \\pagestyle{empty} % do not remove
  2904. % The settings below are copied from fullpage.sty
  2905. \\setlength{\\textwidth}{\\paperwidth}
  2906. \\addtolength{\\textwidth}{-3cm}
  2907. \\setlength{\\oddsidemargin}{1.5cm}
  2908. \\addtolength{\\oddsidemargin}{-2.54cm}
  2909. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2910. \\setlength{\\textheight}{\\paperheight}
  2911. \\addtolength{\\textheight}{-\\headheight}
  2912. \\addtolength{\\textheight}{-\\headsep}
  2913. \\addtolength{\\textheight}{-\\footskip}
  2914. \\addtolength{\\textheight}{-3cm}
  2915. \\setlength{\\topmargin}{1.5cm}
  2916. \\addtolength{\\topmargin}{-2.54cm}"
  2917. "The document header used for processing LaTeX fragments.
  2918. It is imperative that this header make sure that no page number
  2919. appears on the page. The package defined in the variables
  2920. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2921. will either replace the placeholder \"[PACKAGES]\" in this
  2922. header, or they will be appended."
  2923. :group 'org-latex
  2924. :type 'string)
  2925. (defun org-set-packages-alist (var val)
  2926. "Set the packages alist and make sure it has 3 elements per entry."
  2927. (set var (mapcar (lambda (x)
  2928. (if (and (consp x) (= (length x) 2))
  2929. (list (car x) (nth 1 x) t)
  2930. x))
  2931. val)))
  2932. (defun org-get-packages-alist (var)
  2933. "Get the packages alist and make sure it has 3 elements per entry."
  2934. (mapcar (lambda (x)
  2935. (if (and (consp x) (= (length x) 2))
  2936. (list (car x) (nth 1 x) t)
  2937. x))
  2938. (default-value var)))
  2939. (defcustom org-latex-default-packages-alist
  2940. '(("AUTO" "inputenc" t ("pdflatex"))
  2941. ("T1" "fontenc" t ("pdflatex"))
  2942. ("" "graphicx" t)
  2943. ("" "grffile" t)
  2944. ("" "longtable" nil)
  2945. ("" "wrapfig" nil)
  2946. ("" "rotating" nil)
  2947. ("normalem" "ulem" t)
  2948. ("" "amsmath" t)
  2949. ("" "textcomp" t)
  2950. ("" "amssymb" t)
  2951. ("" "capt-of" nil)
  2952. ("" "hyperref" nil))
  2953. "Alist of default packages to be inserted in the header.
  2954. Change this only if one of the packages here causes an
  2955. incompatibility with another package you are using.
  2956. The packages in this list are needed by one part or another of
  2957. Org mode to function properly:
  2958. - inputenc, fontenc: for basic font and character selection
  2959. - graphicx: for including images
  2960. - grffile: allow periods and spaces in graphics file names
  2961. - longtable: For multipage tables
  2962. - wrapfig: for figure placement
  2963. - rotating: for sideways figures and tables
  2964. - ulem: for underline and strike-through
  2965. - amsmath: for subscript and superscript and math environments
  2966. - textcomp, amssymb: for various symbols used
  2967. for interpreting the entities in `org-entities'. You can skip
  2968. some of these packages if you don't use any of their symbols.
  2969. - capt-of: for captions outside of floats
  2970. - hyperref: for cross references
  2971. Therefore you should not modify this variable unless you know
  2972. what you are doing. The one reason to change it anyway is that
  2973. you might be loading some other package that conflicts with one
  2974. of the default packages. Each element is either a cell or
  2975. a string.
  2976. A cell is of the format
  2977. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2978. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2979. when compiling LaTeX snippets into images for inclusion into
  2980. non-LaTeX output.
  2981. COMPILERS is a list of compilers that should include the package,
  2982. see `org-latex-compiler'. If the document compiler is not in the
  2983. list, and the list is non-nil, the package will not be inserted
  2984. in the final document.
  2985. A string will be inserted as-is in the header of the document."
  2986. :group 'org-latex
  2987. :group 'org-export-latex
  2988. :set 'org-set-packages-alist
  2989. :get 'org-get-packages-alist
  2990. :version "26.1"
  2991. :package-version '(Org . "8.3")
  2992. :type '(repeat
  2993. (choice
  2994. (list :tag "options/package pair"
  2995. (string :tag "options")
  2996. (string :tag "package")
  2997. (boolean :tag "Snippet")
  2998. (choice
  2999. (const :tag "For all compilers" nil)
  3000. (repeat :tag "Allowed compiler" string)))
  3001. (string :tag "A line of LaTeX"))))
  3002. (defcustom org-latex-packages-alist nil
  3003. "Alist of packages to be inserted in every LaTeX header.
  3004. These will be inserted after `org-latex-default-packages-alist'.
  3005. Each element is either a cell or a string.
  3006. A cell is of the format:
  3007. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3008. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3009. needed when turning LaTeX snippets into images for inclusion into
  3010. non-LaTeX output.
  3011. COMPILERS is a list of compilers that should include the package,
  3012. see `org-latex-compiler'. If the document compiler is not in the
  3013. list, and the list is non-nil, the package will not be inserted
  3014. in the final document.
  3015. A string will be inserted as-is in the header of the document.
  3016. Make sure that you only list packages here which:
  3017. - you want in every file;
  3018. - do not conflict with the setup in `org-format-latex-header';
  3019. - do not conflict with the default packages in
  3020. `org-latex-default-packages-alist'."
  3021. :group 'org-latex
  3022. :group 'org-export-latex
  3023. :set 'org-set-packages-alist
  3024. :get 'org-get-packages-alist
  3025. :type '(repeat
  3026. (choice
  3027. (list :tag "options/package pair"
  3028. (string :tag "options")
  3029. (string :tag "package")
  3030. (boolean :tag "Snippet"))
  3031. (string :tag "A line of LaTeX"))))
  3032. (defgroup org-appearance nil
  3033. "Settings for Org mode appearance."
  3034. :tag "Org Appearance"
  3035. :group 'org)
  3036. (defcustom org-level-color-stars-only nil
  3037. "Non-nil means fontify only the stars in each headline.
  3038. When nil, the entire headline is fontified.
  3039. Changing it requires restart of `font-lock-mode' to become effective
  3040. also in regions already fontified."
  3041. :group 'org-appearance
  3042. :type 'boolean)
  3043. (defcustom org-hide-leading-stars nil
  3044. "Non-nil means hide the first N-1 stars in a headline.
  3045. This works by using the face `org-hide' for these stars. This
  3046. face is white for a light background, and black for a dark
  3047. background. You may have to customize the face `org-hide' to
  3048. make this work.
  3049. Changing it requires restart of `font-lock-mode' to become effective
  3050. also in regions already fontified.
  3051. You may also set this on a per-file basis by adding one of the following
  3052. lines to the buffer:
  3053. #+STARTUP: hidestars
  3054. #+STARTUP: showstars"
  3055. :group 'org-appearance
  3056. :type 'boolean)
  3057. (defcustom org-hidden-keywords nil
  3058. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3059. For example, a value \\='(title) for this list makes the document's title
  3060. appear in the buffer without the initial \"#+TITLE:\" part."
  3061. :group 'org-appearance
  3062. :package-version '(Org . "9.5")
  3063. :type '(set (const :tag "#+AUTHOR" author)
  3064. (const :tag "#+DATE" date)
  3065. (const :tag "#+EMAIL" email)
  3066. (const :tag "#+SUBTITLE" subtitle)
  3067. (const :tag "#+TITLE" title)))
  3068. (defcustom org-custom-properties nil
  3069. "List of properties (as strings) with a special meaning.
  3070. The default use of these custom properties is to let the user
  3071. hide them with `org-toggle-custom-properties-visibility'."
  3072. :group 'org-properties
  3073. :group 'org-appearance
  3074. :version "24.3"
  3075. :type '(repeat (string :tag "Property Name")))
  3076. (defcustom org-fontify-todo-headline nil
  3077. "Non-nil means change the face of a headline if it is marked as TODO.
  3078. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3079. When this is non-nil, the headline after the keyword is set to the
  3080. `org-headline-todo' as an additional indication."
  3081. :group 'org-appearance
  3082. :package-version '(Org . "9.4")
  3083. :type 'boolean
  3084. :safe t)
  3085. (defcustom org-fontify-done-headline t
  3086. "Non-nil means change the face of a headline if it is marked DONE.
  3087. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3088. When this is non-nil, the headline after the keyword is set to the
  3089. `org-headline-done' as an additional indication."
  3090. :group 'org-appearance
  3091. :package-version '(Org . "9.4")
  3092. :type 'boolean)
  3093. (defcustom org-fontify-emphasized-text t
  3094. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3095. Changing this variable requires a restart of Emacs to take effect."
  3096. :group 'org-appearance
  3097. :type 'boolean)
  3098. (defcustom org-fontify-whole-heading-line nil
  3099. "Non-nil means fontify the whole line for headings.
  3100. This is useful when setting a background color for the
  3101. org-level-* faces."
  3102. :group 'org-appearance
  3103. :type 'boolean)
  3104. (defcustom org-fontify-whole-block-delimiter-line t
  3105. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3106. This is useful when setting a background color for the
  3107. org-block-begin-line and org-block-end-line faces."
  3108. :group 'org-appearance
  3109. :type 'boolean)
  3110. (defcustom org-highlight-latex-and-related nil
  3111. "Non-nil means highlight LaTeX related syntax in the buffer.
  3112. When non-nil, the value should be a list containing any of the
  3113. following symbols:
  3114. `native' Highlight LaTeX snippets and environments natively.
  3115. `latex' Highlight LaTeX snippets and environments.
  3116. `script' Highlight subscript and superscript.
  3117. `entities' Highlight entities."
  3118. :group 'org-appearance
  3119. :version "24.4"
  3120. :package-version '(Org . "8.0")
  3121. :type '(choice
  3122. (const :tag "No highlighting" nil)
  3123. (set :greedy t :tag "Highlight"
  3124. (const :tag "LaTeX snippets and environments (native)" native)
  3125. (const :tag "LaTeX snippets and environments" latex)
  3126. (const :tag "Subscript and superscript" script)
  3127. (const :tag "Entities" entities))))
  3128. (defcustom org-hide-emphasis-markers nil
  3129. "Non-nil mean font-lock should hide the emphasis marker characters."
  3130. :group 'org-appearance
  3131. :type 'boolean
  3132. :safe #'booleanp)
  3133. (defcustom org-hide-macro-markers nil
  3134. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3135. :group 'org-appearance
  3136. :type 'boolean)
  3137. (defcustom org-pretty-entities nil
  3138. "Non-nil means show entities as UTF8 characters.
  3139. When nil, the \\name form remains in the buffer."
  3140. :group 'org-appearance
  3141. :version "24.1"
  3142. :type 'boolean)
  3143. (defcustom org-pretty-entities-include-sub-superscripts t
  3144. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3145. :group 'org-appearance
  3146. :version "24.1"
  3147. :type 'boolean)
  3148. (defvar org-emph-re nil
  3149. "Regular expression for matching emphasis.
  3150. After a match, the match groups contain these elements:
  3151. 0 The match of the full regular expression, including the characters
  3152. before and after the proper match
  3153. 1 The character before the proper match, or empty at beginning of line
  3154. 2 The proper match, including the leading and trailing markers
  3155. 3 The leading marker like * or /, indicating the type of highlighting
  3156. 4 The text between the emphasis markers, not including the markers
  3157. 5 The character after the match, empty at the end of a line")
  3158. (defvar org-verbatim-re nil
  3159. "Regular expression for matching verbatim text.")
  3160. (defvar org-emphasis-regexp-components) ; defined just below
  3161. (defvar org-emphasis-alist) ; defined just below
  3162. (defun org-set-emph-re (var val)
  3163. "Set variable and compute the emphasis regular expression."
  3164. (set var val)
  3165. (when (and (boundp 'org-emphasis-alist)
  3166. (boundp 'org-emphasis-regexp-components)
  3167. org-emphasis-alist org-emphasis-regexp-components)
  3168. (pcase-let*
  3169. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3170. (body (if (<= nl 0) body
  3171. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3172. (template
  3173. (format (concat "\\([%s]\\|^\\)" ;before markers
  3174. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3175. "\\([%s]\\|$\\)") ;after markers
  3176. pre border border body border post)))
  3177. (setq org-emph-re (format template "*/_+"))
  3178. (setq org-verbatim-re (format template "=~")))))
  3179. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3180. ;; set this option proved cumbersome. See this message/thread:
  3181. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3182. (defvar org-emphasis-regexp-components
  3183. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3184. "Components used to build the regular expression for emphasis.
  3185. This is a list with five entries. Terminology: In an emphasis string
  3186. like \" *strong word* \", we call the initial space PREMATCH, the final
  3187. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3188. and \"trong wor\" is the body. The different components in this variable
  3189. specify what is allowed/forbidden in each part:
  3190. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3191. post Chars allowed as postmatch. End of line will be allowed too.
  3192. border The chars *forbidden* as border characters.
  3193. body-regexp A regexp like \".\" to match a body character. Don't use
  3194. non-shy groups here, and don't allow newline here.
  3195. newline The maximum number of newlines allowed in an emphasis exp.
  3196. You need to reload Org or to restart Emacs after setting this.")
  3197. (defcustom org-emphasis-alist
  3198. '(("*" bold)
  3199. ("/" italic)
  3200. ("_" underline)
  3201. ("=" org-verbatim verbatim)
  3202. ("~" org-code verbatim)
  3203. ("+" (:strike-through t)))
  3204. "Alist of characters and faces to emphasize text.
  3205. Text starting and ending with a special character will be emphasized,
  3206. for example *bold*, _underlined_ and /italic/. This variable sets the
  3207. marker characters and the face to be used by font-lock for highlighting
  3208. in Org buffers.
  3209. You need to reload Org or to restart Emacs after customizing this."
  3210. :group 'org-appearance
  3211. :set 'org-set-emph-re
  3212. :version "24.4"
  3213. :package-version '(Org . "8.0")
  3214. :type '(repeat
  3215. (list
  3216. (string :tag "Marker character")
  3217. (choice
  3218. (face :tag "Font-lock-face")
  3219. (plist :tag "Face property list"))
  3220. (option (const verbatim)))))
  3221. (defvar org-protecting-blocks '("src" "example" "export")
  3222. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3223. This is needed for font-lock setup.")
  3224. ;;; Functions and variables from their packages
  3225. ;; Declared here to avoid compiler warnings
  3226. (defvar mark-active)
  3227. ;; Various packages
  3228. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3229. (declare-function calendar-forward-day "cal-move" (arg))
  3230. (declare-function calendar-goto-date "cal-move" (date))
  3231. (declare-function calendar-goto-today "cal-move" ())
  3232. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3233. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3234. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3235. (declare-function cdlatex-tab "ext:cdlatex" ())
  3236. (declare-function dired-get-filename
  3237. "dired"
  3238. (&optional localp no-error-if-not-filep))
  3239. (declare-function iswitchb-read-buffer
  3240. "iswitchb"
  3241. (prompt &optional
  3242. default require-match _predicate start matches-set))
  3243. (declare-function org-agenda-change-all-lines
  3244. "org-agenda"
  3245. (newhead hdmarker &optional fixface just-this))
  3246. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3247. "org-agenda"
  3248. (&optional end))
  3249. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3250. (declare-function org-agenda-format-item
  3251. "org-agenda"
  3252. (extra txt &optional level category tags dotime
  3253. remove-re habitp))
  3254. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3255. (declare-function org-agenda-save-markers-for-cut-and-paste
  3256. "org-agenda"
  3257. (beg end))
  3258. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3259. (declare-function org-agenda-skip "org-agenda" ())
  3260. (declare-function org-attach-expand "org-attach" (file))
  3261. (declare-function org-attach-reveal "org-attach" ())
  3262. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3263. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3264. (declare-function org-indent-mode "org-indent" (&optional arg))
  3265. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3266. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3267. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3268. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3269. (declare-function parse-time-string "parse-time" (string))
  3270. (defvar align-mode-rules-list)
  3271. (defvar calc-embedded-close-formula)
  3272. (defvar calc-embedded-open-formula)
  3273. (defvar calc-embedded-open-mode)
  3274. (defvar font-lock-unfontify-region-function)
  3275. (defvar iswitchb-temp-buflist)
  3276. (defvar org-agenda-tags-todo-honor-ignore-options)
  3277. (defvar remember-data-file)
  3278. (defvar texmathp-why)
  3279. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3280. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3281. (declare-function org-resolve-clocks "org-clock"
  3282. (&optional also-non-dangling-p prompt last-valid))
  3283. (defvar org-clock-start-time)
  3284. (defvar org-clock-marker (make-marker)
  3285. "Marker recording the last clock-in.")
  3286. (defvar org-clock-hd-marker (make-marker)
  3287. "Marker recording the last clock-in, but the headline position.")
  3288. (defvar org-clock-heading ""
  3289. "The heading of the current clock entry.")
  3290. (defun org-clock-is-active ()
  3291. "Return the buffer where the clock is currently running.
  3292. Return nil if no clock is running."
  3293. (marker-buffer org-clock-marker))
  3294. (defun org-check-running-clock ()
  3295. "Check if the current buffer contains the running clock.
  3296. If yes, offer to stop it and to save the buffer with the changes."
  3297. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3298. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3299. (buffer-name))))
  3300. (org-clock-out)
  3301. (when (y-or-n-p "Save changed buffer?")
  3302. (save-buffer))))
  3303. (defun org-clocktable-try-shift (dir n)
  3304. "Check if this line starts a clock table, if yes, shift the time block."
  3305. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3306. (org-clocktable-shift dir n)))
  3307. ;;;###autoload
  3308. (defun org-clock-persistence-insinuate ()
  3309. "Set up hooks for clock persistence."
  3310. (require 'org-clock)
  3311. (add-hook 'org-mode-hook 'org-clock-load)
  3312. (add-hook 'kill-emacs-hook 'org-clock-save))
  3313. (defun org-clock-auto-clockout-insinuate ()
  3314. "Set up hook for auto clocking out when Emacs is idle.
  3315. See `org-clock-auto-clockout-timer'.
  3316. This function is meant to be added to the user configuration."
  3317. (require 'org-clock)
  3318. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3319. (defgroup org-archive nil
  3320. "Options concerning archiving in Org mode."
  3321. :tag "Org Archive"
  3322. :group 'org-structure)
  3323. (defcustom org-archive-location "%s_archive::"
  3324. "The location where subtrees should be archived.
  3325. The value of this variable is a string, consisting of two parts,
  3326. separated by a double-colon. The first part is a filename and
  3327. the second part is a headline.
  3328. When the filename is omitted, archiving happens in the same file.
  3329. %s in the filename will be replaced by the current file
  3330. name (without the directory part). Archiving to a different file
  3331. is useful to keep archived entries from contributing to the
  3332. Org Agenda.
  3333. The archived entries will be filed as subtrees of the specified
  3334. headline. When the headline is omitted, the subtrees are simply
  3335. filed away at the end of the file, as top-level entries. Also in
  3336. the heading you can use %s to represent the file name, this can be
  3337. useful when using the same archive for a number of different files.
  3338. Here are a few examples:
  3339. \"%s_archive::\"
  3340. If the current file is Projects.org, archive in file
  3341. Projects.org_archive, as top-level trees. This is the default.
  3342. \"::* Archived Tasks\"
  3343. Archive in the current file, under the top-level headline
  3344. \"* Archived Tasks\".
  3345. \"~/org/archive.org::\"
  3346. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3347. \"~/org/archive.org::* From %s\"
  3348. Archive in file ~/org/archive.org (absolute path), under headlines
  3349. \"From FILENAME\" where file name is the current file name.
  3350. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3351. The \"datetree/\" string is special, signifying to archive
  3352. items to the datetree. Items are placed in either the CLOSED
  3353. date of the item, or the current date if there is no CLOSED date.
  3354. The heading will be a subentry to the current date. There doesn't
  3355. need to be a heading, but there always needs to be a slash after
  3356. datetree. For example, to store archived items directly in the
  3357. datetree, use \"~/org/datetree.org::datetree/\".
  3358. \"basement::** Finished Tasks\"
  3359. Archive in file ./basement (relative path), as level 3 trees
  3360. below the level 2 heading \"** Finished Tasks\".
  3361. You may define it locally by setting an ARCHIVE property. If
  3362. such a property is found in the file or in an entry, and anywhere
  3363. up the hierarchy, it will be used.
  3364. You can also set it for the whole file using the keyword-syntax:
  3365. #+ARCHIVE: basement::** Finished Tasks"
  3366. :group 'org-archive
  3367. :type 'string)
  3368. (defcustom org-agenda-skip-archived-trees t
  3369. "Non-nil means the agenda will skip any items located in archived trees.
  3370. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3371. variable is no longer recommended, you should leave it at the value t.
  3372. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3373. :group 'org-archive
  3374. :group 'org-agenda-skip
  3375. :type 'boolean)
  3376. (defcustom org-columns-skip-archived-trees t
  3377. "Non-nil means ignore archived trees when creating column view."
  3378. :group 'org-archive
  3379. :group 'org-properties
  3380. :type 'boolean)
  3381. (defcustom org-cycle-open-archived-trees nil
  3382. "Non-nil means `org-cycle' will open archived trees.
  3383. An archived tree is a tree marked with the tag ARCHIVE.
  3384. When nil, archived trees will stay folded. You can still open them with
  3385. normal outline commands like `show-all', but not with the cycling commands."
  3386. :group 'org-archive
  3387. :group 'org-cycle
  3388. :type 'boolean)
  3389. (defcustom org-sparse-tree-open-archived-trees nil
  3390. "Non-nil means sparse tree construction shows matches in archived trees.
  3391. When nil, matches in these trees are highlighted, but the trees are kept in
  3392. collapsed state."
  3393. :group 'org-archive
  3394. :group 'org-sparse-trees
  3395. :type 'boolean)
  3396. (defcustom org-sparse-tree-default-date-type nil
  3397. "The default date type when building a sparse tree.
  3398. When this is nil, a date is a scheduled or a deadline timestamp.
  3399. Otherwise, these types are allowed:
  3400. all: all timestamps
  3401. active: only active timestamps (<...>)
  3402. inactive: only inactive timestamps ([...])
  3403. scheduled: only scheduled timestamps
  3404. deadline: only deadline timestamps"
  3405. :type '(choice (const :tag "Scheduled or deadline" nil)
  3406. (const :tag "All timestamps" all)
  3407. (const :tag "Only active timestamps" active)
  3408. (const :tag "Only inactive timestamps" inactive)
  3409. (const :tag "Only scheduled timestamps" scheduled)
  3410. (const :tag "Only deadline timestamps" deadline)
  3411. (const :tag "Only closed timestamps" closed))
  3412. :version "26.1"
  3413. :package-version '(Org . "8.3")
  3414. :group 'org-sparse-trees)
  3415. (defun org-cycle-hide-archived-subtrees (state)
  3416. "Re-hide all archived subtrees after a visibility state change.
  3417. STATE should be one of the symbols listed in the docstring of
  3418. `org-cycle-hook'."
  3419. (when (and (not org-cycle-open-archived-trees)
  3420. (not (memq state '(overview folded))))
  3421. (save-excursion
  3422. (let* ((globalp (memq state '(contents all)))
  3423. (beg (if globalp (point-min) (point)))
  3424. (end (if globalp (point-max) (org-end-of-subtree t))))
  3425. (org-hide-archived-subtrees beg end)
  3426. (goto-char beg)
  3427. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3428. (message "%s" (substitute-command-keys
  3429. "Subtree is archived and stays closed. Use \
  3430. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3431. (defun org-force-cycle-archived ()
  3432. "Cycle subtree even if it is archived."
  3433. (interactive)
  3434. (setq this-command 'org-cycle)
  3435. (let ((org-cycle-open-archived-trees t))
  3436. (call-interactively 'org-cycle)))
  3437. (defun org-hide-archived-subtrees (beg end)
  3438. "Re-hide all archived subtrees after a visibility state change."
  3439. (org-with-wide-buffer
  3440. (let ((case-fold-search nil)
  3441. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3442. (goto-char beg)
  3443. ;; Include headline point is currently on.
  3444. (beginning-of-line)
  3445. (while (and (< (point) end) (re-search-forward re end t))
  3446. (when (member org-archive-tag (org-get-tags nil t))
  3447. (org-flag-subtree t)
  3448. (org-end-of-subtree t))))))
  3449. (defun org-flag-subtree (flag)
  3450. (save-excursion
  3451. (org-back-to-heading t)
  3452. (org-flag-region (line-end-position)
  3453. (progn (org-end-of-subtree t) (point))
  3454. flag
  3455. 'outline)))
  3456. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3457. ;; Declare Column View Code
  3458. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3459. (declare-function org-columns-compute "org-colview" (property))
  3460. ;; Declare ID code
  3461. (declare-function org-id-store-link "org-id")
  3462. (declare-function org-id-locations-load "org-id")
  3463. (declare-function org-id-locations-save "org-id")
  3464. (defvar org-id-track-globally)
  3465. ;;; Variables for pre-computed regular expressions, all buffer local
  3466. (defvar-local org-todo-regexp nil
  3467. "Matches any of the TODO state keywords.
  3468. Since TODO keywords are case-sensitive, `case-fold-search' is
  3469. expected to be bound to nil when matching against this regexp.")
  3470. (defvar-local org-not-done-regexp nil
  3471. "Matches any of the TODO state keywords except the last one.
  3472. Since TODO keywords are case-sensitive, `case-fold-search' is
  3473. expected to be bound to nil when matching against this regexp.")
  3474. (defvar-local org-not-done-heading-regexp nil
  3475. "Matches a TODO headline that is not done.
  3476. Since TODO keywords are case-sensitive, `case-fold-search' is
  3477. expected to be bound to nil when matching against this regexp.")
  3478. (defvar-local org-todo-line-regexp nil
  3479. "Matches a headline and puts TODO state into group 2 if present.
  3480. Since TODO keywords are case-sensitive, `case-fold-search' is
  3481. expected to be bound to nil when matching against this regexp.")
  3482. (defvar-local org-complex-heading-regexp nil
  3483. "Matches a headline and puts everything into groups:
  3484. group 1: Stars
  3485. group 2: The TODO keyword, maybe
  3486. group 3: Priority cookie
  3487. group 4: True headline
  3488. group 5: Tags
  3489. Since TODO keywords are case-sensitive, `case-fold-search' is
  3490. expected to be bound to nil when matching against this regexp.")
  3491. (defvar-local org-complex-heading-regexp-format nil
  3492. "Printf format to make regexp to match an exact headline.
  3493. This regexp will match the headline of any node which has the
  3494. exact headline text that is put into the format, but may have any
  3495. TODO state, priority and tags.")
  3496. (defvar-local org-todo-line-tags-regexp nil
  3497. "Matches a headline and puts TODO state into group 2 if present.
  3498. Also put tags into group 4 if tags are present.")
  3499. (defconst org-plain-time-of-day-regexp
  3500. (concat
  3501. "\\(\\<[012]?[0-9]"
  3502. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3503. "\\(--?"
  3504. "\\(\\<[012]?[0-9]"
  3505. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3506. "\\)?")
  3507. "Regular expression to match a plain time or time range.
  3508. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3509. groups carry important information:
  3510. 0 the full match
  3511. 1 the first time, range or not
  3512. 8 the second time, if it is a range.")
  3513. (defconst org-plain-time-extension-regexp
  3514. (concat
  3515. "\\(\\<[012]?[0-9]"
  3516. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3517. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3518. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3519. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3520. groups carry important information:
  3521. 0 the full match
  3522. 7 hours of duration
  3523. 9 minutes of duration")
  3524. (defconst org-stamp-time-of-day-regexp
  3525. (concat
  3526. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3527. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3528. "\\(--?"
  3529. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3530. "Regular expression to match a timestamp time or time range.
  3531. After a match, the following groups carry important information:
  3532. 0 the full match
  3533. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3534. 2 the first time, range or not
  3535. 4 the second time, if it is a range.")
  3536. (defconst org-startup-options
  3537. '(("fold" org-startup-folded t)
  3538. ("overview" org-startup-folded t)
  3539. ("nofold" org-startup-folded nil)
  3540. ("showall" org-startup-folded nil)
  3541. ("show2levels" org-startup-folded show2levels)
  3542. ("show3levels" org-startup-folded show3levels)
  3543. ("show4levels" org-startup-folded show4levels)
  3544. ("show5levels" org-startup-folded show5levels)
  3545. ("showeverything" org-startup-folded showeverything)
  3546. ("content" org-startup-folded content)
  3547. ("indent" org-startup-indented t)
  3548. ("noindent" org-startup-indented nil)
  3549. ("num" org-startup-numerated t)
  3550. ("nonum" org-startup-numerated nil)
  3551. ("hidestars" org-hide-leading-stars t)
  3552. ("showstars" org-hide-leading-stars nil)
  3553. ("odd" org-odd-levels-only t)
  3554. ("oddeven" org-odd-levels-only nil)
  3555. ("align" org-startup-align-all-tables t)
  3556. ("noalign" org-startup-align-all-tables nil)
  3557. ("shrink" org-startup-shrink-all-tables t)
  3558. ("inlineimages" org-startup-with-inline-images t)
  3559. ("noinlineimages" org-startup-with-inline-images nil)
  3560. ("latexpreview" org-startup-with-latex-preview t)
  3561. ("nolatexpreview" org-startup-with-latex-preview nil)
  3562. ("customtime" org-display-custom-times t)
  3563. ("logdone" org-log-done time)
  3564. ("lognotedone" org-log-done note)
  3565. ("nologdone" org-log-done nil)
  3566. ("lognoteclock-out" org-log-note-clock-out t)
  3567. ("nolognoteclock-out" org-log-note-clock-out nil)
  3568. ("logrepeat" org-log-repeat state)
  3569. ("lognoterepeat" org-log-repeat note)
  3570. ("logdrawer" org-log-into-drawer t)
  3571. ("nologdrawer" org-log-into-drawer nil)
  3572. ("logstatesreversed" org-log-states-order-reversed t)
  3573. ("nologstatesreversed" org-log-states-order-reversed nil)
  3574. ("nologrepeat" org-log-repeat nil)
  3575. ("logreschedule" org-log-reschedule time)
  3576. ("lognotereschedule" org-log-reschedule note)
  3577. ("nologreschedule" org-log-reschedule nil)
  3578. ("logredeadline" org-log-redeadline time)
  3579. ("lognoteredeadline" org-log-redeadline note)
  3580. ("nologredeadline" org-log-redeadline nil)
  3581. ("logrefile" org-log-refile time)
  3582. ("lognoterefile" org-log-refile note)
  3583. ("nologrefile" org-log-refile nil)
  3584. ("fninline" org-footnote-define-inline t)
  3585. ("nofninline" org-footnote-define-inline nil)
  3586. ("fnlocal" org-footnote-section nil)
  3587. ("fnauto" org-footnote-auto-label t)
  3588. ("fnprompt" org-footnote-auto-label nil)
  3589. ("fnconfirm" org-footnote-auto-label confirm)
  3590. ("fnplain" org-footnote-auto-label plain)
  3591. ("fnadjust" org-footnote-auto-adjust t)
  3592. ("nofnadjust" org-footnote-auto-adjust nil)
  3593. ("constcgs" constants-unit-system cgs)
  3594. ("constSI" constants-unit-system SI)
  3595. ("noptag" org-tag-persistent-alist nil)
  3596. ("hideblocks" org-hide-block-startup t)
  3597. ("nohideblocks" org-hide-block-startup nil)
  3598. ("beamer" org-startup-with-beamer-mode t)
  3599. ("entitiespretty" org-pretty-entities t)
  3600. ("entitiesplain" org-pretty-entities nil))
  3601. "Variable associated with STARTUP options for Org.
  3602. Each element is a list of three items: the startup options (as written
  3603. in the #+STARTUP line), the corresponding variable, and the value to set
  3604. this variable to if the option is found. An optional fourth element PUSH
  3605. means to push this value onto the list in the variable.")
  3606. (defcustom org-group-tags t
  3607. "When non-nil (the default), use group tags.
  3608. This can be turned on/off through `org-toggle-tags-groups'."
  3609. :group 'org-tags
  3610. :group 'org-startup
  3611. :type 'boolean)
  3612. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3613. (defun org-toggle-tags-groups ()
  3614. "Toggle support for group tags.
  3615. Support for group tags is controlled by the option
  3616. `org-group-tags', which is non-nil by default."
  3617. (interactive)
  3618. (setq org-group-tags (not org-group-tags))
  3619. (cond ((and (derived-mode-p 'org-agenda-mode)
  3620. org-group-tags)
  3621. (org-agenda-redo))
  3622. ((derived-mode-p 'org-mode)
  3623. (let ((org-inhibit-startup t)) (org-mode))))
  3624. (message "Groups tags support has been turned %s"
  3625. (if org-group-tags "on" "off")))
  3626. (defun org--tag-add-to-alist (alist1 alist2)
  3627. "Merge tags from ALIST1 into ALIST2.
  3628. Duplicates tags outside a group are removed. Keywords and order
  3629. are preserved.
  3630. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3631. See `org-tag-alist' for their structure."
  3632. (cond
  3633. ((null alist2) alist1)
  3634. ((null alist1) alist2)
  3635. (t
  3636. (let ((to-add nil)
  3637. (group-flag nil))
  3638. (dolist (tag-pair alist1)
  3639. (pcase tag-pair
  3640. (`(,(or :startgrouptag :startgroup))
  3641. (setq group-flag t)
  3642. (push tag-pair to-add))
  3643. (`(,(or :endgrouptag :endgroup))
  3644. (setq group-flag nil)
  3645. (push tag-pair to-add))
  3646. (`(,(or :grouptags :newline))
  3647. (push tag-pair to-add))
  3648. (`(,tag . ,_)
  3649. ;; Remove duplicates from ALIST1, unless they are in
  3650. ;; a group. Indeed, it makes sense to have a tag appear in
  3651. ;; multiple groups.
  3652. (when (or group-flag (not (assoc tag alist2)))
  3653. (push tag-pair to-add)))
  3654. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3655. ;; Preserve order of ALIST1.
  3656. (append (nreverse to-add) alist2)))))
  3657. (defun org-priority-to-value (s)
  3658. "Convert priority string S to its numeric value."
  3659. (or (save-match-data
  3660. (and (string-match "\\([0-9]+\\)" s)
  3661. (string-to-number (match-string 1 s))))
  3662. (string-to-char s)))
  3663. (defun org-set-regexps-and-options (&optional tags-only)
  3664. "Precompute regular expressions used in the current buffer.
  3665. When optional argument TAGS-ONLY is non-nil, only compute tags
  3666. related expressions."
  3667. (when (derived-mode-p 'org-mode)
  3668. (let ((alist (org-collect-keywords
  3669. (append '("FILETAGS" "TAGS")
  3670. (and (not tags-only)
  3671. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3672. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3673. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3674. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3675. ;; Startup options. Get this early since it does change
  3676. ;; behavior for other options (e.g., tags).
  3677. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3678. (cdr (assoc "STARTUP" alist)))))
  3679. (dolist (option startup)
  3680. (pcase (assoc-string option org-startup-options t)
  3681. (`(,_ ,variable ,value t)
  3682. (unless (listp (symbol-value variable))
  3683. (set (make-local-variable variable) nil))
  3684. (add-to-list variable value))
  3685. (`(,_ ,variable ,value . ,_)
  3686. (set (make-local-variable variable) value))
  3687. (_ nil))))
  3688. (setq-local org-file-tags
  3689. (mapcar #'org-add-prop-inherited
  3690. (cl-mapcan (lambda (value)
  3691. (cl-mapcan
  3692. (lambda (k) (org-split-string k ":"))
  3693. (split-string value)))
  3694. (cdr (assoc "FILETAGS" alist)))))
  3695. (setq org-current-tag-alist
  3696. (org--tag-add-to-alist
  3697. org-tag-persistent-alist
  3698. (let ((tags (cdr (assoc "TAGS" alist))))
  3699. (if tags
  3700. (org-tag-string-to-alist
  3701. (mapconcat #'identity tags "\n"))
  3702. org-tag-alist))))
  3703. (setq org-tag-groups-alist
  3704. (org-tag-alist-to-groups org-current-tag-alist))
  3705. (unless tags-only
  3706. ;; Properties.
  3707. (let ((properties nil))
  3708. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3709. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3710. (setq properties (org--update-property-plist
  3711. (match-string-no-properties 1 value)
  3712. (match-string-no-properties 2 value)
  3713. properties))))
  3714. (setq-local org-keyword-properties properties))
  3715. ;; Archive location.
  3716. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3717. (when archive (setq-local org-archive-location archive)))
  3718. ;; Category.
  3719. (let ((category (cdr (assoc "CATEGORY" alist))))
  3720. (when category
  3721. (setq-local org-category (intern category))
  3722. (setq-local org-keyword-properties
  3723. (org--update-property-plist
  3724. "CATEGORY" category org-keyword-properties))))
  3725. ;; Columns.
  3726. (let ((column (cdr (assoc "COLUMNS" alist))))
  3727. (when column (setq-local org-columns-default-format column)))
  3728. ;; Constants.
  3729. (let ((store nil))
  3730. (dolist (pair (cl-mapcan #'split-string
  3731. (cdr (assoc "CONSTANTS" alist))))
  3732. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3733. (let* ((name (match-string 1 pair))
  3734. (value (match-string 2 pair))
  3735. (old (assoc name store)))
  3736. (if old (setcdr old value)
  3737. (push (cons name value) store)))))
  3738. (setq org-table-formula-constants-local store))
  3739. ;; Link abbreviations.
  3740. (let ((links
  3741. (delq nil
  3742. (mapcar
  3743. (lambda (value)
  3744. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3745. (cons (match-string-no-properties 1 value)
  3746. (match-string-no-properties 2 value))))
  3747. (cdr (assoc "LINK" alist))))))
  3748. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3749. ;; Priorities.
  3750. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3751. (pcase (and value (split-string value))
  3752. (`(,high ,low ,default . ,_)
  3753. (setq-local org-priority-highest (org-priority-to-value high))
  3754. (setq-local org-priority-lowest (org-priority-to-value low))
  3755. (setq-local org-priority-default (org-priority-to-value default)))))
  3756. ;; Scripts.
  3757. (let ((value (cdr (assoc "OPTIONS" alist))))
  3758. (dolist (option value)
  3759. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3760. (setq-local org-use-sub-superscripts
  3761. (read (match-string 1 option))))))
  3762. ;; TODO keywords.
  3763. (setq-local org-todo-kwd-alist nil)
  3764. (setq-local org-todo-key-alist nil)
  3765. (setq-local org-todo-key-trigger nil)
  3766. (setq-local org-todo-keywords-1 nil)
  3767. (setq-local org-done-keywords nil)
  3768. (setq-local org-todo-heads nil)
  3769. (setq-local org-todo-sets nil)
  3770. (setq-local org-todo-log-states nil)
  3771. (let ((todo-sequences
  3772. (or (append (mapcar (lambda (value)
  3773. (cons 'type (split-string value)))
  3774. (cdr (assoc "TYP_TODO" alist)))
  3775. (mapcar (lambda (value)
  3776. (cons 'sequence (split-string value)))
  3777. (append (cdr (assoc "TODO" alist))
  3778. (cdr (assoc "SEQ_TODO" alist)))))
  3779. (let ((d (default-value 'org-todo-keywords)))
  3780. (if (not (stringp (car d))) d
  3781. ;; XXX: Backward compatibility code.
  3782. (list (cons org-todo-interpretation d)))))))
  3783. (dolist (sequence todo-sequences)
  3784. (let* ((sequence (or (run-hook-with-args-until-success
  3785. 'org-todo-setup-filter-hook sequence)
  3786. sequence))
  3787. (sequence-type (car sequence))
  3788. (keywords (cdr sequence))
  3789. (sep (member "|" keywords))
  3790. names alist)
  3791. (dolist (k (remove "|" keywords))
  3792. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3793. k)
  3794. (error "Invalid TODO keyword %s" k))
  3795. (let ((name (match-string 1 k))
  3796. (key (match-string 2 k))
  3797. (log (org-extract-log-state-settings k)))
  3798. (push name names)
  3799. (push (cons name (and key (string-to-char key))) alist)
  3800. (when log (push log org-todo-log-states))))
  3801. (let* ((names (nreverse names))
  3802. (done (if sep (org-remove-keyword-keys (cdr sep))
  3803. (last names)))
  3804. (head (car names))
  3805. (tail (list sequence-type head (car done) (org-last done))))
  3806. (add-to-list 'org-todo-heads head 'append)
  3807. (push names org-todo-sets)
  3808. (setq org-done-keywords (append org-done-keywords done nil))
  3809. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3810. (setq org-todo-key-alist
  3811. (append org-todo-key-alist
  3812. (and alist
  3813. (append '((:startgroup))
  3814. (nreverse alist)
  3815. '((:endgroup))))))
  3816. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3817. (setq org-todo-sets (nreverse org-todo-sets)
  3818. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3819. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3820. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3821. ;; Compute the regular expressions and other local variables.
  3822. ;; Using `org-outline-regexp-bol' would complicate them much,
  3823. ;; because of the fixed white space at the end of that string.
  3824. (unless org-done-keywords
  3825. (setq org-done-keywords
  3826. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3827. (setq org-not-done-keywords
  3828. (org-delete-all org-done-keywords
  3829. (copy-sequence org-todo-keywords-1))
  3830. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3831. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3832. org-not-done-heading-regexp
  3833. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3834. org-todo-line-regexp
  3835. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3836. org-complex-heading-regexp
  3837. (concat "^\\(\\*+\\)"
  3838. "\\(?: +" org-todo-regexp "\\)?"
  3839. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3840. "\\(?: +\\(.*?\\)\\)??"
  3841. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3842. "[ \t]*$")
  3843. org-complex-heading-regexp-format
  3844. (concat "^\\(\\*+\\)"
  3845. "\\(?: +" org-todo-regexp "\\)?"
  3846. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3847. "\\(?: +"
  3848. ;; Stats cookies can be stuck to body.
  3849. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3850. "\\(%s\\)"
  3851. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3852. "\\)"
  3853. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3854. "[ \t]*$")
  3855. org-todo-line-tags-regexp
  3856. (concat "^\\(\\*+\\)"
  3857. "\\(?: +" org-todo-regexp "\\)?"
  3858. "\\(?: +\\(.*?\\)\\)??"
  3859. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3860. "[ \t]*$"))
  3861. (org-compute-latex-and-related-regexp)))))
  3862. (defun org-collect-keywords (keywords &optional unique directory)
  3863. "Return values for KEYWORDS in current buffer, as an alist.
  3864. KEYWORDS is a list of strings. Return value is a list of
  3865. elements with the pattern:
  3866. (NAME . LIST-OF-VALUES)
  3867. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3868. is a list of non-empty values, as strings, in order of appearance
  3869. in the buffer.
  3870. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3871. value, empty or not, appearing in the buffer, as a string.
  3872. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3873. (VALUE . DIRECTORY)
  3874. where VALUE is the regular value, and DIRECTORY is the variable
  3875. `default-directory' for the buffer containing the keyword. This
  3876. is important for values containing relative file names, since the
  3877. function follows SETUPFILE keywords, and may change its working
  3878. directory."
  3879. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3880. (unique (mapcar #'upcase unique))
  3881. (alist (org--collect-keywords-1
  3882. keywords unique directory
  3883. (and buffer-file-name (list buffer-file-name))
  3884. nil)))
  3885. ;; Re-order results.
  3886. (dolist (entry alist)
  3887. (pcase entry
  3888. (`(,_ . ,(and value (pred consp)))
  3889. (setcdr entry (nreverse value)))))
  3890. (nreverse alist)))
  3891. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3892. (org-with-point-at 1
  3893. (let ((case-fold-search t)
  3894. (regexp (org-make-options-regexp keywords)))
  3895. (while (and keywords (re-search-forward regexp nil t))
  3896. (let ((element (org-element-at-point)))
  3897. (when (eq 'keyword (org-element-type element))
  3898. (let ((value (org-element-property :value element)))
  3899. (pcase (org-element-property :key element)
  3900. ("SETUPFILE"
  3901. (when (and (org-string-nw-p value)
  3902. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3903. (let* ((uri (org-strip-quotes value))
  3904. (uri-is-url (org-file-url-p uri))
  3905. (uri (if uri-is-url
  3906. uri
  3907. (expand-file-name uri))))
  3908. (unless (member uri files)
  3909. (with-temp-buffer
  3910. (unless uri-is-url
  3911. (setq default-directory (file-name-directory uri)))
  3912. (let ((contents (org-file-contents uri :noerror)))
  3913. (when contents
  3914. (insert contents)
  3915. ;; Fake Org mode: `org-element-at-point'
  3916. ;; doesn't need full set-up.
  3917. (let ((major-mode 'org-mode))
  3918. (setq alist
  3919. (org--collect-keywords-1
  3920. keywords unique directory
  3921. (cons uri files)
  3922. alist))))))))))
  3923. (keyword
  3924. (let ((entry (assoc keyword alist))
  3925. (final
  3926. (cond ((not (member keyword directory)) value)
  3927. (buffer-file-name
  3928. (cons value
  3929. (file-name-directory buffer-file-name)))
  3930. (t (cons value default-directory)))))
  3931. (cond ((member keyword unique)
  3932. (push (cons keyword final) alist)
  3933. (setq keywords (remove keyword keywords))
  3934. (setq regexp (org-make-options-regexp keywords)))
  3935. ((null entry) (push (list keyword final) alist))
  3936. (t (push final (cdr entry)))))))))))
  3937. alist)))
  3938. (defun org-tag-string-to-alist (s)
  3939. "Return tag alist associated to string S.
  3940. S is a value for TAGS keyword or produced with
  3941. `org-tag-alist-to-string'. Return value is an alist suitable for
  3942. `org-tag-alist' or `org-tag-persistent-alist'."
  3943. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3944. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3945. "\\(?:(\\(.\\))\\)?\\'"))
  3946. alist group-flag)
  3947. (dolist (tokens lines (cdr (nreverse alist)))
  3948. (push '(:newline) alist)
  3949. (while tokens
  3950. (let ((token (pop tokens)))
  3951. (pcase token
  3952. ("{"
  3953. (push '(:startgroup) alist)
  3954. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3955. ("}"
  3956. (push '(:endgroup) alist)
  3957. (setq group-flag nil))
  3958. ("["
  3959. (push '(:startgrouptag) alist)
  3960. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3961. ("]"
  3962. (push '(:endgrouptag) alist)
  3963. (setq group-flag nil))
  3964. (":"
  3965. (push '(:grouptags) alist))
  3966. ((guard (string-match tag-re token))
  3967. (let ((tag (match-string 1 token))
  3968. (key (and (match-beginning 2)
  3969. (string-to-char (match-string 2 token)))))
  3970. ;; Push all tags in groups, no matter if they already
  3971. ;; appear somewhere else in the list.
  3972. (when (or group-flag (not (assoc tag alist)))
  3973. (push (cons tag key) alist))))))))))
  3974. (defun org-tag-alist-to-string (alist &optional skip-key)
  3975. "Return tag string associated to ALIST.
  3976. ALIST is an alist, as defined in `org-tag-alist' or
  3977. `org-tag-persistent-alist', or produced with
  3978. `org-tag-string-to-alist'.
  3979. Return value is a string suitable as a value for \"TAGS\"
  3980. keyword.
  3981. When optional argument SKIP-KEY is non-nil, skip selection keys
  3982. next to tags."
  3983. (mapconcat (lambda (token)
  3984. (pcase token
  3985. (`(:startgroup) "{")
  3986. (`(:endgroup) "}")
  3987. (`(:startgrouptag) "[")
  3988. (`(:endgrouptag) "]")
  3989. (`(:grouptags) ":")
  3990. (`(:newline) "\\n")
  3991. ((and
  3992. (guard (not skip-key))
  3993. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3994. (format "%s(%c)" tag key))
  3995. (`(,(and tag (pred stringp)) . ,_) tag)
  3996. (_ (user-error "Invalid tag token: %S" token))))
  3997. alist
  3998. " "))
  3999. (defun org-tag-alist-to-groups (alist)
  4000. "Return group alist from tag ALIST.
  4001. ALIST is an alist, as defined in `org-tag-alist' or
  4002. `org-tag-persistent-alist', or produced with
  4003. `org-tag-string-to-alist'. Return value is an alist following
  4004. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4005. a string, summarizing TAGS, as a list of strings."
  4006. (let (groups group-status current-group)
  4007. (dolist (token alist (nreverse groups))
  4008. (pcase token
  4009. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4010. (`(,(or :endgroup :endgrouptag))
  4011. (when (eq group-status 'append)
  4012. (push (nreverse current-group) groups))
  4013. (setq group-status nil current-group nil))
  4014. (`(:grouptags) (setq group-status 'append))
  4015. ((and `(,tag . ,_) (guard group-status))
  4016. (if (eq group-status 'append) (push tag current-group)
  4017. (setq current-group (list tag))))
  4018. (_ nil)))))
  4019. (defvar org--file-cache (make-hash-table :test #'equal)
  4020. "Hash table to store contents of files referenced via a URL.
  4021. This is the cache of file URLs read using `org-file-contents'.")
  4022. (defun org-reset-file-cache ()
  4023. "Reset the cache of files downloaded by `org-file-contents'."
  4024. (clrhash org--file-cache))
  4025. (defun org-file-url-p (file)
  4026. "Non-nil if FILE is a URL."
  4027. (require 'ffap)
  4028. (string-match-p ffap-url-regexp file))
  4029. (defun org-file-contents (file &optional noerror nocache)
  4030. "Return the contents of FILE, as a string.
  4031. FILE can be a file name or URL.
  4032. If FILE is a URL, download the contents. If the URL contents are
  4033. already cached in the `org--file-cache' hash table, the download step
  4034. is skipped.
  4035. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4036. from file or URL, and return nil.
  4037. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4038. is available. This option applies only if FILE is a URL."
  4039. (let* ((is-url (org-file-url-p file))
  4040. (cache (and is-url
  4041. (not nocache)
  4042. (gethash file org--file-cache))))
  4043. (cond
  4044. (cache)
  4045. (is-url
  4046. (with-current-buffer (url-retrieve-synchronously file)
  4047. (goto-char (point-min))
  4048. ;; Move point to after the url-retrieve header.
  4049. (search-forward "\n\n" nil :move)
  4050. ;; Search for the success code only in the url-retrieve header.
  4051. (if (save-excursion
  4052. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4053. ;; Update the cache `org--file-cache' and return contents.
  4054. (puthash file
  4055. (buffer-substring-no-properties (point) (point-max))
  4056. org--file-cache)
  4057. (funcall (if noerror #'message #'user-error)
  4058. "Unable to fetch file from %S"
  4059. file)
  4060. nil)))
  4061. (t
  4062. (with-temp-buffer
  4063. (condition-case nil
  4064. (progn
  4065. (insert-file-contents file)
  4066. (buffer-string))
  4067. (file-error
  4068. (funcall (if noerror #'message #'user-error)
  4069. "Unable to read file %S"
  4070. file)
  4071. nil)))))))
  4072. (defun org-extract-log-state-settings (x)
  4073. "Extract the log state setting from a TODO keyword string.
  4074. This will extract info from a string like \"WAIT(w@/!)\"."
  4075. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4076. (let ((kw (match-string 1 x))
  4077. (log1 (and (match-end 3) (match-string 3 x)))
  4078. (log2 (and (match-end 4) (match-string 4 x))))
  4079. (and (or log1 log2)
  4080. (list kw
  4081. (and log1 (if (equal log1 "!") 'time 'note))
  4082. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4083. (defun org-remove-keyword-keys (list)
  4084. "Remove a pair of parenthesis at the end of each string in LIST."
  4085. (mapcar (lambda (x)
  4086. (if (string-match "(.*)$" x)
  4087. (substring x 0 (match-beginning 0))
  4088. x))
  4089. list))
  4090. (defun org-assign-fast-keys (alist)
  4091. "Assign fast keys to a keyword-key alist.
  4092. Respect keys that are already there."
  4093. (let (new e (alt ?0))
  4094. (while (setq e (pop alist))
  4095. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4096. (cdr e)) ;; Key already assigned.
  4097. (push e new)
  4098. (let ((clist (string-to-list (downcase (car e))))
  4099. (used (append new alist)))
  4100. (when (= (car clist) ?@)
  4101. (pop clist))
  4102. (while (and clist (rassoc (car clist) used))
  4103. (pop clist))
  4104. (unless clist
  4105. (while (rassoc alt used)
  4106. (cl-incf alt)))
  4107. (push (cons (car e) (or (car clist) alt)) new))))
  4108. (nreverse new)))
  4109. ;;; Some variables used in various places
  4110. (defvar org-window-configuration nil
  4111. "Used in various places to store a window configuration.")
  4112. (defvar org-selected-window nil
  4113. "Used in various places to store a window configuration.")
  4114. (defvar org-finish-function nil
  4115. "Function to be called when `C-c C-c' is used.
  4116. This is for getting out of special buffers like capture.")
  4117. (defvar org-last-state)
  4118. ;; Defined somewhere in this file, but used before definition.
  4119. (defvar org-entities) ;; defined in org-entities.el
  4120. (defvar org-struct-menu)
  4121. (defvar org-org-menu)
  4122. (defvar org-tbl-menu)
  4123. ;;;; Define the Org mode
  4124. (defun org-before-change-function (_beg _end)
  4125. "Every change indicates that a table might need an update."
  4126. (setq org-table-may-need-update t))
  4127. (defvar org-mode-map)
  4128. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4129. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4130. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4131. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4132. (defvar bidi-paragraph-direction)
  4133. (defvar buffer-face-mode-face)
  4134. (require 'outline)
  4135. ;; Other stuff we need.
  4136. (require 'time-date)
  4137. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4138. (require 'easymenu)
  4139. (require 'overlay)
  4140. (require 'org-entities)
  4141. (require 'org-faces)
  4142. (require 'org-list)
  4143. (require 'org-pcomplete)
  4144. (require 'org-src)
  4145. (require 'org-footnote)
  4146. (require 'org-macro)
  4147. ;; babel
  4148. (require 'ob)
  4149. ;;;###autoload
  4150. (define-derived-mode org-mode outline-mode "Org"
  4151. "Outline-based notes management and organizer, alias
  4152. \"Carsten's outline-mode for keeping track of everything.\"
  4153. Org mode develops organizational tasks around a NOTES file which
  4154. contains information about projects as plain text. Org mode is
  4155. implemented on top of Outline mode, which is ideal to keep the content
  4156. of large files well structured. It supports ToDo items, deadlines and
  4157. time stamps, which magically appear in the diary listing of the Emacs
  4158. calendar. Tables are easily created with a built-in table editor.
  4159. Plain text URL-like links connect to websites, emails (VM), Usenet
  4160. messages (Gnus), BBDB entries, and any files related to the project.
  4161. For printing and sharing of notes, an Org file (or a part of it)
  4162. can be exported as a structured ASCII or HTML file.
  4163. The following commands are available:
  4164. \\{org-mode-map}"
  4165. (org-load-modules-maybe)
  4166. (org-install-agenda-files-menu)
  4167. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4168. (add-to-invisibility-spec '(org-hide-block . t))
  4169. (setq-local outline-regexp org-outline-regexp)
  4170. (setq-local outline-level 'org-outline-level)
  4171. (setq bidi-paragraph-direction 'left-to-right)
  4172. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4173. (unless org-display-table
  4174. (setq org-display-table (make-display-table)))
  4175. (set-display-table-slot
  4176. org-display-table 4
  4177. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4178. org-ellipsis)))
  4179. (setq buffer-display-table org-display-table))
  4180. (org-set-regexps-and-options)
  4181. (org-set-font-lock-defaults)
  4182. (when (and org-tag-faces (not org-tags-special-faces-re))
  4183. ;; tag faces set outside customize.... force initialization.
  4184. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4185. ;; Calc embedded
  4186. (setq-local calc-embedded-open-mode "# ")
  4187. ;; Modify a few syntax entries
  4188. (modify-syntax-entry ?\" "\"")
  4189. (modify-syntax-entry ?\\ "_")
  4190. (modify-syntax-entry ?~ "_")
  4191. (modify-syntax-entry ?< "(>")
  4192. (modify-syntax-entry ?> ")<")
  4193. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4194. ;; Activate before-change-function
  4195. (setq-local org-table-may-need-update t)
  4196. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4197. ;; Check for running clock before killing a buffer
  4198. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4199. ;; Initialize macros templates.
  4200. (org-macro-initialize-templates)
  4201. ;; Initialize radio targets.
  4202. (org-update-radio-target-regexp)
  4203. ;; Indentation.
  4204. (setq-local indent-line-function 'org-indent-line)
  4205. (setq-local indent-region-function 'org-indent-region)
  4206. ;; Filling and auto-filling.
  4207. (org-setup-filling)
  4208. ;; Comments.
  4209. (org-setup-comments-handling)
  4210. ;; Initialize cache.
  4211. (org-element-cache-reset)
  4212. ;; Beginning/end of defun
  4213. (setq-local beginning-of-defun-function 'org-backward-element)
  4214. (setq-local end-of-defun-function
  4215. (lambda ()
  4216. (if (not (org-at-heading-p))
  4217. (org-forward-element)
  4218. (org-forward-element)
  4219. (forward-char -1))))
  4220. ;; Next error for sparse trees
  4221. (setq-local next-error-function 'org-occur-next-match)
  4222. ;; Make commit log messages from Org documents easier.
  4223. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4224. ;; Make sure dependence stuff works reliably, even for users who set it
  4225. ;; too late :-(
  4226. (if org-enforce-todo-dependencies
  4227. (add-hook 'org-blocker-hook
  4228. 'org-block-todo-from-children-or-siblings-or-parent)
  4229. (remove-hook 'org-blocker-hook
  4230. 'org-block-todo-from-children-or-siblings-or-parent))
  4231. (if org-enforce-todo-checkbox-dependencies
  4232. (add-hook 'org-blocker-hook
  4233. 'org-block-todo-from-checkboxes)
  4234. (remove-hook 'org-blocker-hook
  4235. 'org-block-todo-from-checkboxes))
  4236. ;; Align options lines
  4237. (setq-local
  4238. align-mode-rules-list
  4239. '((org-in-buffer-settings
  4240. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4241. (modes . '(org-mode)))))
  4242. ;; Setup the pcomplete hooks
  4243. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4244. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4245. (setq-local pcomplete-default-completion-function #'ignore)
  4246. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4247. (setq-local pcomplete-termination-string "")
  4248. (add-hook 'completion-at-point-functions
  4249. #'pcomplete-completions-at-point nil t)
  4250. (setq-local buffer-face-mode-face 'org-default)
  4251. ;; If empty file that did not turn on Org mode automatically, make
  4252. ;; it to.
  4253. (when (and org-insert-mode-line-in-empty-file
  4254. (called-interactively-p 'any)
  4255. (= (point-min) (point-max)))
  4256. (insert "# -*- mode: org -*-\n\n"))
  4257. (unless org-inhibit-startup
  4258. (org-unmodified
  4259. (when org-startup-with-beamer-mode (org-beamer-mode))
  4260. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4261. (org-table-map-tables
  4262. (cond ((and org-startup-align-all-tables
  4263. org-startup-shrink-all-tables)
  4264. (lambda () (org-table-align) (org-table-shrink)))
  4265. (org-startup-align-all-tables #'org-table-align)
  4266. (t #'org-table-shrink))
  4267. t))
  4268. (when org-startup-with-inline-images (org-display-inline-images))
  4269. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4270. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4271. (when org-startup-truncated (setq truncate-lines t))
  4272. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4273. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4274. ;; Activate `org-table-header-line-mode'
  4275. (when org-table-header-line-p
  4276. (org-table-header-line-mode 1))
  4277. ;; Try to set `org-hide' face correctly.
  4278. (let ((foreground (org-find-invisible-foreground)))
  4279. (when foreground
  4280. (set-face-foreground 'org-hide foreground)))
  4281. ;; Set face extension as requested.
  4282. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4283. org-fontify-whole-block-delimiter-line)
  4284. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4285. ;; Update `customize-package-emacs-version-alist'
  4286. (add-to-list 'customize-package-emacs-version-alist
  4287. '(Org ("8.0" . "24.4")
  4288. ("8.1" . "24.4")
  4289. ("8.2" . "24.4")
  4290. ("8.2.7" . "24.4")
  4291. ("8.3" . "26.1")
  4292. ("9.0" . "26.1")
  4293. ("9.1" . "26.1")
  4294. ("9.2" . "27.1")
  4295. ("9.3" . "27.1")
  4296. ("9.4" . "27.2")
  4297. ("9.5" . "28.1")))
  4298. (defvar org-mode-transpose-word-syntax-table
  4299. (let ((st (make-syntax-table text-mode-syntax-table)))
  4300. (dolist (c org-emphasis-alist st)
  4301. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4302. (when (fboundp 'abbrev-table-put)
  4303. (abbrev-table-put org-mode-abbrev-table
  4304. :parents (list text-mode-abbrev-table)))
  4305. (defun org-find-invisible-foreground ()
  4306. (let ((candidates (remove
  4307. "unspecified-bg"
  4308. (nconc
  4309. (list (face-background 'default)
  4310. (face-background 'org-default))
  4311. (mapcar
  4312. (lambda (alist)
  4313. (when (boundp alist)
  4314. (cdr (assq 'background-color (symbol-value alist)))))
  4315. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4316. (list (face-foreground 'org-hide))))))
  4317. (car (remove nil candidates))))
  4318. (defun org-current-time (&optional rounding-minutes past)
  4319. "Current time, possibly rounded to ROUNDING-MINUTES.
  4320. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4321. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4322. the rounding returns a past time."
  4323. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4324. (car org-time-stamp-rounding-minutes)))
  4325. (now (current-time)))
  4326. (if (< r 1)
  4327. now
  4328. (let* ((time (decode-time now))
  4329. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4330. (nthcdr 2 time))))
  4331. (if (or (not past) (org-time-less-p res now))
  4332. res
  4333. (org-time-subtract res (* r 60)))))))
  4334. (defun org-today ()
  4335. "Return today date, considering `org-extend-today-until'."
  4336. (time-to-days
  4337. (org-time-since (* 3600 org-extend-today-until))))
  4338. ;;;; Font-Lock stuff, including the activators
  4339. (defconst org-match-sexp-depth 3
  4340. "Number of stacked braces for sub/superscript matching.")
  4341. (defun org-create-multibrace-regexp (left right n)
  4342. "Create a regular expression which will match a balanced sexp.
  4343. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4344. as single character strings.
  4345. The regexp returned will match the entire expression including the
  4346. delimiters. It will also define a single group which contains the
  4347. match except for the outermost delimiters. The maximum depth of
  4348. stacked delimiters is N. Escaping delimiters is not possible."
  4349. (let* ((nothing (concat "[^" left right "]*?"))
  4350. (or "\\|")
  4351. (re nothing)
  4352. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4353. (while (> n 1)
  4354. (setq n (1- n)
  4355. re (concat re or next)
  4356. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4357. (concat left "\\(" re "\\)" right)))
  4358. (defconst org-match-substring-regexp
  4359. (concat
  4360. "\\(\\S-\\)\\([_^]\\)\\("
  4361. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4362. "\\|"
  4363. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4364. "\\|"
  4365. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4366. "The regular expression matching a sub- or superscript.")
  4367. (defconst org-match-substring-with-braces-regexp
  4368. (concat
  4369. "\\(\\S-\\)\\([_^]\\)"
  4370. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4371. "The regular expression matching a sub- or superscript, forcing braces.")
  4372. (defvar org-emph-face nil)
  4373. (defun org-do-emphasis-faces (limit)
  4374. "Run through the buffer and emphasize strings."
  4375. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4376. (car org-emphasis-regexp-components))))
  4377. (catch :exit
  4378. (while (re-search-forward quick-re limit t)
  4379. (let* ((marker (match-string 2))
  4380. (verbatim? (member marker '("~" "="))))
  4381. (when (save-excursion
  4382. (goto-char (match-beginning 0))
  4383. (and
  4384. ;; Do not match table hlines.
  4385. (not (and (equal marker "+")
  4386. (org-match-line
  4387. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4388. ;; Do not match headline stars. Do not consider
  4389. ;; stars of a headline as closing marker for bold
  4390. ;; markup either.
  4391. (not (and (equal marker "*")
  4392. (save-excursion
  4393. (forward-char)
  4394. (skip-chars-backward "*")
  4395. (looking-at-p org-outline-regexp-bol))))
  4396. ;; Match full emphasis markup regexp.
  4397. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4398. ;; Do not span over paragraph boundaries.
  4399. (not (string-match-p org-element-paragraph-separate
  4400. (match-string 2)))
  4401. ;; Do not span over cells in table rows.
  4402. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4403. (string-match-p "|" (match-string 4))))))
  4404. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4405. (m (if org-hide-emphasis-markers 4 2)))
  4406. (font-lock-prepend-text-property
  4407. (match-beginning m) (match-end m) 'face face)
  4408. (when verbatim?
  4409. (org-remove-flyspell-overlays-in
  4410. (match-beginning 0) (match-end 0))
  4411. (remove-text-properties (match-beginning 2) (match-end 2)
  4412. '(display t invisible t intangible t)))
  4413. (add-text-properties (match-beginning 2) (match-end 2)
  4414. '(font-lock-multiline t org-emphasis t))
  4415. (when (and org-hide-emphasis-markers
  4416. (not (org-at-comment-p)))
  4417. (add-text-properties (match-end 4) (match-beginning 5)
  4418. '(invisible org-link))
  4419. (add-text-properties (match-beginning 3) (match-end 3)
  4420. '(invisible org-link)))
  4421. (throw :exit t))))))))
  4422. (defun org-emphasize (&optional char)
  4423. "Insert or change an emphasis, i.e. a font like bold or italic.
  4424. If there is an active region, change that region to a new emphasis.
  4425. If there is no region, just insert the marker characters and position
  4426. the cursor between them.
  4427. CHAR should be the marker character. If it is a space, it means to
  4428. remove the emphasis of the selected region.
  4429. If CHAR is not given (for example in an interactive call) it will be
  4430. prompted for."
  4431. (interactive)
  4432. (let ((erc org-emphasis-regexp-components)
  4433. (string "") beg end move s)
  4434. (if (org-region-active-p)
  4435. (setq beg (region-beginning)
  4436. end (region-end)
  4437. string (buffer-substring beg end))
  4438. (setq move t))
  4439. (unless char
  4440. (message "Emphasis marker or tag: [%s]"
  4441. (mapconcat #'car org-emphasis-alist ""))
  4442. (setq char (read-char-exclusive)))
  4443. (if (equal char ?\s)
  4444. (setq s ""
  4445. move nil)
  4446. (unless (assoc (char-to-string char) org-emphasis-alist)
  4447. (user-error "No such emphasis marker: \"%c\"" char))
  4448. (setq s (char-to-string char)))
  4449. (while (and (> (length string) 1)
  4450. (equal (substring string 0 1) (substring string -1))
  4451. (assoc (substring string 0 1) org-emphasis-alist))
  4452. (setq string (substring string 1 -1)))
  4453. (setq string (concat s string s))
  4454. (when beg (delete-region beg end))
  4455. (unless (or (bolp)
  4456. (string-match (concat "[" (nth 0 erc) "\n]")
  4457. (char-to-string (char-before (point)))))
  4458. (insert " "))
  4459. (unless (or (eobp)
  4460. (string-match (concat "[" (nth 1 erc) "\n]")
  4461. (char-to-string (char-after (point)))))
  4462. (insert " ") (backward-char 1))
  4463. (insert string)
  4464. (and move (backward-char 1))))
  4465. (defconst org-nonsticky-props
  4466. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4467. (defsubst org-rear-nonsticky-at (pos)
  4468. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4469. (defun org-activate-links (limit)
  4470. "Add link properties to links.
  4471. This includes angle, plain, and bracket links."
  4472. (catch :exit
  4473. (while (re-search-forward org-link-any-re limit t)
  4474. (let* ((start (match-beginning 0))
  4475. (end (match-end 0))
  4476. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4477. (visible-end (or (match-end 3) (match-end 2)))
  4478. (style (cond ((eq ?< (char-after start)) 'angle)
  4479. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4480. (t 'plain))))
  4481. (when (and (memq style org-highlight-links)
  4482. ;; Do not span over paragraph boundaries.
  4483. (not (string-match-p org-element-paragraph-separate
  4484. (match-string 0)))
  4485. ;; Do not confuse plain links with tags.
  4486. (not (and (eq style 'plain)
  4487. (let ((face (get-text-property
  4488. (max (1- start) (point-min)) 'face)))
  4489. (if (consp face) (memq 'org-tag face)
  4490. (eq 'org-tag face))))))
  4491. (let* ((link-object (save-excursion
  4492. (goto-char start)
  4493. (save-match-data (org-element-link-parser))))
  4494. (link (org-element-property :raw-link link-object))
  4495. (type (org-element-property :type link-object))
  4496. (path (org-element-property :path link-object))
  4497. (face-property (pcase (org-link-get-parameter type :face)
  4498. ((and (pred functionp) face) (funcall face path))
  4499. ((and (pred facep) face) face)
  4500. ((and (pred consp) face) face) ;anonymous
  4501. (_ 'org-link)))
  4502. (properties ;for link's visible part
  4503. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4504. 'highlight)
  4505. 'keymap (or (org-link-get-parameter type :keymap)
  4506. org-mouse-map)
  4507. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4508. ((and (pred stringp) echo) echo)
  4509. ((and (pred functionp) echo) echo)
  4510. (_ (concat "LINK: " link)))
  4511. 'htmlize-link (pcase (org-link-get-parameter type
  4512. :htmlize-link)
  4513. ((and (pred functionp) f) (funcall f))
  4514. (_ `(:uri ,link)))
  4515. 'font-lock-multiline t)))
  4516. (org-remove-flyspell-overlays-in start end)
  4517. (org-rear-nonsticky-at end)
  4518. (if (not (eq 'bracket style))
  4519. (progn
  4520. (add-face-text-property start end face-property)
  4521. (add-text-properties start end properties))
  4522. ;; Handle invisible parts in bracket links.
  4523. (remove-text-properties start end '(invisible nil))
  4524. (let ((hidden
  4525. (append `(invisible
  4526. ,(or (org-link-get-parameter type :display)
  4527. 'org-link))
  4528. properties)))
  4529. (add-text-properties start visible-start hidden)
  4530. (add-face-text-property visible-start visible-end face-property)
  4531. (add-text-properties visible-start visible-end properties)
  4532. (add-text-properties visible-end end hidden)
  4533. (org-rear-nonsticky-at visible-start)
  4534. (org-rear-nonsticky-at visible-end)))
  4535. (let ((f (org-link-get-parameter type :activate-func)))
  4536. (when (functionp f)
  4537. (funcall f start end path (eq style 'bracket))))
  4538. (throw :exit t))))) ;signal success
  4539. nil))
  4540. (defun org-activate-code (limit)
  4541. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4542. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4543. (remove-text-properties (match-beginning 0) (match-end 0)
  4544. '(display t invisible t intangible t))
  4545. t))
  4546. (defcustom org-src-fontify-natively t
  4547. "When non-nil, fontify code in code blocks.
  4548. See also the `org-block' face."
  4549. :type 'boolean
  4550. :version "26.1"
  4551. :package-version '(Org . "8.3")
  4552. :group 'org-appearance
  4553. :group 'org-babel)
  4554. (defcustom org-allow-promoting-top-level-subtree nil
  4555. "When non-nil, allow promoting a top level subtree.
  4556. The leading star of the top level headline will be replaced
  4557. by a #."
  4558. :type 'boolean
  4559. :version "24.1"
  4560. :group 'org-appearance)
  4561. (defun org-fontify-meta-lines-and-blocks (limit)
  4562. (condition-case nil
  4563. (org-fontify-meta-lines-and-blocks-1 limit)
  4564. (error (message "Org mode fontification error in %S at %d"
  4565. (current-buffer)
  4566. (line-number-at-pos)))))
  4567. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4568. "Fontify #+ lines and blocks."
  4569. (let ((case-fold-search t))
  4570. (when (re-search-forward
  4571. (rx bol (group (zero-or-more (any " \t")) "#"
  4572. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4573. (any " \t")
  4574. eol))
  4575. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4576. (zero-or-more (any " \t"))
  4577. (group (group (zero-or-more (not (any " \t\n"))))
  4578. (zero-or-more (any " \t"))
  4579. (group (zero-or-more any)))))
  4580. limit t)
  4581. (let ((beg (match-beginning 0))
  4582. (end-of-beginline (match-end 0))
  4583. ;; Including \n at end of #+begin line will include \n
  4584. ;; after the end of block content.
  4585. (block-start (match-end 0))
  4586. (block-end nil)
  4587. (lang (match-string 7)) ; The language, if it is a source block.
  4588. (bol-after-beginline (line-beginning-position 2))
  4589. (dc1 (downcase (match-string 2)))
  4590. (dc3 (downcase (match-string 3)))
  4591. (whole-blockline org-fontify-whole-block-delimiter-line)
  4592. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4593. (cond
  4594. ((and (match-end 4) (equal dc3 "+begin"))
  4595. ;; Truly a block
  4596. (setq block-type (downcase (match-string 5))
  4597. ;; Src, example, export, maybe more.
  4598. quoting (member block-type org-protecting-blocks))
  4599. (when (re-search-forward
  4600. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4601. (seq (zero-or-more (any " \t"))
  4602. "#+end"
  4603. ,(match-string 4)
  4604. word-end
  4605. (zero-or-more any)))))
  4606. ;; We look further than LIMIT on purpose.
  4607. nil t)
  4608. ;; We do have a matching #+end line.
  4609. (setq beg-of-endline (match-beginning 0)
  4610. end-of-endline (match-end 0)
  4611. nl-before-endline (1- (match-beginning 0)))
  4612. (setq block-end (match-beginning 0)) ; Include the final newline.
  4613. (when quoting
  4614. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4615. (remove-text-properties beg end-of-endline
  4616. '(display t invisible t intangible t)))
  4617. (add-text-properties
  4618. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4619. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4620. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4621. (cond
  4622. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4623. (org-src-font-lock-fontify-block lang block-start block-end)
  4624. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4625. (quoting
  4626. (add-text-properties
  4627. bol-after-beginline beg-of-endline
  4628. (list 'face
  4629. (list :inherit
  4630. (let ((face-name
  4631. (intern (format "org-block-%s" lang))))
  4632. (append (and (facep face-name) (list face-name))
  4633. '(org-block)))))))
  4634. ((not org-fontify-quote-and-verse-blocks))
  4635. ((string= block-type "quote")
  4636. (add-face-text-property
  4637. bol-after-beginline beg-of-endline 'org-quote t))
  4638. ((string= block-type "verse")
  4639. (add-face-text-property
  4640. bol-after-beginline beg-of-endline 'org-verse t)))
  4641. ;; Fontify the #+begin and #+end lines of the blocks
  4642. (add-text-properties
  4643. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4644. '(face org-block-begin-line))
  4645. (unless (eq (char-after beg-of-endline) ?*)
  4646. (add-text-properties
  4647. beg-of-endline
  4648. (if whole-blockline
  4649. (let ((beg-of-next-line (1+ end-of-endline)))
  4650. (min (point-max) beg-of-next-line))
  4651. (min (point-max) end-of-endline))
  4652. '(face org-block-end-line)))
  4653. t))
  4654. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4655. (org-remove-flyspell-overlays-in
  4656. (match-beginning 0)
  4657. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4658. (add-text-properties
  4659. beg (match-end 3)
  4660. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4661. '(font-lock-fontified t invisible t)
  4662. '(font-lock-fontified t face org-document-info-keyword)))
  4663. (add-text-properties
  4664. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4665. (if (string-equal dc1 "+title:")
  4666. '(font-lock-fontified t face org-document-title)
  4667. '(font-lock-fontified t face org-document-info))))
  4668. ((string-prefix-p "+caption" dc1)
  4669. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4670. (remove-text-properties (match-beginning 0) (match-end 0)
  4671. '(display t invisible t intangible t))
  4672. ;; Handle short captions
  4673. (save-excursion
  4674. (beginning-of-line)
  4675. (looking-at (rx (group (zero-or-more (any " \t"))
  4676. "#+caption"
  4677. (optional "[" (zero-or-more any) "]")
  4678. ":")
  4679. (zero-or-more (any " \t")))))
  4680. (add-text-properties (line-beginning-position) (match-end 1)
  4681. '(font-lock-fontified t face org-meta-line))
  4682. (add-text-properties (match-end 0) (line-end-position)
  4683. '(font-lock-fontified t face org-block))
  4684. t)
  4685. ((member dc3 '(" " ""))
  4686. ;; Just a comment, the plus was not there
  4687. (org-remove-flyspell-overlays-in beg (match-end 0))
  4688. (add-text-properties
  4689. beg (match-end 0)
  4690. '(font-lock-fontified t face font-lock-comment-face)))
  4691. (t ;; Just any other in-buffer setting, but not indented
  4692. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4693. (remove-text-properties (match-beginning 0) (match-end 0)
  4694. '(display t invisible t intangible t))
  4695. (add-text-properties beg (match-end 0)
  4696. '(font-lock-fontified t face org-meta-line))
  4697. t))))))
  4698. (defun org-fontify-drawers (limit)
  4699. "Fontify drawers."
  4700. (when (re-search-forward org-drawer-regexp limit t)
  4701. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4702. '(font-lock-fontified t face org-drawer))
  4703. (org-remove-flyspell-overlays-in
  4704. (line-beginning-position) (line-beginning-position 2))
  4705. t))
  4706. (defun org-fontify-macros (limit)
  4707. "Fontify macros."
  4708. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4709. (let ((begin (match-beginning 0))
  4710. (opening-end (match-beginning 1)))
  4711. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4712. (match-string 1))
  4713. (let ((end (match-end 1))
  4714. (closing-start (match-beginning 1)))
  4715. (add-text-properties
  4716. begin end
  4717. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4718. (org-remove-flyspell-overlays-in begin end)
  4719. (when org-hide-macro-markers
  4720. (add-text-properties begin opening-end '(invisible t))
  4721. (add-text-properties closing-start end '(invisible t)))
  4722. t)))))
  4723. (defun org-fontify-extend-region (beg end _old-len)
  4724. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4725. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4726. (extend (lambda (r1 r2 dir)
  4727. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4728. (replace-regexp-in-string "[][]" r2
  4729. (match-string-no-properties 0)))))
  4730. (re-search-forward (regexp-quote re) nil t dir)))))
  4731. (save-match-data
  4732. (save-excursion
  4733. (goto-char beg)
  4734. (back-to-indentation)
  4735. (cond ((looking-at end-re)
  4736. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4737. ((looking-at begin-re)
  4738. (cons beg (or (funcall extend "end" "]" 1) end)))
  4739. (t (cons beg end)))))))
  4740. (defun org-activate-footnote-links (limit)
  4741. "Add text properties for footnotes."
  4742. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4743. (when fn
  4744. (let* ((beg (nth 1 fn))
  4745. (end (nth 2 fn))
  4746. (label (car fn))
  4747. (referencep (/= (line-beginning-position) beg)))
  4748. (when (and referencep (nth 3 fn))
  4749. (save-excursion
  4750. (goto-char beg)
  4751. (search-forward (or label "fn:"))
  4752. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4753. (add-text-properties beg end
  4754. (list 'mouse-face 'highlight
  4755. 'keymap org-mouse-map
  4756. 'help-echo
  4757. (if referencep "Footnote reference"
  4758. "Footnote definition")
  4759. 'font-lock-fontified t
  4760. 'font-lock-multiline t
  4761. 'face 'org-footnote))))))
  4762. (defun org-activate-dates (limit)
  4763. "Add text properties for dates."
  4764. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4765. (not (equal (char-before (match-beginning 0)) 91)))
  4766. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4767. (add-text-properties (match-beginning 0) (match-end 0)
  4768. (list 'mouse-face 'highlight
  4769. 'keymap org-mouse-map))
  4770. (org-rear-nonsticky-at (match-end 0))
  4771. (when org-display-custom-times
  4772. ;; If it's a date range, activate custom time for second date.
  4773. (when (match-end 3)
  4774. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4775. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4776. t))
  4777. (defun org-activate-target-links (limit)
  4778. "Add text properties for target matches."
  4779. (when org-target-link-regexp
  4780. (let ((case-fold-search t))
  4781. ;; `org-target-link-regexp' matches one character before the
  4782. ;; actual target.
  4783. (unless (bolp) (forward-char -1))
  4784. (when (re-search-forward org-target-link-regexp limit t)
  4785. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4786. (add-text-properties (match-beginning 1) (match-end 1)
  4787. (list 'mouse-face 'highlight
  4788. 'keymap org-mouse-map
  4789. 'help-echo "Radio target link"
  4790. 'org-linked-text t))
  4791. (org-rear-nonsticky-at (match-end 1))
  4792. t))))
  4793. (defvar org-latex-and-related-regexp nil
  4794. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4795. (defun org-compute-latex-and-related-regexp ()
  4796. "Compute regular expression for LaTeX, entities and sub/superscript.
  4797. Result depends on variable `org-highlight-latex-and-related'."
  4798. (let ((re-sub
  4799. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4800. ((eq org-use-sub-superscripts '{})
  4801. (list org-match-substring-with-braces-regexp))
  4802. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4803. (re-latex
  4804. (when (or (memq 'latex org-highlight-latex-and-related)
  4805. (memq 'native org-highlight-latex-and-related))
  4806. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4807. (delq nil
  4808. (mapcar (lambda (x)
  4809. (and (member (car x) matchers) (nth 1 x)))
  4810. org-latex-regexps)))))
  4811. (re-entities
  4812. (when (memq 'entities org-highlight-latex-and-related)
  4813. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4814. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4815. (setq-local org-latex-and-related-regexp
  4816. (mapconcat #'identity
  4817. (append re-latex re-entities re-sub)
  4818. "\\|"))))
  4819. (defun org-do-latex-and-related (limit)
  4820. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4821. Stop at first highlighted object, if any. Return t if some
  4822. highlighting was done, nil otherwise."
  4823. (when (org-string-nw-p org-latex-and-related-regexp)
  4824. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4825. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4826. (catch 'found
  4827. (while (and (< (point) limit)
  4828. (re-search-forward org-latex-and-related-regexp nil t))
  4829. (cond
  4830. ((cl-some (lambda (f)
  4831. (memq f '(org-code org-verbatim underline
  4832. org-special-keyword)))
  4833. (save-excursion
  4834. (goto-char (1+ (match-beginning 0)))
  4835. (face-at-point nil t))))
  4836. ;; Try to limit false positives. In this case, ignore
  4837. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4838. ;; contain an empty line.
  4839. ((save-excursion
  4840. (goto-char (match-beginning 0))
  4841. (and (looking-at-p latex-prefix-re)
  4842. (save-match-data
  4843. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4844. (t
  4845. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4846. '(?_ ?^))
  4847. 1
  4848. 0))
  4849. (start (+ offset (match-beginning 0)))
  4850. (end (match-end 0)))
  4851. (if (memq 'native org-highlight-latex-and-related)
  4852. (org-src-font-lock-fontify-block "latex" start end)
  4853. (font-lock-prepend-text-property start end
  4854. 'face 'org-latex-and-related))
  4855. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4856. '(font-lock-multiline t))
  4857. (throw 'found t)))))
  4858. nil))))
  4859. (defun org-restart-font-lock ()
  4860. "Restart `font-lock-mode', to force refontification."
  4861. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4862. (font-lock-mode -1)
  4863. (font-lock-mode 1)))
  4864. (defun org-activate-tags (limit)
  4865. (when (re-search-forward org-tag-line-re limit t)
  4866. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4867. (add-text-properties (match-beginning 1) (match-end 1)
  4868. (list 'mouse-face 'highlight
  4869. 'keymap org-mouse-map))
  4870. (org-rear-nonsticky-at (match-end 1))
  4871. t))
  4872. (defun org-outline-level ()
  4873. "Compute the outline level of the heading at point.
  4874. If this is called at a normal headline, the level is the number
  4875. of stars. Use `org-reduced-level' to remove the effect of
  4876. `org-odd-levels'. Unlike to `org-current-level', this function
  4877. takes into consideration inlinetasks."
  4878. (org-with-wide-buffer
  4879. (end-of-line)
  4880. (if (re-search-backward org-outline-regexp-bol nil t)
  4881. (1- (- (match-end 0) (match-beginning 0)))
  4882. 0)))
  4883. (defvar org-font-lock-keywords nil)
  4884. (defsubst org-re-property (property &optional literal allow-null value)
  4885. "Return a regexp matching a PROPERTY line.
  4886. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4887. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4888. non-nil, match properties even without a value.
  4889. Match group 3 is set to the value when it exists. If there is no
  4890. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4891. With optional argument VALUE, match only property lines with
  4892. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4893. unless LITERAL is non-nil."
  4894. (concat
  4895. "^\\(?4:[ \t]*\\)"
  4896. (format "\\(?1::\\(?2:%s\\):\\)"
  4897. (if literal property (regexp-quote property)))
  4898. (cond (value
  4899. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4900. (if literal value (regexp-quote value))))
  4901. (allow-null
  4902. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4903. (t
  4904. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4905. (defconst org-property-re
  4906. (org-re-property "\\S-+" 'literal t)
  4907. "Regular expression matching a property line.
  4908. There are four matching groups:
  4909. 1: :PROPKEY: including the leading and trailing colon,
  4910. 2: PROPKEY without the leading and trailing colon,
  4911. 3: PROPVAL without leading or trailing spaces,
  4912. 4: the indentation of the current line,
  4913. 5: trailing whitespace.")
  4914. (defvar org-font-lock-hook nil
  4915. "Functions to be called for special font lock stuff.")
  4916. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4917. (defvar org-font-lock-set-keywords-hook nil
  4918. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4919. This is called after `org-font-lock-extra-keywords' is defined, but before
  4920. it is installed to be used by font lock. This can be useful if something
  4921. needs to be inserted at a specific position in the font-lock sequence.")
  4922. (defun org-font-lock-hook (limit)
  4923. "Run `org-font-lock-hook' within LIMIT."
  4924. (run-hook-with-args 'org-font-lock-hook limit))
  4925. (defun org-set-font-lock-defaults ()
  4926. "Set font lock defaults for the current buffer."
  4927. (let* ((em org-fontify-emphasized-text)
  4928. (lk org-highlight-links)
  4929. (org-font-lock-extra-keywords
  4930. (list
  4931. ;; Call the hook
  4932. '(org-font-lock-hook)
  4933. ;; Headlines
  4934. `(,(if org-fontify-whole-heading-line
  4935. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4936. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4937. (1 (org-get-level-face 1))
  4938. (2 (org-get-level-face 2))
  4939. (3 (org-get-level-face 3)))
  4940. ;; Table lines
  4941. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4942. (1 'org-table t))
  4943. ;; Table internals
  4944. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4945. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4946. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4947. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4948. ;; Properties
  4949. (list org-property-re
  4950. '(1 'org-special-keyword t)
  4951. '(3 'org-property-value t))
  4952. ;; Drawers
  4953. '(org-fontify-drawers)
  4954. ;; Link related fontification.
  4955. '(org-activate-links)
  4956. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4957. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4958. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4959. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4960. ;; Targets.
  4961. (list org-radio-target-regexp '(0 'org-target t))
  4962. (list org-target-regexp '(0 'org-target t))
  4963. ;; Diary sexps.
  4964. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4965. ;; Macro
  4966. '(org-fontify-macros)
  4967. ;; TODO keyword
  4968. (list (format org-heading-keyword-regexp-format
  4969. org-todo-regexp)
  4970. '(2 (org-get-todo-face 2) prepend))
  4971. ;; TODO
  4972. (when org-fontify-todo-headline
  4973. (list (format org-heading-keyword-regexp-format
  4974. (concat
  4975. "\\(?:"
  4976. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4977. "\\)"))
  4978. '(2 'org-headline-todo prepend)))
  4979. ;; DONE
  4980. (when org-fontify-done-headline
  4981. (list (format org-heading-keyword-regexp-format
  4982. (concat
  4983. "\\(?:"
  4984. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4985. "\\)"))
  4986. '(2 'org-headline-done prepend)))
  4987. ;; Priorities
  4988. '(org-font-lock-add-priority-faces)
  4989. ;; Tags
  4990. '(org-font-lock-add-tag-faces)
  4991. ;; Tags groups
  4992. (when (and org-group-tags org-tag-groups-alist)
  4993. (list (concat org-outline-regexp-bol ".+\\(:"
  4994. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4995. ":\\).*$")
  4996. '(1 'org-tag-group prepend)))
  4997. ;; Special keywords
  4998. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4999. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5000. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5001. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5002. ;; Emphasis
  5003. (when em '(org-do-emphasis-faces))
  5004. ;; Checkboxes
  5005. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5006. 1 'org-checkbox prepend)
  5007. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5008. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5009. (0 (org-get-checkbox-statistics-face) prepend)))
  5010. ;; Description list items
  5011. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5012. 1 'org-list-dt prepend)
  5013. ;; ARCHIVEd headings
  5014. (list (concat
  5015. org-outline-regexp-bol
  5016. "\\(.*:" org-archive-tag ":.*\\)")
  5017. '(1 'org-archived prepend))
  5018. ;; Specials
  5019. '(org-do-latex-and-related)
  5020. '(org-fontify-entities)
  5021. '(org-raise-scripts)
  5022. ;; Code
  5023. '(org-activate-code (1 'org-code t))
  5024. ;; COMMENT
  5025. (list (format
  5026. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5027. org-todo-regexp
  5028. org-comment-string)
  5029. '(9 'org-special-keyword t))
  5030. ;; Blocks and meta lines
  5031. '(org-fontify-meta-lines-and-blocks))))
  5032. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5033. (run-hooks 'org-font-lock-set-keywords-hook)
  5034. ;; Now set the full font-lock-keywords
  5035. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5036. (setq-local font-lock-defaults
  5037. '(org-font-lock-keywords t nil nil backward-paragraph))
  5038. (setq-local font-lock-extend-after-change-region-function
  5039. #'org-fontify-extend-region)
  5040. (kill-local-variable 'font-lock-keywords)
  5041. nil))
  5042. (defun org-toggle-pretty-entities ()
  5043. "Toggle the composition display of entities as UTF8 characters."
  5044. (interactive)
  5045. (setq-local org-pretty-entities (not org-pretty-entities))
  5046. (org-restart-font-lock)
  5047. (if org-pretty-entities
  5048. (message "Entities are now displayed as UTF8 characters")
  5049. (save-restriction
  5050. (widen)
  5051. (decompose-region (point-min) (point-max))
  5052. (message "Entities are now displayed as plain text"))))
  5053. (defvar-local org-custom-properties-overlays nil
  5054. "List of overlays used for custom properties.")
  5055. (defun org-toggle-custom-properties-visibility ()
  5056. "Display or hide properties in `org-custom-properties'."
  5057. (interactive)
  5058. (if org-custom-properties-overlays
  5059. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5060. (setq org-custom-properties-overlays nil))
  5061. (when org-custom-properties
  5062. (org-with-wide-buffer
  5063. (goto-char (point-min))
  5064. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5065. (while (re-search-forward regexp nil t)
  5066. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5067. (when (and end (< (point) end))
  5068. ;; Hide first custom property in current drawer.
  5069. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5070. (overlay-put o 'invisible t)
  5071. (overlay-put o 'org-custom-property t)
  5072. (push o org-custom-properties-overlays))
  5073. ;; Hide additional custom properties in the same drawer.
  5074. (while (re-search-forward regexp end t)
  5075. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5076. (overlay-put o 'invisible t)
  5077. (overlay-put o 'org-custom-property t)
  5078. (push o org-custom-properties-overlays)))))
  5079. ;; Each entry is limited to a single property drawer.
  5080. (outline-next-heading)))))))
  5081. (defun org-fontify-entities (limit)
  5082. "Find an entity to fontify."
  5083. (let (ee)
  5084. (when org-pretty-entities
  5085. (catch 'match
  5086. ;; "\_ "-family is left out on purpose. Only the first one,
  5087. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5088. ;; confusing when adding a second white space character.
  5089. (while (re-search-forward
  5090. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5091. limit t)
  5092. (when (and (not (org-at-comment-p))
  5093. (setq ee (org-entity-get (match-string 1)))
  5094. (= (length (nth 6 ee)) 1))
  5095. (let* ((end (if (equal (match-string 2) "{}")
  5096. (match-end 2)
  5097. (match-end 1))))
  5098. (add-text-properties
  5099. (match-beginning 0) end
  5100. (list 'font-lock-fontified t))
  5101. (compose-region (match-beginning 0) end
  5102. (nth 6 ee) nil)
  5103. (backward-char 1)
  5104. (throw 'match t))))
  5105. nil))))
  5106. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5107. "Fontify string S like in Org mode."
  5108. (with-temp-buffer
  5109. (insert s)
  5110. (let ((org-odd-levels-only odd-levels))
  5111. (org-mode)
  5112. (org-font-lock-ensure)
  5113. (buffer-string))))
  5114. (defun org-get-level-face (n)
  5115. "Get the right face for match N in font-lock matching of headlines."
  5116. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5117. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5118. (org-f (if org-cycle-level-faces
  5119. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5120. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5121. (cond
  5122. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5123. ((eq n 2) org-f)
  5124. (t (unless org-level-color-stars-only org-f)))))
  5125. (defun org-face-from-face-or-color (context inherit face-or-color)
  5126. "Create a face list that inherits INHERIT, but sets the foreground color.
  5127. When FACE-OR-COLOR is not a string, just return it."
  5128. (if (stringp face-or-color)
  5129. (list :inherit inherit
  5130. (cdr (assoc context org-faces-easy-properties))
  5131. face-or-color)
  5132. face-or-color))
  5133. (defun org-get-todo-face (kwd)
  5134. "Get the right face for a TODO keyword KWD.
  5135. If KWD is a number, get the corresponding match group."
  5136. (when (numberp kwd) (setq kwd (match-string kwd)))
  5137. (or (org-face-from-face-or-color
  5138. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5139. (and (member kwd org-done-keywords) 'org-done)
  5140. 'org-todo))
  5141. (defun org-get-priority-face (priority)
  5142. "Get the right face for PRIORITY.
  5143. PRIORITY is a character."
  5144. (or (org-face-from-face-or-color
  5145. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5146. 'org-priority))
  5147. (defun org-get-tag-face (tag)
  5148. "Get the right face for TAG.
  5149. If TAG is a number, get the corresponding match group."
  5150. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5151. (or (org-face-from-face-or-color
  5152. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5153. 'org-tag)))
  5154. (defvar org-priority-regexp) ; defined later in the file
  5155. (defun org-font-lock-add-priority-faces (limit)
  5156. "Add the special priority faces."
  5157. (while (re-search-forward org-priority-regexp limit t)
  5158. (let ((beg (match-beginning 1))
  5159. (end (1+ (match-end 2))))
  5160. (add-face-text-property
  5161. beg end
  5162. (org-get-priority-face (string-to-char (match-string 2))))
  5163. (add-text-properties
  5164. beg end
  5165. (list 'font-lock-fontified t)))))
  5166. (defun org-font-lock-add-tag-faces (limit)
  5167. "Add the special tag faces."
  5168. (when (and org-tag-faces org-tags-special-faces-re)
  5169. (while (re-search-forward org-tags-special-faces-re limit t)
  5170. (add-face-text-property
  5171. (match-beginning 1)
  5172. (match-end 1)
  5173. (org-get-tag-face 1))
  5174. (add-text-properties (match-beginning 1) (match-end 1)
  5175. (list 'font-lock-fontified t))
  5176. (backward-char 1))))
  5177. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5178. "Remove fontification and activation overlays from links."
  5179. (font-lock-default-unfontify-region beg end)
  5180. (let* ((buffer-undo-list t)
  5181. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5182. (inhibit-modification-hooks t)
  5183. deactivate-mark buffer-file-name buffer-file-truename)
  5184. (decompose-region beg end)
  5185. (remove-text-properties beg end
  5186. '(mouse-face t keymap t org-linked-text t
  5187. invisible t intangible t
  5188. org-emphasis t))
  5189. (org-remove-font-lock-display-properties beg end)))
  5190. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5191. ((raise 0.3) (height 0.7))
  5192. ((raise -0.5))
  5193. ((raise 0.5)))
  5194. "Display properties for showing superscripts and subscripts.")
  5195. (defun org-remove-font-lock-display-properties (beg end)
  5196. "Remove specific display properties that have been added by font lock.
  5197. The will remove the raise properties that are used to show superscripts
  5198. and subscripts."
  5199. (let (next prop)
  5200. (while (< beg end)
  5201. (setq next (next-single-property-change beg 'display nil end)
  5202. prop (get-text-property beg 'display))
  5203. (when (member prop org-script-display)
  5204. (put-text-property beg next 'display nil))
  5205. (setq beg next))))
  5206. (defun org-raise-scripts (limit)
  5207. "Add raise properties to sub/superscripts."
  5208. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5209. (re-search-forward
  5210. (if (eq org-use-sub-superscripts t)
  5211. org-match-substring-regexp
  5212. org-match-substring-with-braces-regexp)
  5213. limit t))
  5214. (let* ((pos (point)) table-p comment-p
  5215. (mpos (match-beginning 3))
  5216. (emph-p (get-text-property mpos 'org-emphasis))
  5217. (link-p (get-text-property mpos 'mouse-face))
  5218. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5219. (goto-char (point-at-bol))
  5220. (setq table-p (looking-at-p org-table-dataline-regexp)
  5221. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5222. (goto-char pos)
  5223. ;; Handle a_b^c
  5224. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5225. (unless (or comment-p emph-p link-p keyw-p)
  5226. (put-text-property (match-beginning 3) (match-end 0)
  5227. 'display
  5228. (if (equal (char-after (match-beginning 2)) ?^)
  5229. (nth (if table-p 3 1) org-script-display)
  5230. (nth (if table-p 2 0) org-script-display)))
  5231. (add-text-properties (match-beginning 2) (match-end 2)
  5232. (list 'invisible t))
  5233. (when (and (eq (char-after (match-beginning 3)) ?{)
  5234. (eq (char-before (match-end 3)) ?}))
  5235. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5236. (list 'invisible t))
  5237. (add-text-properties (1- (match-end 3)) (match-end 3)
  5238. (list 'invisible t))))
  5239. t)))
  5240. (defun org-remove-empty-overlays-at (pos)
  5241. "Remove outline overlays that do not contain non-white stuff."
  5242. (dolist (o (overlays-at pos))
  5243. (and (eq 'outline (overlay-get o 'invisible))
  5244. (not (string-match-p "\\S-" (buffer-substring (overlay-start o)
  5245. (overlay-end o))))
  5246. (delete-overlay o))))
  5247. (defun org-show-empty-lines-in-parent ()
  5248. "Move to the parent and re-show empty lines before visible headlines."
  5249. (save-excursion
  5250. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5251. (org-cycle-show-empty-lines context))))
  5252. (defun org-files-list ()
  5253. "Return `org-agenda-files' list, plus all open Org files.
  5254. This is useful for operations that need to scan all of a user's
  5255. open and agenda-wise Org files."
  5256. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5257. (dolist (buf (buffer-list))
  5258. (with-current-buffer buf
  5259. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5260. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5261. :test #'equal))))
  5262. files))
  5263. (defsubst org-entry-beginning-position ()
  5264. "Return the beginning position of the current entry."
  5265. (save-excursion (org-back-to-heading t) (point)))
  5266. (defsubst org-entry-end-position ()
  5267. "Return the end position of the current entry."
  5268. (save-excursion (outline-next-heading) (point)))
  5269. (defun org-subtree-end-visible-p ()
  5270. "Is the end of the current subtree visible?"
  5271. (pos-visible-in-window-p
  5272. (save-excursion (org-end-of-subtree t) (point))))
  5273. (defun org-first-headline-recenter ()
  5274. "Move cursor to the first headline and recenter the headline."
  5275. (let ((window (get-buffer-window)))
  5276. (when window
  5277. (goto-char (point-min))
  5278. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5279. (set-window-start window (line-beginning-position))))))
  5280. ;;; Visibility (headlines, blocks, drawers)
  5281. ;;;; Headlines visibility
  5282. (defun org-show-entry ()
  5283. "Show the body directly following its heading.
  5284. Show the heading too, if it is currently invisible."
  5285. (interactive)
  5286. (save-excursion
  5287. (org-back-to-heading-or-point-min t)
  5288. (org-flag-region
  5289. (line-end-position 0)
  5290. (save-excursion
  5291. (if (re-search-forward
  5292. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5293. (match-beginning 1)
  5294. (point-max)))
  5295. nil
  5296. 'outline)
  5297. (org-cycle-hide-drawers 'children)))
  5298. (defun org-hide-entry ()
  5299. "Hide the body directly following its heading."
  5300. (interactive)
  5301. (save-excursion
  5302. (org-back-to-heading-or-point-min t)
  5303. (when (org-at-heading-p) (forward-line))
  5304. (org-flag-region
  5305. (line-end-position 0)
  5306. (save-excursion
  5307. (if (re-search-forward
  5308. (concat "[\r\n]" org-outline-regexp) nil t)
  5309. (line-end-position 0)
  5310. (point-max)))
  5311. t
  5312. 'outline)))
  5313. (defun org-show-children (&optional level)
  5314. "Show all direct subheadings of this heading.
  5315. Prefix arg LEVEL is how many levels below the current level
  5316. should be shown. Default is enough to cause the following
  5317. heading to appear."
  5318. (interactive "p")
  5319. (unless (org-before-first-heading-p)
  5320. (save-excursion
  5321. (org-with-limited-levels (org-back-to-heading t))
  5322. (let* ((current-level (funcall outline-level))
  5323. (max-level (org-get-valid-level
  5324. current-level
  5325. (if level (prefix-numeric-value level) 1)))
  5326. (end (save-excursion (org-end-of-subtree t t)))
  5327. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5328. (past-first-child nil)
  5329. ;; Make sure to skip inlinetasks.
  5330. (re (format regexp-fmt
  5331. current-level
  5332. (cond
  5333. ((not (featurep 'org-inlinetask)) "")
  5334. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5335. 3))
  5336. (t (1- org-inlinetask-min-level))))))
  5337. ;; Display parent heading.
  5338. (org-flag-heading nil)
  5339. (forward-line)
  5340. ;; Display children. First child may be deeper than expected
  5341. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5342. ;; MAX-LEVEL accordingly.
  5343. (while (re-search-forward re end t)
  5344. (unless past-first-child
  5345. (setq re (format regexp-fmt
  5346. current-level
  5347. (max (funcall outline-level) max-level)))
  5348. (setq past-first-child t))
  5349. (org-flag-heading nil))))))
  5350. (defun org-show-subtree ()
  5351. "Show everything after this heading at deeper levels."
  5352. (interactive)
  5353. (org-flag-region
  5354. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5355. ;;;; Blocks and drawers visibility
  5356. (defun org--hide-wrapper-toggle (element category force no-error)
  5357. "Toggle visibility for ELEMENT.
  5358. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5359. either `block' or `drawer'. When FORCE is `off', show the block
  5360. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5361. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5362. Return a non-nil value when toggling is successful."
  5363. (let ((type (org-element-type element)))
  5364. (cond
  5365. ((memq type
  5366. (pcase category
  5367. (`drawer '(drawer property-drawer))
  5368. (`block '(center-block
  5369. comment-block dynamic-block example-block export-block
  5370. quote-block special-block src-block verse-block))
  5371. (_ (error "Unknown category: %S" category))))
  5372. (let* ((post (org-element-property :post-affiliated element))
  5373. (start (save-excursion
  5374. (goto-char post)
  5375. (line-end-position)))
  5376. (end (save-excursion
  5377. (goto-char (org-element-property :end element))
  5378. (skip-chars-backward " \t\n")
  5379. (line-end-position))))
  5380. ;; Do nothing when not before or at the block opening line or
  5381. ;; at the block closing line.
  5382. (unless (let ((eol (line-end-position)))
  5383. (and (> eol start) (/= eol end)))
  5384. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5385. (flag
  5386. (cond ((eq force 'off) nil)
  5387. (force t)
  5388. ((eq spec (get-char-property start 'invisible)) nil)
  5389. (t t))))
  5390. (org-flag-region start end flag spec))
  5391. ;; When the block is hidden away, make sure point is left in
  5392. ;; a visible part of the buffer.
  5393. (when (invisible-p (max (1- (point)) (point-min)))
  5394. (goto-char post))
  5395. ;; Signal success.
  5396. t)))
  5397. (no-error nil)
  5398. (t
  5399. (user-error (if (eq category 'drawer)
  5400. "Not at a drawer"
  5401. "Not at a block"))))))
  5402. (defun org-hide-block-toggle (&optional force no-error element)
  5403. "Toggle the visibility of the current block.
  5404. When optional argument FORCE is `off', make block visible. If it
  5405. is non-nil, hide it unconditionally. Throw an error when not at
  5406. a block, unless NO-ERROR is non-nil. When optional argument
  5407. ELEMENT is provided, consider it instead of the current block.
  5408. Return a non-nil value when toggling is successful."
  5409. (interactive)
  5410. (org--hide-wrapper-toggle
  5411. (or element (org-element-at-point)) 'block force no-error))
  5412. (defun org-hide-drawer-toggle (&optional force no-error element)
  5413. "Toggle the visibility of the current drawer.
  5414. When optional argument FORCE is `off', make drawer visible. If
  5415. it is non-nil, hide it unconditionally. Throw an error when not
  5416. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5417. ELEMENT is provided, consider it instead of the current drawer.
  5418. Return a non-nil value when toggling is successful."
  5419. (interactive)
  5420. (org--hide-wrapper-toggle
  5421. (or element (org-element-at-point)) 'drawer force no-error))
  5422. (defun org-hide-block-all ()
  5423. "Fold all blocks in the current buffer."
  5424. (interactive)
  5425. (org-show-all '(blocks))
  5426. (org-block-map 'org-hide-block-toggle))
  5427. (defun org-hide-drawer-all ()
  5428. "Fold all drawers in the current buffer."
  5429. (let ((begin (point-min))
  5430. (end (point-max)))
  5431. (org--hide-drawers begin end)))
  5432. (defun org-cycle-hide-drawers (state)
  5433. "Re-hide all drawers after a visibility state change.
  5434. STATE should be one of the symbols listed in the docstring of
  5435. `org-cycle-hook'."
  5436. (when (derived-mode-p 'org-mode)
  5437. (cond ((not (memq state '(overview folded contents)))
  5438. (let* ((global? (eq state 'all))
  5439. (beg (if global? (point-min) (line-beginning-position)))
  5440. (end (cond (global? (point-max))
  5441. ((eq state 'children) (org-entry-end-position))
  5442. (t (save-excursion (org-end-of-subtree t t))))))
  5443. (org--hide-drawers beg end)))
  5444. ((memq state '(overview contents))
  5445. ;; Hide drawers before first heading.
  5446. (let ((beg (point-min))
  5447. (end (save-excursion
  5448. (goto-char (point-min))
  5449. (if (org-before-first-heading-p)
  5450. (org-entry-end-position)
  5451. (point-min)))))
  5452. (when (< beg end)
  5453. (org--hide-drawers beg end)))))))
  5454. (defun org--hide-drawers (begin end)
  5455. "Hide all drawers between BEGIN and END."
  5456. (save-excursion
  5457. (goto-char begin)
  5458. (while (re-search-forward org-drawer-regexp end t)
  5459. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5460. 'invisible))
  5461. (o (cdr-safe pair)))
  5462. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5463. (pcase (get-char-property-and-overlay (point) 'invisible)
  5464. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5465. (_
  5466. (let* ((drawer (org-element-at-point))
  5467. (type (org-element-type drawer)))
  5468. (when (memq type '(drawer property-drawer))
  5469. (org-hide-drawer-toggle t nil drawer)
  5470. ;; Make sure to skip drawer entirely or we might flag it
  5471. ;; another time when matching its ending line with
  5472. ;; `org-drawer-regexp'.
  5473. (goto-char (org-element-property :end drawer)))))))))))
  5474. ;;;; Visibility cycling
  5475. (defvar-local org-cycle-global-status nil)
  5476. (put 'org-cycle-global-status 'org-state t)
  5477. (defvar-local org-cycle-subtree-status nil)
  5478. (put 'org-cycle-subtree-status 'org-state t)
  5479. (defun org-show-all (&optional types)
  5480. "Show all contents in the visible part of the buffer.
  5481. By default, the function expands headings, blocks and drawers.
  5482. When optional argument TYPE is a list of symbols among `blocks',
  5483. `drawers' and `headings', to only expand one specific type."
  5484. (interactive)
  5485. (let ((types (or types '(blocks drawers headings))))
  5486. (when (memq 'blocks types)
  5487. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5488. (cond
  5489. ;; Fast path. Since headings and drawers share the same
  5490. ;; invisible spec, clear everything in one go.
  5491. ((and (memq 'headings types)
  5492. (memq 'drawers types))
  5493. (org-flag-region (point-min) (point-max) nil 'outline))
  5494. ((memq 'headings types)
  5495. (org-flag-region (point-min) (point-max) nil 'outline)
  5496. (org-cycle-hide-drawers 'all))
  5497. ((memq 'drawers types)
  5498. (save-excursion
  5499. (goto-char (point-min))
  5500. (while (re-search-forward org-drawer-regexp nil t)
  5501. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5502. 'invisible))
  5503. (o (cdr-safe pair)))
  5504. (if (overlayp o) (goto-char (overlay-end o))
  5505. (pcase (get-char-property-and-overlay (point) 'invisible)
  5506. (`(outline . ,o)
  5507. (goto-char (overlay-end o))
  5508. (delete-overlay o))
  5509. (_ nil))))))))))
  5510. ;;;###autoload
  5511. (defun org-cycle (&optional arg)
  5512. "TAB-action and visibility cycling for Org mode.
  5513. This is the command invoked in Org mode by the `TAB' key. Its main
  5514. purpose is outline visibility cycling, but it also invokes other actions
  5515. in special contexts.
  5516. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5517. the entire
  5518. buffer through 3 states (global cycling)
  5519. 1. OVERVIEW: Show only top-level headlines.
  5520. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5521. 3. SHOW ALL: Show everything.
  5522. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5523. switch to the startup visibility,
  5524. determined by the variable `org-startup-folded', and by any VISIBILITY
  5525. properties in the buffer.
  5526. With a `\\[universal-argument] \\[universal-argument] \
  5527. \\[universal-argument]' prefix argument, show the entire buffer, including
  5528. any drawers.
  5529. When inside a table, re-align the table and move to the next field.
  5530. When point is at the beginning of a headline, rotate the subtree started
  5531. by this line through 3 different states (local cycling)
  5532. 1. FOLDED: Only the main headline is shown.
  5533. 2. CHILDREN: The main headline and the direct children are shown.
  5534. From this state, you can move to one of the children
  5535. and zoom in further.
  5536. 3. SUBTREE: Show the entire subtree, including body text.
  5537. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5538. When point is at the beginning of an empty headline and the variable
  5539. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5540. of the headline by demoting and promoting it to likely levels. This
  5541. speeds up creation document structure by pressing `TAB' once or several
  5542. times right after creating a new headline.
  5543. When there is a numeric prefix, go up to a heading with level ARG, do
  5544. a `show-subtree' and return to the previous cursor position. If ARG
  5545. is negative, go up that many levels.
  5546. When point is not at the beginning of a headline, execute the global
  5547. binding for `TAB', which is re-indenting the line. See the option
  5548. `org-cycle-emulate-tab' for details.
  5549. As a special case, if point is at the very beginning of the buffer, if
  5550. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5551. is non-nil, this function acts as if called with prefix argument \
  5552. \(`\\[universal-argument] TAB',
  5553. same as `S-TAB') also when called without prefix argument."
  5554. (interactive "P")
  5555. (org-load-modules-maybe)
  5556. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5557. (and org-cycle-level-after-item/entry-creation
  5558. (or (org-cycle-level)
  5559. (org-cycle-item-indentation))))
  5560. (let* ((limit-level
  5561. (or org-cycle-max-level
  5562. (and (boundp 'org-inlinetask-min-level)
  5563. org-inlinetask-min-level
  5564. (1- org-inlinetask-min-level))))
  5565. (nstars
  5566. (and limit-level
  5567. (if org-odd-levels-only
  5568. (1- (* 2 limit-level))
  5569. limit-level)))
  5570. (org-outline-regexp
  5571. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5572. (cond
  5573. ((equal arg '(16))
  5574. (setq last-command 'dummy)
  5575. (org-set-startup-visibility)
  5576. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5577. ((equal arg '(64))
  5578. (org-show-all)
  5579. (org-unlogged-message "Entire buffer visible, including drawers"))
  5580. ((equal arg '(4)) (org-cycle-internal-global))
  5581. ;; Show-subtree, ARG levels up from here.
  5582. ((integerp arg)
  5583. (save-excursion
  5584. (org-back-to-heading)
  5585. (outline-up-heading (if (< arg 0) (- arg)
  5586. (- (funcall outline-level) arg)))
  5587. (org-show-subtree)))
  5588. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5589. ((and org-cycle-global-at-bob
  5590. (bobp)
  5591. (not (looking-at org-outline-regexp)))
  5592. (let ((org-cycle-hook
  5593. (remq 'org-optimize-window-after-visibility-change
  5594. org-cycle-hook)))
  5595. (org-cycle-internal-global)))
  5596. ;; Try CDLaTeX TAB completion.
  5597. ((org-try-cdlatex-tab))
  5598. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5599. ((and (featurep 'org-inlinetask)
  5600. (org-inlinetask-at-task-p)
  5601. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5602. (org-inlinetask-toggle-visibility))
  5603. (t
  5604. (let ((pos (point))
  5605. (element (org-element-at-point)))
  5606. (cond
  5607. ;; Try toggling visibility for block at point.
  5608. ((org-hide-block-toggle nil t element))
  5609. ;; Try toggling visibility for drawer at point.
  5610. ((org-hide-drawer-toggle nil t element))
  5611. ;; Table: enter it or move to the next field.
  5612. ((and (org-match-line "[ \t]*[|+]")
  5613. (org-element-lineage element '(table) t))
  5614. (if (and (eq 'table (org-element-type element))
  5615. (eq 'table.el (org-element-property :type element)))
  5616. (message (substitute-command-keys "\\<org-mode-map>\
  5617. Use `\\[org-edit-special]' to edit table.el tables"))
  5618. (org-table-justify-field-maybe)
  5619. (call-interactively #'org-table-next-field)))
  5620. ((run-hook-with-args-until-success
  5621. 'org-tab-after-check-for-table-hook))
  5622. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5623. ((and (or (and org-cycle-include-plain-lists
  5624. (let ((item (org-element-lineage element
  5625. '(item plain-list)
  5626. t)))
  5627. (and item
  5628. (= (line-beginning-position)
  5629. (org-element-property :post-affiliated
  5630. item)))))
  5631. (org-match-line org-outline-regexp))
  5632. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5633. (org-cycle-internal-local))
  5634. ;; From there: TAB emulation and template completion.
  5635. (buffer-read-only (org-back-to-heading))
  5636. ((run-hook-with-args-until-success
  5637. 'org-tab-after-check-for-cycling-hook))
  5638. ((run-hook-with-args-until-success
  5639. 'org-tab-before-tab-emulation-hook))
  5640. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5641. (or (not (bolp))
  5642. (not (looking-at org-outline-regexp))))
  5643. (call-interactively (global-key-binding (kbd "TAB"))))
  5644. ((or (eq org-cycle-emulate-tab t)
  5645. (and (memq org-cycle-emulate-tab '(white whitestart))
  5646. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5647. (or (and (eq org-cycle-emulate-tab 'white)
  5648. (= (match-end 0) (point-at-eol)))
  5649. (and (eq org-cycle-emulate-tab 'whitestart)
  5650. (>= (match-end 0) pos)))))
  5651. (call-interactively (global-key-binding (kbd "TAB"))))
  5652. (t
  5653. (save-excursion
  5654. (org-back-to-heading)
  5655. (org-cycle))))))))))
  5656. (defun org-cycle-internal-global ()
  5657. "Do the global cycling action."
  5658. ;; Hack to avoid display of messages for .org attachments in Gnus
  5659. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5660. (cond
  5661. ((and (eq last-command this-command)
  5662. (eq org-cycle-global-status 'overview))
  5663. ;; We just created the overview - now do table of contents
  5664. ;; This can be slow in very large buffers, so indicate action
  5665. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5666. (unless ga (org-unlogged-message "CONTENTS..."))
  5667. (org-content)
  5668. (unless ga (org-unlogged-message "CONTENTS...done"))
  5669. (setq org-cycle-global-status 'contents)
  5670. (run-hook-with-args 'org-cycle-hook 'contents))
  5671. ((and (eq last-command this-command)
  5672. (eq org-cycle-global-status 'contents))
  5673. ;; We just showed the table of contents - now show everything
  5674. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5675. (org-show-all '(headings blocks))
  5676. (unless ga (org-unlogged-message "SHOW ALL"))
  5677. (setq org-cycle-global-status 'all)
  5678. (run-hook-with-args 'org-cycle-hook 'all))
  5679. (t
  5680. ;; Default action: go to overview
  5681. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5682. (org-overview)
  5683. (unless ga (org-unlogged-message "OVERVIEW"))
  5684. (setq org-cycle-global-status 'overview)
  5685. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5686. (defvar org-called-with-limited-levels nil
  5687. "Non-nil when `org-with-limited-levels' is currently active.")
  5688. (defun org-cycle-internal-local ()
  5689. "Do the local cycling action."
  5690. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5691. ;; First, determine end of headline (EOH), end of subtree or item
  5692. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5693. (save-excursion
  5694. (if (org-at-item-p)
  5695. (progn
  5696. (beginning-of-line)
  5697. (setq struct (org-list-struct))
  5698. (setq eoh (point-at-eol))
  5699. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5700. (setq has-children (org-list-has-child-p (point) struct)))
  5701. (org-back-to-heading)
  5702. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5703. (setq eos (save-excursion
  5704. (org-end-of-subtree t t)
  5705. (unless (eobp) (forward-char -1))
  5706. (point)))
  5707. (setq has-children
  5708. (or
  5709. (save-excursion
  5710. (let ((level (funcall outline-level)))
  5711. (outline-next-heading)
  5712. (and (org-at-heading-p t)
  5713. (> (funcall outline-level) level))))
  5714. (and (eq org-cycle-include-plain-lists 'integrate)
  5715. (save-excursion
  5716. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5717. ;; Determine end invisible part of buffer (EOL)
  5718. (beginning-of-line 2)
  5719. (while (and (not (eobp)) ;this is like `next-line'
  5720. (get-char-property (1- (point)) 'invisible))
  5721. (goto-char (next-single-char-property-change (point) 'invisible))
  5722. (and (eolp) (beginning-of-line 2)))
  5723. (setq eol (point)))
  5724. ;; Find out what to do next and set `this-command'
  5725. (cond
  5726. ((= eos eoh)
  5727. ;; Nothing is hidden behind this heading
  5728. (unless (org-before-first-heading-p)
  5729. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5730. (org-unlogged-message "EMPTY ENTRY")
  5731. (setq org-cycle-subtree-status nil)
  5732. (save-excursion
  5733. (goto-char eos)
  5734. (outline-next-heading)
  5735. (when (org-invisible-p) (org-flag-heading nil))))
  5736. ((and (or (>= eol eos)
  5737. (not (string-match "\\S-" (buffer-substring eol eos))))
  5738. (or has-children
  5739. (not (setq children-skipped
  5740. org-cycle-skip-children-state-if-no-children))))
  5741. ;; Entire subtree is hidden in one line: children view
  5742. (unless (org-before-first-heading-p)
  5743. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5744. (if (org-at-item-p)
  5745. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5746. (org-show-entry)
  5747. (org-with-limited-levels (org-show-children))
  5748. (org-show-set-visibility 'canonical)
  5749. ;; Fold every list in subtree to top-level items.
  5750. (when (eq org-cycle-include-plain-lists 'integrate)
  5751. (save-excursion
  5752. (org-back-to-heading)
  5753. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5754. (beginning-of-line 1)
  5755. (let* ((struct (org-list-struct))
  5756. (prevs (org-list-prevs-alist struct))
  5757. (end (org-list-get-bottom-point struct)))
  5758. (dolist (e (org-list-get-all-items (point) struct prevs))
  5759. (org-list-set-item-visibility e struct 'folded))
  5760. (goto-char (if (< end eos) end eos)))))))
  5761. (org-unlogged-message "CHILDREN")
  5762. (save-excursion
  5763. (goto-char eos)
  5764. (outline-next-heading)
  5765. (when (org-invisible-p) (org-flag-heading nil)))
  5766. (setq org-cycle-subtree-status 'children)
  5767. (unless (org-before-first-heading-p)
  5768. (run-hook-with-args 'org-cycle-hook 'children)))
  5769. ((or children-skipped
  5770. (and (eq last-command this-command)
  5771. (eq org-cycle-subtree-status 'children)))
  5772. ;; We just showed the children, or no children are there,
  5773. ;; now show everything.
  5774. (unless (org-before-first-heading-p)
  5775. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5776. (org-flag-region eoh eos nil 'outline)
  5777. (org-unlogged-message
  5778. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5779. (setq org-cycle-subtree-status 'subtree)
  5780. (unless (org-before-first-heading-p)
  5781. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5782. (t
  5783. ;; Default action: hide the subtree.
  5784. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5785. (org-flag-region eoh eos t 'outline)
  5786. (org-unlogged-message "FOLDED")
  5787. (setq org-cycle-subtree-status 'folded)
  5788. (unless (org-before-first-heading-p)
  5789. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5790. ;;;###autoload
  5791. (defun org-global-cycle (&optional arg)
  5792. "Cycle the global visibility. For details see `org-cycle'.
  5793. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5794. With a numeric prefix, show all headlines up to that level."
  5795. (interactive "P")
  5796. (cond
  5797. ((integerp arg)
  5798. (org-content arg)
  5799. (setq org-cycle-global-status 'contents))
  5800. ((equal arg '(4))
  5801. (org-set-startup-visibility)
  5802. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5803. (t
  5804. (org-cycle '(4)))))
  5805. (defun org-set-startup-visibility ()
  5806. "Set the visibility required by startup options and properties."
  5807. (cond
  5808. ((eq org-startup-folded t)
  5809. (org-overview))
  5810. ((eq org-startup-folded 'content)
  5811. (org-content))
  5812. ((eq org-startup-folded 'show2levels)
  5813. (org-content 2))
  5814. ((eq org-startup-folded 'show3levels)
  5815. (org-content 3))
  5816. ((eq org-startup-folded 'show4levels)
  5817. (org-content 4))
  5818. ((eq org-startup-folded 'show5levels)
  5819. (org-content 5))
  5820. ((or (eq org-startup-folded 'showeverything)
  5821. (eq org-startup-folded nil))
  5822. (org-show-all)))
  5823. (unless (eq org-startup-folded 'showeverything)
  5824. (when org-hide-block-startup (org-hide-block-all))
  5825. (org-set-visibility-according-to-property)
  5826. (org-cycle-hide-archived-subtrees 'all)
  5827. (org-cycle-hide-drawers 'all)
  5828. (org-cycle-show-empty-lines t)))
  5829. (defun org-set-visibility-according-to-property ()
  5830. "Switch subtree visibility according to VISIBILITY property."
  5831. (interactive)
  5832. (let ((regexp (org-re-property "VISIBILITY")))
  5833. (org-with-point-at 1
  5834. (while (re-search-forward regexp nil t)
  5835. (let ((state (match-string 3)))
  5836. (if (not (org-at-property-p)) (outline-next-heading)
  5837. (save-excursion
  5838. (org-back-to-heading t)
  5839. (org-flag-subtree t)
  5840. (org-reveal)
  5841. (pcase state
  5842. ("folded"
  5843. (org-flag-subtree t))
  5844. ("children"
  5845. (org-show-hidden-entry)
  5846. (org-show-children))
  5847. ("content"
  5848. (save-excursion
  5849. (save-restriction
  5850. (org-narrow-to-subtree)
  5851. (org-content))))
  5852. ((or "all" "showall")
  5853. (outline-show-subtree))
  5854. (_ nil)))
  5855. (org-end-of-subtree)))))))
  5856. (defun org-overview ()
  5857. "Switch to overview mode, showing only top-level headlines."
  5858. (interactive)
  5859. (org-show-all '(headings drawers))
  5860. (save-excursion
  5861. (goto-char (point-min))
  5862. (when (re-search-forward org-outline-regexp-bol nil t)
  5863. (let* ((last (line-end-position))
  5864. (level (- (match-end 0) (match-beginning 0) 1))
  5865. (regexp (format "^\\*\\{1,%d\\} " level)))
  5866. (while (re-search-forward regexp nil :move)
  5867. (org-flag-region last (line-end-position 0) t 'outline)
  5868. (setq last (line-end-position))
  5869. (setq level (- (match-end 0) (match-beginning 0) 1))
  5870. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5871. (org-flag-region last (point) t 'outline)))))
  5872. (defun org-content (&optional arg)
  5873. "Show all headlines in the buffer, like a table of contents.
  5874. With numerical argument N, show content up to level N."
  5875. (interactive "p")
  5876. (org-show-all '(headings drawers))
  5877. (save-excursion
  5878. (goto-char (point-max))
  5879. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5880. (format "^\\*\\{1,%d\\} " arg)
  5881. "^\\*+ "))
  5882. (last (point)))
  5883. (while (re-search-backward regexp nil t)
  5884. (org-flag-region (line-end-position) last t 'outline)
  5885. (setq last (line-end-position 0))))))
  5886. (defvar org-scroll-position-to-restore nil
  5887. "Temporarily store scroll position to restore.")
  5888. (defun org-optimize-window-after-visibility-change (state)
  5889. "Adjust the window after a change in outline visibility.
  5890. This function is the default value of the hook `org-cycle-hook'."
  5891. (when (get-buffer-window (current-buffer))
  5892. (let ((repeat (eq last-command this-command)))
  5893. (unless repeat
  5894. (setq org-scroll-position-to-restore nil))
  5895. (cond
  5896. ((eq state 'content) nil)
  5897. ((eq state 'all) nil)
  5898. ((and org-scroll-position-to-restore repeat
  5899. (eq state 'folded))
  5900. (set-window-start nil org-scroll-position-to-restore))
  5901. ((eq state 'folded) nil)
  5902. ((eq state 'children)
  5903. (setq org-scroll-position-to-restore (window-start))
  5904. (or (org-subtree-end-visible-p) (recenter 1)))
  5905. ((eq state 'subtree)
  5906. (unless repeat
  5907. (setq org-scroll-position-to-restore (window-start)))
  5908. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5909. (defun org-clean-visibility-after-subtree-move ()
  5910. "Fix visibility issues after moving a subtree."
  5911. ;; First, find a reasonable region to look at:
  5912. ;; Start two siblings above, end three below
  5913. (let* ((beg (save-excursion
  5914. (and (org-get-last-sibling)
  5915. (org-get-last-sibling))
  5916. (point)))
  5917. (end (save-excursion
  5918. (and (org-get-next-sibling)
  5919. (org-get-next-sibling)
  5920. (org-get-next-sibling))
  5921. (if (org-at-heading-p)
  5922. (point-at-eol)
  5923. (point))))
  5924. (level (looking-at "\\*+"))
  5925. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5926. (save-excursion
  5927. (save-restriction
  5928. (narrow-to-region beg end)
  5929. (when re
  5930. ;; Properly fold already folded siblings
  5931. (goto-char (point-min))
  5932. (while (re-search-forward re nil t)
  5933. (when (and (not (org-invisible-p))
  5934. (org-invisible-p (line-end-position)))
  5935. (outline-hide-entry))))
  5936. (org-cycle-hide-drawers 'all)
  5937. (org-cycle-show-empty-lines 'overview)))))
  5938. (defun org-cycle-show-empty-lines (state)
  5939. "Show empty lines above all visible headlines.
  5940. The region to be covered depends on STATE when called through
  5941. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5942. entire buffer covered. Note that an empty line is only shown if there
  5943. are at least `org-cycle-separator-lines' empty lines before the headline."
  5944. (when (/= org-cycle-separator-lines 0)
  5945. (save-excursion
  5946. (let* ((n (abs org-cycle-separator-lines))
  5947. (re (cond
  5948. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5949. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5950. (t (let ((ns (number-to-string (- n 2))))
  5951. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5952. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5953. beg end)
  5954. (cond
  5955. ((memq state '(overview contents t))
  5956. (setq beg (point-min) end (point-max)))
  5957. ((memq state '(children folded))
  5958. (setq beg (point)
  5959. end (progn (org-end-of-subtree t t)
  5960. (line-beginning-position 2)))))
  5961. (when beg
  5962. (goto-char beg)
  5963. (while (re-search-forward re end t)
  5964. (unless (get-char-property (match-end 1) 'invisible)
  5965. (let ((e (match-end 1))
  5966. (b (if (>= org-cycle-separator-lines 0)
  5967. (match-beginning 1)
  5968. (save-excursion
  5969. (goto-char (match-beginning 0))
  5970. (skip-chars-backward " \t\n")
  5971. (line-end-position)))))
  5972. (org-flag-region b e nil 'outline))))))))
  5973. ;; Never hide empty lines at the end of the file.
  5974. (save-excursion
  5975. (goto-char (point-max))
  5976. (outline-previous-heading)
  5977. (outline-end-of-heading)
  5978. (when (and (looking-at "[ \t\n]+")
  5979. (= (match-end 0) (point-max)))
  5980. (org-flag-region (point) (match-end 0) nil 'outline))))
  5981. ;;;; Reveal point location
  5982. (defun org-show-context (&optional key)
  5983. "Make sure point and context are visible.
  5984. Optional argument KEY, when non-nil, is a symbol. See
  5985. `org-show-context-detail' for allowed values and how much is to
  5986. be shown."
  5987. (org-show-set-visibility
  5988. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5989. ((cdr (assq key org-show-context-detail)))
  5990. (t (cdr (assq 'default org-show-context-detail))))))
  5991. (defun org-show-set-visibility (detail)
  5992. "Set visibility around point according to DETAIL.
  5993. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5994. `tree', `canonical' or t. See `org-show-context-detail' for more
  5995. information."
  5996. ;; Show current heading and possibly its entry, following headline
  5997. ;; or all children.
  5998. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5999. (org-flag-heading nil)
  6000. (org-show-entry)
  6001. ;; If point is hidden within a drawer or a block, make sure to
  6002. ;; expose it.
  6003. (dolist (o (overlays-at (point)))
  6004. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6005. (delete-overlay o)))
  6006. (unless (org-before-first-heading-p)
  6007. (org-with-limited-levels
  6008. (cl-case detail
  6009. ((tree canonical t) (org-show-children))
  6010. ((nil minimal ancestors))
  6011. (t (save-excursion
  6012. (outline-next-heading)
  6013. (org-flag-heading nil)))))))
  6014. ;; Show all siblings.
  6015. (when (eq detail 'lineage) (org-show-siblings))
  6016. ;; Show ancestors, possibly with their children.
  6017. (when (memq detail '(ancestors lineage tree canonical t))
  6018. (save-excursion
  6019. (while (org-up-heading-safe)
  6020. (org-flag-heading nil)
  6021. (when (memq detail '(canonical t)) (org-show-entry))
  6022. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6023. (defvar org-reveal-start-hook nil
  6024. "Hook run before revealing a location.")
  6025. (defun org-reveal (&optional siblings)
  6026. "Show current entry, hierarchy above it, and the following headline.
  6027. This can be used to show a consistent set of context around
  6028. locations exposed with `org-show-context'.
  6029. With optional argument SIBLINGS, on each level of the hierarchy all
  6030. siblings are shown. This repairs the tree structure to what it would
  6031. look like when opened with hierarchical calls to `org-cycle'.
  6032. With a \\[universal-argument] \\[universal-argument] prefix, \
  6033. go to the parent and show the entire tree."
  6034. (interactive "P")
  6035. (run-hooks 'org-reveal-start-hook)
  6036. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6037. ((equal siblings '(16))
  6038. (save-excursion
  6039. (when (org-up-heading-safe)
  6040. (org-show-subtree)
  6041. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6042. (t (org-show-set-visibility 'lineage))))
  6043. ;;; Indirect buffer display of subtrees
  6044. (defvar org-indirect-dedicated-frame nil
  6045. "This is the frame being used for indirect tree display.")
  6046. (defvar org-last-indirect-buffer nil)
  6047. (defun org-tree-to-indirect-buffer (&optional arg)
  6048. "Create indirect buffer and narrow it to current subtree.
  6049. With a numerical prefix ARG, go up to this level and then take that tree.
  6050. If ARG is negative, go up that many levels.
  6051. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6052. indirect buffer previously made with this command, to avoid proliferation of
  6053. indirect buffers. However, when you call the command with a \
  6054. `\\[universal-argument]' prefix, or
  6055. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6056. so that you can work with several indirect buffers at the same time. If
  6057. `org-indirect-buffer-display' is `dedicated-frame', the \
  6058. `\\[universal-argument]' prefix also
  6059. requests that a new frame be made for the new buffer, so that the dedicated
  6060. frame is not changed."
  6061. (interactive "P")
  6062. (let ((cbuf (current-buffer))
  6063. (cwin (selected-window))
  6064. (pos (point))
  6065. beg end level heading ibuf)
  6066. (save-excursion
  6067. (org-back-to-heading t)
  6068. (when (numberp arg)
  6069. (setq level (org-outline-level))
  6070. (when (< arg 0) (setq arg (+ level arg)))
  6071. (while (> (setq level (org-outline-level)) arg)
  6072. (org-up-heading-safe)))
  6073. (setq beg (point)
  6074. heading (org-get-heading 'no-tags))
  6075. (org-end-of-subtree t t)
  6076. (when (org-at-heading-p) (backward-char 1))
  6077. (setq end (point)))
  6078. (when (and (buffer-live-p org-last-indirect-buffer)
  6079. (not (eq org-indirect-buffer-display 'new-frame))
  6080. (not arg))
  6081. (kill-buffer org-last-indirect-buffer))
  6082. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6083. org-last-indirect-buffer ibuf)
  6084. (cond
  6085. ((or (eq org-indirect-buffer-display 'new-frame)
  6086. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6087. (select-frame (make-frame))
  6088. (delete-other-windows)
  6089. (pop-to-buffer-same-window ibuf)
  6090. (org-set-frame-title heading))
  6091. ((eq org-indirect-buffer-display 'dedicated-frame)
  6092. (raise-frame
  6093. (select-frame (or (and org-indirect-dedicated-frame
  6094. (frame-live-p org-indirect-dedicated-frame)
  6095. org-indirect-dedicated-frame)
  6096. (setq org-indirect-dedicated-frame (make-frame)))))
  6097. (delete-other-windows)
  6098. (pop-to-buffer-same-window ibuf)
  6099. (org-set-frame-title (concat "Indirect: " heading)))
  6100. ((eq org-indirect-buffer-display 'current-window)
  6101. (pop-to-buffer-same-window ibuf))
  6102. ((eq org-indirect-buffer-display 'other-window)
  6103. (pop-to-buffer ibuf))
  6104. (t (error "Invalid value")))
  6105. (narrow-to-region beg end)
  6106. (org-show-all '(headings drawers blocks))
  6107. (goto-char pos)
  6108. (run-hook-with-args 'org-cycle-hook 'all)
  6109. (and (window-live-p cwin) (select-window cwin))))
  6110. (defun org-get-indirect-buffer (&optional buffer heading)
  6111. (setq buffer (or buffer (current-buffer)))
  6112. (let ((n 1) (base (buffer-name buffer)) bname)
  6113. (while (buffer-live-p
  6114. (get-buffer
  6115. (setq bname
  6116. (concat base "-"
  6117. (if heading (concat heading "-" (number-to-string n))
  6118. (number-to-string n))))))
  6119. (setq n (1+ n)))
  6120. (condition-case nil
  6121. (make-indirect-buffer buffer bname 'clone)
  6122. (error (make-indirect-buffer buffer bname)))))
  6123. (defun org-set-frame-title (title)
  6124. "Set the title of the current frame to the string TITLE."
  6125. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6126. ;;;; Structure editing
  6127. ;;; Inserting headlines
  6128. (defun org--blank-before-heading-p (&optional parent)
  6129. "Non-nil when an empty line should precede a new heading here.
  6130. When optional argument PARENT is non-nil, consider parent
  6131. headline instead of current one."
  6132. (pcase (assq 'heading org-blank-before-new-entry)
  6133. (`(heading . auto)
  6134. (save-excursion
  6135. (org-with-limited-levels
  6136. (unless (and (org-before-first-heading-p)
  6137. (not (outline-next-heading)))
  6138. (org-back-to-heading t)
  6139. (when parent (org-up-heading-safe))
  6140. (cond ((not (bobp))
  6141. (org-previous-line-empty-p))
  6142. ((outline-next-heading)
  6143. (org-previous-line-empty-p))
  6144. ;; Ignore trailing spaces on last buffer line.
  6145. ((progn (skip-chars-backward " \t") (bolp))
  6146. (org-previous-line-empty-p))
  6147. (t nil))))))
  6148. (`(heading . ,value) value)
  6149. (_ nil)))
  6150. (defun org-insert-heading (&optional arg invisible-ok top)
  6151. "Insert a new heading or an item with the same depth at point.
  6152. If point is at the beginning of a heading, insert a new heading
  6153. or a new headline above the current one. When at the beginning
  6154. of a regular line of text, turn it into a heading.
  6155. If point is in the middle of a line, split it and create a new
  6156. headline with the text in the current line after point (see
  6157. `org-M-RET-may-split-line' on how to modify this behavior). As
  6158. a special case, on a headline, splitting can only happen on the
  6159. title itself. E.g., this excludes breaking stars or tags.
  6160. With a `\\[universal-argument]' prefix, set \
  6161. `org-insert-heading-respect-content' to
  6162. a non-nil value for the duration of the command. This forces the
  6163. insertion of a heading after the current subtree, independently
  6164. on the location of point.
  6165. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6166. insert the heading at the end of the tree
  6167. above the current heading. For example, if point is within a
  6168. 2nd-level heading, then it will insert a 2nd-level heading at
  6169. the end of the 1st-level parent subtree.
  6170. When INVISIBLE-OK is set, stop at invisible headlines when going
  6171. back. This is important for non-interactive uses of the
  6172. command.
  6173. When optional argument TOP is non-nil, insert a level 1 heading,
  6174. unconditionally."
  6175. (interactive "P")
  6176. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6177. (level (org-current-level))
  6178. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6179. (cond
  6180. ((or org-insert-heading-respect-content
  6181. (member arg '((4) (16)))
  6182. (and (not invisible-ok)
  6183. (invisible-p (max (1- (point)) (point-min)))))
  6184. ;; Position point at the location of insertion. Make sure we
  6185. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6186. (org-with-limited-levels
  6187. (if (not level) (outline-next-heading) ;before first headline
  6188. (org-back-to-heading invisible-ok)
  6189. (when (equal arg '(16)) (org-up-heading-safe))
  6190. (org-end-of-subtree)))
  6191. (unless (bolp) (insert "\n"))
  6192. (unless (and blank? (org-previous-line-empty-p))
  6193. (org-N-empty-lines-before-current (if blank? 1 0)))
  6194. (insert stars " ")
  6195. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6196. ;; is visible.
  6197. (unless invisible-ok
  6198. (pcase (get-char-property-and-overlay (point) 'invisible)
  6199. (`(outline . ,o)
  6200. (move-overlay o (overlay-start o) (line-end-position 0)))
  6201. (_ nil))))
  6202. ;; At a headline...
  6203. ((org-at-heading-p)
  6204. (cond ((bolp)
  6205. (when blank? (save-excursion (insert "\n")))
  6206. (save-excursion (insert stars " \n"))
  6207. (unless (and blank? (org-previous-line-empty-p))
  6208. (org-N-empty-lines-before-current (if blank? 1 0)))
  6209. (end-of-line))
  6210. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6211. (org-match-line org-complex-heading-regexp)
  6212. (org-pos-in-match-range (point) 4))
  6213. ;; Grab the text that should moved to the new headline.
  6214. ;; Preserve tags.
  6215. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6216. (if (looking-at "[ \t]*$") (replace-match "")
  6217. (org-align-tags))
  6218. (end-of-line)
  6219. (when blank? (insert "\n"))
  6220. (insert "\n" stars " ")
  6221. (when (org-string-nw-p split) (insert split))))
  6222. (t
  6223. (end-of-line)
  6224. (when blank? (insert "\n"))
  6225. (insert "\n" stars " "))))
  6226. ;; On regular text, turn line into a headline or split, if
  6227. ;; appropriate.
  6228. ((bolp)
  6229. (insert stars " ")
  6230. (unless (and blank? (org-previous-line-empty-p))
  6231. (org-N-empty-lines-before-current (if blank? 1 0))))
  6232. (t
  6233. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6234. (end-of-line))
  6235. (insert "\n" stars " ")
  6236. (unless (and blank? (org-previous-line-empty-p))
  6237. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6238. (run-hooks 'org-insert-heading-hook))
  6239. (defun org-N-empty-lines-before-current (n)
  6240. "Make the number of empty lines before current exactly N.
  6241. So this will delete or add empty lines."
  6242. (let ((column (current-column)))
  6243. (beginning-of-line)
  6244. (unless (bobp)
  6245. (let ((start (save-excursion
  6246. (skip-chars-backward " \r\t\n")
  6247. (line-end-position))))
  6248. (delete-region start (line-end-position 0))))
  6249. (insert (make-string n ?\n))
  6250. (move-to-column column)))
  6251. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6252. "Return the heading of the current entry, without the stars.
  6253. When NO-TAGS is non-nil, don't include tags.
  6254. When NO-TODO is non-nil, don't include TODO keywords.
  6255. When NO-PRIORITY is non-nil, don't include priority cookie.
  6256. When NO-COMMENT is non-nil, don't include COMMENT string.
  6257. Return nil before first heading."
  6258. (unless (org-before-first-heading-p)
  6259. (save-excursion
  6260. (org-back-to-heading t)
  6261. (let ((case-fold-search nil))
  6262. (looking-at org-complex-heading-regexp)
  6263. (let ((todo (and (not no-todo) (match-string 2)))
  6264. (priority (and (not no-priority) (match-string 3)))
  6265. (headline (pcase (match-string 4)
  6266. (`nil "")
  6267. ((and (guard no-comment) h)
  6268. (replace-regexp-in-string
  6269. (eval-when-compile
  6270. (format "\\`%s[ \t]+" org-comment-string))
  6271. "" h))
  6272. (h h)))
  6273. (tags (and (not no-tags) (match-string 5))))
  6274. (mapconcat #'identity
  6275. (delq nil (list todo priority headline tags))
  6276. " "))))))
  6277. (defun org-heading-components ()
  6278. "Return the components of the current heading.
  6279. This is a list with the following elements:
  6280. - the level as an integer
  6281. - the reduced level, different if `org-odd-levels-only' is set.
  6282. - the TODO keyword, or nil
  6283. - the priority character, like ?A, or nil if no priority is given
  6284. - the headline text itself, or the tags string if no headline text
  6285. - the tags string, or nil."
  6286. (save-excursion
  6287. (org-back-to-heading t)
  6288. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6289. (list (length (match-string 1))
  6290. (org-reduced-level (length (match-string 1)))
  6291. (match-string-no-properties 2)
  6292. (and (match-end 3) (aref (match-string 3) 2))
  6293. (match-string-no-properties 4)
  6294. (match-string-no-properties 5)))))
  6295. (defun org-get-entry ()
  6296. "Get the entry text, after heading, entire subtree."
  6297. (save-excursion
  6298. (org-back-to-heading t)
  6299. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6300. (defun org-edit-headline (&optional heading)
  6301. "Edit the current headline.
  6302. Set it to HEADING when provided."
  6303. (interactive)
  6304. (org-with-wide-buffer
  6305. (org-back-to-heading t)
  6306. (let ((case-fold-search nil))
  6307. (when (looking-at org-complex-heading-regexp)
  6308. (let* ((old (match-string-no-properties 4))
  6309. (new (save-match-data
  6310. (org-trim (or heading (read-string "Edit: " old))))))
  6311. (unless (equal old new)
  6312. (if old (replace-match new t t nil 4)
  6313. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6314. (insert " " new))
  6315. (org-align-tags)
  6316. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6317. (defun org-insert-heading-after-current ()
  6318. "Insert a new heading with same level as current, after current subtree."
  6319. (interactive)
  6320. (org-back-to-heading)
  6321. (org-insert-heading)
  6322. (org-move-subtree-down)
  6323. (end-of-line 1))
  6324. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6325. "Insert heading with `org-insert-heading-respect-content' set to t."
  6326. (interactive)
  6327. (org-insert-heading '(4) invisible-ok))
  6328. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6329. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6330. (interactive)
  6331. (org-insert-todo-heading force-state '(4)))
  6332. (defun org-insert-todo-heading (arg &optional force-heading)
  6333. "Insert a new heading with the same level and TODO state as current heading.
  6334. If the heading has no TODO state, or if the state is DONE, use
  6335. the first state (TODO by default). Also with one prefix arg,
  6336. force first state. With two prefix args, force inserting at the
  6337. end of the parent subtree.
  6338. When called at a plain list item, insert a new item with an
  6339. unchecked check box."
  6340. (interactive "P")
  6341. (when (or force-heading (not (org-insert-item 'checkbox)))
  6342. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6343. force-heading))
  6344. (save-excursion
  6345. (org-forward-heading-same-level -1)
  6346. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6347. (let* ((new-mark-x
  6348. (if (or (equal arg '(4))
  6349. (not (match-beginning 2))
  6350. (member (match-string 2) org-done-keywords))
  6351. (car org-todo-keywords-1)
  6352. (match-string 2)))
  6353. (new-mark
  6354. (or
  6355. (run-hook-with-args-until-success
  6356. 'org-todo-get-default-hook new-mark-x nil)
  6357. new-mark-x)))
  6358. (beginning-of-line 1)
  6359. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6360. (if org-treat-insert-todo-heading-as-state-change
  6361. (org-todo new-mark)
  6362. (insert new-mark " "))))
  6363. (when org-provide-todo-statistics
  6364. (org-update-parent-todo-statistics))))
  6365. (defun org-insert-subheading (arg)
  6366. "Insert a new subheading and demote it.
  6367. Works for outline headings and for plain lists alike."
  6368. (interactive "P")
  6369. (org-insert-heading arg)
  6370. (cond
  6371. ((org-at-heading-p) (org-do-demote))
  6372. ((org-at-item-p) (org-indent-item))))
  6373. (defun org-insert-todo-subheading (arg)
  6374. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6375. Works for outline headings and for plain lists alike."
  6376. (interactive "P")
  6377. (org-insert-todo-heading arg)
  6378. (cond
  6379. ((org-at-heading-p) (org-do-demote))
  6380. ((org-at-item-p) (org-indent-item))))
  6381. ;;; Promotion and Demotion
  6382. (defvar org-after-demote-entry-hook nil
  6383. "Hook run after an entry has been demoted.
  6384. The cursor will be at the beginning of the entry.
  6385. When a subtree is being demoted, the hook will be called for each node.")
  6386. (defvar org-after-promote-entry-hook nil
  6387. "Hook run after an entry has been promoted.
  6388. The cursor will be at the beginning of the entry.
  6389. When a subtree is being promoted, the hook will be called for each node.")
  6390. (defun org-promote-subtree ()
  6391. "Promote the entire subtree.
  6392. See also `org-promote'."
  6393. (interactive)
  6394. (save-excursion
  6395. (org-with-limited-levels (org-map-tree 'org-promote)))
  6396. (org-fix-position-after-promote))
  6397. (defun org-demote-subtree ()
  6398. "Demote the entire subtree.
  6399. See `org-demote' and `org-promote'."
  6400. (interactive)
  6401. (save-excursion
  6402. (org-with-limited-levels (org-map-tree 'org-demote)))
  6403. (org-fix-position-after-promote))
  6404. (defun org-do-promote ()
  6405. "Promote the current heading higher up the tree.
  6406. If the region is active in `transient-mark-mode', promote all
  6407. headings in the region."
  6408. (interactive)
  6409. (save-excursion
  6410. (if (org-region-active-p)
  6411. (org-map-region 'org-promote (region-beginning) (region-end))
  6412. (org-promote)))
  6413. (org-fix-position-after-promote))
  6414. (defun org-do-demote ()
  6415. "Demote the current heading lower down the tree.
  6416. If the region is active in `transient-mark-mode', demote all
  6417. headings in the region."
  6418. (interactive)
  6419. (save-excursion
  6420. (if (org-region-active-p)
  6421. (org-map-region 'org-demote (region-beginning) (region-end))
  6422. (org-demote)))
  6423. (org-fix-position-after-promote))
  6424. (defun org-fix-position-after-promote ()
  6425. "Fix cursor position and indentation after demoting/promoting."
  6426. (let ((pos (point)))
  6427. (when (save-excursion
  6428. (beginning-of-line)
  6429. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6430. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6431. (cond ((eobp) (insert " "))
  6432. ((eolp) (insert " "))
  6433. ((equal (char-after) ?\s) (forward-char 1))))))
  6434. (defun org-current-level ()
  6435. "Return the level of the current entry, or nil if before the first headline.
  6436. The level is the number of stars at the beginning of the
  6437. headline. Use `org-reduced-level' to remove the effect of
  6438. `org-odd-levels'. Unlike to `org-outline-level', this function
  6439. ignores inlinetasks."
  6440. (let ((level (org-with-limited-levels (org-outline-level))))
  6441. (and (> level 0) level)))
  6442. (defun org-get-previous-line-level ()
  6443. "Return the outline depth of the last headline before the current line.
  6444. Returns 0 for the first headline in the buffer, and nil if before the
  6445. first headline."
  6446. (and (org-current-level)
  6447. (or (and (/= (line-beginning-position) (point-min))
  6448. (save-excursion (beginning-of-line 0) (org-current-level)))
  6449. 0)))
  6450. (defun org-reduced-level (l)
  6451. "Compute the effective level of a heading.
  6452. This takes into account the setting of `org-odd-levels-only'."
  6453. (cond
  6454. ((zerop l) 0)
  6455. (org-odd-levels-only (1+ (floor (/ l 2))))
  6456. (t l)))
  6457. (defun org-level-increment ()
  6458. "Return the number of stars that will be added or removed at a
  6459. time to headlines when structure editing, based on the value of
  6460. `org-odd-levels-only'."
  6461. (if org-odd-levels-only 2 1))
  6462. (defun org-get-valid-level (level &optional change)
  6463. "Rectify a level change under the influence of `org-odd-levels-only'.
  6464. LEVEL is a current level, CHANGE is by how much the level should
  6465. be modified. Even if CHANGE is nil, LEVEL may be returned
  6466. modified because even level numbers will become the next higher
  6467. odd number. Returns values greater than 0."
  6468. (if org-odd-levels-only
  6469. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6470. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6471. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6472. (max 1 (+ level (or change 0)))))
  6473. (defun org-promote ()
  6474. "Promote the current heading higher up the tree."
  6475. (org-with-wide-buffer
  6476. (org-back-to-heading t)
  6477. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6478. after-change-functions))
  6479. (level (save-match-data (funcall outline-level)))
  6480. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6481. (diff (abs (- level (length up-head) -1))))
  6482. (cond
  6483. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6484. (replace-match "# " nil t))
  6485. ((= level 1)
  6486. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6487. (t (replace-match up-head nil t)))
  6488. (unless (= level 1)
  6489. (when org-auto-align-tags (org-align-tags))
  6490. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6491. (run-hooks 'org-after-promote-entry-hook))))
  6492. (defun org-demote ()
  6493. "Demote the current heading lower down the tree."
  6494. (org-with-wide-buffer
  6495. (org-back-to-heading t)
  6496. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6497. after-change-functions))
  6498. (level (save-match-data (funcall outline-level)))
  6499. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6500. (diff (abs (- level (length down-head) -1))))
  6501. (replace-match down-head nil t)
  6502. (when org-auto-align-tags (org-align-tags))
  6503. (when org-adapt-indentation (org-fixup-indentation diff))
  6504. (run-hooks 'org-after-demote-entry-hook))))
  6505. (defun org-cycle-level ()
  6506. "Cycle the level of an empty headline through possible states.
  6507. This goes first to child, then to parent, level, then up the hierarchy.
  6508. After top level, it switches back to sibling level."
  6509. (interactive)
  6510. (let ((org-adapt-indentation nil))
  6511. (when (org-point-at-end-of-empty-headline)
  6512. (setq this-command 'org-cycle-level) ; Only needed for caching
  6513. (let ((cur-level (org-current-level))
  6514. (prev-level (org-get-previous-line-level)))
  6515. (cond
  6516. ;; If first headline in file, promote to top-level.
  6517. ((= prev-level 0)
  6518. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6519. do (org-do-promote)))
  6520. ;; If same level as prev, demote one.
  6521. ((= prev-level cur-level)
  6522. (org-do-demote))
  6523. ;; If parent is top-level, promote to top level if not already.
  6524. ((= prev-level 1)
  6525. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6526. do (org-do-promote)))
  6527. ;; If top-level, return to prev-level.
  6528. ((= cur-level 1)
  6529. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6530. do (org-do-demote)))
  6531. ;; If less than prev-level, promote one.
  6532. ((< cur-level prev-level)
  6533. (org-do-promote))
  6534. ;; If deeper than prev-level, promote until higher than
  6535. ;; prev-level.
  6536. ((> cur-level prev-level)
  6537. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6538. do (org-do-promote))))
  6539. t))))
  6540. (defun org-map-tree (fun)
  6541. "Call FUN for every heading underneath the current one."
  6542. (org-back-to-heading t)
  6543. (let ((level (funcall outline-level)))
  6544. (save-excursion
  6545. (funcall fun)
  6546. (while (and (progn
  6547. (outline-next-heading)
  6548. (> (funcall outline-level) level))
  6549. (not (eobp)))
  6550. (funcall fun)))))
  6551. (defun org-map-region (fun beg end)
  6552. "Call FUN for every heading between BEG and END."
  6553. (let ((org-ignore-region t))
  6554. (save-excursion
  6555. (setq end (copy-marker end))
  6556. (goto-char beg)
  6557. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6558. (< (point) end))
  6559. (funcall fun))
  6560. (while (and (progn
  6561. (outline-next-heading)
  6562. (< (point) end))
  6563. (not (eobp)))
  6564. (funcall fun)))))
  6565. (defun org-fixup-indentation (diff)
  6566. "Change the indentation in the current entry by DIFF.
  6567. DIFF is an integer. Indentation is done according to the
  6568. following rules:
  6569. - Planning information and property drawers are always indented
  6570. according to the new level of the headline;
  6571. - Footnote definitions and their contents are ignored;
  6572. - Inlinetasks' boundaries are not shifted;
  6573. - Empty lines are ignored;
  6574. - Other lines' indentation are shifted by DIFF columns, unless
  6575. it would introduce a structural change in the document, in
  6576. which case no shifting is done at all.
  6577. Assume point is at a heading or an inlinetask beginning."
  6578. (org-with-wide-buffer
  6579. (narrow-to-region (line-beginning-position)
  6580. (save-excursion
  6581. (if (org-with-limited-levels (org-at-heading-p))
  6582. (org-with-limited-levels (outline-next-heading))
  6583. (org-inlinetask-goto-end))
  6584. (point)))
  6585. (forward-line)
  6586. ;; Indent properly planning info and property drawer.
  6587. (when (looking-at-p org-planning-line-re)
  6588. (org-indent-line)
  6589. (forward-line))
  6590. (when (looking-at org-property-drawer-re)
  6591. (goto-char (match-end 0))
  6592. (forward-line)
  6593. (org-indent-region (match-beginning 0) (match-end 0)))
  6594. (when (looking-at org-logbook-drawer-re)
  6595. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6596. (col (+ (current-indentation) diff)))
  6597. (when (wholenump col)
  6598. (while (< (point) end-marker)
  6599. (indent-line-to col)
  6600. (forward-line)))))
  6601. (catch 'no-shift
  6602. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6603. (throw 'no-shift nil))
  6604. ;; If DIFF is negative, first check if a shift is possible at all
  6605. ;; (e.g., it doesn't break structure). This can only happen if
  6606. ;; some contents are not properly indented.
  6607. (let ((case-fold-search t))
  6608. (when (< diff 0)
  6609. (let ((diff (- diff))
  6610. (forbidden-re (concat org-outline-regexp
  6611. "\\|"
  6612. (substring org-footnote-definition-re 1))))
  6613. (save-excursion
  6614. (while (not (eobp))
  6615. (cond
  6616. ((looking-at-p "[ \t]*$") (forward-line))
  6617. ((and (looking-at-p org-footnote-definition-re)
  6618. (let ((e (org-element-at-point)))
  6619. (and (eq (org-element-type e) 'footnote-definition)
  6620. (goto-char (org-element-property :end e))))))
  6621. ((looking-at-p org-outline-regexp) (forward-line))
  6622. ;; Give up if shifting would move before column 0 or
  6623. ;; if it would introduce a headline or a footnote
  6624. ;; definition.
  6625. (t
  6626. (skip-chars-forward " \t")
  6627. (let ((ind (current-column)))
  6628. (when (or (< ind diff)
  6629. (and (= ind diff) (looking-at-p forbidden-re)))
  6630. (throw 'no-shift nil)))
  6631. ;; Ignore contents of example blocks and source
  6632. ;; blocks if their indentation is meant to be
  6633. ;; preserved. Jump to block's closing line.
  6634. (beginning-of-line)
  6635. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6636. (let ((e (org-element-at-point)))
  6637. (and (memq (org-element-type e)
  6638. '(example-block src-block))
  6639. (or org-src-preserve-indentation
  6640. (org-element-property :preserve-indent e))
  6641. (goto-char (org-element-property :end e))
  6642. (progn (skip-chars-backward " \r\t\n")
  6643. (beginning-of-line)
  6644. t))))
  6645. (forward-line))))))))
  6646. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6647. ;; by DIFF. Also skip contents of source or example blocks
  6648. ;; when indentation is meant to be preserved.
  6649. (while (not (eobp))
  6650. (cond
  6651. ((and (looking-at-p org-footnote-definition-re)
  6652. (let ((e (org-element-at-point)))
  6653. (and (eq (org-element-type e) 'footnote-definition)
  6654. (goto-char (org-element-property :end e))))))
  6655. ((looking-at-p org-outline-regexp) (forward-line))
  6656. ((looking-at-p "[ \t]*$") (forward-line))
  6657. (t
  6658. (indent-line-to (+ (current-indentation) diff))
  6659. (beginning-of-line)
  6660. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6661. (let ((e (org-element-at-point)))
  6662. (and (memq (org-element-type e)
  6663. '(example-block src-block))
  6664. (or org-src-preserve-indentation
  6665. (org-element-property :preserve-indent e))
  6666. (goto-char (org-element-property :end e))
  6667. (progn (skip-chars-backward " \r\t\n")
  6668. (beginning-of-line)
  6669. t))))
  6670. (forward-line)))))))))
  6671. (defun org-convert-to-odd-levels ()
  6672. "Convert an Org file with all levels allowed to one with odd levels.
  6673. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6674. level 5 etc."
  6675. (interactive)
  6676. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6677. (let ((outline-level 'org-outline-level)
  6678. (org-odd-levels-only nil) n)
  6679. (save-excursion
  6680. (goto-char (point-min))
  6681. (while (re-search-forward "^\\*\\*+ " nil t)
  6682. (setq n (- (length (match-string 0)) 2))
  6683. (while (>= (setq n (1- n)) 0)
  6684. (org-demote))
  6685. (end-of-line 1))))))
  6686. (defun org-convert-to-oddeven-levels ()
  6687. "Convert an Org file with only odd levels to one with odd/even levels.
  6688. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6689. file contains a section with an even level, conversion would
  6690. destroy the structure of the file. An error is signaled in this
  6691. case."
  6692. (interactive)
  6693. (goto-char (point-min))
  6694. ;; First check if there are no even levels
  6695. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6696. (org-show-set-visibility 'canonical)
  6697. (error "Not all levels are odd in this file. Conversion not possible"))
  6698. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6699. (let ((outline-regexp org-outline-regexp)
  6700. (outline-level 'org-outline-level)
  6701. (org-odd-levels-only nil) n)
  6702. (save-excursion
  6703. (goto-char (point-min))
  6704. (while (re-search-forward "^\\*\\*+ " nil t)
  6705. (setq n (/ (1- (length (match-string 0))) 2))
  6706. (while (>= (setq n (1- n)) 0)
  6707. (org-promote))
  6708. (end-of-line 1))))))
  6709. (defun org-tr-level (n)
  6710. "Make N odd if required."
  6711. (if org-odd-levels-only (1+ (/ n 2)) n))
  6712. ;;; Vertical tree motion, cutting and pasting of subtrees
  6713. (defun org-move-subtree-up (&optional arg)
  6714. "Move the current subtree up past ARG headlines of the same level."
  6715. (interactive "p")
  6716. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6717. (defun org-move-subtree-down (&optional arg)
  6718. "Move the current subtree down past ARG headlines of the same level."
  6719. (interactive "p")
  6720. (setq arg (prefix-numeric-value arg))
  6721. (org-preserve-local-variables
  6722. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6723. 'org-get-last-sibling))
  6724. (ins-point (make-marker))
  6725. (cnt (abs arg))
  6726. (col (current-column))
  6727. beg end txt folded)
  6728. ;; Select the tree
  6729. (org-back-to-heading)
  6730. (setq beg (point))
  6731. (save-match-data
  6732. (save-excursion (outline-end-of-heading)
  6733. (setq folded (org-invisible-p)))
  6734. (progn (org-end-of-subtree nil t)
  6735. (unless (eobp) (backward-char))))
  6736. (outline-next-heading)
  6737. (setq end (point))
  6738. (goto-char beg)
  6739. ;; Find insertion point, with error handling
  6740. (while (> cnt 0)
  6741. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6742. (goto-char beg)
  6743. (user-error "Cannot move past superior level or buffer limit"))
  6744. (setq cnt (1- cnt)))
  6745. (when (> arg 0)
  6746. ;; Moving forward - still need to move over subtree
  6747. (org-end-of-subtree t t)
  6748. (save-excursion
  6749. (org-back-over-empty-lines)
  6750. (or (bolp) (newline))))
  6751. (move-marker ins-point (point))
  6752. (setq txt (buffer-substring beg end))
  6753. (org-save-markers-in-region beg end)
  6754. (delete-region beg end)
  6755. (org-remove-empty-overlays-at beg)
  6756. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6757. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6758. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6759. (let ((bbb (point)))
  6760. (insert-before-markers txt)
  6761. (org-reinstall-markers-in-region bbb)
  6762. (move-marker ins-point bbb))
  6763. (or (bolp) (insert "\n"))
  6764. (goto-char ins-point)
  6765. (org-skip-whitespace)
  6766. (move-marker ins-point nil)
  6767. (if folded
  6768. (org-flag-subtree t)
  6769. (org-show-entry)
  6770. (org-show-children))
  6771. (org-clean-visibility-after-subtree-move)
  6772. ;; move back to the initial column we were at
  6773. (move-to-column col))))
  6774. (defvar org-subtree-clip ""
  6775. "Clipboard for cut and paste of subtrees.
  6776. This is actually only a copy of the kill, because we use the normal kill
  6777. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6778. (defvar org-subtree-clip-folded nil
  6779. "Was the last copied subtree folded?
  6780. This is used to fold the tree back after pasting.")
  6781. (defun org-cut-subtree (&optional n)
  6782. "Cut the current subtree into the clipboard.
  6783. With prefix arg N, cut this many sequential subtrees.
  6784. This is a short-hand for marking the subtree and then cutting it."
  6785. (interactive "p")
  6786. (org-copy-subtree n 'cut))
  6787. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6788. "Copy the current subtree into the clipboard.
  6789. With prefix arg N, copy this many sequential subtrees.
  6790. This is a short-hand for marking the subtree and then copying it.
  6791. If CUT is non-nil, actually cut the subtree.
  6792. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6793. of some markers in the region, even if CUT is non-nil. This is
  6794. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6795. (interactive "p")
  6796. (org-preserve-local-variables
  6797. (let (beg end folded (beg0 (point)))
  6798. (if (called-interactively-p 'any)
  6799. (org-back-to-heading nil) ; take what looks like a subtree
  6800. (org-back-to-heading t)) ; take what is really there
  6801. (setq beg (point))
  6802. (skip-chars-forward " \t\r\n")
  6803. (save-match-data
  6804. (if nosubtrees
  6805. (outline-next-heading)
  6806. (save-excursion (outline-end-of-heading)
  6807. (setq folded (org-invisible-p)))
  6808. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6809. (org-end-of-subtree t t)))
  6810. ;; Include the end of an inlinetask
  6811. (when (and (featurep 'org-inlinetask)
  6812. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6813. "END[ \t]*$")))
  6814. (end-of-line))
  6815. (setq end (point))
  6816. (goto-char beg0)
  6817. (when (> end beg)
  6818. (setq org-subtree-clip-folded folded)
  6819. (when (or cut force-store-markers)
  6820. (org-save-markers-in-region beg end))
  6821. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6822. (setq org-subtree-clip (current-kill 0))
  6823. (message "%s: Subtree(s) with %d characters"
  6824. (if cut "Cut" "Copied")
  6825. (length org-subtree-clip))))))
  6826. (defun org-paste-subtree (&optional level tree for-yank remove)
  6827. "Paste the clipboard as a subtree, with modification of headline level.
  6828. The entire subtree is promoted or demoted in order to match a new headline
  6829. level.
  6830. If the cursor is at the beginning of a headline, the same level as
  6831. that headline is used to paste the tree.
  6832. If not, the new level is derived from the *visible* headings
  6833. before and after the insertion point, and taken to be the inferior headline
  6834. level of the two. So if the previous visible heading is level 3 and the
  6835. next is level 4 (or vice versa), level 4 will be used for insertion.
  6836. This makes sure that the subtree remains an independent subtree and does
  6837. not swallow low level entries.
  6838. You can also force a different level, either by using a numeric prefix
  6839. argument, or by inserting the heading marker by hand. For example, if the
  6840. cursor is after \"*****\", then the tree will be shifted to level 5.
  6841. If optional TREE is given, use this text instead of the kill ring.
  6842. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6843. move back over whitespace before inserting, and move point to the end of
  6844. the inserted text when done.
  6845. When REMOVE is non-nil, remove the subtree from the clipboard."
  6846. (interactive "P")
  6847. (setq tree (or tree (and kill-ring (current-kill 0))))
  6848. (unless (org-kill-is-subtree-p tree)
  6849. (user-error
  6850. (substitute-command-keys
  6851. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6852. (org-with-limited-levels
  6853. (let* ((visp (not (org-invisible-p)))
  6854. (txt tree)
  6855. (old-level (if (string-match org-outline-regexp-bol txt)
  6856. (- (match-end 0) (match-beginning 0) 1)
  6857. -1))
  6858. (force-level
  6859. (cond
  6860. (level (prefix-numeric-value level))
  6861. ;; When point is after the stars in an otherwise empty
  6862. ;; headline, use the number of stars as the forced level.
  6863. ((and (org-match-line "^\\*+[ \t]*$")
  6864. (not (eq ?* (char-after))))
  6865. (org-outline-level))
  6866. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6867. (previous-level
  6868. (save-excursion
  6869. (org-previous-visible-heading 1)
  6870. (if (org-at-heading-p) (org-outline-level) 1)))
  6871. (next-level
  6872. (save-excursion
  6873. (if (org-at-heading-p) (org-outline-level)
  6874. (org-next-visible-heading 1)
  6875. (if (org-at-heading-p) (org-outline-level) 1))))
  6876. (new-level (or force-level (max previous-level next-level)))
  6877. (shift (if (or (= old-level -1)
  6878. (= new-level -1)
  6879. (= old-level new-level))
  6880. 0
  6881. (- new-level old-level)))
  6882. (delta (if (> shift 0) -1 1))
  6883. (func (if (> shift 0) #'org-demote #'org-promote))
  6884. (org-odd-levels-only nil)
  6885. beg end newend)
  6886. ;; Remove the forced level indicator.
  6887. (when (and force-level (not level))
  6888. (delete-region (line-beginning-position) (point)))
  6889. ;; Paste before the next visible heading or at end of buffer,
  6890. ;; unless point is at the beginning of a headline.
  6891. (unless (and (bolp) (org-at-heading-p))
  6892. (org-next-visible-heading 1)
  6893. (unless (bolp) (insert "\n")))
  6894. (setq beg (point))
  6895. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6896. (insert-before-markers txt)
  6897. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6898. (setq newend (point))
  6899. (org-reinstall-markers-in-region beg)
  6900. (setq end (point))
  6901. (goto-char beg)
  6902. (skip-chars-forward " \t\n\r")
  6903. (setq beg (point))
  6904. (when (and (org-invisible-p) visp)
  6905. (save-excursion (outline-show-heading)))
  6906. ;; Shift if necessary.
  6907. (unless (= shift 0)
  6908. (save-restriction
  6909. (narrow-to-region beg end)
  6910. (while (not (= shift 0))
  6911. (org-map-region func (point-min) (point-max))
  6912. (setq shift (+ delta shift)))
  6913. (goto-char (point-min))
  6914. (setq newend (point-max))))
  6915. (when (or for-yank (called-interactively-p 'interactive))
  6916. (message "Clipboard pasted as level %d subtree" new-level))
  6917. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6918. kill-ring
  6919. (equal org-subtree-clip (current-kill 0))
  6920. org-subtree-clip-folded)
  6921. ;; The tree was folded before it was killed/copied
  6922. (org-flag-subtree t))
  6923. (when for-yank (goto-char newend))
  6924. (when remove (pop kill-ring)))))
  6925. (defun org-kill-is-subtree-p (&optional txt)
  6926. "Check if the current kill is an outline subtree, or a set of trees.
  6927. Returns nil if kill does not start with a headline, or if the first
  6928. headline level is not the largest headline level in the tree.
  6929. So this will actually accept several entries of equal levels as well,
  6930. which is OK for `org-paste-subtree'.
  6931. If optional TXT is given, check this string instead of the current kill."
  6932. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6933. (re (org-get-limited-outline-regexp))
  6934. (^re (concat "^" re))
  6935. (start-level (and kill
  6936. (string-match
  6937. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6938. kill)
  6939. (- (match-end 2) (match-beginning 2) 1)))
  6940. (start (1+ (or (match-beginning 2) -1))))
  6941. (if (not start-level)
  6942. (progn
  6943. nil) ;; does not even start with a heading
  6944. (catch 'exit
  6945. (while (setq start (string-match ^re kill (1+ start)))
  6946. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6947. (throw 'exit nil)))
  6948. t))))
  6949. (defvar org-markers-to-move nil
  6950. "Markers that should be moved with a cut-and-paste operation.
  6951. Those markers are stored together with their positions relative to
  6952. the start of the region.")
  6953. (defun org-save-markers-in-region (beg end)
  6954. "Check markers in region.
  6955. If these markers are between BEG and END, record their position relative
  6956. to BEG, so that after moving the block of text, we can put the markers back
  6957. into place.
  6958. This function gets called just before an entry or tree gets cut from the
  6959. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6960. called immediately, to move the markers with the entries."
  6961. (setq org-markers-to-move nil)
  6962. (when (featurep 'org-clock)
  6963. (org-clock-save-markers-for-cut-and-paste beg end))
  6964. (when (featurep 'org-agenda)
  6965. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6966. (defun org-check-and-save-marker (marker beg end)
  6967. "Check if MARKER is between BEG and END.
  6968. If yes, remember the marker and the distance to BEG."
  6969. (when (and (marker-buffer marker)
  6970. (equal (marker-buffer marker) (current-buffer))
  6971. (>= marker beg) (< marker end))
  6972. (push (cons marker (- marker beg)) org-markers-to-move)))
  6973. (defun org-reinstall-markers-in-region (beg)
  6974. "Move all remembered markers to their position relative to BEG."
  6975. (dolist (x org-markers-to-move)
  6976. (move-marker (car x) (+ beg (cdr x))))
  6977. (setq org-markers-to-move nil))
  6978. (defun org-narrow-to-subtree ()
  6979. "Narrow buffer to the current subtree."
  6980. (interactive)
  6981. (save-excursion
  6982. (save-match-data
  6983. (org-with-limited-levels
  6984. (narrow-to-region
  6985. (progn (org-back-to-heading t) (point))
  6986. (progn (org-end-of-subtree t t)
  6987. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6988. (point)))))))
  6989. (defun org-toggle-narrow-to-subtree ()
  6990. "Narrow to the subtree at point or widen a narrowed buffer."
  6991. (interactive)
  6992. (if (buffer-narrowed-p)
  6993. (progn (widen) (message "Buffer widen"))
  6994. (org-narrow-to-subtree)
  6995. (message "Buffer narrowed to current subtree")))
  6996. (defun org-narrow-to-block ()
  6997. "Narrow buffer to the current block."
  6998. (interactive)
  6999. (let* ((case-fold-search t)
  7000. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7001. "^[ \t]*#\\+end_.*")))
  7002. (if blockp
  7003. (narrow-to-region (car blockp) (cdr blockp))
  7004. (user-error "Not in a block"))))
  7005. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7006. "Clone the task (subtree) at point N times.
  7007. The clones will be inserted as siblings.
  7008. In interactive use, the user will be prompted for the number of
  7009. clones to be produced. If the entry has a timestamp, the user
  7010. will also be prompted for a time shift, which may be a repeater
  7011. as used in time stamps, for example `+3d'. To disable this,
  7012. you can call the function with a universal prefix argument.
  7013. When a valid repeater is given and the entry contains any time
  7014. stamps, the clones will become a sequence in time, with time
  7015. stamps in the subtree shifted for each clone produced. If SHIFT
  7016. is nil or the empty string, time stamps will be left alone. The
  7017. ID property of the original subtree is removed.
  7018. In each clone, all the CLOCK entries will be removed. This
  7019. prevents Org from considering that the clocked times overlap.
  7020. If the original subtree did contain time stamps with a repeater,
  7021. the following will happen:
  7022. - the repeater will be removed in each clone
  7023. - an additional clone will be produced, with the current, unshifted
  7024. date(s) in the entry.
  7025. - the original entry will be placed *after* all the clones, with
  7026. repeater intact.
  7027. - the start days in the repeater in the original entry will be shifted
  7028. to past the last clone.
  7029. In this way you can spell out a number of instances of a repeating task,
  7030. and still retain the repeater to cover future instances of the task.
  7031. As described above, N+1 clones are produced when the original
  7032. subtree has a repeater. Setting N to 0, then, can be used to
  7033. remove the repeater from a subtree and create a shifted clone
  7034. with the original repeater."
  7035. (interactive "nNumber of clones to produce: ")
  7036. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7037. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7038. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7039. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7040. (shift
  7041. (or shift
  7042. (if (and (not (equal current-prefix-arg '(4)))
  7043. (save-excursion
  7044. (goto-char beg)
  7045. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7046. (read-from-minibuffer
  7047. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7048. ""))) ;No time shift
  7049. (doshift
  7050. (and (org-string-nw-p shift)
  7051. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7052. shift)
  7053. (user-error "Invalid shift specification %s" shift)))))
  7054. (goto-char end-of-tree)
  7055. (unless (bolp) (insert "\n"))
  7056. (let* ((end (point))
  7057. (template (buffer-substring beg end))
  7058. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7059. (shift-what (pcase (and doshift (match-string 2 shift))
  7060. (`nil nil)
  7061. ("d" 'day)
  7062. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7063. ("m" 'month)
  7064. ("y" 'year)
  7065. (_ (error "Unsupported time unit"))))
  7066. (nmin 1)
  7067. (nmax n)
  7068. (n-no-remove -1)
  7069. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7070. (idprop (org-entry-get beg "ID")))
  7071. (when (and doshift
  7072. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7073. template))
  7074. (delete-region beg end)
  7075. (setq end beg)
  7076. (setq nmin 0)
  7077. (setq nmax (1+ nmax))
  7078. (setq n-no-remove nmax))
  7079. (goto-char end)
  7080. (cl-loop for n from nmin to nmax do
  7081. (insert
  7082. ;; Prepare clone.
  7083. (with-temp-buffer
  7084. (insert template)
  7085. (org-mode)
  7086. (goto-char (point-min))
  7087. (org-show-subtree)
  7088. (and idprop (if org-clone-delete-id
  7089. (org-entry-delete nil "ID")
  7090. (org-id-get-create t)))
  7091. (unless (= n 0)
  7092. (while (re-search-forward org-clock-line-re nil t)
  7093. (delete-region (line-beginning-position)
  7094. (line-beginning-position 2)))
  7095. (goto-char (point-min))
  7096. (while (re-search-forward org-drawer-regexp nil t)
  7097. (org-remove-empty-drawer-at (point))))
  7098. (goto-char (point-min))
  7099. (when doshift
  7100. (while (re-search-forward org-ts-regexp-both nil t)
  7101. (org-timestamp-change (* n shift-n) shift-what))
  7102. (unless (= n n-no-remove)
  7103. (goto-char (point-min))
  7104. (while (re-search-forward org-ts-regexp nil t)
  7105. (save-excursion
  7106. (goto-char (match-beginning 0))
  7107. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7108. (delete-region (match-beginning 1) (match-end 1)))))))
  7109. (buffer-string)))))
  7110. (goto-char beg)))
  7111. ;;; Outline path
  7112. (defvar org-outline-path-cache nil
  7113. "Alist between buffer positions and outline paths.
  7114. It value is an alist (POSITION . PATH) where POSITION is the
  7115. buffer position at the beginning of an entry and PATH is a list
  7116. of strings describing the outline path for that entry, in reverse
  7117. order.")
  7118. (defun org--get-outline-path-1 (&optional use-cache)
  7119. "Return outline path to current headline.
  7120. Outline path is a list of strings, in reverse order. When
  7121. optional argument USE-CACHE is non-nil, make use of a cache. See
  7122. `org-get-outline-path' for details.
  7123. Assume buffer is widened and point is on a headline."
  7124. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7125. (let ((p (point))
  7126. (heading (let ((case-fold-search nil))
  7127. (looking-at org-complex-heading-regexp)
  7128. (if (not (match-end 4)) ""
  7129. ;; Remove statistics cookies.
  7130. (org-trim
  7131. (org-link-display-format
  7132. (replace-regexp-in-string
  7133. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7134. (match-string-no-properties 4))))))))
  7135. (if (org-up-heading-safe)
  7136. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7137. (when use-cache
  7138. (push (cons p path) org-outline-path-cache))
  7139. path)
  7140. ;; This is a new root node. Since we assume we are moving
  7141. ;; forward, we can drop previous cache so as to limit number
  7142. ;; of associations there.
  7143. (let ((path (list heading)))
  7144. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7145. path)))))
  7146. (defun org-get-outline-path (&optional with-self use-cache)
  7147. "Return the outline path to the current entry.
  7148. An outline path is a list of ancestors for current headline, as
  7149. a list of strings. Statistics cookies are removed and links are
  7150. replaced with their description, if any, or their path otherwise.
  7151. When optional argument WITH-SELF is non-nil, the path also
  7152. includes the current headline.
  7153. When optional argument USE-CACHE is non-nil, cache outline paths
  7154. between calls to this function so as to avoid backtracking. This
  7155. argument is useful when planning to find more than one outline
  7156. path in the same document. In that case, there are two
  7157. conditions to satisfy:
  7158. - `org-outline-path-cache' is set to nil before starting the
  7159. process;
  7160. - outline paths are computed by increasing buffer positions."
  7161. (org-with-wide-buffer
  7162. (and (or (and with-self (org-back-to-heading t))
  7163. (org-up-heading-safe))
  7164. (reverse (org--get-outline-path-1 use-cache)))))
  7165. (defun org-format-outline-path (path &optional width prefix separator)
  7166. "Format the outline path PATH for display.
  7167. WIDTH is the maximum number of characters that is available.
  7168. PREFIX is a prefix to be included in the returned string,
  7169. such as the file name.
  7170. SEPARATOR is inserted between the different parts of the path,
  7171. the default is \"/\"."
  7172. (setq width (or width 79))
  7173. (setq path (delq nil path))
  7174. (unless (> width 0)
  7175. (user-error "Argument `width' must be positive"))
  7176. (setq separator (or separator "/"))
  7177. (let* ((org-odd-levels-only nil)
  7178. (fpath (concat
  7179. prefix (and prefix path separator)
  7180. (mapconcat
  7181. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7182. (cl-loop for head in path
  7183. for n from 0
  7184. collect (org-add-props
  7185. head nil 'face
  7186. (nth (% n org-n-level-faces) org-level-faces)))
  7187. separator))))
  7188. (when (> (length fpath) width)
  7189. (if (< width 7)
  7190. ;; It's unlikely that `width' will be this small, but don't
  7191. ;; waste characters by adding ".." if it is.
  7192. (setq fpath (substring fpath 0 width))
  7193. (setf (substring fpath (- width 2)) "..")))
  7194. fpath))
  7195. (defun org-display-outline-path (&optional file current separator just-return-string)
  7196. "Display the current outline path in the echo area.
  7197. If FILE is non-nil, prepend the output with the file name.
  7198. If CURRENT is non-nil, append the current heading to the output.
  7199. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7200. the different parts of the path and defaults to \"/\".
  7201. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7202. (interactive "P")
  7203. (let* (case-fold-search
  7204. (bfn (buffer-file-name (buffer-base-buffer)))
  7205. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7206. res)
  7207. (when current (setq path (append path
  7208. (save-excursion
  7209. (org-back-to-heading t)
  7210. (when (looking-at org-complex-heading-regexp)
  7211. (list (match-string 4)))))))
  7212. (setq res
  7213. (org-format-outline-path
  7214. path
  7215. (1- (frame-width))
  7216. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7217. separator))
  7218. (add-face-text-property 0 (length res)
  7219. `(:height ,(face-attribute 'default :height))
  7220. nil res)
  7221. (if just-return-string
  7222. res
  7223. (org-unlogged-message "%s" res))))
  7224. ;;; Outline Sorting
  7225. (defun org-sort (&optional with-case)
  7226. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7227. Optional argument WITH-CASE means sort case-sensitively."
  7228. (interactive "P")
  7229. (org-call-with-arg
  7230. (cond ((org-at-table-p) #'org-table-sort-lines)
  7231. ((org-at-item-p) #'org-sort-list)
  7232. (t #'org-sort-entries))
  7233. with-case))
  7234. (defun org-sort-remove-invisible (s)
  7235. "Remove invisible part of links and emphasis markers from string S."
  7236. (remove-text-properties 0 (length s) org-rm-props s)
  7237. (replace-regexp-in-string
  7238. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7239. (replace-regexp-in-string
  7240. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7241. (org-link-display-format s)
  7242. t t) t t))
  7243. (defvar org-after-sorting-entries-or-items-hook nil
  7244. "Hook that is run after a bunch of entries or items have been sorted.
  7245. When children are sorted, the cursor is in the parent line when this
  7246. hook gets called. When a region or a plain list is sorted, the cursor
  7247. will be in the first entry of the sorted region/list.")
  7248. (defun org-sort-entries
  7249. (&optional with-case sorting-type getkey-func compare-func property
  7250. interactive?)
  7251. "Sort entries on a certain level of an outline tree.
  7252. If there is an active region, the entries in the region are sorted.
  7253. Else, if the cursor is before the first entry, sort the top-level items.
  7254. Else, the children of the entry at point are sorted.
  7255. Sorting can be alphabetically, numerically, by date/time as given by
  7256. a time stamp, by a property, by priority order, or by a custom function.
  7257. The command prompts for the sorting type unless it has been given to the
  7258. function through the SORTING-TYPE argument, which needs to be a character,
  7259. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7260. the precise meaning of each character:
  7261. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7262. c By creation time, which is assumed to be the first inactive time stamp
  7263. at the beginning of a line.
  7264. d By deadline date/time.
  7265. k By clocking time.
  7266. n Numerically, by converting the beginning of the entry/item to a number.
  7267. o By order of TODO keywords.
  7268. p By priority according to the cookie.
  7269. r By the value of a property.
  7270. s By scheduled date/time.
  7271. t By date/time, either the first active time stamp in the entry, or, if
  7272. none exist, by the first inactive one.
  7273. Capital letters will reverse the sort order.
  7274. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7275. called with point at the beginning of the record. It must return a
  7276. value that is compatible with COMPARE-FUNC, the function used to
  7277. compare entries.
  7278. Comparing entries ignores case by default. However, with an optional argument
  7279. WITH-CASE, the sorting considers case as well.
  7280. Sorting is done against the visible part of the headlines, it ignores hidden
  7281. links.
  7282. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7283. A non-nil value for INTERACTIVE? is used to signal that this
  7284. function is being called interactively."
  7285. (interactive (list current-prefix-arg nil nil nil nil t))
  7286. (let ((case-func (if with-case 'identity 'downcase))
  7287. start beg end stars re re2
  7288. txt what tmp)
  7289. ;; Find beginning and end of region to sort
  7290. (cond
  7291. ((org-region-active-p)
  7292. ;; we will sort the region
  7293. (setq end (region-end)
  7294. what "region")
  7295. (goto-char (region-beginning))
  7296. (unless (org-at-heading-p) (outline-next-heading))
  7297. (setq start (point)))
  7298. ((or (org-at-heading-p)
  7299. (ignore-errors (progn (org-back-to-heading) t)))
  7300. ;; we will sort the children of the current headline
  7301. (org-back-to-heading)
  7302. (setq start (point)
  7303. end (progn (org-end-of-subtree t t)
  7304. (or (bolp) (insert "\n"))
  7305. (when (>= (org-back-over-empty-lines) 1)
  7306. (forward-line 1))
  7307. (point))
  7308. what "children")
  7309. (goto-char start)
  7310. (outline-show-subtree)
  7311. (outline-next-heading))
  7312. (t
  7313. ;; we will sort the top-level entries in this file
  7314. (goto-char (point-min))
  7315. (or (org-at-heading-p) (outline-next-heading))
  7316. (setq start (point))
  7317. (goto-char (point-max))
  7318. (beginning-of-line 1)
  7319. (when (looking-at ".*?\\S-")
  7320. ;; File ends in a non-white line
  7321. (end-of-line 1)
  7322. (insert "\n"))
  7323. (setq end (point-max))
  7324. (setq what "top-level")
  7325. (goto-char start)
  7326. (org-show-all '(headings drawers blocks))))
  7327. (setq beg (point))
  7328. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7329. (looking-at "\\(\\*+\\)")
  7330. (setq stars (match-string 1)
  7331. re (concat "^" (regexp-quote stars) " +")
  7332. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7333. txt (buffer-substring beg end))
  7334. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7335. (when (and (not (equal stars "*")) (string-match re2 txt))
  7336. (user-error "Region to sort contains a level above the first entry"))
  7337. (unless sorting-type
  7338. (message
  7339. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7340. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7341. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7342. what)
  7343. (setq sorting-type (read-char-exclusive)))
  7344. (unless getkey-func
  7345. (and (= (downcase sorting-type) ?f)
  7346. (setq getkey-func
  7347. (or (and interactive?
  7348. (org-read-function
  7349. "Function for extracting keys: "))
  7350. (error "Missing key extractor")))))
  7351. (and (= (downcase sorting-type) ?r)
  7352. (not property)
  7353. (setq property
  7354. (completing-read "Property: "
  7355. (mapcar #'list (org-buffer-property-keys t))
  7356. nil t)))
  7357. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7358. (message "Sorting entries...")
  7359. (save-restriction
  7360. (narrow-to-region start end)
  7361. (let ((restore-clock?
  7362. ;; The clock marker is lost when using `sort-subr'; mark
  7363. ;; the clock with temporary `:org-clock-marker-backup'
  7364. ;; text property.
  7365. (when (and (eq (org-clock-is-active) (current-buffer))
  7366. (<= start (marker-position org-clock-marker))
  7367. (>= end (marker-position org-clock-marker)))
  7368. (with-silent-modifications
  7369. (put-text-property (1- org-clock-marker) org-clock-marker
  7370. :org-clock-marker-backup t))
  7371. t))
  7372. (dcst (downcase sorting-type))
  7373. (case-fold-search nil)
  7374. (now (current-time)))
  7375. (org-preserve-local-variables
  7376. (sort-subr
  7377. (/= dcst sorting-type)
  7378. ;; This function moves to the beginning character of the
  7379. ;; "record" to be sorted.
  7380. (lambda nil
  7381. (if (re-search-forward re nil t)
  7382. (goto-char (match-beginning 0))
  7383. (goto-char (point-max))))
  7384. ;; This function moves to the last character of the "record" being
  7385. ;; sorted.
  7386. (lambda nil
  7387. (save-match-data
  7388. (condition-case nil
  7389. (outline-forward-same-level 1)
  7390. (error
  7391. (goto-char (point-max))))))
  7392. ;; This function returns the value that gets sorted against.
  7393. (lambda ()
  7394. (cond
  7395. ((= dcst ?n)
  7396. (string-to-number
  7397. (org-sort-remove-invisible (org-get-heading t t t t))))
  7398. ((= dcst ?a)
  7399. (funcall case-func
  7400. (org-sort-remove-invisible (org-get-heading t t t t))))
  7401. ((= dcst ?k)
  7402. (or (get-text-property (point) :org-clock-minutes) 0))
  7403. ((= dcst ?t)
  7404. (let ((end (save-excursion (outline-next-heading) (point))))
  7405. (if (or (re-search-forward org-ts-regexp end t)
  7406. (re-search-forward org-ts-regexp-both end t))
  7407. (org-time-string-to-seconds (match-string 0))
  7408. (float-time now))))
  7409. ((= dcst ?c)
  7410. (let ((end (save-excursion (outline-next-heading) (point))))
  7411. (if (re-search-forward
  7412. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7413. end t)
  7414. (org-time-string-to-seconds (match-string 0))
  7415. (float-time now))))
  7416. ((= dcst ?s)
  7417. (let ((end (save-excursion (outline-next-heading) (point))))
  7418. (if (re-search-forward org-scheduled-time-regexp end t)
  7419. (org-time-string-to-seconds (match-string 1))
  7420. (float-time now))))
  7421. ((= dcst ?d)
  7422. (let ((end (save-excursion (outline-next-heading) (point))))
  7423. (if (re-search-forward org-deadline-time-regexp end t)
  7424. (org-time-string-to-seconds (match-string 1))
  7425. (float-time now))))
  7426. ((= dcst ?p)
  7427. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7428. (string-to-char (match-string 2))
  7429. org-priority-default))
  7430. ((= dcst ?r)
  7431. (or (org-entry-get nil property) ""))
  7432. ((= dcst ?o)
  7433. (when (looking-at org-complex-heading-regexp)
  7434. (let* ((m (match-string 2))
  7435. (s (if (member m org-done-keywords) '- '+)))
  7436. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7437. ((= dcst ?f)
  7438. (if getkey-func
  7439. (progn
  7440. (setq tmp (funcall getkey-func))
  7441. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7442. tmp)
  7443. (error "Invalid key function `%s'" getkey-func)))
  7444. (t (error "Invalid sorting type `%c'" sorting-type))))
  7445. nil
  7446. (cond
  7447. ((= dcst ?a) 'org-string-collate-lessp)
  7448. ((= dcst ?f)
  7449. (or compare-func
  7450. (and interactive?
  7451. (org-read-function
  7452. (concat "Function for comparing keys "
  7453. "(empty for default `sort-subr' predicate): ")
  7454. 'allow-empty))))
  7455. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7456. (org-cycle-hide-drawers 'all)
  7457. (when restore-clock?
  7458. (move-marker org-clock-marker
  7459. (1+ (next-single-property-change
  7460. start :org-clock-marker-backup)))
  7461. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7462. '(:org-clock-marker-backup t)))))
  7463. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7464. (message "Sorting entries...done")))
  7465. (defun org-contextualize-keys (alist contexts)
  7466. "Return valid elements in ALIST depending on CONTEXTS.
  7467. `org-agenda-custom-commands' or `org-capture-templates' are the
  7468. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7469. or `org-capture-templates-contexts' are the associated contexts
  7470. definitions."
  7471. (let ((contexts
  7472. ;; normalize contexts
  7473. (mapcar
  7474. (lambda(c) (cond ((listp (cadr c))
  7475. (list (car c) (car c) (nth 1 c)))
  7476. ((string= "" (cadr c))
  7477. (list (car c) (car c) (nth 2 c)))
  7478. (t c)))
  7479. contexts))
  7480. (a alist) r s)
  7481. ;; loop over all commands or templates
  7482. (dolist (c a)
  7483. (let (vrules repl)
  7484. (cond
  7485. ((not (assoc (car c) contexts))
  7486. (push c r))
  7487. ((and (assoc (car c) contexts)
  7488. (setq vrules (org-contextualize-validate-key
  7489. (car c) contexts)))
  7490. (mapc (lambda (vr)
  7491. (unless (equal (car vr) (cadr vr))
  7492. (setq repl vr)))
  7493. vrules)
  7494. (if (not repl) (push c r)
  7495. (push (cadr repl) s)
  7496. (push
  7497. (cons (car c)
  7498. (cdr (or (assoc (cadr repl) alist)
  7499. (error "Undefined key `%s' as contextual replacement for `%s'"
  7500. (cadr repl) (car c)))))
  7501. r))))))
  7502. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7503. (delq
  7504. nil
  7505. (delete-dups
  7506. (mapcar (lambda (x)
  7507. (let ((tpl (car x)))
  7508. (unless (delq
  7509. nil
  7510. (mapcar (lambda (y)
  7511. (equal y tpl))
  7512. s))
  7513. x)))
  7514. (reverse r))))))
  7515. (defun org-contextualize-validate-key (key contexts)
  7516. "Check CONTEXTS for agenda or capture KEY."
  7517. (let (res)
  7518. (dolist (r contexts)
  7519. (dolist (rr (car (last r)))
  7520. (when
  7521. (and (equal key (car r))
  7522. (if (functionp rr) (funcall rr)
  7523. (or (and (eq (car rr) 'in-file)
  7524. (buffer-file-name)
  7525. (string-match (cdr rr) (buffer-file-name)))
  7526. (and (eq (car rr) 'in-mode)
  7527. (string-match (cdr rr) (symbol-name major-mode)))
  7528. (and (eq (car rr) 'in-buffer)
  7529. (string-match (cdr rr) (buffer-name)))
  7530. (when (and (eq (car rr) 'not-in-file)
  7531. (buffer-file-name))
  7532. (not (string-match (cdr rr) (buffer-file-name))))
  7533. (when (eq (car rr) 'not-in-mode)
  7534. (not (string-match (cdr rr) (symbol-name major-mode))))
  7535. (when (eq (car rr) 'not-in-buffer)
  7536. (not (string-match (cdr rr) (buffer-name)))))))
  7537. (push r res))))
  7538. (delete-dups (delq nil res))))
  7539. ;; Defined to provide a value for defcustom, since there is no
  7540. ;; string-collate-greaterp in Emacs.
  7541. (defun org-string-collate-greaterp (s1 s2)
  7542. "Return non-nil if S1 is greater than S2 in collation order."
  7543. (not (org-string-collate-lessp s1 s2)))
  7544. ;;;###autoload
  7545. (defun org-run-like-in-org-mode (cmd)
  7546. "Run a command, pretending that the current buffer is in Org mode.
  7547. This will temporarily bind local variables that are typically bound in
  7548. Org mode to the values they have in Org mode, and then interactively
  7549. call CMD."
  7550. (org-load-modules-maybe)
  7551. (let (binds)
  7552. (dolist (var (org-get-local-variables))
  7553. (when (or (not (boundp (car var)))
  7554. (eq (symbol-value (car var))
  7555. (default-value (car var))))
  7556. (push (list (car var) `(quote ,(cadr var))) binds)))
  7557. (eval `(let ,binds
  7558. (call-interactively (quote ,cmd))))))
  7559. (defun org-get-category (&optional pos force-refresh)
  7560. "Get the category applying to position POS."
  7561. (save-match-data
  7562. (when force-refresh (org-refresh-category-properties))
  7563. (let ((pos (or pos (point))))
  7564. (or (get-text-property pos 'org-category)
  7565. (progn (org-refresh-category-properties)
  7566. (get-text-property pos 'org-category))))))
  7567. ;;; Refresh properties
  7568. (defun org-refresh-properties (dprop tprop)
  7569. "Refresh buffer text properties.
  7570. DPROP is the drawer property and TPROP is either the
  7571. corresponding text property to set, or an alist with each element
  7572. being a text property (as a symbol) and a function to apply to
  7573. the value of the drawer property."
  7574. (let* ((case-fold-search t)
  7575. (inhibit-read-only t)
  7576. (inherit? (org-property-inherit-p dprop))
  7577. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7578. (global-or-keyword (and inherit?
  7579. (org--property-global-or-keyword-value dprop nil))))
  7580. (with-silent-modifications
  7581. (org-with-point-at 1
  7582. ;; Set global and keyword based values to the whole buffer.
  7583. (when global-or-keyword
  7584. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7585. ;; Set values based on property-drawers throughout the document.
  7586. (while (re-search-forward property-re nil t)
  7587. (when (org-at-property-p)
  7588. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7589. (outline-next-heading))))))
  7590. (defun org-refresh-property (tprop p &optional inherit)
  7591. "Refresh the buffer text property TPROP from the drawer property P.
  7592. The refresh happens only for the current entry, or the whole
  7593. sub-tree if optional argument INHERIT is non-nil.
  7594. If point is before first headline, the function applies to the
  7595. part before the first headline. In that particular case, when
  7596. optional argument INHERIT is non-nil, it refreshes properties for
  7597. the whole buffer."
  7598. (save-excursion
  7599. (org-back-to-heading-or-point-min t)
  7600. (let ((start (point))
  7601. (end (save-excursion
  7602. (cond ((and inherit (org-before-first-heading-p))
  7603. (point-max))
  7604. (inherit
  7605. (org-end-of-subtree t t))
  7606. ((outline-next-heading))
  7607. ((point-max))))))
  7608. (if (symbolp tprop)
  7609. ;; TPROP is a text property symbol.
  7610. (put-text-property start end tprop p)
  7611. ;; TPROP is an alist with (property . function) elements.
  7612. (pcase-dolist (`(,prop . ,f) tprop)
  7613. (put-text-property start end prop (funcall f p)))))))
  7614. (defun org-refresh-category-properties ()
  7615. "Refresh category text properties in the buffer."
  7616. (let ((case-fold-search t)
  7617. (inhibit-read-only t)
  7618. (default-category
  7619. (cond ((null org-category)
  7620. (if buffer-file-name
  7621. (file-name-sans-extension
  7622. (file-name-nondirectory buffer-file-name))
  7623. "???"))
  7624. ((symbolp org-category) (symbol-name org-category))
  7625. (t org-category))))
  7626. (with-silent-modifications
  7627. (org-with-wide-buffer
  7628. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7629. ;; keyword. If none is found, fall-back to `org-category' or
  7630. ;; buffer file name, or set it by the document property drawer.
  7631. (put-text-property
  7632. (point-min) (point-max)
  7633. 'org-category
  7634. (catch 'buffer-category
  7635. (goto-char (point-max))
  7636. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7637. (let ((element (org-element-at-point)))
  7638. (when (eq (org-element-type element) 'keyword)
  7639. (throw 'buffer-category
  7640. (org-element-property :value element)))))
  7641. default-category))
  7642. ;; Set categories from the document property drawer or
  7643. ;; property drawers in the outline. If category is found in
  7644. ;; the property drawer for the whole buffer that value
  7645. ;; overrides the keyword-based value set above.
  7646. (goto-char (point-min))
  7647. (let ((regexp (org-re-property "CATEGORY")))
  7648. (while (re-search-forward regexp nil t)
  7649. (let ((value (match-string-no-properties 3)))
  7650. (when (org-at-property-p)
  7651. (put-text-property
  7652. (save-excursion (org-back-to-heading-or-point-min t))
  7653. (save-excursion (if (org-before-first-heading-p)
  7654. (point-max)
  7655. (org-end-of-subtree t t)))
  7656. 'org-category
  7657. value)))))))))
  7658. (defun org-refresh-stats-properties ()
  7659. "Refresh stats text properties in the buffer."
  7660. (with-silent-modifications
  7661. (org-with-point-at 1
  7662. (let ((regexp (concat org-outline-regexp-bol
  7663. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7664. (while (re-search-forward regexp nil t)
  7665. (let* ((numerator (string-to-number (match-string 1)))
  7666. (denominator (and (match-end 2)
  7667. (string-to-number (match-string 2))))
  7668. (stats (cond ((not denominator) numerator) ;percent
  7669. ((= denominator 0) 0)
  7670. (t (/ (* numerator 100) denominator)))))
  7671. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7672. 'org-stats stats)))))))
  7673. (defun org-refresh-effort-properties ()
  7674. "Refresh effort properties."
  7675. (org-refresh-properties
  7676. org-effort-property
  7677. '((effort . identity)
  7678. (effort-minutes . org-duration-to-minutes))))
  7679. (defun org-find-file-at-mouse (ev)
  7680. "Open file link or URL at mouse."
  7681. (interactive "e")
  7682. (mouse-set-point ev)
  7683. (org-open-at-point 'in-emacs))
  7684. (defun org-open-at-mouse (ev)
  7685. "Open file link or URL at mouse.
  7686. See the docstring of `org-open-file' for details."
  7687. (interactive "e")
  7688. (mouse-set-point ev)
  7689. (when (eq major-mode 'org-agenda-mode)
  7690. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7691. (org-open-at-point))
  7692. (defvar org-window-config-before-follow-link nil
  7693. "The window configuration before following a link.
  7694. This is saved in case the need arises to restore it.")
  7695. (defun org--file-default-apps ()
  7696. "Return the default applications for this operating system."
  7697. (pcase system-type
  7698. (`darwin org-file-apps-macos)
  7699. (`windows-nt org-file-apps-windowsnt)
  7700. (_ org-file-apps-gnu)))
  7701. (defun org--file-apps-entry-dlink-p (entry)
  7702. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7703. It assumes that is the case when the entry uses a regular
  7704. expression which has at least one grouping construct and the
  7705. action is either a Lisp form or a command string containing
  7706. \"%1\", i.e., using at least one subexpression match as
  7707. a parameter."
  7708. (pcase entry
  7709. (`(,selector . ,action)
  7710. (and (stringp selector)
  7711. (> (regexp-opt-depth selector) 0)
  7712. (or (and (stringp action)
  7713. (string-match "%[0-9]" action))
  7714. (consp action))))
  7715. (_ nil)))
  7716. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7717. "Convert extensions to regular expressions in the cars of LIST.
  7718. Also, weed out any non-string entries, because the return value
  7719. is used only for regexp matching.
  7720. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7721. point to the symbol `emacs', indicating that the file should be
  7722. opened in Emacs."
  7723. (append
  7724. (delq nil
  7725. (mapcar (lambda (x)
  7726. (unless (not (stringp (car x)))
  7727. (if (string-match "\\W" (car x))
  7728. x
  7729. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7730. list))
  7731. (when add-auto-mode
  7732. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7733. ;;;###autoload
  7734. (defun org-open-file (path &optional in-emacs line search)
  7735. "Open the file at PATH.
  7736. First, this expands any special file name abbreviations. Then the
  7737. configuration variable `org-file-apps' is checked if it contains an
  7738. entry for this file type, and if yes, the corresponding command is launched.
  7739. If no application is found, Emacs simply visits the file.
  7740. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7741. With a double \\[universal-argument] \\[universal-argument] \
  7742. prefix arg, Org tries to avoid opening in Emacs
  7743. and to use an external application to visit the file.
  7744. Optional LINE specifies a line to go to, optional SEARCH a string
  7745. to search for. If LINE or SEARCH is given, the file will be
  7746. opened in Emacs, unless an entry from `org-file-apps' that makes
  7747. use of groups in a regexp matches.
  7748. If you want to change the way frames are used when following a
  7749. link, please customize `org-link-frame-setup'.
  7750. If the file does not exist, throw an error."
  7751. (let* ((file (if (equal path "") buffer-file-name
  7752. (substitute-in-file-name (expand-file-name path))))
  7753. (file-apps (append org-file-apps (org--file-default-apps)))
  7754. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7755. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7756. file-apps))
  7757. (remp (and (assq 'remote apps) (file-remote-p file)))
  7758. (dirp (unless remp (file-directory-p file)))
  7759. (file (if (and dirp org-open-directory-means-index-dot-org)
  7760. (concat (file-name-as-directory file) "index.org")
  7761. file))
  7762. (a-m-a-p (assq 'auto-mode apps))
  7763. (dfile (downcase file))
  7764. ;; Reconstruct the original link from the PATH, LINE and
  7765. ;; SEARCH args.
  7766. (link (cond (line (concat file "::" (number-to-string line)))
  7767. (search (concat file "::" search))
  7768. (t file)))
  7769. (dlink (downcase link))
  7770. (ext
  7771. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7772. (match-string 1 dfile)))
  7773. (save-position-maybe
  7774. (let ((old-buffer (current-buffer))
  7775. (old-pos (point))
  7776. (old-mode major-mode))
  7777. (lambda ()
  7778. (and (derived-mode-p 'org-mode)
  7779. (eq old-mode 'org-mode)
  7780. (or (not (eq old-buffer (current-buffer)))
  7781. (not (eq old-pos (point))))
  7782. (org-mark-ring-push old-pos old-buffer)))))
  7783. cmd link-match-data)
  7784. (cond
  7785. ((member in-emacs '((16) system))
  7786. (setq cmd (cdr (assq 'system apps))))
  7787. (in-emacs (setq cmd 'emacs))
  7788. (t
  7789. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7790. (and dirp (cdr (assq 'directory apps)))
  7791. ;; First, try matching against apps-dlink if we
  7792. ;; get a match here, store the match data for
  7793. ;; later.
  7794. (let ((match (assoc-default dlink apps-dlink
  7795. 'string-match)))
  7796. (if match
  7797. (progn (setq link-match-data (match-data))
  7798. match)
  7799. (progn (setq in-emacs (or in-emacs line search))
  7800. nil))) ; if we have no match in apps-dlink,
  7801. ; always open the file in emacs if line or search
  7802. ; is given (for backwards compatibility)
  7803. (assoc-default dfile
  7804. (org--file-apps-regexp-alist apps a-m-a-p)
  7805. 'string-match)
  7806. (cdr (assoc ext apps))
  7807. (cdr (assq t apps))))))
  7808. (when (eq cmd 'system)
  7809. (setq cmd (cdr (assq 'system apps))))
  7810. (when (eq cmd 'default)
  7811. (setq cmd (cdr (assoc t apps))))
  7812. (when (eq cmd 'mailcap)
  7813. (require 'mailcap)
  7814. (mailcap-parse-mailcaps)
  7815. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7816. (command (mailcap-mime-info mime-type)))
  7817. (if (stringp command)
  7818. (setq cmd command)
  7819. (setq cmd 'emacs))))
  7820. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7821. (not (file-exists-p file))
  7822. (not org-open-non-existing-files))
  7823. (user-error "No such file: %s" file))
  7824. (cond
  7825. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7826. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7827. (while (string-match "['\"]%s['\"]" cmd)
  7828. (setq cmd (replace-match "%s" t t cmd)))
  7829. (setq cmd (replace-regexp-in-string
  7830. "%s"
  7831. (shell-quote-argument (convert-standard-filename file))
  7832. cmd
  7833. nil t))
  7834. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7835. (save-match-data
  7836. (let ((match-index 1)
  7837. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7838. (set-match-data link-match-data)
  7839. (while (<= match-index number-of-groups)
  7840. (let ((regex (concat "%" (number-to-string match-index)))
  7841. (replace-with (match-string match-index dlink)))
  7842. (while (string-match regex cmd)
  7843. (setq cmd (replace-match replace-with t t cmd))))
  7844. (setq match-index (+ match-index 1)))))
  7845. (save-window-excursion
  7846. (message "Running %s...done" cmd)
  7847. (start-process-shell-command cmd nil cmd)
  7848. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7849. ((or (stringp cmd)
  7850. (eq cmd 'emacs))
  7851. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7852. (widen)
  7853. (cond (line (org-goto-line line)
  7854. (when (derived-mode-p 'org-mode) (org-reveal)))
  7855. (search (condition-case err
  7856. (org-link-search search)
  7857. ;; Save position before error-ing out so user
  7858. ;; can easily move back to the original buffer.
  7859. (error (funcall save-position-maybe)
  7860. (error (nth 1 err)))))))
  7861. ((functionp cmd)
  7862. (save-match-data
  7863. (set-match-data link-match-data)
  7864. (condition-case nil
  7865. (funcall cmd file link)
  7866. ;; FIXME: Remove this check when most default installations
  7867. ;; of Emacs have at least Org 9.0.
  7868. ((debug wrong-number-of-arguments wrong-type-argument
  7869. invalid-function)
  7870. (user-error "Please see Org News for version 9.0 about \
  7871. `org-file-apps'--Lisp error: %S" cmd)))))
  7872. ((consp cmd)
  7873. ;; FIXME: Remove this check when most default installations of
  7874. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7875. ;; fall back to `org-link-frame-setup' for an old usage of
  7876. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7877. (user-error "Please see Org News for version 9.0 about \
  7878. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7879. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7880. (funcall save-position-maybe)))
  7881. ;;;###autoload
  7882. (defun org-open-at-point-global ()
  7883. "Follow a link or a time-stamp like Org mode does.
  7884. Also follow links and emails as seen by `thing-at-point'.
  7885. This command can be called in any mode to follow an external
  7886. link or a time-stamp that has Org mode syntax. Its behavior
  7887. is undefined when called on internal links like fuzzy links.
  7888. Raise a user error when there is nothing to follow."
  7889. (interactive)
  7890. (let ((tap-url (thing-at-point 'url))
  7891. (tap-email (thing-at-point 'email)))
  7892. (cond ((org-in-regexp org-link-any-re)
  7893. (org-link-open-from-string (match-string-no-properties 0)))
  7894. ((or (org-in-regexp org-ts-regexp-both nil t)
  7895. (org-in-regexp org-tsr-regexp-both nil t))
  7896. (org-follow-timestamp-link))
  7897. (tap-url (org-link-open-from-string tap-url))
  7898. (tap-email (org-link-open-from-string
  7899. (concat "mailto:" tap-email)))
  7900. (t (user-error "No link found")))))
  7901. (defvar org-open-at-point-functions nil
  7902. "Hook that is run when following a link at point.
  7903. Functions in this hook must return t if they identify and follow
  7904. a link at point. If they don't find anything interesting at point,
  7905. they must return nil.")
  7906. (defun org-open-at-point (&optional arg)
  7907. "Open link, timestamp, footnote or tags at point.
  7908. When point is on a link, follow it. Normally, files will be
  7909. opened by an appropriate application. If the optional prefix
  7910. argument ARG is non-nil, Emacs will visit the file. With
  7911. a double prefix argument, try to open outside of Emacs, in the
  7912. application the system uses for this file type.
  7913. When point is on a timestamp, open the agenda at the day
  7914. specified.
  7915. When point is a footnote definition, move to the first reference
  7916. found. If it is on a reference, move to the associated
  7917. definition.
  7918. When point is on a headline, display a list of every link in the
  7919. entry, so it is possible to pick one, or all, of them. If point
  7920. is on a tag, call `org-tags-view' instead.
  7921. On top of syntactically correct links, this function also tries
  7922. to open links and time-stamps in comments, node properties, and
  7923. keywords if point is on something looking like a timestamp or
  7924. a link."
  7925. (interactive "P")
  7926. (org-load-modules-maybe)
  7927. (setq org-window-config-before-follow-link (current-window-configuration))
  7928. (org-remove-occur-highlights nil nil t)
  7929. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7930. (let* ((context
  7931. ;; Only consider supported types, even if they are not the
  7932. ;; closest one.
  7933. (org-element-lineage
  7934. (org-element-context)
  7935. '(clock comment comment-block footnote-definition
  7936. footnote-reference headline inline-src-block inlinetask
  7937. keyword link node-property planning src-block timestamp)
  7938. t))
  7939. (type (org-element-type context))
  7940. (value (org-element-property :value context)))
  7941. (cond
  7942. ((not type) (user-error "No link found"))
  7943. ;; No valid link at point. For convenience, look if something
  7944. ;; looks like a link under point in some specific places.
  7945. ((memq type '(comment comment-block node-property keyword))
  7946. (call-interactively #'org-open-at-point-global))
  7947. ;; On a headline or an inlinetask, but not on a timestamp,
  7948. ;; a link, a footnote reference.
  7949. ((memq type '(headline inlinetask))
  7950. (org-match-line org-complex-heading-regexp)
  7951. (let ((tags-beg (match-beginning 5))
  7952. (tags-end (match-end 5)))
  7953. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7954. ;; On tags.
  7955. (org-tags-view
  7956. arg
  7957. (save-excursion
  7958. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7959. (end-tag (search-forward ":" tags-end nil 2)))
  7960. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7961. ;; Not on tags.
  7962. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7963. (`(nil . ,_)
  7964. (require 'org-attach)
  7965. (when (org-attach-dir)
  7966. (message "Opening attachment")
  7967. (if (equal arg '(4))
  7968. (org-attach-reveal-in-emacs)
  7969. (org-attach-reveal))))
  7970. (`(,links . ,links-end)
  7971. (dolist (link (if (stringp links) (list links) links))
  7972. (search-forward link nil links-end)
  7973. (goto-char (match-beginning 0))
  7974. (org-open-at-point arg)))))))
  7975. ;; On a footnote reference or at definition's label.
  7976. ((or (eq type 'footnote-reference)
  7977. (and (eq type 'footnote-definition)
  7978. (save-excursion
  7979. ;; Do not validate action when point is on the
  7980. ;; spaces right after the footnote label, in order
  7981. ;; to be on par with behavior on links.
  7982. (skip-chars-forward " \t")
  7983. (let ((begin
  7984. (org-element-property :contents-begin context)))
  7985. (if begin (< (point) begin)
  7986. (= (org-element-property :post-affiliated context)
  7987. (line-beginning-position)))))))
  7988. (org-footnote-action))
  7989. ;; On a planning line. Check if we are really on a timestamp.
  7990. ((and (eq type 'planning)
  7991. (org-in-regexp org-ts-regexp-both nil t))
  7992. (org-follow-timestamp-link))
  7993. ;; On a clock line, make sure point is on the timestamp
  7994. ;; before opening it.
  7995. ((and (eq type 'clock)
  7996. value
  7997. (>= (point) (org-element-property :begin value))
  7998. (<= (point) (org-element-property :end value)))
  7999. (org-follow-timestamp-link))
  8000. ((eq type 'src-block) (org-babel-open-src-block-result))
  8001. ;; Do nothing on white spaces after an object.
  8002. ((>= (point)
  8003. (save-excursion
  8004. (goto-char (org-element-property :end context))
  8005. (skip-chars-backward " \t")
  8006. (point)))
  8007. (user-error "No link found"))
  8008. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8009. ((eq type 'timestamp) (org-follow-timestamp-link))
  8010. ((eq type 'link) (org-link-open context arg))
  8011. (t (user-error "No link found")))))
  8012. (run-hook-with-args 'org-follow-link-hook))
  8013. ;;;###autoload
  8014. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8015. "Offer links in the current entry and return the selected link.
  8016. If there is only one link, return it.
  8017. If NTH is an integer, return the NTH link found.
  8018. If ZERO is a string, check also this string for a link, and if
  8019. there is one, return it."
  8020. (with-current-buffer buffer
  8021. (org-with-wide-buffer
  8022. (goto-char marker)
  8023. (let ((cnt ?0)
  8024. have-zero end links link c)
  8025. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8026. (push (match-string 0 zero) links)
  8027. (setq cnt (1- cnt) have-zero t))
  8028. (save-excursion
  8029. (org-back-to-heading t)
  8030. (setq end (save-excursion (outline-next-heading) (point)))
  8031. (while (re-search-forward org-link-any-re end t)
  8032. (push (match-string 0) links))
  8033. (setq links (org-uniquify (reverse links))))
  8034. (cond
  8035. ((null links)
  8036. (message "No links"))
  8037. ((equal (length links) 1)
  8038. (setq link (car links)))
  8039. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8040. (setq link (nth (if have-zero nth (1- nth)) links)))
  8041. (t ; we have to select a link
  8042. (save-excursion
  8043. (save-window-excursion
  8044. (delete-other-windows)
  8045. (with-output-to-temp-buffer "*Select Link*"
  8046. (dolist (l links)
  8047. (cond
  8048. ((not (string-match org-link-bracket-re l))
  8049. (princ (format "[%c] %s\n" (cl-incf cnt)
  8050. (org-unbracket-string "<" ">" l))))
  8051. ((match-end 2)
  8052. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8053. (match-string 2 l) (match-string 1 l))))
  8054. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8055. (match-string 1 l)))))))
  8056. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8057. (message "Select link to open, RET to open all:")
  8058. (setq c (read-char-exclusive))
  8059. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8060. (when (equal c ?q) (user-error "Abort"))
  8061. (if (equal c ?\C-m)
  8062. (setq link links)
  8063. (setq nth (- c ?0))
  8064. (when have-zero (setq nth (1+ nth)))
  8065. (unless (and (integerp nth) (>= (length links) nth))
  8066. (user-error "Invalid link selection"))
  8067. (setq link (nth (1- nth) links)))))
  8068. (cons link end)))))
  8069. ;;; File search
  8070. (defun org-do-occur (regexp &optional cleanup)
  8071. "Call the Emacs command `occur'.
  8072. If CLEANUP is non-nil, remove the printout of the regular expression
  8073. in the *Occur* buffer. This is useful if the regex is long and not useful
  8074. to read."
  8075. (occur regexp)
  8076. (when cleanup
  8077. (let ((cwin (selected-window)) win beg end)
  8078. (when (setq win (get-buffer-window "*Occur*"))
  8079. (select-window win))
  8080. (goto-char (point-min))
  8081. (when (re-search-forward "match[a-z]+" nil t)
  8082. (setq beg (match-end 0))
  8083. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8084. (setq end (1- (match-beginning 0)))))
  8085. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8086. (goto-char (point-min))
  8087. (select-window cwin))))
  8088. ;;; The Mark Ring
  8089. (defvar org-mark-ring nil
  8090. "Mark ring for positions before jumps in Org mode.")
  8091. (defvar org-mark-ring-last-goto nil
  8092. "Last position in the mark ring used to go back.")
  8093. ;; Fill and close the ring
  8094. (setq org-mark-ring nil)
  8095. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8096. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8097. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8098. org-mark-ring)
  8099. (defun org-mark-ring-push (&optional pos buffer)
  8100. "Put the current position into the mark ring and rotate it.
  8101. Also push position into the Emacs mark ring. If optional
  8102. argument POS and BUFFER are not nil, mark this location instead."
  8103. (interactive)
  8104. (let ((pos (or pos (point)))
  8105. (buffer (or buffer (current-buffer))))
  8106. (with-current-buffer buffer
  8107. (org-with-point-at pos (push-mark nil t)))
  8108. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8109. (move-marker (car org-mark-ring) pos buffer))
  8110. (message
  8111. (substitute-command-keys
  8112. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8113. (defun org-mark-ring-goto (&optional n)
  8114. "Jump to the previous position in the mark ring.
  8115. With prefix arg N, jump back that many stored positions. When
  8116. called several times in succession, walk through the entire ring.
  8117. Org mode commands jumping to a different position in the current file,
  8118. or to another Org file, automatically push the old position onto the ring."
  8119. (interactive "p")
  8120. (let (p m)
  8121. (if (eq last-command this-command)
  8122. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8123. (setq p org-mark-ring))
  8124. (setq org-mark-ring-last-goto p)
  8125. (setq m (car p))
  8126. (pop-to-buffer-same-window (marker-buffer m))
  8127. (goto-char m)
  8128. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8129. ;;; Following specific links
  8130. (defvar org-agenda-buffer-tmp-name)
  8131. (defvar org-agenda-start-on-weekday)
  8132. (defun org-follow-timestamp-link ()
  8133. "Open an agenda view for the time-stamp date/range at point."
  8134. (cond
  8135. ((org-at-date-range-p t)
  8136. (let ((org-agenda-start-on-weekday)
  8137. (t1 (match-string 1))
  8138. (t2 (match-string 2)) tt1 tt2)
  8139. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8140. tt2 (time-to-days (org-time-string-to-time t2)))
  8141. (let ((org-agenda-buffer-tmp-name
  8142. (format "*Org Agenda(a:%s)"
  8143. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8144. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8145. ((org-at-timestamp-p 'lax)
  8146. (let ((org-agenda-buffer-tmp-name
  8147. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8148. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8149. (substring (match-string 1) 0 10)))
  8150. 1)))
  8151. (t (error "This should not happen"))))
  8152. ;;; Following file links
  8153. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8154. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8155. (declare-function mailcap-mime-info
  8156. "mailcap" (string &optional request no-decode))
  8157. (defvar org-wait nil)
  8158. ;;;; Refiling
  8159. (defun org-get-org-file ()
  8160. "Read a filename, with default directory `org-directory'."
  8161. (let ((default (or org-default-notes-file remember-data-file)))
  8162. (read-file-name (format "File name [%s]: " default)
  8163. (file-name-as-directory org-directory)
  8164. default)))
  8165. (defun org-notes-order-reversed-p ()
  8166. "Check if the current file should receive notes in reversed order."
  8167. (cond
  8168. ((not org-reverse-note-order) nil)
  8169. ((eq t org-reverse-note-order) t)
  8170. ((not (listp org-reverse-note-order)) nil)
  8171. (t (catch 'exit
  8172. (dolist (entry org-reverse-note-order)
  8173. (when (string-match (car entry) buffer-file-name)
  8174. (throw 'exit (cdr entry))))))))
  8175. (defvar org-agenda-new-buffers nil
  8176. "Buffers created to visit agenda files.")
  8177. (declare-function org-string-nw-p "org-macs" (s))
  8178. ;;;; Dynamic blocks
  8179. (defun org-find-dblock (name)
  8180. "Find the first dynamic block with name NAME in the buffer.
  8181. If not found, stay at current position and return nil."
  8182. (let ((case-fold-search t) pos)
  8183. (save-excursion
  8184. (goto-char (point-min))
  8185. (setq pos (and (re-search-forward
  8186. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8187. (match-beginning 0))))
  8188. (when pos (goto-char pos))
  8189. pos))
  8190. (defun org-create-dblock (plist)
  8191. "Create a dynamic block section, with parameters taken from PLIST.
  8192. PLIST must contain a :name entry which is used as the name of the block."
  8193. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8194. (end-of-line 1)
  8195. (newline))
  8196. (let ((col (current-column))
  8197. (name (plist-get plist :name)))
  8198. (insert "#+BEGIN: " name)
  8199. (while plist
  8200. (if (eq (car plist) :name)
  8201. (setq plist (cddr plist))
  8202. (insert " " (prin1-to-string (pop plist)))))
  8203. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8204. (beginning-of-line -2)))
  8205. (defun org-prepare-dblock ()
  8206. "Prepare dynamic block for refresh.
  8207. This empties the block, puts the cursor at the insert position and returns
  8208. the property list including an extra property :name with the block name."
  8209. (unless (looking-at org-dblock-start-re)
  8210. (user-error "Not at a dynamic block"))
  8211. (let* ((begdel (1+ (match-end 0)))
  8212. (name (org-no-properties (match-string 1)))
  8213. (params (append (list :name name)
  8214. (read (concat "(" (match-string 3) ")")))))
  8215. (save-excursion
  8216. (beginning-of-line 1)
  8217. (skip-chars-forward " \t")
  8218. (setq params (plist-put params :indentation-column (current-column))))
  8219. (unless (re-search-forward org-dblock-end-re nil t)
  8220. (error "Dynamic block not terminated"))
  8221. (setq params
  8222. (append params
  8223. (list :content (buffer-substring
  8224. begdel (match-beginning 0)))))
  8225. (delete-region begdel (match-beginning 0))
  8226. (goto-char begdel)
  8227. (open-line 1)
  8228. params))
  8229. (defun org-map-dblocks (&optional command)
  8230. "Apply COMMAND to all dynamic blocks in the current buffer.
  8231. If COMMAND is not given, use `org-update-dblock'."
  8232. (let ((cmd (or command 'org-update-dblock)))
  8233. (save-excursion
  8234. (goto-char (point-min))
  8235. (while (re-search-forward org-dblock-start-re nil t)
  8236. (goto-char (match-beginning 0))
  8237. (save-excursion
  8238. (condition-case nil
  8239. (funcall cmd)
  8240. (error (message "Error during update of dynamic block"))))
  8241. (unless (re-search-forward org-dblock-end-re nil t)
  8242. (error "Dynamic block not terminated"))))))
  8243. (defvar org-dynamic-block-alist nil
  8244. "Alist defining all the Org dynamic blocks.
  8245. The key is the dynamic block type name, as a string. The value
  8246. is the function used to insert the dynamic block.
  8247. Use `org-dynamic-block-define' to populate it.")
  8248. (defun org-dynamic-block-function (type)
  8249. "Return function associated to a given dynamic block type.
  8250. TYPE is the dynamic block type, as a string."
  8251. (cdr (assoc type org-dynamic-block-alist)))
  8252. (defun org-dynamic-block-types ()
  8253. "List all defined dynamic block types."
  8254. (mapcar #'car org-dynamic-block-alist))
  8255. (defun org-dynamic-block-define (type func)
  8256. "Define dynamic block TYPE with FUNC.
  8257. TYPE is a string. FUNC is the function creating the dynamic
  8258. block of such type."
  8259. (pcase (assoc type org-dynamic-block-alist)
  8260. (`nil (push (cons type func) org-dynamic-block-alist))
  8261. (def (setcdr def func))))
  8262. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8263. "Insert a dynamic block of type TYPE.
  8264. When used interactively, select the dynamic block types among
  8265. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8266. is non-nil, call the dynamic block function interactively."
  8267. (interactive (list (completing-read "Dynamic block: "
  8268. (org-dynamic-block-types))
  8269. t))
  8270. (pcase (org-dynamic-block-function type)
  8271. (`nil (error "No such dynamic block: %S" type))
  8272. ((and f (pred functionp))
  8273. (if interactive-p (call-interactively f) (funcall f)))
  8274. (_ (error "Invalid function for dynamic block %S" type))))
  8275. (defun org-dblock-update (&optional arg)
  8276. "User command for updating dynamic blocks.
  8277. Update the dynamic block at point. With prefix ARG, update all dynamic
  8278. blocks in the buffer."
  8279. (interactive "P")
  8280. (if arg
  8281. (org-update-all-dblocks)
  8282. (or (looking-at org-dblock-start-re)
  8283. (org-beginning-of-dblock))
  8284. (org-update-dblock)))
  8285. (defun org-update-dblock ()
  8286. "Update the dynamic block at point.
  8287. This means to empty the block, parse for parameters and then call
  8288. the correct writing function."
  8289. (interactive)
  8290. (save-excursion
  8291. (let* ((win (selected-window))
  8292. (pos (point))
  8293. (line (org-current-line))
  8294. (params (org-prepare-dblock))
  8295. (name (plist-get params :name))
  8296. (indent (plist-get params :indentation-column))
  8297. (cmd (intern (concat "org-dblock-write:" name))))
  8298. (message "Updating dynamic block `%s' at line %d..." name line)
  8299. (funcall cmd params)
  8300. (message "Updating dynamic block `%s' at line %d...done" name line)
  8301. (goto-char pos)
  8302. (when (and indent (> indent 0))
  8303. (setq indent (make-string indent ?\ ))
  8304. (save-excursion
  8305. (select-window win)
  8306. (org-beginning-of-dblock)
  8307. (forward-line 1)
  8308. (while (not (looking-at org-dblock-end-re))
  8309. (insert indent)
  8310. (beginning-of-line 2))
  8311. (when (looking-at org-dblock-end-re)
  8312. (and (looking-at "[ \t]+")
  8313. (replace-match ""))
  8314. (insert indent)))))))
  8315. (defun org-beginning-of-dblock ()
  8316. "Find the beginning of the dynamic block at point.
  8317. Error if there is no such block at point."
  8318. (let ((pos (point))
  8319. beg)
  8320. (end-of-line 1)
  8321. (if (and (re-search-backward org-dblock-start-re nil t)
  8322. (setq beg (match-beginning 0))
  8323. (re-search-forward org-dblock-end-re nil t)
  8324. (> (match-end 0) pos))
  8325. (goto-char beg)
  8326. (goto-char pos)
  8327. (error "Not in a dynamic block"))))
  8328. (defun org-update-all-dblocks ()
  8329. "Update all dynamic blocks in the buffer.
  8330. This function can be used in a hook."
  8331. (interactive)
  8332. (when (derived-mode-p 'org-mode)
  8333. (org-map-dblocks 'org-update-dblock)))
  8334. ;;;; Completion
  8335. (declare-function org-export-backend-options "ox" (cl-x) t)
  8336. (defun org-get-export-keywords ()
  8337. "Return a list of all currently understood export keywords.
  8338. Export keywords include options, block names, attributes and
  8339. keywords relative to each registered export back-end."
  8340. (let (keywords)
  8341. (dolist (backend
  8342. (bound-and-true-p org-export-registered-backends)
  8343. (delq nil keywords))
  8344. ;; Back-end name (for keywords, like #+LATEX:)
  8345. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8346. (dolist (option-entry (org-export-backend-options backend))
  8347. ;; Back-end options.
  8348. (push (nth 1 option-entry) keywords)))))
  8349. (defconst org-options-keywords
  8350. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8351. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8352. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8353. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8354. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8355. (defcustom org-structure-template-alist
  8356. '(("a" . "export ascii")
  8357. ("c" . "center")
  8358. ("C" . "comment")
  8359. ("e" . "example")
  8360. ("E" . "export")
  8361. ("h" . "export html")
  8362. ("l" . "export latex")
  8363. ("q" . "quote")
  8364. ("s" . "src")
  8365. ("v" . "verse"))
  8366. "An alist of keys and block types.
  8367. `org-insert-structure-template' will display a menu with this
  8368. list of templates to choose from. The block type is inserted,
  8369. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8370. The menu keys are defined by the car of each entry in this alist.
  8371. If two entries have the keys \"a\" and \"aa\" respectively, the
  8372. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8373. latter will be inserted by typing \"aa\". If an entry with the
  8374. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8375. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8376. block can be inserted by pressing TAB after the string \"<KEY\"."
  8377. :group 'org-edit-structure
  8378. :type '(repeat
  8379. (cons (string :tag "Key")
  8380. (string :tag "Template")))
  8381. :package-version '(Org . "9.2"))
  8382. (defun org--check-org-structure-template-alist (&optional checklist)
  8383. "Check whether `org-structure-template-alist' is set up correctly.
  8384. In particular, check if the Org 9.2 format is used as opposed to
  8385. previous format."
  8386. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8387. (or (eval checklist)
  8388. org-structure-template-alist))))
  8389. (when elm
  8390. (org-display-warning
  8391. (format "
  8392. Please update the entries of `%s'.
  8393. In Org 9.2 the format was changed from something like
  8394. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8395. to something like
  8396. (\"s\" . \"src\")
  8397. Please refer to the documentation of `org-structure-template-alist'.
  8398. The following entries must be updated:
  8399. %s"
  8400. (or checklist 'org-structure-template-alist)
  8401. (pp-to-string elm))))))
  8402. (defun org--insert-structure-template-mks ()
  8403. "Present `org-structure-template-alist' with `org-mks'.
  8404. Menus are added if keys require more than one keystroke. Tabs
  8405. are added to single key entries when more than one stroke is
  8406. needed. Keys longer than two characters are reduced to two
  8407. characters."
  8408. (org--check-org-structure-template-alist)
  8409. (let* (case-fold-search
  8410. (templates (append org-structure-template-alist
  8411. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8412. (keys (mapcar #'car templates))
  8413. (start-letters
  8414. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8415. ;; Sort each element of `org-structure-template-alist' into
  8416. ;; sublists according to the first letter.
  8417. (superlist
  8418. (mapcar (lambda (letter)
  8419. (list letter
  8420. (cl-remove-if-not
  8421. (apply-partially #'string-match-p (concat "^" letter))
  8422. templates :key #'car)))
  8423. start-letters)))
  8424. (org-mks
  8425. (apply #'append
  8426. ;; Make an `org-mks' table. If only one element is
  8427. ;; present in a sublist, make it part of the top-menu,
  8428. ;; otherwise make a submenu according to the starting
  8429. ;; letter and populate it.
  8430. (mapcar (lambda (sublist)
  8431. (if (eq 1 (length (cadr sublist)))
  8432. (mapcar (lambda (elm)
  8433. (list (substring (car elm) 0 1)
  8434. (cdr elm) ""))
  8435. (cadr sublist))
  8436. ;; Create submenu.
  8437. (let* ((topkey (car sublist))
  8438. (elms (cadr sublist))
  8439. (keys (mapcar #'car elms))
  8440. (long (> (length elms) 3)))
  8441. (append
  8442. (list
  8443. ;; Make a description of the submenu.
  8444. (list topkey
  8445. (concat
  8446. (mapconcat #'cdr
  8447. (cl-subseq elms 0 (if long 3 (length elms)))
  8448. ", ")
  8449. (when long ", ..."))))
  8450. ;; List of entries in submenu.
  8451. (cl-mapcar #'list
  8452. (org--insert-structure-template-unique-keys keys)
  8453. (mapcar #'cdr elms)
  8454. (make-list (length elms) ""))))))
  8455. superlist))
  8456. "Select a key\n============"
  8457. "Key: ")))
  8458. (defun org--insert-structure-template-unique-keys (keys)
  8459. "Make a list of unique, two characters long elements from KEYS.
  8460. Elements of length one have a tab appended. Elements of length
  8461. two are kept as is. Longer elements are truncated to length two.
  8462. If an element cannot be made unique, an error is raised."
  8463. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8464. menu-keys)
  8465. (dolist (key ordered-keys)
  8466. (let ((potential-key
  8467. (cl-case (length key)
  8468. (1 (concat key "\t"))
  8469. (2 key)
  8470. (otherwise
  8471. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8472. (mapcar (apply-partially #'concat (substring key 0 1))
  8473. (split-string (substring key 1) "" t)))))))
  8474. (if (or (not potential-key) (assoc potential-key menu-keys))
  8475. (user-error "Could not make unique key for %s." key)
  8476. (push (cons potential-key key) menu-keys))))
  8477. (mapcar #'car
  8478. (cl-sort menu-keys #'<
  8479. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8480. (defun org-insert-structure-template (type)
  8481. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8482. Select a block from `org-structure-template-alist' then type
  8483. either RET, TAB or SPC to write the block type. With an active
  8484. region, wrap the region in the block. Otherwise, insert an empty
  8485. block."
  8486. (interactive
  8487. (list (pcase (org--insert-structure-template-mks)
  8488. (`("\t" . ,_) (read-string "Structure type: "))
  8489. (`(,_ ,choice . ,_) choice))))
  8490. (let* ((region? (use-region-p))
  8491. (region-start (and region? (region-beginning)))
  8492. (region-end (and region? (copy-marker (region-end))))
  8493. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8494. (verbatim? (string-match-p
  8495. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8496. type)))
  8497. (when region? (goto-char region-start))
  8498. (let ((column (current-indentation)))
  8499. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8500. (beginning-of-line)
  8501. (insert "\n"))
  8502. (save-excursion
  8503. (indent-to column)
  8504. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8505. (when region?
  8506. (when verbatim? (org-escape-code-in-region (point) region-end))
  8507. (goto-char region-end)
  8508. ;; Ignore empty lines at the end of the region.
  8509. (skip-chars-backward " \r\t\n")
  8510. (end-of-line))
  8511. (unless (bolp) (insert "\n"))
  8512. (indent-to column)
  8513. (insert (format "#+end_%s" (car (split-string type))))
  8514. (if (looking-at "[ \t]*$") (replace-match "")
  8515. (insert "\n"))
  8516. (when (and (eobp) (not (bolp))) (insert "\n")))
  8517. (if extended? (end-of-line)
  8518. (forward-line)
  8519. (skip-chars-forward " \t")))))
  8520. ;;;; TODO, DEADLINE, Comments
  8521. (defun org-toggle-comment ()
  8522. "Change the COMMENT state of an entry."
  8523. (interactive)
  8524. (save-excursion
  8525. (org-back-to-heading)
  8526. (let ((case-fold-search nil))
  8527. (looking-at org-complex-heading-regexp))
  8528. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8529. (skip-chars-forward " \t")
  8530. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8531. (if (org-in-commented-heading-p t)
  8532. (delete-region (point)
  8533. (progn (search-forward " " (line-end-position) 'move)
  8534. (skip-chars-forward " \t")
  8535. (point)))
  8536. (insert org-comment-string)
  8537. (unless (eolp) (insert " ")))))
  8538. (defvar org-last-todo-state-is-todo nil
  8539. "This is non-nil when the last TODO state change led to a TODO state.
  8540. If the last change removed the TODO tag or switched to DONE, then
  8541. this is nil.")
  8542. (defvar org-todo-setup-filter-hook nil
  8543. "Hook for functions that pre-filter todo specs.
  8544. Each function takes a todo spec and returns either nil or the spec
  8545. transformed into canonical form." )
  8546. (defvar org-todo-get-default-hook nil
  8547. "Hook for functions that get a default item for todo.
  8548. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8549. nil or a string to be used for the todo mark." )
  8550. (defvar org-agenda-headline-snapshot-before-repeat)
  8551. (defun org-current-effective-time ()
  8552. "Return current time adjusted for `org-extend-today-until' variable."
  8553. (let* ((ct (org-current-time))
  8554. (dct (decode-time ct))
  8555. (ct1
  8556. (cond
  8557. (org-use-last-clock-out-time-as-effective-time
  8558. (or (org-clock-get-last-clock-out-time) ct))
  8559. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8560. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8561. (t ct))))
  8562. ct1))
  8563. (defun org-todo-yesterday (&optional arg)
  8564. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8565. (interactive "P")
  8566. (if (eq major-mode 'org-agenda-mode)
  8567. (apply 'org-agenda-todo-yesterday arg)
  8568. (let* ((org-use-effective-time t)
  8569. (hour (nth 2 (decode-time (org-current-time))))
  8570. (org-extend-today-until (1+ hour)))
  8571. (org-todo arg))))
  8572. (defvar org-block-entry-blocking ""
  8573. "First entry preventing the TODO state change.")
  8574. (defun org-cancel-repeater ()
  8575. "Cancel a repeater by setting its numeric value to zero."
  8576. (interactive)
  8577. (save-excursion
  8578. (org-back-to-heading t)
  8579. (let ((bound1 (point))
  8580. (bound0 (save-excursion (outline-next-heading) (point))))
  8581. (when (and (re-search-forward
  8582. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8583. org-deadline-time-regexp "\\)\\|\\("
  8584. org-ts-regexp "\\)")
  8585. bound0 t)
  8586. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8587. bound1 t))
  8588. (replace-match "0" t nil nil 1)))))
  8589. (defvar org-state)
  8590. (defvar org-blocked-by-checkboxes)
  8591. (defun org-todo (&optional arg)
  8592. "Change the TODO state of an item.
  8593. The state of an item is given by a keyword at the start of the heading,
  8594. like
  8595. *** TODO Write paper
  8596. *** DONE Call mom
  8597. The different keywords are specified in the variable `org-todo-keywords'.
  8598. By default the available states are \"TODO\" and \"DONE\". So, for this
  8599. example: when the item starts with TODO, it is changed to DONE.
  8600. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8601. DONE are present, add TODO at the beginning of the heading.
  8602. You can set up single-character keys to fast-select the new state. See the
  8603. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8604. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8605. and take a
  8606. logging note.
  8607. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8608. next set of TODO \
  8609. keywords (nextset).
  8610. Another way to achieve this is `S-C-<right>'.
  8611. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8612. prefix, circumvent any state blocking.
  8613. With numeric prefix arg, switch to the Nth state.
  8614. With a numeric prefix arg of 0, inhibit note taking for the change.
  8615. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8616. When called through ELisp, arg is also interpreted in the following way:
  8617. `none' -> empty state
  8618. \"\" -> switch to empty state
  8619. `done' -> switch to DONE
  8620. `nextset' -> switch to the next set of keywords
  8621. `previousset' -> switch to the previous set of keywords
  8622. \"WAITING\" -> switch to the specified keyword, but only if it
  8623. really is a member of `org-todo-keywords'."
  8624. (interactive "P")
  8625. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8626. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8627. 'region-start-level 'region))
  8628. org-loop-over-headlines-in-active-region)
  8629. (org-map-entries
  8630. (lambda () (org-todo arg))
  8631. nil cl
  8632. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8633. (when (equal arg '(16)) (setq arg 'nextset))
  8634. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8635. (let ((org-blocker-hook org-blocker-hook)
  8636. commentp
  8637. case-fold-search)
  8638. (when (equal arg '(64))
  8639. (setq arg nil org-blocker-hook nil))
  8640. (when (and org-blocker-hook
  8641. (or org-inhibit-blocking
  8642. (org-entry-get nil "NOBLOCKING")))
  8643. (setq org-blocker-hook nil))
  8644. (save-excursion
  8645. (catch 'exit
  8646. (org-back-to-heading t)
  8647. (when (org-in-commented-heading-p t)
  8648. (org-toggle-comment)
  8649. (setq commentp t))
  8650. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8651. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8652. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8653. (let* ((match-data (match-data))
  8654. (startpos (copy-marker (line-beginning-position)))
  8655. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8656. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8657. (org-log-done org-log-done)
  8658. (org-log-repeat org-log-repeat)
  8659. (org-todo-log-states org-todo-log-states)
  8660. (org-inhibit-logging
  8661. (if (equal arg 0)
  8662. (progn (setq arg nil) 'note) org-inhibit-logging))
  8663. (this (match-string 1))
  8664. (hl-pos (match-beginning 0))
  8665. (head (org-get-todo-sequence-head this))
  8666. (ass (assoc head org-todo-kwd-alist))
  8667. (interpret (nth 1 ass))
  8668. (done-word (nth 3 ass))
  8669. (final-done-word (nth 4 ass))
  8670. (org-last-state (or this ""))
  8671. (completion-ignore-case t)
  8672. (member (member this org-todo-keywords-1))
  8673. (tail (cdr member))
  8674. (org-state (cond
  8675. ((eq arg 'right)
  8676. ;; Next state
  8677. (if this
  8678. (if tail (car tail) nil)
  8679. (car org-todo-keywords-1)))
  8680. ((eq arg 'left)
  8681. ;; Previous state
  8682. (unless (equal member org-todo-keywords-1)
  8683. (if this
  8684. (nth (- (length org-todo-keywords-1)
  8685. (length tail) 2)
  8686. org-todo-keywords-1)
  8687. (org-last org-todo-keywords-1))))
  8688. (arg
  8689. ;; User or caller requests a specific state.
  8690. (cond
  8691. ((equal arg "") nil)
  8692. ((eq arg 'none) nil)
  8693. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8694. ((eq arg 'nextset)
  8695. (or (car (cdr (member head org-todo-heads)))
  8696. (car org-todo-heads)))
  8697. ((eq arg 'previousset)
  8698. (let ((org-todo-heads (reverse org-todo-heads)))
  8699. (or (car (cdr (member head org-todo-heads)))
  8700. (car org-todo-heads))))
  8701. ((car (member arg org-todo-keywords-1)))
  8702. ((stringp arg)
  8703. (user-error "State `%s' not valid in this file" arg))
  8704. ((nth (1- (prefix-numeric-value arg))
  8705. org-todo-keywords-1))))
  8706. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8707. ;; Use fast selection.
  8708. (org-fast-todo-selection this))
  8709. ((null member) (or head (car org-todo-keywords-1)))
  8710. ((equal this final-done-word) nil) ;-> make empty
  8711. ((null tail) nil) ;-> first entry
  8712. ((memq interpret '(type priority))
  8713. (if (eq this-command last-command)
  8714. (car tail)
  8715. (if (> (length tail) 0)
  8716. (or done-word (car org-done-keywords))
  8717. nil)))
  8718. (t
  8719. (car tail))))
  8720. (org-state (or
  8721. (run-hook-with-args-until-success
  8722. 'org-todo-get-default-hook org-state org-last-state)
  8723. org-state))
  8724. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8725. (change-plist (list :type 'todo-state-change :from this :to org-state
  8726. :position startpos))
  8727. dolog now-done-p)
  8728. (when org-blocker-hook
  8729. (let (org-blocked-by-checkboxes block-reason)
  8730. (setq org-last-todo-state-is-todo
  8731. (not (member this org-done-keywords)))
  8732. (unless (save-excursion
  8733. (save-match-data
  8734. (org-with-wide-buffer
  8735. (run-hook-with-args-until-failure
  8736. 'org-blocker-hook change-plist))))
  8737. (setq block-reason (if org-blocked-by-checkboxes
  8738. "contained checkboxes"
  8739. (format "\"%s\"" org-block-entry-blocking)))
  8740. (if (called-interactively-p 'interactive)
  8741. (user-error "TODO state change from %s to %s blocked (by %s)"
  8742. this org-state block-reason)
  8743. ;; Fail silently.
  8744. (message "TODO state change from %s to %s blocked (by %s)"
  8745. this org-state block-reason)
  8746. (throw 'exit nil)))))
  8747. (store-match-data match-data)
  8748. (replace-match next t t)
  8749. (cond ((and org-state (equal this org-state))
  8750. (message "TODO state was already %s" (org-trim next)))
  8751. ((not (pos-visible-in-window-p hl-pos))
  8752. (message "TODO state changed to %s" (org-trim next))))
  8753. (unless head
  8754. (setq head (org-get-todo-sequence-head org-state)
  8755. ass (assoc head org-todo-kwd-alist)
  8756. interpret (nth 1 ass)
  8757. done-word (nth 3 ass)
  8758. final-done-word (nth 4 ass)))
  8759. (when (memq arg '(nextset previousset))
  8760. (message "Keyword-Set %d/%d: %s"
  8761. (- (length org-todo-sets) -1
  8762. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8763. (length org-todo-sets)
  8764. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8765. (setq org-last-todo-state-is-todo
  8766. (not (member org-state org-done-keywords)))
  8767. (setq now-done-p (and (member org-state org-done-keywords)
  8768. (not (member this org-done-keywords))))
  8769. (and logging (org-local-logging logging))
  8770. (when (or (and (or org-todo-log-states org-log-done)
  8771. (not (eq org-inhibit-logging t))
  8772. (not (memq arg '(nextset previousset))))
  8773. force-log)
  8774. ;; We need to look at recording a time and note.
  8775. (setq dolog (or (if force-log 'note)
  8776. (nth 1 (assoc org-state org-todo-log-states))
  8777. (nth 2 (assoc this org-todo-log-states))))
  8778. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8779. (setq dolog 'time))
  8780. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8781. (and org-state
  8782. (member org-state org-not-done-keywords)
  8783. (not (member this org-not-done-keywords))))
  8784. ;; This is now a todo state and was not one before
  8785. ;; If there was a CLOSED time stamp, get rid of it.
  8786. (org-add-planning-info nil nil 'closed))
  8787. (when (and now-done-p org-log-done)
  8788. ;; It is now done, and it was not done before.
  8789. (org-add-planning-info 'closed (org-current-effective-time))
  8790. (when (and (not dolog) (eq 'note org-log-done))
  8791. (org-add-log-setup 'done org-state this 'note)))
  8792. (when (and org-state dolog)
  8793. ;; This is a non-nil state, and we need to log it.
  8794. (org-add-log-setup 'state org-state this dolog)))
  8795. ;; Fixup tag positioning.
  8796. (org-todo-trigger-tag-changes org-state)
  8797. (when org-auto-align-tags (org-align-tags))
  8798. (when org-provide-todo-statistics
  8799. (org-update-parent-todo-statistics))
  8800. (when (bound-and-true-p org-clock-out-when-done)
  8801. (org-clock-out-if-current))
  8802. (run-hooks 'org-after-todo-state-change-hook)
  8803. (when (and arg (not (member org-state org-done-keywords)))
  8804. (setq head (org-get-todo-sequence-head org-state)))
  8805. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8806. ;; Do we need to trigger a repeat?
  8807. (when now-done-p
  8808. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8809. ;; This is for the agenda, take a snapshot of the headline.
  8810. (save-match-data
  8811. (setq org-agenda-headline-snapshot-before-repeat
  8812. (org-get-heading))))
  8813. (org-auto-repeat-maybe org-state))
  8814. ;; Fixup cursor location if close to the keyword.
  8815. (when (and (outline-on-heading-p)
  8816. (not (bolp))
  8817. (save-excursion (beginning-of-line 1)
  8818. (looking-at org-todo-line-regexp))
  8819. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8820. (goto-char (or (match-end 2) (match-end 1)))
  8821. (and (looking-at " ")
  8822. (not (looking-at " *:"))
  8823. (just-one-space)))
  8824. (when org-trigger-hook
  8825. (save-excursion
  8826. (run-hook-with-args 'org-trigger-hook change-plist)))
  8827. (when commentp (org-toggle-comment))))))))
  8828. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8829. "Block turning an entry into a TODO, using the hierarchy.
  8830. This checks whether the current task should be blocked from state
  8831. changes. Such blocking occurs when:
  8832. 1. The task has children which are not all in a completed state.
  8833. 2. A task has a parent with the property :ORDERED:, and there
  8834. are siblings prior to the current task with incomplete
  8835. status.
  8836. 3. The parent of the task is blocked because it has siblings that should
  8837. be done first, or is child of a block grandparent TODO entry."
  8838. (if (not org-enforce-todo-dependencies)
  8839. t ; if locally turned off don't block
  8840. (catch 'dont-block
  8841. ;; If this is not a todo state change, or if this entry is already DONE,
  8842. ;; do not block
  8843. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8844. (member (plist-get change-plist :from)
  8845. (cons 'done org-done-keywords))
  8846. (member (plist-get change-plist :to)
  8847. (cons 'todo org-not-done-keywords))
  8848. (not (plist-get change-plist :to)))
  8849. (throw 'dont-block t))
  8850. ;; If this task has children, and any are undone, it's blocked
  8851. (save-excursion
  8852. (org-back-to-heading t)
  8853. (let ((this-level (funcall outline-level)))
  8854. (outline-next-heading)
  8855. (let ((child-level (funcall outline-level)))
  8856. (while (and (not (eobp))
  8857. (> child-level this-level))
  8858. ;; this todo has children, check whether they are all
  8859. ;; completed
  8860. (when (and (not (org-entry-is-done-p))
  8861. (org-entry-is-todo-p))
  8862. (setq org-block-entry-blocking (org-get-heading))
  8863. (throw 'dont-block nil))
  8864. (outline-next-heading)
  8865. (setq child-level (funcall outline-level))))))
  8866. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8867. ;; any previous siblings are undone, it's blocked
  8868. (save-excursion
  8869. (org-back-to-heading t)
  8870. (let* ((pos (point))
  8871. (parent-pos (and (org-up-heading-safe) (point)))
  8872. (case-fold-search nil))
  8873. (unless parent-pos (throw 'dont-block t)) ; no parent
  8874. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8875. (forward-line 1)
  8876. (re-search-forward org-not-done-heading-regexp pos t))
  8877. (setq org-block-entry-blocking (match-string 0))
  8878. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8879. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8880. (while t
  8881. (goto-char parent-pos)
  8882. (unless (looking-at org-not-done-heading-regexp)
  8883. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8884. (setq pos (point))
  8885. (setq parent-pos (and (org-up-heading-safe) (point)))
  8886. (unless parent-pos (throw 'dont-block t)) ; no parent
  8887. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8888. (forward-line 1)
  8889. (re-search-forward org-not-done-heading-regexp pos t)
  8890. (setq org-block-entry-blocking (org-get-heading)))
  8891. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8892. (defcustom org-track-ordered-property-with-tag nil
  8893. "Should the ORDERED property also be shown as a tag?
  8894. The ORDERED property decides if an entry should require subtasks to be
  8895. completed in sequence. Since a property is not very visible, setting
  8896. this option means that toggling the ORDERED property with the command
  8897. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8898. not relevant for the behavior, but it makes things more visible.
  8899. Note that toggling the tag with tags commands will not change the property
  8900. and therefore not influence behavior!
  8901. This can be t, meaning the tag ORDERED should be used. It can also be a
  8902. string to select a different tag for this task."
  8903. :group 'org-todo
  8904. :type '(choice
  8905. (const :tag "No tracking" nil)
  8906. (const :tag "Track with ORDERED tag" t)
  8907. (string :tag "Use other tag")))
  8908. (defun org-toggle-ordered-property ()
  8909. "Toggle the ORDERED property of the current entry.
  8910. For better visibility, you can track the value of this property with a tag.
  8911. See variable `org-track-ordered-property-with-tag'."
  8912. (interactive)
  8913. (let* ((t1 org-track-ordered-property-with-tag)
  8914. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8915. (save-excursion
  8916. (org-back-to-heading)
  8917. (if (org-entry-get nil "ORDERED")
  8918. (progn
  8919. (org-delete-property "ORDERED")
  8920. (and tag (org-toggle-tag tag 'off))
  8921. (message "Subtasks can be completed in arbitrary order"))
  8922. (org-entry-put nil "ORDERED" "t")
  8923. (and tag (org-toggle-tag tag 'on))
  8924. (message "Subtasks must be completed in sequence")))))
  8925. (defun org-block-todo-from-checkboxes (change-plist)
  8926. "Block turning an entry into a TODO, using checkboxes.
  8927. This checks whether the current task should be blocked from state
  8928. changes because there are unchecked boxes in this entry."
  8929. (if (not org-enforce-todo-checkbox-dependencies)
  8930. t ; if locally turned off don't block
  8931. (catch 'dont-block
  8932. ;; If this is not a todo state change, or if this entry is already DONE,
  8933. ;; do not block
  8934. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8935. (member (plist-get change-plist :from)
  8936. (cons 'done org-done-keywords))
  8937. (member (plist-get change-plist :to)
  8938. (cons 'todo org-not-done-keywords))
  8939. (not (plist-get change-plist :to)))
  8940. (throw 'dont-block t))
  8941. ;; If this task has checkboxes that are not checked, it's blocked
  8942. (save-excursion
  8943. (org-back-to-heading t)
  8944. (let ((beg (point)) end)
  8945. (outline-next-heading)
  8946. (setq end (point))
  8947. (goto-char beg)
  8948. (when (org-list-search-forward
  8949. (concat (org-item-beginning-re)
  8950. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8951. "\\[[- ]\\]")
  8952. end t)
  8953. (when (boundp 'org-blocked-by-checkboxes)
  8954. (setq org-blocked-by-checkboxes t))
  8955. (throw 'dont-block nil))))
  8956. t))) ; do not block
  8957. (defun org-entry-blocked-p ()
  8958. "Non-nil if entry at point is blocked."
  8959. (and (not (org-entry-get nil "NOBLOCKING"))
  8960. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8961. (not (run-hook-with-args-until-failure
  8962. 'org-blocker-hook
  8963. (list :type 'todo-state-change
  8964. :position (point)
  8965. :from 'todo
  8966. :to 'done)))))
  8967. (defun org-update-statistics-cookies (all)
  8968. "Update the statistics cookie, either from TODO or from checkboxes.
  8969. This should be called with the cursor in a line with a statistics
  8970. cookie. When called with a \\[universal-argument] prefix, update
  8971. all statistics cookies in the buffer."
  8972. (interactive "P")
  8973. (if all
  8974. (progn
  8975. (org-update-checkbox-count 'all)
  8976. (org-map-entries 'org-update-parent-todo-statistics))
  8977. (if (not (org-at-heading-p))
  8978. (org-update-checkbox-count)
  8979. (let ((pos (point-marker))
  8980. end l1 l2)
  8981. (ignore-errors (org-back-to-heading t))
  8982. (if (not (org-at-heading-p))
  8983. (org-update-checkbox-count)
  8984. (setq l1 (org-outline-level))
  8985. (setq end (save-excursion
  8986. (outline-next-heading)
  8987. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8988. (point)))
  8989. (if (and (save-excursion
  8990. (re-search-forward
  8991. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8992. (not (save-excursion (re-search-forward
  8993. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8994. (org-update-checkbox-count)
  8995. (if (and l2 (> l2 l1))
  8996. (progn
  8997. (goto-char end)
  8998. (org-update-parent-todo-statistics))
  8999. (goto-char pos)
  9000. (beginning-of-line 1)
  9001. (while (re-search-forward
  9002. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9003. (point-at-eol) t)
  9004. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9005. (goto-char pos)
  9006. (move-marker pos nil)))))
  9007. (defvar org-entry-property-inherited-from) ;; defined below
  9008. (defun org-update-parent-todo-statistics ()
  9009. "Update any statistics cookie in the parent of the current headline.
  9010. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9011. the entire subtree and this will travel up the hierarchy and update
  9012. statistics everywhere."
  9013. (let* ((prop (save-excursion (org-up-heading-safe)
  9014. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9015. (recursive (or (not org-hierarchical-todo-statistics)
  9016. (and prop (string-match "\\<recursive\\>" prop))))
  9017. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9018. 0))
  9019. (first t)
  9020. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9021. level ltoggle l1 new ndel
  9022. (cnt-all 0) (cnt-done 0) is-percent kwd
  9023. checkbox-beg cookie-present)
  9024. (catch 'exit
  9025. (save-excursion
  9026. (beginning-of-line 1)
  9027. (setq ltoggle (funcall outline-level))
  9028. ;; Three situations are to consider:
  9029. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9030. ;; to the top-level ancestor on the headline;
  9031. ;; 2. If parent has "recursive" property, repeat up to the
  9032. ;; headline setting that property, taking inheritance into
  9033. ;; account;
  9034. ;; 3. Else, move up to direct parent and proceed only once.
  9035. (while (and (setq level (org-up-heading-safe))
  9036. (or recursive first)
  9037. (>= (point) lim))
  9038. (setq first nil cookie-present nil)
  9039. (unless (and level
  9040. (not (string-match
  9041. "\\<checkbox\\>"
  9042. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9043. "")))))
  9044. (throw 'exit nil))
  9045. (while (re-search-forward box-re (point-at-eol) t)
  9046. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9047. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9048. (save-match-data
  9049. (unless (outline-next-heading) (throw 'exit nil))
  9050. (while (and (looking-at org-complex-heading-regexp)
  9051. (> (setq l1 (length (match-string 1))) level))
  9052. (setq kwd (and (or recursive (= l1 ltoggle))
  9053. (match-string 2)))
  9054. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9055. (and (eq org-provide-todo-statistics t)
  9056. (or (member kwd org-done-keywords)))
  9057. (and (listp org-provide-todo-statistics)
  9058. (stringp (car org-provide-todo-statistics))
  9059. (or (member kwd org-provide-todo-statistics)
  9060. (member kwd org-done-keywords)))
  9061. (and (listp org-provide-todo-statistics)
  9062. (listp (car org-provide-todo-statistics))
  9063. (or (member kwd (car org-provide-todo-statistics))
  9064. (and (member kwd org-done-keywords)
  9065. (member kwd (cadr org-provide-todo-statistics))))))
  9066. (setq cnt-all (1+ cnt-all))
  9067. (and (eq org-provide-todo-statistics t)
  9068. kwd
  9069. (setq cnt-all (1+ cnt-all))))
  9070. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9071. (member kwd org-done-keywords))
  9072. (and (listp org-provide-todo-statistics)
  9073. (listp (car org-provide-todo-statistics))
  9074. (member kwd org-done-keywords)
  9075. (member kwd (cadr org-provide-todo-statistics)))
  9076. (and (listp org-provide-todo-statistics)
  9077. (stringp (car org-provide-todo-statistics))
  9078. (member kwd org-done-keywords)))
  9079. (setq cnt-done (1+ cnt-done)))
  9080. (outline-next-heading)))
  9081. (setq new
  9082. (if is-percent
  9083. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9084. (max 1 cnt-all)))
  9085. (format "[%d/%d]" cnt-done cnt-all))
  9086. ndel (- (match-end 0) checkbox-beg))
  9087. (goto-char checkbox-beg)
  9088. (insert new)
  9089. (delete-region (point) (+ (point) ndel))
  9090. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9091. (when cookie-present
  9092. (run-hook-with-args 'org-after-todo-statistics-hook
  9093. cnt-done (- cnt-all cnt-done))))))
  9094. (run-hooks 'org-todo-statistics-hook)))
  9095. (defvar org-after-todo-statistics-hook nil
  9096. "Hook that is called after a TODO statistics cookie has been updated.
  9097. Each function is called with two arguments: the number of not-done entries
  9098. and the number of done entries.
  9099. For example, the following function, when added to this hook, will switch
  9100. an entry to DONE when all children are done, and back to TODO when new
  9101. entries are set to a TODO status. Note that this hook is only called
  9102. when there is a statistics cookie in the headline!
  9103. (defun org-summary-todo (n-done n-not-done)
  9104. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9105. (let (org-log-done org-log-states) ; turn off logging
  9106. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9107. (defvar org-todo-statistics-hook nil
  9108. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9109. This hook runs even if there is no statistics cookie present, in which case
  9110. `org-after-todo-statistics-hook' would not run.")
  9111. (defun org-todo-trigger-tag-changes (state)
  9112. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9113. (let ((l org-todo-state-tags-triggers)
  9114. changes)
  9115. (when (or (not state) (equal state ""))
  9116. (setq changes (append changes (cdr (assoc "" l)))))
  9117. (when (and (stringp state) (> (length state) 0))
  9118. (setq changes (append changes (cdr (assoc state l)))))
  9119. (when (member state org-not-done-keywords)
  9120. (setq changes (append changes (cdr (assq 'todo l)))))
  9121. (when (member state org-done-keywords)
  9122. (setq changes (append changes (cdr (assq 'done l)))))
  9123. (dolist (c changes)
  9124. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9125. (defun org-local-logging (value)
  9126. "Get logging settings from a property VALUE."
  9127. ;; Directly set the variables, they are already local.
  9128. (setq org-log-done nil
  9129. org-log-repeat nil
  9130. org-todo-log-states nil)
  9131. (dolist (w (split-string value))
  9132. (let (a)
  9133. (cond
  9134. ((setq a (assoc w org-startup-options))
  9135. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9136. (set (nth 1 a) (nth 2 a))))
  9137. ((setq a (org-extract-log-state-settings w))
  9138. (and (member (car a) org-todo-keywords-1)
  9139. (push a org-todo-log-states)))))))
  9140. (defun org-get-todo-sequence-head (kwd)
  9141. "Return the head of the TODO sequence to which KWD belongs.
  9142. If KWD is not set, check if there is a text property remembering the
  9143. right sequence."
  9144. (let (p)
  9145. (cond
  9146. ((not kwd)
  9147. (or (get-text-property (point-at-bol) 'org-todo-head)
  9148. (progn
  9149. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9150. nil (point-at-eol)))
  9151. (get-text-property p 'org-todo-head))))
  9152. ((not (member kwd org-todo-keywords-1))
  9153. (car org-todo-keywords-1))
  9154. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9155. (defun org-fast-todo-selection (&optional current-state)
  9156. "Fast TODO keyword selection with single keys.
  9157. Returns the new TODO keyword, or nil if no state change should occur.
  9158. When CURRENT-STATE is given and selection letters are not unique globally,
  9159. prefer a state in the current sequence over on in another sequence."
  9160. (let* ((fulltable org-todo-key-alist)
  9161. (head (org-get-todo-sequence-head current-state))
  9162. (done-keywords org-done-keywords) ;; needed for the faces.
  9163. (maxlen (apply 'max (mapcar
  9164. (lambda (x)
  9165. (if (stringp (car x)) (string-width (car x)) 0))
  9166. fulltable)))
  9167. (expert (equal org-use-fast-todo-selection 'expert))
  9168. (prompt "")
  9169. (fwidth (+ maxlen 3 1 3))
  9170. (ncol (/ (- (window-width) 4) fwidth))
  9171. tg cnt e c tbl subtable
  9172. groups ingroup in-current-sequence)
  9173. (save-excursion
  9174. (save-window-excursion
  9175. (if expert
  9176. (set-buffer (get-buffer-create " *Org todo*"))
  9177. (delete-other-windows)
  9178. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9179. (org-switch-to-buffer-other-window " *Org todo*"))
  9180. (erase-buffer)
  9181. (setq-local org-done-keywords done-keywords)
  9182. (setq tbl fulltable cnt 0)
  9183. (while (setq e (pop tbl))
  9184. (cond
  9185. ((equal e '(:startgroup))
  9186. (push '() groups) (setq ingroup t)
  9187. (unless (= cnt 0)
  9188. (setq cnt 0)
  9189. (insert "\n"))
  9190. (setq prompt (concat prompt "{"))
  9191. (insert "{ "))
  9192. ((equal e '(:endgroup))
  9193. (setq ingroup nil cnt 0 in-current-sequence nil)
  9194. (setq prompt (concat prompt "}"))
  9195. (insert "}\n"))
  9196. ((equal e '(:newline))
  9197. (unless (= cnt 0)
  9198. (setq cnt 0)
  9199. (insert "\n")
  9200. (setq e (car tbl))
  9201. (while (equal (car tbl) '(:newline))
  9202. (insert "\n")
  9203. (setq tbl (cdr tbl)))))
  9204. (t
  9205. (setq tg (car e) c (cdr e))
  9206. (if (equal tg head) (setq in-current-sequence t))
  9207. (when ingroup (push tg (car groups)))
  9208. (when in-current-sequence (push e subtable))
  9209. (setq tg (org-add-props tg nil 'face
  9210. (org-get-todo-face tg)))
  9211. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9212. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9213. (insert "[" c "] " tg (make-string
  9214. (- fwidth 4 (length tg)) ?\ ))
  9215. (when (and (= (setq cnt (1+ cnt)) ncol)
  9216. ;; Avoid lines with just a closing delimiter.
  9217. (not (equal (car tbl) '(:endgroup))))
  9218. (insert "\n")
  9219. (when ingroup (insert " "))
  9220. (setq cnt 0)))))
  9221. (insert "\n")
  9222. (goto-char (point-min))
  9223. (unless expert (org-fit-window-to-buffer))
  9224. (message (concat "[a-z..]:Set [SPC]:clear"
  9225. (if expert (concat "\n" prompt) "")))
  9226. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9227. (setq subtable (nreverse subtable))
  9228. (cond
  9229. ((or (= c ?\C-g)
  9230. (and (= c ?q) (not (rassoc c fulltable))))
  9231. (setq quit-flag t))
  9232. ((= c ?\ ) nil)
  9233. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9234. tg (car e))
  9235. tg)
  9236. (t (setq quit-flag t)))))))
  9237. (defun org-entry-is-todo-p ()
  9238. (member (org-get-todo-state) org-not-done-keywords))
  9239. (defun org-entry-is-done-p ()
  9240. (member (org-get-todo-state) org-done-keywords))
  9241. (defun org-get-todo-state ()
  9242. "Return the TODO keyword of the current subtree."
  9243. (save-excursion
  9244. (org-back-to-heading t)
  9245. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9246. (match-end 2)
  9247. (match-string 2))))
  9248. (defun org-at-date-range-p (&optional inactive-ok)
  9249. "Non-nil if point is inside a date range.
  9250. When optional argument INACTIVE-OK is non-nil, also consider
  9251. inactive time ranges.
  9252. When this function returns a non-nil value, match data is set
  9253. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9254. on INACTIVE-OK."
  9255. (interactive)
  9256. (save-excursion
  9257. (catch 'exit
  9258. (let ((pos (point)))
  9259. (skip-chars-backward "^[<\r\n")
  9260. (skip-chars-backward "<[")
  9261. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9262. (>= (match-end 0) pos)
  9263. (throw 'exit t))
  9264. (skip-chars-backward "^<[\r\n")
  9265. (skip-chars-backward "<[")
  9266. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9267. (>= (match-end 0) pos)
  9268. (throw 'exit t)))
  9269. nil)))
  9270. (defun org-get-repeat (&optional timestamp)
  9271. "Check if there is a time-stamp with repeater in this entry.
  9272. Return the repeater, as a string, or nil. Also return nil when
  9273. this function is called before first heading.
  9274. When optional argument TIMESTAMP is a string, extract the
  9275. repeater from there instead."
  9276. (save-match-data
  9277. (cond (timestamp
  9278. (and (string-match org-repeat-re timestamp)
  9279. (match-string-no-properties 1 timestamp)))
  9280. ((org-before-first-heading-p) nil)
  9281. (t
  9282. (save-excursion
  9283. (org-back-to-heading t)
  9284. (let ((end (org-entry-end-position)))
  9285. (catch :repeat
  9286. (while (re-search-forward org-repeat-re end t)
  9287. (when (save-match-data (org-at-timestamp-p 'agenda))
  9288. (throw :repeat (match-string-no-properties 1)))))))))))
  9289. (defvar org-last-changed-timestamp)
  9290. (defvar org-last-inserted-timestamp)
  9291. (defvar org-log-post-message)
  9292. (defvar org-log-note-purpose)
  9293. (defvar org-log-note-how nil)
  9294. (defvar org-log-note-extra)
  9295. (defun org-auto-repeat-maybe (done-word)
  9296. "Check if the current headline contains a repeated time-stamp.
  9297. If yes, set TODO state back to what it was and change the base date
  9298. of repeating deadline/scheduled time stamps to new date.
  9299. This function is run automatically after each state change to a DONE state."
  9300. (let* ((repeat (org-get-repeat))
  9301. (aa (assoc org-last-state org-todo-kwd-alist))
  9302. (interpret (nth 1 aa))
  9303. (head (nth 2 aa))
  9304. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9305. (msg "Entry repeats: ")
  9306. (org-log-done nil)
  9307. (org-todo-log-states nil)
  9308. (end (copy-marker (org-entry-end-position))))
  9309. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9310. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9311. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9312. (and (stringp org-todo-repeat-to-state)
  9313. org-todo-repeat-to-state)
  9314. (and org-todo-repeat-to-state org-last-state))))
  9315. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9316. to-state)
  9317. ((eq interpret 'type) org-last-state)
  9318. (head)
  9319. (t 'none))))
  9320. (org-back-to-heading t)
  9321. (org-add-planning-info nil nil 'closed)
  9322. ;; When `org-log-repeat' is non-nil or entry contains
  9323. ;; a clock, set LAST_REPEAT property.
  9324. (when (or org-log-repeat
  9325. (catch :clock
  9326. (save-excursion
  9327. (while (re-search-forward org-clock-line-re end t)
  9328. (when (org-at-clock-log-p) (throw :clock t))))))
  9329. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9330. (org-time-stamp-format t t))))
  9331. (when org-log-repeat
  9332. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9333. (memq 'org-add-log-note post-command-hook))
  9334. ;; We are already setup for some record.
  9335. (when (eq org-log-repeat 'note)
  9336. ;; Make sure we take a note, not only a time stamp.
  9337. (setq org-log-note-how 'note))
  9338. ;; Set up for taking a record.
  9339. (org-add-log-setup 'state
  9340. (or done-word (car org-done-keywords))
  9341. org-last-state
  9342. org-log-repeat)))
  9343. ;; Time-stamps without a repeater are usually skipped. However,
  9344. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9345. ;; longer relevant.
  9346. (save-excursion
  9347. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9348. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9349. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9350. ;; Update every time-stamp with a repeater in the entry.
  9351. (let ((planning-re (regexp-opt
  9352. (list org-scheduled-string org-deadline-string))))
  9353. (while (re-search-forward org-repeat-re end t)
  9354. (let* ((ts (match-string 0))
  9355. (type (if (not (org-at-planning-p)) "Plain:"
  9356. (save-excursion
  9357. (re-search-backward
  9358. planning-re (line-beginning-position) t)
  9359. (match-string 0)))))
  9360. (when (and (org-at-timestamp-p 'agenda)
  9361. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9362. (let ((n (string-to-number (match-string 2 ts)))
  9363. (what (match-string 3 ts)))
  9364. (when (equal what "w") (setq n (* n 7) what "d"))
  9365. (when (and (equal what "h")
  9366. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9367. ts)))
  9368. (user-error
  9369. "Cannot repeat in %d hour(s) because no hour has been set"
  9370. n))
  9371. ;; Preparation, see if we need to modify the start
  9372. ;; date for the change.
  9373. (when (match-end 1)
  9374. (let ((time (save-match-data (org-time-string-to-time ts)))
  9375. (repeater-type (match-string 1 ts)))
  9376. (cond
  9377. ((equal "." repeater-type)
  9378. ;; Shift starting date to today, or now if
  9379. ;; repeater is by hours.
  9380. (if (equal what "h")
  9381. (org-timestamp-change
  9382. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9383. (org-timestamp-change
  9384. (- (org-today) (time-to-days time)) 'day)))
  9385. ((equal "+" repeater-type)
  9386. (let ((nshiftmax 10)
  9387. (nshift 0))
  9388. (while (or (= nshift 0)
  9389. (not (org-time-less-p nil time)))
  9390. (when (= nshiftmax (cl-incf nshift))
  9391. (or (y-or-n-p
  9392. (format "%d repeater intervals were not \
  9393. enough to shift date past today. Continue? "
  9394. nshift))
  9395. (user-error "Abort")))
  9396. (org-timestamp-change n (cdr (assoc what whata)))
  9397. (org-in-regexp org-ts-regexp3)
  9398. (setq ts (match-string 1))
  9399. (setq time
  9400. (save-match-data
  9401. (org-time-string-to-time ts)))))
  9402. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9403. ;; Rematch, so that we have everything in place
  9404. ;; for the real shift.
  9405. (org-in-regexp org-ts-regexp3)
  9406. (setq ts (match-string 1))
  9407. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9408. ts)))))
  9409. (save-excursion
  9410. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9411. (setq msg
  9412. (concat msg type " " org-last-changed-timestamp " ")))))))
  9413. (run-hooks 'org-todo-repeat-hook)
  9414. (setq org-log-post-message msg)
  9415. (message msg))))
  9416. (defun org-show-todo-tree (arg)
  9417. "Make a compact tree which shows all headlines marked with TODO.
  9418. The tree will show the lines where the regexp matches, and all higher
  9419. headlines above the match.
  9420. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9421. With a numeric prefix N, construct a sparse tree for the Nth element
  9422. of `org-todo-keywords-1'."
  9423. (interactive "P")
  9424. (let ((case-fold-search nil)
  9425. (kwd-re
  9426. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9427. ((equal arg '(4))
  9428. (let ((kwd
  9429. (completing-read "Keyword (or KWD1|KWD2|...): "
  9430. (mapcar #'list org-todo-keywords-1))))
  9431. (concat "\\("
  9432. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9433. "\\)\\>")))
  9434. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9435. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9436. org-todo-keywords-1)))
  9437. (t (user-error "Invalid prefix argument: %s" arg)))))
  9438. (message "%d TODO entries found"
  9439. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9440. (defun org--deadline-or-schedule (arg type time)
  9441. "Insert DEADLINE or SCHEDULE information in current entry.
  9442. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9443. `org-schedule' for information about ARG and TIME arguments."
  9444. (let* ((deadline? (eq type 'deadline))
  9445. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9446. (log (if deadline? org-log-redeadline org-log-reschedule))
  9447. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9448. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9449. ;; Save repeater cookie from either TIME or current scheduled
  9450. ;; time stamp. We are going to insert it back at the end of
  9451. ;; the process.
  9452. (repeater (or (and (org-string-nw-p time)
  9453. ;; We use `org-repeat-re' because we need
  9454. ;; to tell the difference between a real
  9455. ;; repeater and a time delta, e.g. "+2d".
  9456. (string-match org-repeat-re time)
  9457. (match-string 1 time))
  9458. (and (org-string-nw-p old-date)
  9459. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9460. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9461. old-date)
  9462. (match-string 1 old-date)))))
  9463. (pcase arg
  9464. (`(4)
  9465. (if (not old-date)
  9466. (message (if deadline? "Entry had no deadline to remove"
  9467. "Entry was not scheduled"))
  9468. (when (and old-date log)
  9469. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9470. nil old-date log))
  9471. (org-remove-timestamp-with-keyword keyword)
  9472. (message (if deadline? "Entry no longer has a deadline."
  9473. "Entry is no longer scheduled."))))
  9474. (`(16)
  9475. (save-excursion
  9476. (org-back-to-heading t)
  9477. (let ((regexp (if deadline? org-deadline-time-regexp
  9478. org-scheduled-time-regexp)))
  9479. (if (not (re-search-forward regexp (line-end-position 2) t))
  9480. (user-error (if deadline? "No deadline information to update"
  9481. "No scheduled information to update"))
  9482. (let* ((rpl0 (match-string 1))
  9483. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9484. (msg (if deadline? "Warn starting from" "Delay until")))
  9485. (replace-match
  9486. (concat keyword
  9487. " <" rpl
  9488. (format " -%dd"
  9489. (abs (- (time-to-days
  9490. (save-match-data
  9491. (org-read-date
  9492. nil t nil msg old-date-time)))
  9493. (time-to-days old-date-time))))
  9494. ">") t t))))))
  9495. (_
  9496. (org-add-planning-info type time 'closed)
  9497. (when (and old-date
  9498. log
  9499. (not (equal old-date org-last-inserted-timestamp)))
  9500. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9501. org-last-inserted-timestamp
  9502. old-date
  9503. log))
  9504. (when repeater
  9505. (save-excursion
  9506. (org-back-to-heading t)
  9507. (when (re-search-forward
  9508. (concat keyword " " org-last-inserted-timestamp)
  9509. (line-end-position 2)
  9510. t)
  9511. (goto-char (1- (match-end 0)))
  9512. (insert " " repeater)
  9513. (setq org-last-inserted-timestamp
  9514. (concat (substring org-last-inserted-timestamp 0 -1)
  9515. " " repeater
  9516. (substring org-last-inserted-timestamp -1))))))
  9517. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9518. org-last-inserted-timestamp)))))
  9519. (defun org-deadline (arg &optional time)
  9520. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9521. When called interactively, this command pops up the Emacs calendar to let
  9522. the user select a date.
  9523. With one universal prefix argument, remove any deadline from the item.
  9524. With two universal prefix arguments, prompt for a warning delay.
  9525. With argument TIME, set the deadline at the corresponding date. TIME
  9526. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9527. (interactive "P")
  9528. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9529. (org-map-entries
  9530. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9531. nil
  9532. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9533. 'region-start-level
  9534. 'region)
  9535. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9536. (org--deadline-or-schedule arg 'deadline time)))
  9537. (defun org-schedule (arg &optional time)
  9538. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9539. When called interactively, this command pops up the Emacs calendar to let
  9540. the user select a date.
  9541. With one universal prefix argument, remove any scheduling date from the item.
  9542. With two universal prefix arguments, prompt for a delay cookie.
  9543. With argument TIME, scheduled at the corresponding date. TIME can
  9544. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9545. (interactive "P")
  9546. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9547. (org-map-entries
  9548. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9549. nil
  9550. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9551. 'region-start-level
  9552. 'region)
  9553. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9554. (org--deadline-or-schedule arg 'scheduled time)))
  9555. (defun org-get-scheduled-time (pom &optional inherit)
  9556. "Get the scheduled time as a time tuple, of a format suitable
  9557. for calling org-schedule with, or if there is no scheduling,
  9558. returns nil."
  9559. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9560. (when time
  9561. (org-time-string-to-time time))))
  9562. (defun org-get-deadline-time (pom &optional inherit)
  9563. "Get the deadline as a time tuple, of a format suitable for
  9564. calling org-deadline with, or if there is no scheduling, returns
  9565. nil."
  9566. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9567. (when time
  9568. (org-time-string-to-time time))))
  9569. (defun org-remove-timestamp-with-keyword (keyword)
  9570. "Remove all time stamps with KEYWORD in the current entry."
  9571. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9572. beg)
  9573. (save-excursion
  9574. (org-back-to-heading t)
  9575. (setq beg (point))
  9576. (outline-next-heading)
  9577. (while (re-search-backward re beg t)
  9578. (replace-match "")
  9579. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9580. (equal (char-before) ?\ ))
  9581. (backward-delete-char 1)
  9582. (when (string-match "^[ \t]*$" (buffer-substring
  9583. (point-at-bol) (point-at-eol)))
  9584. (delete-region (point-at-bol)
  9585. (min (point-max) (1+ (point-at-eol))))))))))
  9586. (defvar org-time-was-given) ; dynamically scoped parameter
  9587. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9588. (defun org-at-planning-p ()
  9589. "Non-nil when point is on a planning info line."
  9590. ;; This is as accurate and faster than `org-element-at-point' since
  9591. ;; planning info location is fixed in the section.
  9592. (org-with-wide-buffer
  9593. (beginning-of-line)
  9594. (and (looking-at-p org-planning-line-re)
  9595. (eq (point)
  9596. (ignore-errors
  9597. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9598. (org-back-to-heading t)
  9599. (org-with-limited-levels (org-back-to-heading t)))
  9600. (line-beginning-position 2))))))
  9601. (defun org-add-planning-info (what &optional time &rest remove)
  9602. "Insert new timestamp with keyword in the planning line.
  9603. WHAT indicates what kind of time stamp to add. It is a symbol
  9604. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9605. the time to use. If none is given, the user is prompted for
  9606. a date. REMOVE indicates what kind of entries to remove. An old
  9607. WHAT entry will also be removed."
  9608. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9609. (when (and (memq what '(scheduled deadline))
  9610. (or (not time)
  9611. (and (stringp time)
  9612. (string-match "^[-+]+[0-9]" time))))
  9613. ;; Try to get a default date/time from existing timestamp
  9614. (save-excursion
  9615. (org-back-to-heading t)
  9616. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9617. (when (re-search-forward (if (eq what 'scheduled)
  9618. org-scheduled-time-regexp
  9619. org-deadline-time-regexp)
  9620. end t)
  9621. (setq ts (match-string 1)
  9622. default-time (org-time-string-to-time ts)
  9623. default-input (and ts (org-get-compact-tod ts)))))))
  9624. (when what
  9625. (setq time
  9626. (if (stringp time)
  9627. ;; This is a string (relative or absolute), set
  9628. ;; proper date.
  9629. (apply #'encode-time
  9630. (org-read-date-analyze
  9631. time default-time (decode-time default-time)))
  9632. ;; If necessary, get the time from the user
  9633. (or time (org-read-date nil 'to-time nil
  9634. (cl-case what
  9635. (deadline "DEADLINE")
  9636. (scheduled "SCHEDULED")
  9637. (otherwise nil))
  9638. default-time default-input)))))
  9639. (org-with-wide-buffer
  9640. (org-back-to-heading t)
  9641. (let ((planning? (save-excursion
  9642. (forward-line)
  9643. (looking-at-p org-planning-line-re))))
  9644. (cond
  9645. (planning?
  9646. (forward-line)
  9647. ;; Move to current indentation.
  9648. (skip-chars-forward " \t")
  9649. ;; Check if we have to remove something.
  9650. (dolist (type (if what (cons what remove) remove))
  9651. (save-excursion
  9652. (when (re-search-forward
  9653. (cl-case type
  9654. (closed org-closed-time-regexp)
  9655. (deadline org-deadline-time-regexp)
  9656. (scheduled org-scheduled-time-regexp)
  9657. (otherwise (error "Invalid planning type: %s" type)))
  9658. (line-end-position)
  9659. t)
  9660. ;; Delete until next keyword or end of line.
  9661. (delete-region
  9662. (match-beginning 0)
  9663. (if (re-search-forward org-keyword-time-not-clock-regexp
  9664. (line-end-position)
  9665. t)
  9666. (match-beginning 0)
  9667. (line-end-position))))))
  9668. ;; If there is nothing more to add and no more keyword is
  9669. ;; left, remove the line completely.
  9670. (if (and (looking-at-p "[ \t]*$") (not what))
  9671. (delete-region (line-end-position 0)
  9672. (line-end-position))
  9673. ;; If we removed last keyword, do not leave trailing white
  9674. ;; space at the end of line.
  9675. (let ((p (point)))
  9676. (save-excursion
  9677. (end-of-line)
  9678. (unless (= (skip-chars-backward " \t" p) 0)
  9679. (delete-region (point) (line-end-position)))))))
  9680. (what
  9681. (end-of-line)
  9682. (insert "\n")
  9683. (when org-adapt-indentation
  9684. (indent-to-column (1+ (org-outline-level)))))
  9685. (t nil)))
  9686. (when what
  9687. ;; Insert planning keyword.
  9688. (insert (cl-case what
  9689. (closed org-closed-string)
  9690. (deadline org-deadline-string)
  9691. (scheduled org-scheduled-string)
  9692. (otherwise (error "Invalid planning type: %s" what)))
  9693. " ")
  9694. ;; Insert associated timestamp.
  9695. (let ((ts (org-insert-time-stamp
  9696. time
  9697. (or org-time-was-given
  9698. (and (eq what 'closed) org-log-done-with-time))
  9699. (eq what 'closed)
  9700. nil nil (list org-end-time-was-given))))
  9701. (unless (eolp) (insert " "))
  9702. ts)))))
  9703. (defvar org-log-note-marker (make-marker)
  9704. "Marker pointing at the entry where the note is to be inserted.")
  9705. (defvar org-log-note-purpose nil)
  9706. (defvar org-log-note-state nil)
  9707. (defvar org-log-note-previous-state nil)
  9708. (defvar org-log-note-extra nil)
  9709. (defvar org-log-note-window-configuration nil)
  9710. (defvar org-log-note-return-to (make-marker))
  9711. (defvar org-log-note-effective-time nil
  9712. "Remembered current time.
  9713. So that dynamically scoped `org-extend-today-until' affects
  9714. timestamps in state change log.")
  9715. (defvar org-log-post-message nil
  9716. "Message to be displayed after a log note has been stored.
  9717. The auto-repeater uses this.")
  9718. (defun org-add-note ()
  9719. "Add a note to the current entry.
  9720. This is done in the same way as adding a state change note."
  9721. (interactive)
  9722. (org-add-log-setup 'note))
  9723. (defun org-log-beginning (&optional create)
  9724. "Return expected start of log notes in current entry.
  9725. When optional argument CREATE is non-nil, the function creates
  9726. a drawer to store notes, if necessary. Returned position ignores
  9727. narrowing."
  9728. (org-with-wide-buffer
  9729. (let ((drawer (org-log-into-drawer)))
  9730. (cond
  9731. (drawer
  9732. (org-end-of-meta-data)
  9733. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9734. (end (if (org-at-heading-p) (point)
  9735. (save-excursion (outline-next-heading) (point))))
  9736. (case-fold-search t))
  9737. (catch 'exit
  9738. ;; Try to find existing drawer.
  9739. (while (re-search-forward regexp end t)
  9740. (let ((element (org-element-at-point)))
  9741. (when (eq (org-element-type element) 'drawer)
  9742. (let ((cend (org-element-property :contents-end element)))
  9743. (when (and (not org-log-states-order-reversed) cend)
  9744. (goto-char cend)))
  9745. (throw 'exit nil))))
  9746. ;; No drawer found. Create one, if permitted.
  9747. (when create
  9748. (unless (bolp) (insert "\n"))
  9749. (let ((beg (point)))
  9750. (insert ":" drawer ":\n:END:\n")
  9751. (org-indent-region beg (point))
  9752. (org-flag-region (line-end-position -1) (1- (point)) t 'outline))
  9753. (end-of-line -1)))))
  9754. (t
  9755. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9756. (skip-chars-forward " \t\n")
  9757. (beginning-of-line)
  9758. (unless org-log-states-order-reversed
  9759. (org-skip-over-state-notes)
  9760. (skip-chars-backward " \t\n")
  9761. (forward-line)))))
  9762. (if (bolp) (point) (line-beginning-position 2))))
  9763. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9764. "Set up the post command hook to take a note.
  9765. If this is about to TODO state change, the new state is expected in STATE.
  9766. HOW is an indicator what kind of note should be created.
  9767. EXTRA is additional text that will be inserted into the notes buffer."
  9768. (move-marker org-log-note-marker (point))
  9769. (setq org-log-note-purpose purpose
  9770. org-log-note-state state
  9771. org-log-note-previous-state prev-state
  9772. org-log-note-how how
  9773. org-log-note-extra extra
  9774. org-log-note-effective-time (org-current-effective-time))
  9775. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9776. (defun org-skip-over-state-notes ()
  9777. "Skip past the list of State notes in an entry."
  9778. (when (ignore-errors (goto-char (org-in-item-p)))
  9779. (let* ((struct (org-list-struct))
  9780. (prevs (org-list-prevs-alist struct))
  9781. (regexp
  9782. (concat "[ \t]*- +"
  9783. (replace-regexp-in-string
  9784. " +" " +"
  9785. (org-replace-escapes
  9786. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9787. `(("%d" . ,org-ts-regexp-inactive)
  9788. ("%D" . ,org-ts-regexp)
  9789. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9790. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9791. ("%t" . ,org-ts-regexp-inactive)
  9792. ("%T" . ,org-ts-regexp)
  9793. ("%u" . ".*?")
  9794. ("%U" . ".*?")))))))
  9795. (while (looking-at-p regexp)
  9796. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9797. (org-list-get-item-end (point) struct)))))))
  9798. (defun org-add-log-note (&optional _purpose)
  9799. "Pop up a window for taking a note, and add this note later."
  9800. (remove-hook 'post-command-hook 'org-add-log-note)
  9801. (setq org-log-note-window-configuration (current-window-configuration))
  9802. (delete-other-windows)
  9803. (move-marker org-log-note-return-to (point))
  9804. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9805. (goto-char org-log-note-marker)
  9806. (org-switch-to-buffer-other-window "*Org Note*")
  9807. (erase-buffer)
  9808. (if (memq org-log-note-how '(time state))
  9809. (org-store-log-note)
  9810. (let ((org-inhibit-startup t)) (org-mode))
  9811. (insert (format "# Insert note for %s.
  9812. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9813. (cl-case org-log-note-purpose
  9814. (clock-out "stopped clock")
  9815. (done "closed todo item")
  9816. (reschedule "rescheduling")
  9817. (delschedule "no longer scheduled")
  9818. (redeadline "changing deadline")
  9819. (deldeadline "removing deadline")
  9820. (refile "refiling")
  9821. (note "this entry")
  9822. (state
  9823. (format "state change from \"%s\" to \"%s\""
  9824. (or org-log-note-previous-state "")
  9825. (or org-log-note-state "")))
  9826. (t (error "This should not happen")))))
  9827. (when org-log-note-extra (insert org-log-note-extra))
  9828. (setq-local org-finish-function 'org-store-log-note)
  9829. (run-hooks 'org-log-buffer-setup-hook)))
  9830. (defvar org-note-abort nil) ; dynamically scoped
  9831. (defun org-store-log-note ()
  9832. "Finish taking a log note, and insert it to where it belongs."
  9833. (let ((txt (prog1 (buffer-string)
  9834. (kill-buffer)))
  9835. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9836. lines)
  9837. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9838. (setq txt (replace-match "" t t txt)))
  9839. (when (string-match "\\s-+\\'" txt)
  9840. (setq txt (replace-match "" t t txt)))
  9841. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9842. (when (org-string-nw-p note)
  9843. (setq note
  9844. (org-replace-escapes
  9845. note
  9846. (list (cons "%u" (user-login-name))
  9847. (cons "%U" user-full-name)
  9848. (cons "%t" (format-time-string
  9849. (org-time-stamp-format 'long 'inactive)
  9850. org-log-note-effective-time))
  9851. (cons "%T" (format-time-string
  9852. (org-time-stamp-format 'long nil)
  9853. org-log-note-effective-time))
  9854. (cons "%d" (format-time-string
  9855. (org-time-stamp-format nil 'inactive)
  9856. org-log-note-effective-time))
  9857. (cons "%D" (format-time-string
  9858. (org-time-stamp-format nil nil)
  9859. org-log-note-effective-time))
  9860. (cons "%s" (cond
  9861. ((not org-log-note-state) "")
  9862. ((string-match-p org-ts-regexp
  9863. org-log-note-state)
  9864. (format "\"[%s]\""
  9865. (substring org-log-note-state 1 -1)))
  9866. (t (format "\"%s\"" org-log-note-state))))
  9867. (cons "%S"
  9868. (cond
  9869. ((not org-log-note-previous-state) "")
  9870. ((string-match-p org-ts-regexp
  9871. org-log-note-previous-state)
  9872. (format "\"[%s]\""
  9873. (substring
  9874. org-log-note-previous-state 1 -1)))
  9875. (t (format "\"%s\""
  9876. org-log-note-previous-state)))))))
  9877. (when lines (setq note (concat note " \\\\")))
  9878. (push note lines))
  9879. (when (and lines (not org-note-abort))
  9880. (with-current-buffer (marker-buffer org-log-note-marker)
  9881. (org-with-wide-buffer
  9882. ;; Find location for the new note.
  9883. (goto-char org-log-note-marker)
  9884. (set-marker org-log-note-marker nil)
  9885. ;; Note associated to a clock is to be located right after
  9886. ;; the clock. Do not move point.
  9887. (unless (eq org-log-note-purpose 'clock-out)
  9888. (goto-char (org-log-beginning t)))
  9889. ;; Make sure point is at the beginning of an empty line.
  9890. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9891. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9892. ;; In an existing list, add a new item at the top level.
  9893. ;; Otherwise, indent line like a regular one.
  9894. (let ((itemp (org-in-item-p)))
  9895. (if itemp
  9896. (indent-line-to
  9897. (let ((struct (save-excursion
  9898. (goto-char itemp) (org-list-struct))))
  9899. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9900. (org-indent-line)))
  9901. (insert (org-list-bullet-string "-") (pop lines))
  9902. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9903. (dolist (line lines)
  9904. (insert "\n")
  9905. (indent-line-to ind)
  9906. (insert line)))
  9907. (message "Note stored")
  9908. (org-back-to-heading t))
  9909. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9910. ;; from within `org-add-log-note' because `buffer-undo-list'
  9911. ;; is then modified outside of `org-with-remote-undo'.
  9912. (when (eq this-command 'org-agenda-todo)
  9913. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9914. ;; Don't add undo information when called from `org-agenda-todo'.
  9915. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9916. (set-window-configuration org-log-note-window-configuration)
  9917. (with-current-buffer (marker-buffer org-log-note-return-to)
  9918. (goto-char org-log-note-return-to))
  9919. (move-marker org-log-note-return-to nil)
  9920. (when org-log-post-message (message "%s" org-log-post-message))))
  9921. (defun org-remove-empty-drawer-at (pos)
  9922. "Remove an empty drawer at position POS.
  9923. POS may also be a marker."
  9924. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9925. (org-with-wide-buffer
  9926. (goto-char pos)
  9927. (let ((drawer (org-element-at-point)))
  9928. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9929. (not (org-element-property :contents-begin drawer)))
  9930. (delete-region (org-element-property :begin drawer)
  9931. (progn (goto-char (org-element-property :end drawer))
  9932. (skip-chars-backward " \r\t\n")
  9933. (forward-line)
  9934. (point))))))))
  9935. (defvar org-ts-type nil)
  9936. (defun org-sparse-tree (&optional arg type)
  9937. "Create a sparse tree, prompt for the details.
  9938. This command can create sparse trees. You first need to select the type
  9939. of match used to create the tree:
  9940. t Show all TODO entries.
  9941. T Show entries with a specific TODO keyword.
  9942. m Show entries selected by a tags/property match.
  9943. p Enter a property name and its value (both with completion on existing
  9944. names/values) and show entries with that property.
  9945. r Show entries matching a regular expression (`/' can be used as well).
  9946. b Show deadlines and scheduled items before a date.
  9947. a Show deadlines and scheduled items after a date.
  9948. d Show deadlines due within `org-deadline-warning-days'.
  9949. D Show deadlines and scheduled items between a date range."
  9950. (interactive "P")
  9951. (setq type (or type org-sparse-tree-default-date-type))
  9952. (setq org-ts-type type)
  9953. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9954. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9955. [c]ycle through date types: %s"
  9956. (cl-case type
  9957. (all "all timestamps")
  9958. (scheduled "only scheduled")
  9959. (deadline "only deadline")
  9960. (active "only active timestamps")
  9961. (inactive "only inactive timestamps")
  9962. (closed "with a closed time-stamp")
  9963. (otherwise "scheduled/deadline")))
  9964. (let ((answer (read-char-exclusive)))
  9965. (cl-case answer
  9966. (?c
  9967. (org-sparse-tree
  9968. arg
  9969. (cadr
  9970. (memq type '(nil all scheduled deadline active inactive closed)))))
  9971. (?d (call-interactively 'org-check-deadlines))
  9972. (?b (call-interactively 'org-check-before-date))
  9973. (?a (call-interactively 'org-check-after-date))
  9974. (?D (call-interactively 'org-check-dates-range))
  9975. (?t (call-interactively 'org-show-todo-tree))
  9976. (?T (org-show-todo-tree '(4)))
  9977. (?m (call-interactively 'org-match-sparse-tree))
  9978. ((?p ?P)
  9979. (let* ((kwd (completing-read
  9980. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9981. (value (completing-read
  9982. "Value: " (mapcar #'list (org-property-values kwd)))))
  9983. (unless (string-match "\\`{.*}\\'" value)
  9984. (setq value (concat "\"" value "\"")))
  9985. (org-match-sparse-tree arg (concat kwd "=" value))))
  9986. ((?r ?R ?/) (call-interactively 'org-occur))
  9987. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9988. (defvar-local org-occur-highlights nil
  9989. "List of overlays used for occur matches.")
  9990. (defvar-local org-occur-parameters nil
  9991. "Parameters of the active org-occur calls.
  9992. This is a list, each call to org-occur pushes as cons cell,
  9993. containing the regular expression and the callback, onto the list.
  9994. The list can contain several entries if `org-occur' has been called
  9995. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9996. will only contain one set of parameters. When the highlights are
  9997. removed (for example with `C-c C-c', or with the next edit (depending
  9998. on `org-remove-highlights-with-change'), this variable is emptied
  9999. as well.")
  10000. (defun org-occur (regexp &optional keep-previous callback)
  10001. "Make a compact tree showing all matches of REGEXP.
  10002. The tree will show the lines where the regexp matches, and any other context
  10003. defined in `org-show-context-detail', which see.
  10004. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10005. done by a previous call to `org-occur' will be kept, to allow stacking of
  10006. calls to this command.
  10007. Optional argument CALLBACK can be a function of no argument. In this case,
  10008. it is called with point at the end of the match, match data being set
  10009. accordingly. Current match is shown only if the return value is non-nil.
  10010. The function must neither move point nor alter narrowing."
  10011. (interactive "sRegexp: \nP")
  10012. (when (equal regexp "")
  10013. (user-error "Regexp cannot be empty"))
  10014. (unless keep-previous
  10015. (org-remove-occur-highlights nil nil t))
  10016. (push (cons regexp callback) org-occur-parameters)
  10017. (let ((cnt 0))
  10018. (save-excursion
  10019. (goto-char (point-min))
  10020. (when (or (not keep-previous) ; do not want to keep
  10021. (not org-occur-highlights)) ; no previous matches
  10022. ;; hide everything
  10023. (org-overview))
  10024. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10025. (isearch-no-upper-case-p regexp t)
  10026. org-occur-case-fold-search)))
  10027. (while (re-search-forward regexp nil t)
  10028. (when (or (not callback)
  10029. (save-match-data (funcall callback)))
  10030. (setq cnt (1+ cnt))
  10031. (when org-highlight-sparse-tree-matches
  10032. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10033. (org-show-context 'occur-tree)))))
  10034. (when org-remove-highlights-with-change
  10035. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10036. nil 'local))
  10037. (unless org-sparse-tree-open-archived-trees
  10038. (org-hide-archived-subtrees (point-min) (point-max)))
  10039. (run-hooks 'org-occur-hook)
  10040. (when (called-interactively-p 'interactive)
  10041. (message "%d match(es) for regexp %s" cnt regexp))
  10042. cnt))
  10043. (defun org-occur-next-match (&optional n _reset)
  10044. "Function for `next-error-function' to find sparse tree matches.
  10045. N is the number of matches to move, when negative move backwards.
  10046. This function always goes back to the starting point when no
  10047. match is found."
  10048. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10049. (search-func (if (< n 0)
  10050. 'previous-single-char-property-change
  10051. 'next-single-char-property-change))
  10052. (n (abs n))
  10053. (pos (point))
  10054. p1)
  10055. (catch 'exit
  10056. (while (setq p1 (funcall search-func (point) 'org-type))
  10057. (when (equal p1 limit)
  10058. (goto-char pos)
  10059. (user-error "No more matches"))
  10060. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10061. (setq n (1- n))
  10062. (when (= n 0)
  10063. (goto-char p1)
  10064. (throw 'exit (point))))
  10065. (goto-char p1))
  10066. (goto-char p1)
  10067. (user-error "No more matches"))))
  10068. (defun org-highlight-new-match (beg end)
  10069. "Highlight from BEG to END and mark the highlight is an occur headline."
  10070. (let ((ov (make-overlay beg end)))
  10071. (overlay-put ov 'face 'secondary-selection)
  10072. (overlay-put ov 'org-type 'org-occur)
  10073. (push ov org-occur-highlights)))
  10074. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10075. "Remove the occur highlights from the buffer.
  10076. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10077. from the `before-change-functions' in the current buffer."
  10078. (interactive)
  10079. (unless org-inhibit-highlight-removal
  10080. (mapc #'delete-overlay org-occur-highlights)
  10081. (setq org-occur-highlights nil)
  10082. (setq org-occur-parameters nil)
  10083. (unless noremove
  10084. (remove-hook 'before-change-functions
  10085. 'org-remove-occur-highlights 'local))))
  10086. ;;;; Priorities
  10087. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10088. "Regular expression matching the priority indicator.
  10089. A priority indicator can be e.g. [#A] or [#1].
  10090. This regular expression matches these groups:
  10091. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10092. 1 : the priority cookie, e.g. \"[#A]\"
  10093. 2 : the value of the priority cookie, e.g. \"A\".")
  10094. (defun org-priority-up ()
  10095. "Increase the priority of the current item."
  10096. (interactive)
  10097. (org-priority 'up))
  10098. (defun org-priority-down ()
  10099. "Decrease the priority of the current item."
  10100. (interactive)
  10101. (org-priority 'down))
  10102. (defun org-priority (&optional action show)
  10103. "Change the priority of an item.
  10104. When called interactively with a `\\[universal-argument]' prefix,
  10105. show the priority in the minibuffer instead of changing it.
  10106. When called programmatically, ACTION can be `set', `up', `down',
  10107. or a character."
  10108. (interactive "P")
  10109. (when show
  10110. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10111. ;; passed the SHOW argument should be removed.
  10112. (warn "`org-priority' called with deprecated SHOW argument"))
  10113. (if (equal action '(4))
  10114. (org-priority-show)
  10115. (unless org-priority-enable-commands
  10116. (user-error "Priority commands are disabled"))
  10117. (setq action (or action 'set))
  10118. (let ((nump (< org-priority-lowest 65))
  10119. current new news have remove)
  10120. (save-excursion
  10121. (org-back-to-heading t)
  10122. (when (looking-at org-priority-regexp)
  10123. (let ((ms (match-string 2)))
  10124. (setq current (org-priority-to-value ms)
  10125. have t)))
  10126. (cond
  10127. ((eq action 'remove)
  10128. (setq remove t new ?\ ))
  10129. ((or (eq action 'set)
  10130. (integerp action))
  10131. (if (not (eq action 'set))
  10132. (setq new action)
  10133. (setq
  10134. new
  10135. (if nump
  10136. (string-to-number
  10137. (read-string (format "Priority %s-%s, SPC to remove: "
  10138. (number-to-string org-priority-highest)
  10139. (number-to-string org-priority-lowest))))
  10140. (progn (message "Priority %c-%c, SPC to remove: "
  10141. org-priority-highest org-priority-lowest)
  10142. (save-match-data
  10143. (setq new (read-char-exclusive)))))))
  10144. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10145. (= (upcase org-priority-lowest) org-priority-lowest))
  10146. (setq new (upcase new)))
  10147. (cond ((equal new ?\s) (setq remove t))
  10148. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10149. (user-error
  10150. (if nump
  10151. "Priority must be between `%s' and `%s'"
  10152. "Priority must be between `%c' and `%c'")
  10153. org-priority-highest org-priority-lowest))))
  10154. ((eq action 'up)
  10155. (setq new (if have
  10156. (1- current) ; normal cycling
  10157. ;; last priority was empty
  10158. (if (eq last-command this-command)
  10159. org-priority-lowest ; wrap around empty to lowest
  10160. ;; default
  10161. (if org-priority-start-cycle-with-default
  10162. org-priority-default
  10163. (1- org-priority-default))))))
  10164. ((eq action 'down)
  10165. (setq new (if have
  10166. (1+ current) ; normal cycling
  10167. ;; last priority was empty
  10168. (if (eq last-command this-command)
  10169. org-priority-highest ; wrap around empty to highest
  10170. ;; default
  10171. (if org-priority-start-cycle-with-default
  10172. org-priority-default
  10173. (1+ org-priority-default))))))
  10174. (t (user-error "Invalid action")))
  10175. (when (or (< (upcase new) org-priority-highest)
  10176. (> (upcase new) org-priority-lowest))
  10177. (if (and (memq action '(up down))
  10178. (not have) (not (eq last-command this-command)))
  10179. ;; `new' is from default priority
  10180. (error
  10181. "The default can not be set, see `org-priority-default' why")
  10182. ;; normal cycling: `new' is beyond highest/lowest priority
  10183. ;; and is wrapped around to the empty priority
  10184. (setq remove t)))
  10185. ;; Numerical priorities are limited to 64, beyond that number,
  10186. ;; assume the priority cookie is a character.
  10187. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10188. (if have
  10189. (if remove
  10190. (replace-match "" t t nil 1)
  10191. (replace-match news t t nil 2))
  10192. (if remove
  10193. (user-error "No priority cookie found in line")
  10194. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10195. (if (match-end 2)
  10196. (progn
  10197. (goto-char (match-end 2))
  10198. (insert " [#" news "]"))
  10199. (goto-char (match-beginning 3))
  10200. (insert "[#" news "] "))))
  10201. (org-align-tags))
  10202. (if remove
  10203. (message "Priority removed")
  10204. (message "Priority of current item set to %s" news)))))
  10205. (defalias 'org-show-priority 'org-priority-show)
  10206. (defun org-priority-show ()
  10207. "Show the priority of the current item.
  10208. This priority is composed of the main priority given with the [#A] cookies,
  10209. and by additional input from the age of a schedules or deadline entry."
  10210. (interactive)
  10211. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10212. (org-get-at-bol 'priority)
  10213. (save-excursion
  10214. (save-match-data
  10215. (beginning-of-line)
  10216. (and (looking-at org-heading-regexp)
  10217. (org-get-priority (match-string 0))))))))
  10218. (message "Priority is %d" (if pri pri -1000))))
  10219. (defun org-get-priority (s)
  10220. "Find priority cookie and return priority.
  10221. S is a string against which you can match `org-priority-regexp'.
  10222. If `org-priority-get-priority-function' is set to a custom
  10223. function, use it. Otherwise process S and output the priority
  10224. value, an integer."
  10225. (save-match-data
  10226. (if (functionp org-priority-get-priority-function)
  10227. (funcall org-priority-get-priority-function s)
  10228. (if (not (string-match org-priority-regexp s))
  10229. (* 1000 (- org-priority-lowest org-priority-default))
  10230. (* 1000 (- org-priority-lowest
  10231. (org-priority-to-value (match-string 2 s))))))))
  10232. ;;;; Tags
  10233. (defvar org-agenda-archives-mode)
  10234. (defvar org-map-continue-from nil
  10235. "Position from where mapping should continue.
  10236. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10237. (defvar org-scanner-tags nil
  10238. "The current tag list while the tags scanner is running.")
  10239. (defvar org-trust-scanner-tags nil
  10240. "Should `org-get-tags' use the tags for the scanner.
  10241. This is for internal dynamical scoping only.
  10242. When this is non-nil, the function `org-get-tags' will return the value
  10243. of `org-scanner-tags' instead of building the list by itself. This
  10244. can lead to large speed-ups when the tags scanner is used in a file with
  10245. many entries, and when the list of tags is retrieved, for example to
  10246. obtain a list of properties. Building the tags list for each entry in such
  10247. a file becomes an N^2 operation - but with this variable set, it scales
  10248. as N.")
  10249. (defvar org--matcher-tags-todo-only nil)
  10250. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10251. "Scan headline tags with inheritance and produce output ACTION.
  10252. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10253. or `agenda' to produce an entry list for an agenda view. It can also be
  10254. a Lisp form or a function that should be called at each matched headline, in
  10255. this case the return value is a list of all return values from these calls.
  10256. MATCHER is a function accepting three arguments, returning
  10257. a non-nil value whenever a given set of tags qualifies a headline
  10258. for inclusion. See `org-make-tags-matcher' for more information.
  10259. As a special case, it can also be set to t (respectively nil) in
  10260. order to match all (respectively none) headline.
  10261. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10262. included in the output.
  10263. START-LEVEL can be a string with asterisks, reducing the scope to
  10264. headlines matching this string."
  10265. (require 'org-agenda)
  10266. (let* ((re (concat "^"
  10267. (if start-level
  10268. ;; Get the correct level to match
  10269. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10270. org-outline-regexp)
  10271. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10272. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10273. (props (list 'face 'default
  10274. 'done-face 'org-agenda-done
  10275. 'undone-face 'default
  10276. 'mouse-face 'highlight
  10277. 'org-not-done-regexp org-not-done-regexp
  10278. 'org-todo-regexp org-todo-regexp
  10279. 'org-complex-heading-regexp org-complex-heading-regexp
  10280. 'help-echo
  10281. (format "mouse-2 or RET jump to Org file %S"
  10282. (abbreviate-file-name
  10283. (or (buffer-file-name (buffer-base-buffer))
  10284. (buffer-name (buffer-base-buffer)))))))
  10285. (org-map-continue-from nil)
  10286. lspos tags tags-list
  10287. (tags-alist (list (cons 0 org-file-tags)))
  10288. (llast 0) rtn rtn1 level category i txt
  10289. todo marker entry priority
  10290. ts-date ts-date-type ts-date-pair)
  10291. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10292. (setq action (list 'lambda nil action)))
  10293. (save-excursion
  10294. (goto-char (point-min))
  10295. (when (eq action 'sparse-tree)
  10296. (org-overview)
  10297. (org-remove-occur-highlights))
  10298. (while (let (case-fold-search)
  10299. (re-search-forward re nil t))
  10300. (setq org-map-continue-from nil)
  10301. (catch :skip
  10302. ;; Ignore closing parts of inline tasks.
  10303. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10304. (throw :skip t))
  10305. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10306. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10307. (goto-char (setq lspos (match-beginning 0)))
  10308. (setq level (org-reduced-level (org-outline-level))
  10309. category (org-get-category))
  10310. (when (eq action 'agenda)
  10311. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10312. ts-date (car ts-date-pair)
  10313. ts-date-type (cdr ts-date-pair)))
  10314. (setq i llast llast level)
  10315. ;; remove tag lists from same and sublevels
  10316. (while (>= i level)
  10317. (when (setq entry (assoc i tags-alist))
  10318. (setq tags-alist (delete entry tags-alist)))
  10319. (setq i (1- i)))
  10320. ;; add the next tags
  10321. (when tags
  10322. (setq tags (org-split-string tags ":")
  10323. tags-alist
  10324. (cons (cons level tags) tags-alist)))
  10325. ;; compile tags for current headline
  10326. (setq tags-list
  10327. (if org-use-tag-inheritance
  10328. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10329. tags)
  10330. org-scanner-tags tags-list)
  10331. (when org-use-tag-inheritance
  10332. (setcdr (car tags-alist)
  10333. (mapcar (lambda (x)
  10334. (setq x (copy-sequence x))
  10335. (org-add-prop-inherited x))
  10336. (cdar tags-alist))))
  10337. (when (and tags org-use-tag-inheritance
  10338. (or (not (eq t org-use-tag-inheritance))
  10339. org-tags-exclude-from-inheritance))
  10340. ;; Selective inheritance, remove uninherited ones.
  10341. (setcdr (car tags-alist)
  10342. (org-remove-uninherited-tags (cdar tags-alist))))
  10343. (when (and
  10344. ;; eval matcher only when the todo condition is OK
  10345. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10346. (if (functionp matcher)
  10347. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10348. (funcall matcher todo tags-list level))
  10349. matcher))
  10350. ;; Call the skipper, but return t if it does not
  10351. ;; skip, so that the `and' form continues evaluating.
  10352. (progn
  10353. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10354. t)
  10355. ;; Check if timestamps are deselecting this entry
  10356. (or (not todo-only)
  10357. (and (member todo org-todo-keywords-1)
  10358. (or (not org-agenda-tags-todo-honor-ignore-options)
  10359. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10360. ;; select this headline
  10361. (cond
  10362. ((eq action 'sparse-tree)
  10363. (and org-highlight-sparse-tree-matches
  10364. (org-get-heading) (match-end 0)
  10365. (org-highlight-new-match
  10366. (match-beginning 1) (match-end 1)))
  10367. (org-show-context 'tags-tree))
  10368. ((eq action 'agenda)
  10369. (setq txt (org-agenda-format-item
  10370. ""
  10371. (concat
  10372. (if (eq org-tags-match-list-sublevels 'indented)
  10373. (make-string (1- level) ?.) "")
  10374. (org-get-heading))
  10375. (make-string level ?\s)
  10376. category
  10377. tags-list)
  10378. priority (org-get-priority txt))
  10379. (goto-char lspos)
  10380. (setq marker (org-agenda-new-marker))
  10381. (org-add-props txt props
  10382. 'org-marker marker 'org-hd-marker marker 'org-category category
  10383. 'todo-state todo
  10384. 'ts-date ts-date
  10385. 'priority priority
  10386. 'type (concat "tagsmatch" ts-date-type))
  10387. (push txt rtn))
  10388. ((functionp action)
  10389. (setq org-map-continue-from nil)
  10390. (save-excursion
  10391. (setq rtn1 (funcall action))
  10392. (push rtn1 rtn)))
  10393. (t (user-error "Invalid action")))
  10394. ;; if we are to skip sublevels, jump to end of subtree
  10395. (unless org-tags-match-list-sublevels
  10396. (org-end-of-subtree t)
  10397. (backward-char 1))))
  10398. ;; Get the correct position from where to continue
  10399. (if org-map-continue-from
  10400. (goto-char org-map-continue-from)
  10401. (and (= (point) lspos) (end-of-line 1)))))
  10402. (when (and (eq action 'sparse-tree)
  10403. (not org-sparse-tree-open-archived-trees))
  10404. (org-hide-archived-subtrees (point-min) (point-max)))
  10405. (nreverse rtn)))
  10406. (defun org-remove-uninherited-tags (tags)
  10407. "Remove all tags that are not inherited from the list TAGS."
  10408. (cond
  10409. ((eq org-use-tag-inheritance t)
  10410. (if org-tags-exclude-from-inheritance
  10411. (org-delete-all org-tags-exclude-from-inheritance tags)
  10412. tags))
  10413. ((not org-use-tag-inheritance) nil)
  10414. ((stringp org-use-tag-inheritance)
  10415. (delq nil (mapcar
  10416. (lambda (x)
  10417. (if (and (string-match org-use-tag-inheritance x)
  10418. (not (member x org-tags-exclude-from-inheritance)))
  10419. x nil))
  10420. tags)))
  10421. ((listp org-use-tag-inheritance)
  10422. (delq nil (mapcar
  10423. (lambda (x)
  10424. (if (member x org-use-tag-inheritance) x nil))
  10425. tags)))))
  10426. (defun org-match-sparse-tree (&optional todo-only match)
  10427. "Create a sparse tree according to tags string MATCH.
  10428. MATCH is a string with match syntax. It can contain a selection
  10429. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10430. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10431. those. See the manual for details.
  10432. If optional argument TODO-ONLY is non-nil, only select lines that
  10433. are also TODO tasks."
  10434. (interactive "P")
  10435. (org-agenda-prepare-buffers (list (current-buffer)))
  10436. (let ((org--matcher-tags-todo-only todo-only))
  10437. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10438. org--matcher-tags-todo-only)))
  10439. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10440. (defvar org-cached-props nil)
  10441. (defun org-cached-entry-get (pom property)
  10442. (if (or (eq t org-use-property-inheritance)
  10443. (and (stringp org-use-property-inheritance)
  10444. (let ((case-fold-search t))
  10445. (string-match-p org-use-property-inheritance property)))
  10446. (and (listp org-use-property-inheritance)
  10447. (member-ignore-case property org-use-property-inheritance)))
  10448. ;; Caching is not possible, check it directly.
  10449. (org-entry-get pom property 'inherit)
  10450. ;; Get all properties, so we can do complicated checks easily.
  10451. (cdr (assoc-string property
  10452. (or org-cached-props
  10453. (setq org-cached-props (org-entry-properties pom)))
  10454. t))))
  10455. (defun org-global-tags-completion-table (&optional files)
  10456. "Return the list of all tags in all agenda buffer/files.
  10457. Optional FILES argument is a list of files which can be used
  10458. instead of the agenda files."
  10459. (save-excursion
  10460. (org-uniquify
  10461. (delq nil
  10462. (apply #'append
  10463. (mapcar
  10464. (lambda (file)
  10465. (set-buffer (find-file-noselect file))
  10466. (org--tag-add-to-alist
  10467. (org-get-buffer-tags)
  10468. (mapcar (lambda (x)
  10469. (and (stringp (car-safe x))
  10470. (list (car-safe x))))
  10471. org-current-tag-alist)))
  10472. (if (car-safe files) files
  10473. (org-agenda-files))))))))
  10474. (defun org-make-tags-matcher (match &optional only-local-tags)
  10475. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10476. Returns a cons of the selection string MATCH and a function
  10477. implementing the matcher.
  10478. The matcher is to be called at an Org entry, with point on the
  10479. headline, and returns non-nil if the entry matches the selection
  10480. string MATCH. It must be called with three arguments: the TODO
  10481. keyword at the entry (or nil if none), the list of all tags at
  10482. the entry including inherited ones and the reduced level of the
  10483. headline. Additionally, the category of the entry, if any, must
  10484. be specified as the text property `org-category' on the headline.
  10485. This function sets the variable `org--matcher-tags-todo-only' to
  10486. a non-nil value if the matcher restricts matching to TODO
  10487. entries, otherwise it is not touched.
  10488. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10489. table, only get buffer tags.
  10490. See also `org-scan-tags'."
  10491. (unless match
  10492. ;; Get a new match request, with completion against the global
  10493. ;; tags table and the local tags in current buffer.
  10494. (let ((org-last-tags-completion-table
  10495. (org--tag-add-to-alist
  10496. (org-get-buffer-tags)
  10497. (unless only-local-tags
  10498. (org-global-tags-completion-table)))))
  10499. (setq match
  10500. (completing-read
  10501. "Match: "
  10502. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10503. (let ((match0 match)
  10504. (re (concat
  10505. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10506. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10507. "\\([<>=]\\{1,2\\}\\)"
  10508. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10509. "\\|" org-tag-re "\\)"))
  10510. (start 0)
  10511. tagsmatch todomatch tagsmatcher todomatcher)
  10512. ;; Expand group tags.
  10513. (setq match (org-tags-expand match))
  10514. ;; Check if there is a TODO part of this match, which would be the
  10515. ;; part after a "/". To make sure that this slash is not part of
  10516. ;; a property value to be matched against, we also check that
  10517. ;; there is no / after that slash. First, find the last slash.
  10518. (let ((s 0))
  10519. (while (string-match "/+" match s)
  10520. (setq start (match-beginning 0))
  10521. (setq s (match-end 0))))
  10522. (if (and (string-match "/+" match start)
  10523. (not (string-match-p "\"" match start)))
  10524. ;; Match contains also a TODO-matching request.
  10525. (progn
  10526. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10527. (setq todomatch (substring match (match-end 0)))
  10528. (when (string-prefix-p "!" todomatch)
  10529. (setq org--matcher-tags-todo-only t)
  10530. (setq todomatch (substring todomatch 1)))
  10531. (when (string-match "\\`\\s-*\\'" todomatch)
  10532. (setq todomatch nil)))
  10533. ;; Only matching tags.
  10534. (setq tagsmatch match)
  10535. (setq todomatch nil))
  10536. ;; Make the tags matcher.
  10537. (when (org-string-nw-p tagsmatch)
  10538. (let ((orlist nil)
  10539. (orterms (org-split-string tagsmatch "|"))
  10540. term)
  10541. (while (setq term (pop orterms))
  10542. (while (and (equal (substring term -1) "\\") orterms)
  10543. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10544. (while (string-match re term)
  10545. (let* ((rest (substring term (match-end 0)))
  10546. (minus (and (match-end 1)
  10547. (equal (match-string 1 term) "-")))
  10548. (tag (save-match-data
  10549. (replace-regexp-in-string
  10550. "\\\\-" "-" (match-string 2 term))))
  10551. (regexp (eq (string-to-char tag) ?{))
  10552. (levelp (match-end 4))
  10553. (propp (match-end 5))
  10554. (mm
  10555. (cond
  10556. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10557. (levelp
  10558. `(,(org-op-to-function (match-string 3 term))
  10559. level
  10560. ,(string-to-number (match-string 4 term))))
  10561. (propp
  10562. (let* ((gv (pcase (upcase (match-string 5 term))
  10563. ("CATEGORY"
  10564. '(get-text-property (point) 'org-category))
  10565. ("TODO" 'todo)
  10566. (p `(org-cached-entry-get nil ,p))))
  10567. (pv (match-string 7 term))
  10568. (regexp (eq (string-to-char pv) ?{))
  10569. (strp (eq (string-to-char pv) ?\"))
  10570. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10571. (po (org-op-to-function (match-string 6 term)
  10572. (if timep 'time strp))))
  10573. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10574. (when timep (setq pv (org-matcher-time pv)))
  10575. (cond ((and regexp (eq po '/=))
  10576. `(not (string-match ,pv (or ,gv ""))))
  10577. (regexp `(string-match ,pv (or ,gv "")))
  10578. (strp `(,po (or ,gv "") ,pv))
  10579. (t
  10580. `(,po
  10581. (string-to-number (or ,gv ""))
  10582. ,(string-to-number pv))))))
  10583. (t `(member ,tag tags-list)))))
  10584. (push (if minus `(not ,mm) mm) tagsmatcher)
  10585. (setq term rest)))
  10586. (push `(and ,@tagsmatcher) orlist)
  10587. (setq tagsmatcher nil))
  10588. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10589. ;; Make the TODO matcher.
  10590. (when (org-string-nw-p todomatch)
  10591. (let ((orlist nil))
  10592. (dolist (term (org-split-string todomatch "|"))
  10593. (while (string-match re term)
  10594. (let* ((minus (and (match-end 1)
  10595. (equal (match-string 1 term) "-")))
  10596. (kwd (match-string 2 term))
  10597. (regexp (eq (string-to-char kwd) ?{))
  10598. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10599. `(equal todo ,kwd))))
  10600. (push (if minus `(not ,mm) mm) todomatcher))
  10601. (setq term (substring term (match-end 0))))
  10602. (push (if (> (length todomatcher) 1)
  10603. (cons 'and todomatcher)
  10604. (car todomatcher))
  10605. orlist)
  10606. (setq todomatcher nil))
  10607. (setq todomatcher (cons 'or orlist))))
  10608. ;; Return the string and function of the matcher. If no
  10609. ;; tags-specific or todo-specific matcher exists, match
  10610. ;; everything.
  10611. (let ((matcher (if (and tagsmatcher todomatcher)
  10612. `(and ,tagsmatcher ,todomatcher)
  10613. (or tagsmatcher todomatcher t))))
  10614. (when org--matcher-tags-todo-only
  10615. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10616. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10617. (defun org--tags-expand-group (group tag-groups expanded)
  10618. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10619. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10620. an accumulator used in recursive calls."
  10621. (dolist (tag group)
  10622. (unless (member tag expanded)
  10623. (let ((group (assoc tag tag-groups)))
  10624. (push tag expanded)
  10625. (when group
  10626. (setq expanded
  10627. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10628. expanded)
  10629. (defun org-tags-expand (match &optional single-as-list downcased)
  10630. "Expand group tags in MATCH.
  10631. This replaces every group tag in MATCH with a regexp tag search.
  10632. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10633. will be replaced like this:
  10634. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10635. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10636. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10637. Replacing by a regexp preserves the structure of the match.
  10638. E.g., this expansion
  10639. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10640. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10641. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10642. A group tag in MATCH can contain regular expressions of its own.
  10643. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10644. will be replaced like this:
  10645. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10646. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10647. assumed to be a single group tag, and the function will return
  10648. the list of tags in this group.
  10649. When DOWNCASED is non-nil, expand downcased TAGS."
  10650. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10651. (let ((tag-groups
  10652. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10653. (if (not downcased) g
  10654. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10655. (cond
  10656. (single-as-list (org--tags-expand-group
  10657. (list (if downcased (downcase match) match))
  10658. tag-groups nil))
  10659. (org-group-tags
  10660. (let* ((case-fold-search t)
  10661. (tag-syntax org-mode-syntax-table)
  10662. (group-keys (mapcar #'car tag-groups))
  10663. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10664. (return-match (if downcased (downcase match) match)))
  10665. ;; Mark regexp-expressions in the match-expression so that we
  10666. ;; do not replace them later on.
  10667. (let ((s 0))
  10668. (while (string-match "{.+?}" return-match s)
  10669. (setq s (match-end 0))
  10670. (add-text-properties
  10671. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10672. ;; @ and _ are allowed as word-components in tags.
  10673. (modify-syntax-entry ?@ "w" tag-syntax)
  10674. (modify-syntax-entry ?_ "w" tag-syntax)
  10675. ;; For each tag token found in MATCH, compute a regexp and it
  10676. (with-syntax-table tag-syntax
  10677. (replace-regexp-in-string
  10678. key-regexp
  10679. (lambda (m)
  10680. (if (get-text-property (match-beginning 2) 'regexp m)
  10681. m ;regexp tag: ignore
  10682. (let* ((operator (match-string 1 m))
  10683. (tag-token (let ((tag (match-string 2 m)))
  10684. (list (if downcased (downcase tag) tag))))
  10685. regexp-tags regular-tags)
  10686. ;; Partition tags between regexp and regular tags.
  10687. ;; Remove curly bracket syntax from regexp tags.
  10688. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10689. (save-match-data
  10690. (if (string-match "{\\(.+?\\)}" tag)
  10691. (push (match-string 1 tag) regexp-tags)
  10692. (push tag regular-tags))))
  10693. ;; Replace tag token by the appropriate regexp.
  10694. ;; Regular tags need to be regexp-quoted, whereas
  10695. ;; regexp-tags are inserted as-is.
  10696. (let ((regular (regexp-opt regular-tags))
  10697. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10698. (concat operator
  10699. (cond
  10700. ((null regular-tags) (format "{%s}" regexp))
  10701. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10702. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10703. return-match
  10704. t t))))
  10705. (t match))))
  10706. (defun org-op-to-function (op &optional stringp)
  10707. "Turn an operator into the appropriate function."
  10708. (setq op
  10709. (cond
  10710. ((equal op "<" ) '(< org-string< org-time<))
  10711. ((equal op ">" ) '(> org-string> org-time>))
  10712. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10713. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10714. ((member op '("=" "==")) '(= string= org-time=))
  10715. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10716. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10717. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10718. (defvar org-tags-overlay (make-overlay 1 1))
  10719. (delete-overlay org-tags-overlay)
  10720. (defun org-add-prop-inherited (s)
  10721. (add-text-properties 0 (length s) '(inherited t) s)
  10722. s)
  10723. (defun org-toggle-tag (tag &optional onoff)
  10724. "Toggle the tag TAG for the current line.
  10725. If ONOFF is `on' or `off', don't toggle but set to this state."
  10726. (save-excursion
  10727. (org-back-to-heading t)
  10728. (let ((current
  10729. ;; Reverse the tags list so any new tag is appended to the
  10730. ;; current list of tags.
  10731. (nreverse (org-get-tags nil t)))
  10732. res)
  10733. (pcase onoff
  10734. (`off (setq current (delete tag current)))
  10735. ((or `on (guard (not (member tag current))))
  10736. (setq res t)
  10737. (cl-pushnew tag current :test #'equal))
  10738. (_ (setq current (delete tag current))))
  10739. (org-set-tags (nreverse current))
  10740. res)))
  10741. (defun org--align-tags-here (to-col)
  10742. "Align tags on the current headline to TO-COL.
  10743. Assume point is on a headline. Preserve point when aligning
  10744. tags."
  10745. (when (org-match-line org-tag-line-re)
  10746. (let* ((tags-start (match-beginning 1))
  10747. (blank-start (save-excursion
  10748. (goto-char tags-start)
  10749. (skip-chars-backward " \t")
  10750. (point)))
  10751. (new (max (if (>= to-col 0) to-col
  10752. (- (abs to-col) (string-width (match-string 1))))
  10753. ;; Introduce at least one space after the heading
  10754. ;; or the stars.
  10755. (save-excursion
  10756. (goto-char blank-start)
  10757. (1+ (current-column)))))
  10758. (current
  10759. (save-excursion (goto-char tags-start) (current-column)))
  10760. (origin (point-marker))
  10761. (column (current-column))
  10762. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10763. (when (/= new current)
  10764. (delete-region blank-start tags-start)
  10765. (goto-char blank-start)
  10766. (let ((indent-tabs-mode nil)) (indent-to new))
  10767. ;; Try to move back to original position. If point was in the
  10768. ;; blanks before the tags, ORIGIN marker is of no use because
  10769. ;; it now points to BLANK-START. Use COLUMN instead.
  10770. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10771. (defun org-set-tags-command (&optional arg)
  10772. "Set the tags for the current visible entry.
  10773. When called with `\\[universal-argument]' prefix argument ARG, \
  10774. realign all tags
  10775. in the current buffer.
  10776. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10777. unconditionally do not
  10778. offer the fast tag selection interface.
  10779. If a region is active, set tags in the region according to the
  10780. setting of `org-loop-over-headlines-in-active-region'.
  10781. This function is for interactive use only;
  10782. in Lisp code use `org-set-tags' instead."
  10783. (interactive "P")
  10784. (let ((org-use-fast-tag-selection
  10785. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10786. (cond
  10787. ((equal '(4) arg) (org-align-tags t))
  10788. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10789. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10790. (org-map-entries
  10791. #'org-set-tags-command
  10792. nil
  10793. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10794. 'region-start-level
  10795. 'region)
  10796. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10797. (t
  10798. (save-excursion
  10799. (org-back-to-heading)
  10800. (let* ((all-tags (org-get-tags))
  10801. (table (setq org-last-tags-completion-table
  10802. (org--tag-add-to-alist
  10803. (and org-complete-tags-always-offer-all-agenda-tags
  10804. (org-global-tags-completion-table
  10805. (org-agenda-files)))
  10806. (or org-current-tag-alist (org-get-buffer-tags)))))
  10807. (current-tags
  10808. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10809. all-tags))
  10810. (inherited-tags
  10811. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10812. all-tags))
  10813. (tags
  10814. (replace-regexp-in-string
  10815. ;; Ignore all forbidden characters in tags.
  10816. "[^[:alnum:]_@#%]+" ":"
  10817. (if (or (eq t org-use-fast-tag-selection)
  10818. (and org-use-fast-tag-selection
  10819. (delq nil (mapcar #'cdr table))))
  10820. (org-fast-tag-selection
  10821. current-tags
  10822. inherited-tags
  10823. table
  10824. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10825. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10826. (org-trim (completing-read
  10827. "Tags: "
  10828. #'org-tags-completion-function
  10829. nil nil (org-make-tag-string current-tags)
  10830. 'org-tags-history)))))))
  10831. (org-set-tags tags)))))
  10832. ;; `save-excursion' may not replace the point at the right
  10833. ;; position.
  10834. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10835. (looking-at-p " "))
  10836. (forward-char))))
  10837. (defun org-align-tags (&optional all)
  10838. "Align tags in current entry.
  10839. When optional argument ALL is non-nil, align all tags in the
  10840. visible part of the buffer."
  10841. (let ((get-indent-column
  10842. (lambda ()
  10843. (let ((offset (if (bound-and-true-p org-indent-mode)
  10844. (* (1- org-indent-indentation-per-level)
  10845. (1- (org-current-level)))
  10846. 0)))
  10847. (+ org-tags-column
  10848. (if (> org-tags-column 0) (- offset) offset))))))
  10849. (if (and (not all) (org-at-heading-p))
  10850. (org--align-tags-here (funcall get-indent-column))
  10851. (save-excursion
  10852. (if all
  10853. (progn
  10854. (goto-char (point-min))
  10855. (while (re-search-forward org-tag-line-re nil t)
  10856. (org--align-tags-here (funcall get-indent-column))))
  10857. (org-back-to-heading t)
  10858. (org--align-tags-here (funcall get-indent-column)))))))
  10859. (defun org-set-tags (tags)
  10860. "Set the tags of the current entry to TAGS, replacing current tags.
  10861. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10862. If TAGS is nil or the empty string, all tags are removed.
  10863. This function assumes point is on a headline."
  10864. (org-with-wide-buffer
  10865. (let ((tags (pcase tags
  10866. ((pred listp) tags)
  10867. ((pred stringp) (split-string (org-trim tags) ":" t))
  10868. (_ (error "Invalid tag specification: %S" tags))))
  10869. (old-tags (org-get-tags nil t))
  10870. (tags-change? nil))
  10871. (when (functionp org-tags-sort-function)
  10872. (setq tags (sort tags org-tags-sort-function)))
  10873. (setq tags-change? (not (equal tags old-tags)))
  10874. (when tags-change?
  10875. ;; Delete previous tags and any trailing white space.
  10876. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10877. (line-end-position)))
  10878. (skip-chars-backward " \t")
  10879. (delete-region (point) (line-end-position))
  10880. ;; Deleting white spaces may break an otherwise empty headline.
  10881. ;; Re-introduce one space in this case.
  10882. (unless (org-at-heading-p) (insert " "))
  10883. (when tags
  10884. (save-excursion (insert " " (org-make-tag-string tags)))
  10885. ;; When text is being inserted on an invisible region
  10886. ;; boundary, it can be inadvertently sucked into
  10887. ;; invisibility.
  10888. (unless (org-invisible-p (line-beginning-position))
  10889. (org-flag-region (point) (line-end-position) nil 'outline))))
  10890. ;; Align tags, if any.
  10891. (when tags (org-align-tags))
  10892. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10893. (defun org-change-tag-in-region (beg end tag off)
  10894. "Add or remove TAG for each entry in the region.
  10895. This works in the agenda, and also in an Org buffer."
  10896. (interactive
  10897. (list (region-beginning) (region-end)
  10898. (let ((org-last-tags-completion-table
  10899. (if (derived-mode-p 'org-mode)
  10900. (org--tag-add-to-alist
  10901. (org-get-buffer-tags)
  10902. (org-global-tags-completion-table))
  10903. (org-global-tags-completion-table))))
  10904. (completing-read
  10905. "Tag: " 'org-tags-completion-function nil nil nil
  10906. 'org-tags-history))
  10907. (progn
  10908. (message "[s]et or [r]emove? ")
  10909. (equal (read-char-exclusive) ?r))))
  10910. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10911. (let ((agendap (equal major-mode 'org-agenda-mode))
  10912. l1 l2 m buf pos newhead (cnt 0))
  10913. (goto-char end)
  10914. (setq l2 (1- (org-current-line)))
  10915. (goto-char beg)
  10916. (setq l1 (org-current-line))
  10917. (cl-loop for l from l1 to l2 do
  10918. (org-goto-line l)
  10919. (setq m (get-text-property (point) 'org-hd-marker))
  10920. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10921. (and agendap m))
  10922. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10923. pos (if agendap m (point)))
  10924. (with-current-buffer buf
  10925. (save-excursion
  10926. (save-restriction
  10927. (goto-char pos)
  10928. (setq cnt (1+ cnt))
  10929. (org-toggle-tag tag (if off 'off 'on))
  10930. (setq newhead (org-get-heading)))))
  10931. (and agendap (org-agenda-change-all-lines newhead m))))
  10932. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10933. (defun org-tags-completion-function (string _predicate &optional flag)
  10934. "Complete tag STRING.
  10935. FLAG specifies the type of completion operation to perform. This
  10936. function is passed as a collection function to `completing-read',
  10937. which see."
  10938. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10939. (confirm (lambda (x) (stringp (car x))))
  10940. (prefix ""))
  10941. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10942. (setq prefix (match-string 1 string))
  10943. (setq string (match-string 2 string)))
  10944. (pcase flag
  10945. (`t (all-completions string org-last-tags-completion-table confirm))
  10946. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10947. (`nil
  10948. (pcase (try-completion string org-last-tags-completion-table confirm)
  10949. ((and completion (pred stringp))
  10950. (concat prefix
  10951. completion
  10952. (if (and org-add-colon-after-tag-completion
  10953. (assoc completion org-last-tags-completion-table))
  10954. ":"
  10955. "")))
  10956. (completion completion)))
  10957. (_ nil))))
  10958. (defun org-fast-tag-insert (kwd tags face &optional end)
  10959. "Insert KWD, and the TAGS, the latter with face FACE.
  10960. Also insert END."
  10961. (insert (format "%-12s" (concat kwd ":"))
  10962. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10963. (or end "")))
  10964. (defun org-fast-tag-show-exit (flag)
  10965. (save-excursion
  10966. (org-goto-line 3)
  10967. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10968. (replace-match ""))
  10969. (when flag
  10970. (end-of-line 1)
  10971. (org-move-to-column (- (window-width) 19) t)
  10972. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10973. (defun org-set-current-tags-overlay (current prefix)
  10974. "Add an overlay to CURRENT tag with PREFIX."
  10975. (let ((s (org-make-tag-string current)))
  10976. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10977. (org-overlay-display org-tags-overlay (concat prefix s))))
  10978. (defvar org-last-tag-selection-key nil)
  10979. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10980. "Fast tag selection with single keys.
  10981. CURRENT is the current list of tags in the headline, INHERITED is the
  10982. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10983. possibly with grouping information. TODO-TABLE is a similar table with
  10984. TODO keywords, should these have keys assigned to them.
  10985. If the keys are nil, a-z are automatically assigned.
  10986. Returns the new tags string, or nil to not change the current settings."
  10987. (let* ((fulltable (append table todo-table))
  10988. (maxlen (if (null fulltable) 0
  10989. (apply #'max
  10990. (mapcar (lambda (x)
  10991. (if (stringp (car x)) (string-width (car x))
  10992. 0))
  10993. fulltable))))
  10994. (buf (current-buffer))
  10995. (expert (eq org-fast-tag-selection-single-key 'expert))
  10996. (buffer-tags nil)
  10997. (fwidth (+ maxlen 3 1 3))
  10998. (ncol (/ (- (window-width) 4) fwidth))
  10999. (i-face 'org-done)
  11000. (c-face 'org-todo)
  11001. tg cnt e c char c1 c2 ntable tbl rtn
  11002. ov-start ov-end ov-prefix
  11003. (exit-after-next org-fast-tag-selection-single-key)
  11004. (done-keywords org-done-keywords)
  11005. groups ingroup intaggroup)
  11006. (save-excursion
  11007. (beginning-of-line)
  11008. (if (looking-at org-tag-line-re)
  11009. (setq ov-start (match-beginning 1)
  11010. ov-end (match-end 1)
  11011. ov-prefix "")
  11012. (setq ov-start (1- (point-at-eol))
  11013. ov-end (1+ ov-start))
  11014. (skip-chars-forward "^\n\r")
  11015. (setq ov-prefix
  11016. (concat
  11017. (buffer-substring (1- (point)) (point))
  11018. (if (> (current-column) org-tags-column)
  11019. " "
  11020. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11021. (move-overlay org-tags-overlay ov-start ov-end)
  11022. (save-excursion
  11023. (save-window-excursion
  11024. (if expert
  11025. (set-buffer (get-buffer-create " *Org tags*"))
  11026. (delete-other-windows)
  11027. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11028. (org-switch-to-buffer-other-window " *Org tags*"))
  11029. (erase-buffer)
  11030. (setq-local org-done-keywords done-keywords)
  11031. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11032. (org-fast-tag-insert "Current" current c-face "\n\n")
  11033. (org-fast-tag-show-exit exit-after-next)
  11034. (org-set-current-tags-overlay current ov-prefix)
  11035. (setq tbl fulltable char ?a cnt 0)
  11036. (while (setq e (pop tbl))
  11037. (cond
  11038. ((eq (car e) :startgroup)
  11039. (push '() groups) (setq ingroup t)
  11040. (unless (zerop cnt)
  11041. (setq cnt 0)
  11042. (insert "\n"))
  11043. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11044. ((eq (car e) :endgroup)
  11045. (setq ingroup nil cnt 0)
  11046. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11047. ((eq (car e) :startgrouptag)
  11048. (setq intaggroup t)
  11049. (unless (zerop cnt)
  11050. (setq cnt 0)
  11051. (insert "\n"))
  11052. (insert "[ "))
  11053. ((eq (car e) :endgrouptag)
  11054. (setq intaggroup nil cnt 0)
  11055. (insert "]\n"))
  11056. ((equal e '(:newline))
  11057. (unless (zerop cnt)
  11058. (setq cnt 0)
  11059. (insert "\n")
  11060. (setq e (car tbl))
  11061. (while (equal (car tbl) '(:newline))
  11062. (insert "\n")
  11063. (setq tbl (cdr tbl)))))
  11064. ((equal e '(:grouptags)) (insert " : "))
  11065. (t
  11066. (setq tg (copy-sequence (car e)) c2 nil)
  11067. (if (cdr e)
  11068. (setq c (cdr e))
  11069. ;; automatically assign a character.
  11070. (setq c1 (string-to-char
  11071. (downcase (substring
  11072. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11073. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11074. (while (or (rassoc char ntable) (rassoc char table))
  11075. (setq char (1+ char)))
  11076. (setq c2 c1))
  11077. (setq c (or c2 char)))
  11078. (when ingroup (push tg (car groups)))
  11079. (setq tg (org-add-props tg nil 'face
  11080. (cond
  11081. ((not (assoc tg table))
  11082. (org-get-todo-face tg))
  11083. ((member tg current) c-face)
  11084. ((member tg inherited) i-face))))
  11085. (when (equal (caar tbl) :grouptags)
  11086. (org-add-props tg nil 'face 'org-tag-group))
  11087. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11088. (insert "[" c "] " tg (make-string
  11089. (- fwidth 4 (length tg)) ?\ ))
  11090. (push (cons tg c) ntable)
  11091. (when (= (cl-incf cnt) ncol)
  11092. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11093. (insert "\n")
  11094. (when (or ingroup intaggroup) (insert " ")))
  11095. (setq cnt 0)))))
  11096. (setq ntable (nreverse ntable))
  11097. (insert "\n")
  11098. (goto-char (point-min))
  11099. (unless expert (org-fit-window-to-buffer))
  11100. (setq rtn
  11101. (catch 'exit
  11102. (while t
  11103. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11104. (if (not groups) "no " "")
  11105. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11106. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11107. (setq org-last-tag-selection-key c)
  11108. (cond
  11109. ((= c ?\r) (throw 'exit t))
  11110. ((= c ?!)
  11111. (setq groups (not groups))
  11112. (goto-char (point-min))
  11113. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11114. ((= c ?\C-c)
  11115. (if (not expert)
  11116. (org-fast-tag-show-exit
  11117. (setq exit-after-next (not exit-after-next)))
  11118. (setq expert nil)
  11119. (delete-other-windows)
  11120. (set-window-buffer (split-window-vertically) " *Org tags*")
  11121. (org-switch-to-buffer-other-window " *Org tags*")
  11122. (org-fit-window-to-buffer)))
  11123. ((or (= c ?\C-g)
  11124. (and (= c ?q) (not (rassoc c ntable))))
  11125. (delete-overlay org-tags-overlay)
  11126. (setq quit-flag t))
  11127. ((= c ?\ )
  11128. (setq current nil)
  11129. (when exit-after-next (setq exit-after-next 'now)))
  11130. ((= c ?\t)
  11131. (condition-case nil
  11132. (setq tg (completing-read
  11133. "Tag: "
  11134. (or buffer-tags
  11135. (with-current-buffer buf
  11136. (setq buffer-tags
  11137. (org-get-buffer-tags))))))
  11138. (quit (setq tg "")))
  11139. (when (string-match "\\S-" tg)
  11140. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11141. (if (member tg current)
  11142. (setq current (delete tg current))
  11143. (push tg current)))
  11144. (when exit-after-next (setq exit-after-next 'now)))
  11145. ((setq e (rassoc c todo-table) tg (car e))
  11146. (with-current-buffer buf
  11147. (save-excursion (org-todo tg)))
  11148. (when exit-after-next (setq exit-after-next 'now)))
  11149. ((setq e (rassoc c ntable) tg (car e))
  11150. (if (member tg current)
  11151. (setq current (delete tg current))
  11152. (cl-loop for g in groups do
  11153. (when (member tg g)
  11154. (dolist (x g) (setq current (delete x current)))))
  11155. (push tg current))
  11156. (when exit-after-next (setq exit-after-next 'now))))
  11157. ;; Create a sorted list
  11158. (setq current
  11159. (sort current
  11160. (lambda (a b)
  11161. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11162. (when (eq exit-after-next 'now) (throw 'exit t))
  11163. (goto-char (point-min))
  11164. (beginning-of-line 2)
  11165. (delete-region (point) (point-at-eol))
  11166. (org-fast-tag-insert "Current" current c-face)
  11167. (org-set-current-tags-overlay current ov-prefix)
  11168. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11169. (while (re-search-forward tag-re nil t)
  11170. (let ((tag (match-string 1)))
  11171. (add-text-properties
  11172. (match-beginning 1) (match-end 1)
  11173. (list 'face
  11174. (cond
  11175. ((member tag current) c-face)
  11176. ((member tag inherited) i-face)
  11177. (t (get-text-property (match-beginning 1) '
  11178. face))))))))
  11179. (goto-char (point-min)))))
  11180. (delete-overlay org-tags-overlay)
  11181. (if rtn
  11182. (mapconcat 'identity current ":")
  11183. nil)))))
  11184. (defun org-make-tag-string (tags)
  11185. "Return string associated to TAGS.
  11186. TAGS is a list of strings."
  11187. (if (null tags) ""
  11188. (format ":%s:" (mapconcat #'identity tags ":"))))
  11189. (defun org--get-local-tags ()
  11190. "Return list of tags for the current headline.
  11191. Assume point is at the beginning of the headline."
  11192. (and (looking-at org-tag-line-re)
  11193. (split-string (match-string-no-properties 2) ":" t)))
  11194. (defun org-get-tags (&optional pos local)
  11195. "Get the list of tags specified in the current headline.
  11196. When argument POS is non-nil, retrieve tags for headline at POS.
  11197. According to `org-use-tag-inheritance', tags may be inherited
  11198. from parent headlines, and from the whole document, through
  11199. `org-file-tags'. In this case, the returned list of tags
  11200. contains tags in this order: file tags, tags inherited from
  11201. parent headlines, local tags. If a tag appears multiple times,
  11202. only the most local tag is returned.
  11203. However, when optional argument LOCAL is non-nil, only return
  11204. tags specified at the headline.
  11205. Inherited tags have the `inherited' text property."
  11206. (if (and org-trust-scanner-tags
  11207. (or (not pos) (eq pos (point)))
  11208. (not local))
  11209. org-scanner-tags
  11210. (org-with-point-at (or pos (point))
  11211. (unless (org-before-first-heading-p)
  11212. (org-back-to-heading t)
  11213. (let ((ltags (org--get-local-tags)) itags)
  11214. (if (or local (not org-use-tag-inheritance)) ltags
  11215. (while (org-up-heading-safe)
  11216. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11217. (org--get-local-tags))
  11218. itags)))
  11219. (setq itags (append org-file-tags itags))
  11220. (nreverse
  11221. (delete-dups
  11222. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11223. (defun org-get-buffer-tags ()
  11224. "Get a table of all tags used in the buffer, for completion."
  11225. (org-with-point-at 1
  11226. (let (tags)
  11227. (while (re-search-forward org-tag-line-re nil t)
  11228. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11229. tags)))
  11230. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11231. ;;;; The mapping API
  11232. (defvar org-agenda-skip-comment-trees)
  11233. (defvar org-agenda-skip-function)
  11234. (defun org-map-entries (func &optional match scope &rest skip)
  11235. "Call FUNC at each headline selected by MATCH in SCOPE.
  11236. FUNC is a function or a lisp form. The function will be called without
  11237. arguments, with the cursor positioned at the beginning of the headline.
  11238. The return values of all calls to the function will be collected and
  11239. returned as a list.
  11240. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11241. does not need to preserve point. After evaluation, the cursor will be
  11242. moved to the end of the line (presumably of the headline of the
  11243. processed entry) and search continues from there. Under some
  11244. circumstances, this may not produce the wanted results. For example,
  11245. if you have removed (e.g. archived) the current (sub)tree it could
  11246. mean that the next entry will be skipped entirely. In such cases, you
  11247. can specify the position from where search should continue by making
  11248. FUNC set the variable `org-map-continue-from' to the desired buffer
  11249. position.
  11250. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11251. Only headlines that are matched by this query will be considered during
  11252. the iteration. When MATCH is nil or t, all headlines will be
  11253. visited by the iteration.
  11254. SCOPE determines the scope of this command. It can be any of:
  11255. nil The current buffer, respecting the restriction if any
  11256. tree The subtree started with the entry at point
  11257. region The entries within the active region, if any
  11258. region-start-level
  11259. The entries within the active region, but only those at
  11260. the same level than the first one.
  11261. file The current buffer, without restriction
  11262. file-with-archives
  11263. The current buffer, and any archives associated with it
  11264. agenda All agenda files
  11265. agenda-with-archives
  11266. All agenda files with any archive files associated with them
  11267. \(file1 file2 ...)
  11268. If this is a list, all files in the list will be scanned
  11269. The remaining args are treated as settings for the skipping facilities of
  11270. the scanner. The following items can be given here:
  11271. archive skip trees with the archive tag
  11272. comment skip trees with the COMMENT keyword
  11273. function or Emacs Lisp form:
  11274. will be used as value for `org-agenda-skip-function', so
  11275. whenever the function returns a position, FUNC will not be
  11276. called for that entry and search will continue from the
  11277. position returned
  11278. If your function needs to retrieve the tags including inherited tags
  11279. at the *current* entry, you can use the value of the variable
  11280. `org-scanner-tags' which will be much faster than getting the value
  11281. with `org-get-tags'. If your function gets properties with
  11282. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11283. to t around the call to `org-entry-properties' to get the same speedup.
  11284. Note that if your function moves around to retrieve tags and properties at
  11285. a *different* entry, you cannot use these techniques."
  11286. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11287. (not (org-region-active-p)))
  11288. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11289. (org-agenda-skip-archived-trees (memq 'archive skip))
  11290. (org-agenda-skip-comment-trees (memq 'comment skip))
  11291. (org-agenda-skip-function
  11292. (car (org-delete-all '(comment archive) skip)))
  11293. (org-tags-match-list-sublevels t)
  11294. (start-level (eq scope 'region-start-level))
  11295. matcher res
  11296. org-todo-keywords-for-agenda
  11297. org-done-keywords-for-agenda
  11298. org-todo-keyword-alist-for-agenda
  11299. org-tag-alist-for-agenda
  11300. org--matcher-tags-todo-only)
  11301. (cond
  11302. ((eq match t) (setq matcher t))
  11303. ((eq match nil) (setq matcher t))
  11304. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11305. (save-excursion
  11306. (save-restriction
  11307. (cond ((eq scope 'tree)
  11308. (org-back-to-heading t)
  11309. (org-narrow-to-subtree)
  11310. (setq scope nil))
  11311. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11312. (org-region-active-p))
  11313. ;; If needed, set start-level to a string like "2"
  11314. (when start-level
  11315. (save-excursion
  11316. (goto-char (region-beginning))
  11317. (unless (org-at-heading-p) (outline-next-heading))
  11318. (setq start-level (org-current-level))))
  11319. (narrow-to-region (region-beginning)
  11320. (save-excursion
  11321. (goto-char (region-end))
  11322. (unless (and (bolp) (org-at-heading-p))
  11323. (outline-next-heading))
  11324. (point)))
  11325. (setq scope nil)))
  11326. (if (not scope)
  11327. (progn
  11328. (org-agenda-prepare-buffers
  11329. (and buffer-file-name (list buffer-file-name)))
  11330. (setq res
  11331. (org-scan-tags
  11332. func matcher org--matcher-tags-todo-only start-level)))
  11333. ;; Get the right scope
  11334. (cond
  11335. ((and scope (listp scope) (symbolp (car scope)))
  11336. (setq scope (eval scope)))
  11337. ((eq scope 'agenda)
  11338. (setq scope (org-agenda-files t)))
  11339. ((eq scope 'agenda-with-archives)
  11340. (setq scope (org-agenda-files t))
  11341. (setq scope (org-add-archive-files scope)))
  11342. ((eq scope 'file)
  11343. (setq scope (and buffer-file-name (list buffer-file-name))))
  11344. ((eq scope 'file-with-archives)
  11345. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11346. (org-agenda-prepare-buffers scope)
  11347. (dolist (file scope)
  11348. (with-current-buffer (org-find-base-buffer-visiting file)
  11349. (org-with-wide-buffer
  11350. (goto-char (point-min))
  11351. (setq res
  11352. (append
  11353. res
  11354. (org-scan-tags
  11355. func matcher org--matcher-tags-todo-only)))))))))
  11356. res)))
  11357. ;;; Properties API
  11358. (defconst org-special-properties
  11359. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11360. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11361. "The special properties valid in Org mode.
  11362. These are properties that are not defined in the property drawer,
  11363. but in some other way.")
  11364. (defconst org-default-properties
  11365. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11366. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11367. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11368. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11369. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11370. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11371. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11372. "Some properties that are used by Org mode for various purposes.
  11373. Being in this list makes sure that they are offered for completion.")
  11374. (defun org--valid-property-p (property)
  11375. "Non-nil when string PROPERTY is a valid property name."
  11376. (not
  11377. (or (equal property "")
  11378. (string-match-p "\\s-" property))))
  11379. (defun org--update-property-plist (key val props)
  11380. "Associate KEY to VAL in alist PROPS.
  11381. Modifications are made by side-effect. Return new alist."
  11382. (let* ((appending (string= (substring key -1) "+"))
  11383. (key (if appending (substring key 0 -1) key))
  11384. (old (assoc-string key props t)))
  11385. (if (not old) (cons (cons key val) props)
  11386. (setcdr old (if appending (concat (cdr old) " " val) val))
  11387. props)))
  11388. (defun org-get-property-block (&optional beg force)
  11389. "Return the (beg . end) range of the body of the property drawer.
  11390. BEG is the beginning of the current subtree or the beginning of
  11391. the document if before the first headline. If it is not given,
  11392. it will be found. If the drawer does not exist, create it if
  11393. FORCE is non-nil, or return nil."
  11394. (org-with-wide-buffer
  11395. (let ((beg (cond (beg (goto-char beg))
  11396. ((or (not (featurep 'org-inlinetask))
  11397. (org-inlinetask-in-task-p))
  11398. (org-back-to-heading-or-point-min t) (point))
  11399. (t (org-with-limited-levels
  11400. (org-back-to-heading-or-point-min t))
  11401. (point)))))
  11402. ;; Move point to its position according to its positional rules.
  11403. (cond ((org-before-first-heading-p)
  11404. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11405. (t (forward-line)
  11406. (when (looking-at-p org-planning-line-re) (forward-line))))
  11407. (cond ((looking-at org-property-drawer-re)
  11408. (forward-line)
  11409. (cons (point) (progn (goto-char (match-end 0))
  11410. (line-beginning-position))))
  11411. (force
  11412. (goto-char beg)
  11413. (org-insert-property-drawer)
  11414. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11415. (line-beginning-position))))
  11416. (cons pos pos)))))))
  11417. (defun org-at-property-drawer-p ()
  11418. "Non-nil when point is at the first line of a property drawer."
  11419. (org-with-wide-buffer
  11420. (beginning-of-line)
  11421. (and (looking-at org-property-drawer-re)
  11422. (or (bobp)
  11423. (progn
  11424. (forward-line -1)
  11425. (cond ((org-at-heading-p))
  11426. ((looking-at org-planning-line-re)
  11427. (forward-line -1)
  11428. (org-at-heading-p))
  11429. ((looking-at org-comment-regexp)
  11430. (forward-line -1)
  11431. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11432. (forward-line -1))
  11433. (looking-at org-comment-regexp))
  11434. (t nil)))))))
  11435. (defun org-at-property-p ()
  11436. "Non-nil when point is inside a property drawer.
  11437. See `org-property-re' for match data, if applicable."
  11438. (save-excursion
  11439. (beginning-of-line)
  11440. (and (looking-at org-property-re)
  11441. (let ((property-drawer (save-match-data (org-get-property-block))))
  11442. (and property-drawer
  11443. (>= (point) (car property-drawer))
  11444. (< (point) (cdr property-drawer)))))))
  11445. (defun org-property-action ()
  11446. "Do an action on properties."
  11447. (interactive)
  11448. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11449. (let ((c (read-char-exclusive)))
  11450. (cl-case c
  11451. (?s (call-interactively #'org-set-property))
  11452. (?d (call-interactively #'org-delete-property))
  11453. (?D (call-interactively #'org-delete-property-globally))
  11454. (?c (call-interactively #'org-compute-property-at-point))
  11455. (otherwise (user-error "No such property action %c" c)))))
  11456. (defun org-inc-effort ()
  11457. "Increment the value of the effort property in the current entry."
  11458. (interactive)
  11459. (org-set-effort t))
  11460. (defvar org-clock-effort) ; Defined in org-clock.el.
  11461. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11462. (defun org-set-effort (&optional increment value)
  11463. "Set the effort property of the current entry.
  11464. If INCREMENT is non-nil, set the property to the next allowed
  11465. value. Otherwise, if optional argument VALUE is provided, use
  11466. it. Eventually, prompt for the new value if none of the previous
  11467. variables is set."
  11468. (interactive "P")
  11469. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11470. (current (org-entry-get nil org-effort-property))
  11471. (value
  11472. (cond
  11473. (increment
  11474. (unless allowed (user-error "Allowed effort values are not set"))
  11475. (or (cl-caadr (member (list current) allowed))
  11476. (user-error "Unknown value %S among allowed values" current)))
  11477. (value
  11478. (if (stringp value) value
  11479. (error "Invalid effort value: %S" value)))
  11480. (t
  11481. (let ((must-match
  11482. (and allowed
  11483. (not (get-text-property 0 'org-unrestricted
  11484. (caar allowed))))))
  11485. (completing-read "Effort: " allowed nil must-match))))))
  11486. ;; Test whether the value can be interpreted as a duration before
  11487. ;; inserting it in the buffer:
  11488. (org-duration-to-minutes value)
  11489. ;; Maybe update the effort value:
  11490. (unless (equal current value)
  11491. (org-entry-put nil org-effort-property value))
  11492. (org-refresh-property '((effort . identity)
  11493. (effort-minutes . org-duration-to-minutes))
  11494. value)
  11495. (when (equal (org-get-heading t t t t)
  11496. (bound-and-true-p org-clock-current-task))
  11497. (setq org-clock-effort value)
  11498. (org-clock-update-mode-line))
  11499. (message "%s is now %s" org-effort-property value)))
  11500. (defun org-entry-properties (&optional pom which)
  11501. "Get all properties of the current entry.
  11502. When POM is a buffer position, get all properties from the entry
  11503. there instead.
  11504. This includes the TODO keyword, the tags, time strings for
  11505. deadline, scheduled, and clocking, and any additional properties
  11506. defined in the entry.
  11507. If WHICH is nil or `all', get all properties. If WHICH is
  11508. `special' or `standard', only get that subclass. If WHICH is
  11509. a string, only get that property.
  11510. Return value is an alist. Keys are properties, as upcased
  11511. strings."
  11512. (org-with-point-at pom
  11513. (when (and (derived-mode-p 'org-mode)
  11514. (org-back-to-heading-or-point-min t))
  11515. (catch 'exit
  11516. (let* ((beg (point))
  11517. (specific (and (stringp which) (upcase which)))
  11518. (which (cond ((not specific) which)
  11519. ((member specific org-special-properties) 'special)
  11520. (t 'standard)))
  11521. props)
  11522. ;; Get the special properties, like TODO and TAGS.
  11523. (when (memq which '(nil all special))
  11524. (when (or (not specific) (string= specific "CLOCKSUM"))
  11525. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11526. (when clocksum
  11527. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11528. props)))
  11529. (when specific (throw 'exit props)))
  11530. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11531. (let ((clocksumt (get-text-property (point)
  11532. :org-clock-minutes-today)))
  11533. (when clocksumt
  11534. (push (cons "CLOCKSUM_T"
  11535. (org-duration-from-minutes clocksumt))
  11536. props)))
  11537. (when specific (throw 'exit props)))
  11538. (when (or (not specific) (string= specific "ITEM"))
  11539. (let ((case-fold-search nil))
  11540. (when (looking-at org-complex-heading-regexp)
  11541. (push (cons "ITEM"
  11542. (let ((title (match-string-no-properties 4)))
  11543. (if (org-string-nw-p title)
  11544. (org-remove-tabs title)
  11545. "")))
  11546. props)))
  11547. (when specific (throw 'exit props)))
  11548. (when (or (not specific) (string= specific "TODO"))
  11549. (let ((case-fold-search nil))
  11550. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11551. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11552. (when specific (throw 'exit props)))
  11553. (when (or (not specific) (string= specific "PRIORITY"))
  11554. (push (cons "PRIORITY"
  11555. (if (looking-at org-priority-regexp)
  11556. (match-string-no-properties 2)
  11557. (char-to-string org-priority-default)))
  11558. props)
  11559. (when specific (throw 'exit props)))
  11560. (when (or (not specific) (string= specific "FILE"))
  11561. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11562. props)
  11563. (when specific (throw 'exit props)))
  11564. (when (or (not specific) (string= specific "TAGS"))
  11565. (let ((tags (org-get-tags nil t)))
  11566. (when tags
  11567. (push (cons "TAGS" (org-make-tag-string tags))
  11568. props)))
  11569. (when specific (throw 'exit props)))
  11570. (when (or (not specific) (string= specific "ALLTAGS"))
  11571. (let ((tags (org-get-tags)))
  11572. (when tags
  11573. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11574. props)))
  11575. (when specific (throw 'exit props)))
  11576. (when (or (not specific) (string= specific "BLOCKED"))
  11577. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11578. (when specific (throw 'exit props)))
  11579. (when (or (not specific)
  11580. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11581. (forward-line)
  11582. (when (looking-at-p org-planning-line-re)
  11583. (end-of-line)
  11584. (let ((bol (line-beginning-position))
  11585. ;; Backward compatibility: time keywords used to
  11586. ;; be configurable (before 8.3). Make sure we
  11587. ;; get the correct keyword.
  11588. (key-assoc `(("CLOSED" . ,org-closed-string)
  11589. ("DEADLINE" . ,org-deadline-string)
  11590. ("SCHEDULED" . ,org-scheduled-string))))
  11591. (dolist (pair (if specific (list (assoc specific key-assoc))
  11592. key-assoc))
  11593. (save-excursion
  11594. (when (search-backward (cdr pair) bol t)
  11595. (goto-char (match-end 0))
  11596. (skip-chars-forward " \t")
  11597. (and (looking-at org-ts-regexp-both)
  11598. (push (cons (car pair)
  11599. (match-string-no-properties 0))
  11600. props)))))))
  11601. (when specific (throw 'exit props)))
  11602. (when (or (not specific)
  11603. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11604. (let ((find-ts
  11605. (lambda (end ts)
  11606. ;; Fix next time-stamp before END. TS is the
  11607. ;; list of time-stamps found so far.
  11608. (let ((ts ts)
  11609. (regexp (cond
  11610. ((string= specific "TIMESTAMP")
  11611. org-ts-regexp)
  11612. ((string= specific "TIMESTAMP_IA")
  11613. org-ts-regexp-inactive)
  11614. ((assoc "TIMESTAMP_IA" ts)
  11615. org-ts-regexp)
  11616. ((assoc "TIMESTAMP" ts)
  11617. org-ts-regexp-inactive)
  11618. (t org-ts-regexp-both))))
  11619. (catch 'next
  11620. (while (re-search-forward regexp end t)
  11621. (backward-char)
  11622. (let ((object (org-element-context)))
  11623. ;; Accept to match timestamps in node
  11624. ;; properties, too.
  11625. (when (memq (org-element-type object)
  11626. '(node-property timestamp))
  11627. (let ((type
  11628. (org-element-property :type object)))
  11629. (cond
  11630. ((and (memq type '(active active-range))
  11631. (not (equal specific "TIMESTAMP_IA")))
  11632. (unless (assoc "TIMESTAMP" ts)
  11633. (push (cons "TIMESTAMP"
  11634. (org-element-property
  11635. :raw-value object))
  11636. ts)
  11637. (when specific (throw 'exit ts))))
  11638. ((and (memq type '(inactive inactive-range))
  11639. (not (string= specific "TIMESTAMP")))
  11640. (unless (assoc "TIMESTAMP_IA" ts)
  11641. (push (cons "TIMESTAMP_IA"
  11642. (org-element-property
  11643. :raw-value object))
  11644. ts)
  11645. (when specific (throw 'exit ts))))))
  11646. ;; Both timestamp types are found,
  11647. ;; move to next part.
  11648. (when (= (length ts) 2) (throw 'next ts)))))
  11649. ts)))))
  11650. (goto-char beg)
  11651. ;; First look for timestamps within headline.
  11652. (let ((ts (funcall find-ts (line-end-position) nil)))
  11653. (if (= (length ts) 2) (setq props (nconc ts props))
  11654. ;; Then find timestamps in the section, skipping
  11655. ;; planning line.
  11656. (let ((end (save-excursion (outline-next-heading))))
  11657. (forward-line)
  11658. (when (looking-at-p org-planning-line-re) (forward-line))
  11659. (setq props (nconc (funcall find-ts end ts) props))))))))
  11660. ;; Get the standard properties, like :PROP:.
  11661. (when (memq which '(nil all standard))
  11662. ;; If we are looking after a specific property, delegate
  11663. ;; to `org-entry-get', which is faster. However, make an
  11664. ;; exception for "CATEGORY", since it can be also set
  11665. ;; through keywords (i.e. #+CATEGORY).
  11666. (if (and specific (not (equal specific "CATEGORY")))
  11667. (let ((value (org-entry-get beg specific nil t)))
  11668. (throw 'exit (and value (list (cons specific value)))))
  11669. (let ((range (org-get-property-block beg)))
  11670. (when range
  11671. (let ((end (cdr range)) seen-base)
  11672. (goto-char (car range))
  11673. ;; Unlike to `org--update-property-plist', we
  11674. ;; handle the case where base values is found
  11675. ;; after its extension. We also forbid standard
  11676. ;; properties to be named as special properties.
  11677. (while (re-search-forward org-property-re end t)
  11678. (let* ((key (upcase (match-string-no-properties 2)))
  11679. (extendp (string-match-p "\\+\\'" key))
  11680. (key-base (if extendp (substring key 0 -1) key))
  11681. (value (match-string-no-properties 3)))
  11682. (cond
  11683. ((member-ignore-case key-base org-special-properties))
  11684. (extendp
  11685. (setq props
  11686. (org--update-property-plist key value props)))
  11687. ((member key seen-base))
  11688. (t (push key seen-base)
  11689. (let ((p (assoc-string key props t)))
  11690. (if p (setcdr p (concat value " " (cdr p)))
  11691. (push (cons key value) props))))))))))))
  11692. (unless (assoc "CATEGORY" props)
  11693. (push (cons "CATEGORY" (org-get-category beg)) props)
  11694. (when (string= specific "CATEGORY") (throw 'exit props)))
  11695. ;; Return value.
  11696. props)))))
  11697. (defun org--property-local-values (property literal-nil)
  11698. "Return value for PROPERTY in current entry.
  11699. Value is a list whose car is the base value for PROPERTY and cdr
  11700. a list of accumulated values. Return nil if neither is found in
  11701. the entry. Also return nil when PROPERTY is set to \"nil\",
  11702. unless LITERAL-NIL is non-nil."
  11703. (let ((range (org-get-property-block)))
  11704. (when range
  11705. (goto-char (car range))
  11706. (let* ((case-fold-search t)
  11707. (end (cdr range))
  11708. (value
  11709. ;; Base value.
  11710. (save-excursion
  11711. (let ((v (and (re-search-forward
  11712. (org-re-property property nil t) end t)
  11713. (match-string-no-properties 3))))
  11714. (list (if literal-nil v (org-not-nil v)))))))
  11715. ;; Find additional values.
  11716. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11717. (while (re-search-forward property+ end t)
  11718. (push (match-string-no-properties 3) value)))
  11719. ;; Return final values.
  11720. (and (not (equal value '(nil))) (nreverse value))))))
  11721. (defun org--property-global-or-keyword-value (property literal-nil)
  11722. "Return value for PROPERTY as defined by global properties or by keyword.
  11723. Return value is a string. Return nil if property is not set
  11724. globally or by keyword. Also return nil when PROPERTY is set to
  11725. \"nil\", unless LITERAL-NIL is non-nil."
  11726. (let ((global
  11727. (cdr (or (assoc-string property org-keyword-properties t)
  11728. (assoc-string property org-global-properties t)
  11729. (assoc-string property org-global-properties-fixed t)))))
  11730. (if literal-nil global (org-not-nil global))))
  11731. (defun org-entry-get (pom property &optional inherit literal-nil)
  11732. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11733. If INHERIT is non-nil and the entry does not have the property,
  11734. then also check higher levels of the hierarchy. If INHERIT is
  11735. the symbol `selective', use inheritance only if the setting in
  11736. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11737. If the property is present but empty, the return value is the
  11738. empty string. If the property is not present at all, nil is
  11739. returned. In any other case, return the value as a string.
  11740. Search is case-insensitive.
  11741. If LITERAL-NIL is set, return the string value \"nil\" as
  11742. a string, do not interpret it as the list atom nil. This is used
  11743. for inheritance when a \"nil\" value can supersede a non-nil
  11744. value higher up the hierarchy."
  11745. (org-with-point-at pom
  11746. (cond
  11747. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11748. ;; We need a special property. Use `org-entry-properties' to
  11749. ;; retrieve it, but specify the wanted property.
  11750. (cdr (assoc-string property (org-entry-properties nil property))))
  11751. ((and inherit
  11752. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11753. (org-entry-get-with-inheritance property literal-nil))
  11754. (t
  11755. (let* ((local (org--property-local-values property literal-nil))
  11756. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11757. (if literal-nil value (org-not-nil value)))))))
  11758. (defun org-property-or-variable-value (var &optional inherit)
  11759. "Check if there is a property fixing the value of VAR.
  11760. If yes, return this value. If not, return the current value of the variable."
  11761. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11762. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11763. (read prop)
  11764. (symbol-value var))))
  11765. (defun org-entry-delete (pom property)
  11766. "Delete PROPERTY from entry at point-or-marker POM.
  11767. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11768. non-nil when a property was removed."
  11769. (org-with-point-at pom
  11770. (pcase (org-get-property-block)
  11771. (`(,begin . ,origin)
  11772. (let* ((end (copy-marker origin))
  11773. (re (org-re-property
  11774. (concat (regexp-quote property) "\\+?") t t)))
  11775. (goto-char begin)
  11776. (while (re-search-forward re end t)
  11777. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11778. ;; If drawer is empty, remove it altogether.
  11779. (when (= begin end)
  11780. (delete-region (line-beginning-position 0)
  11781. (line-beginning-position 2)))
  11782. ;; Return non-nil if some property was removed.
  11783. (prog1 (/= end origin) (set-marker end nil))))
  11784. (_ nil))))
  11785. ;; Multi-values properties are properties that contain multiple values
  11786. ;; These values are assumed to be single words, separated by whitespace.
  11787. (defun org-entry-add-to-multivalued-property (pom property value)
  11788. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11789. (let* ((old (org-entry-get pom property))
  11790. (values (and old (split-string old))))
  11791. (setq value (org-entry-protect-space value))
  11792. (unless (member value values)
  11793. (setq values (append values (list value)))
  11794. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11795. (defun org-entry-remove-from-multivalued-property (pom property value)
  11796. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11797. (let* ((old (org-entry-get pom property))
  11798. (values (and old (split-string old))))
  11799. (setq value (org-entry-protect-space value))
  11800. (when (member value values)
  11801. (setq values (delete value values))
  11802. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11803. (defun org-entry-member-in-multivalued-property (pom property value)
  11804. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11805. (let* ((old (org-entry-get pom property))
  11806. (values (and old (split-string old))))
  11807. (setq value (org-entry-protect-space value))
  11808. (member value values)))
  11809. (defun org-entry-get-multivalued-property (pom property)
  11810. "Return a list of values in a multivalued property."
  11811. (let* ((value (org-entry-get pom property))
  11812. (values (and value (split-string value))))
  11813. (mapcar #'org-entry-restore-space values)))
  11814. (defun org-entry-put-multivalued-property (pom property &rest values)
  11815. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11816. VALUES should be a list of strings. Spaces will be protected."
  11817. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11818. (let* ((value (org-entry-get pom property))
  11819. (values (and value (split-string value))))
  11820. (mapcar #'org-entry-restore-space values)))
  11821. (defun org-entry-protect-space (s)
  11822. "Protect spaces and newline in string S."
  11823. (while (string-match " " s)
  11824. (setq s (replace-match "%20" t t s)))
  11825. (while (string-match "\n" s)
  11826. (setq s (replace-match "%0A" t t s)))
  11827. s)
  11828. (defun org-entry-restore-space (s)
  11829. "Restore spaces and newline in string S."
  11830. (while (string-match "%20" s)
  11831. (setq s (replace-match " " t t s)))
  11832. (while (string-match "%0A" s)
  11833. (setq s (replace-match "\n" t t s)))
  11834. s)
  11835. (defvar org-entry-property-inherited-from (make-marker)
  11836. "Marker pointing to the entry from where a property was inherited.
  11837. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11838. location of the entry where the inheritance search matched. If there was
  11839. no match, the marker will point nowhere.
  11840. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11841. is set.")
  11842. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11843. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11844. The search will stop at the first ancestor which has the property defined.
  11845. If the value found is \"nil\", return nil to show that the property
  11846. should be considered as undefined (this is the meaning of nil here).
  11847. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11848. (move-marker org-entry-property-inherited-from nil)
  11849. (org-with-wide-buffer
  11850. (let (value)
  11851. (catch 'exit
  11852. (while t
  11853. (let ((v (org--property-local-values property literal-nil)))
  11854. (when v
  11855. (setq value
  11856. (concat (mapconcat #'identity (delq nil v) " ")
  11857. (and value " ")
  11858. value)))
  11859. (cond
  11860. ((car v)
  11861. (org-back-to-heading-or-point-min t)
  11862. (move-marker org-entry-property-inherited-from (point))
  11863. (throw 'exit nil))
  11864. ((org-up-heading-or-point-min))
  11865. (t
  11866. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11867. (cond ((not global))
  11868. (value (setq value (concat global " " value)))
  11869. (t (setq value global))))
  11870. (throw 'exit nil))))))
  11871. (if literal-nil value (org-not-nil value)))))
  11872. (defvar org-property-changed-functions nil
  11873. "Hook called when the value of a property has changed.
  11874. Each hook function should accept two arguments, the name of the property
  11875. and the new value.")
  11876. (defun org-entry-put (pom property value)
  11877. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11878. If the value is nil, it is converted to the empty string. If it
  11879. is not a string, an error is raised. Also raise an error on
  11880. invalid property names.
  11881. PROPERTY can be any regular property (see
  11882. `org-special-properties'). It can also be \"TODO\",
  11883. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11884. For the last two properties, VALUE may have any of the special
  11885. values \"earlier\" and \"later\". The function then increases or
  11886. decreases scheduled or deadline date by one day."
  11887. (cond ((null value) (setq value ""))
  11888. ((not (stringp value)) (error "Properties values should be strings"))
  11889. ((not (org--valid-property-p property))
  11890. (user-error "Invalid property name: \"%s\"" property)))
  11891. (org-with-point-at pom
  11892. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11893. (org-back-to-heading-or-point-min t)
  11894. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11895. (let ((beg (point)))
  11896. (cond
  11897. ((equal property "TODO")
  11898. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11899. ((not (member value org-todo-keywords-1))
  11900. (user-error "\"%s\" is not a valid TODO state" value)))
  11901. (org-todo value)
  11902. (org-align-tags))
  11903. ((equal property "PRIORITY")
  11904. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11905. (org-align-tags))
  11906. ((equal property "SCHEDULED")
  11907. (forward-line)
  11908. (if (and (looking-at-p org-planning-line-re)
  11909. (re-search-forward
  11910. org-scheduled-time-regexp (line-end-position) t))
  11911. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11912. ((string= value "later") (org-timestamp-change 1 'day))
  11913. ((string= value "") (org-schedule '(4)))
  11914. (t (org-schedule nil value)))
  11915. (if (member value '("earlier" "later" ""))
  11916. (call-interactively #'org-schedule)
  11917. (org-schedule nil value))))
  11918. ((equal property "DEADLINE")
  11919. (forward-line)
  11920. (if (and (looking-at-p org-planning-line-re)
  11921. (re-search-forward
  11922. org-deadline-time-regexp (line-end-position) t))
  11923. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11924. ((string= value "later") (org-timestamp-change 1 'day))
  11925. ((string= value "") (org-deadline '(4)))
  11926. (t (org-deadline nil value)))
  11927. (if (member value '("earlier" "later" ""))
  11928. (call-interactively #'org-deadline)
  11929. (org-deadline nil value))))
  11930. ((member property org-special-properties)
  11931. (error "The %s property cannot be set with `org-entry-put'" property))
  11932. (t
  11933. (let* ((range (org-get-property-block beg 'force))
  11934. (end (cdr range))
  11935. (case-fold-search t))
  11936. (goto-char (car range))
  11937. (if (re-search-forward (org-re-property property nil t) end t)
  11938. (progn (delete-region (match-beginning 0) (match-end 0))
  11939. (goto-char (match-beginning 0)))
  11940. (goto-char end)
  11941. (insert "\n")
  11942. (backward-char))
  11943. (insert ":" property ":")
  11944. (when value (insert " " value))
  11945. (org-indent-line)))))
  11946. (run-hook-with-args 'org-property-changed-functions property value)))
  11947. (defun org-buffer-property-keys (&optional specials defaults columns)
  11948. "Get all property keys in the current buffer.
  11949. When SPECIALS is non-nil, also list the special properties that
  11950. reflect things like tags and TODO state.
  11951. When DEFAULTS is non-nil, also include properties that has
  11952. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11953. DESCRIPTION, LOCATION, and LOGGING and others.
  11954. When COLUMNS in non-nil, also include property names given in
  11955. COLUMN formats in the current buffer."
  11956. (let ((case-fold-search t)
  11957. (props (append
  11958. (and specials org-special-properties)
  11959. (and defaults (cons org-effort-property org-default-properties))
  11960. ;; Get property names from #+PROPERTY keywords as well
  11961. (mapcar (lambda (s)
  11962. (nth 0 (split-string s)))
  11963. (cdar (org-collect-keywords '("PROPERTY")))))))
  11964. (org-with-wide-buffer
  11965. (goto-char (point-min))
  11966. (while (re-search-forward org-property-start-re nil t)
  11967. (catch :skip
  11968. (let ((range (org-get-property-block)))
  11969. (unless range (throw :skip nil))
  11970. (goto-char (car range))
  11971. (let ((begin (car range))
  11972. (end (cdr range)))
  11973. ;; Make sure that found property block is not located
  11974. ;; before current point, as it would generate an infloop.
  11975. ;; It can happen, for example, in the following
  11976. ;; situation:
  11977. ;;
  11978. ;; * Headline
  11979. ;; :PROPERTIES:
  11980. ;; ...
  11981. ;; :END:
  11982. ;; *************** Inlinetask
  11983. ;; #+BEGIN_EXAMPLE
  11984. ;; :PROPERTIES:
  11985. ;; #+END_EXAMPLE
  11986. ;;
  11987. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11988. (while (< (point) end)
  11989. (let ((p (progn (looking-at org-property-re)
  11990. (match-string-no-properties 2))))
  11991. ;; Only add true property name, not extension symbol.
  11992. (push (if (not (string-match-p "\\+\\'" p)) p
  11993. (substring p 0 -1))
  11994. props))
  11995. (forward-line))))
  11996. (outline-next-heading)))
  11997. (when columns
  11998. (goto-char (point-min))
  11999. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12000. (let ((element (org-element-at-point)))
  12001. (when (memq (org-element-type element) '(keyword node-property))
  12002. (let ((value (org-element-property :value element))
  12003. (start 0))
  12004. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12005. \\(?:{[^}]+}\\)?"
  12006. value start)
  12007. (setq start (match-end 0))
  12008. (let ((p (match-string-no-properties 1 value)))
  12009. (unless (member-ignore-case p org-special-properties)
  12010. (push p props))))))))))
  12011. (sort (delete-dups
  12012. (append props
  12013. ;; for each xxx_ALL property, make sure the bare
  12014. ;; xxx property is also included
  12015. (delq nil (mapcar (lambda (p)
  12016. (and (string-match-p "._ALL\\'" p)
  12017. (substring p 0 -4)))
  12018. props))))
  12019. (lambda (a b) (string< (upcase a) (upcase b))))))
  12020. (defun org-property-values (key)
  12021. "List all non-nil values of property KEY in current buffer."
  12022. (org-with-wide-buffer
  12023. (goto-char (point-min))
  12024. (let ((case-fold-search t)
  12025. (re (org-re-property key))
  12026. values)
  12027. (while (re-search-forward re nil t)
  12028. (push (org-entry-get (point) key) values))
  12029. (delete-dups values))))
  12030. (defun org-insert-property-drawer ()
  12031. "Insert a property drawer into the current entry.
  12032. Do nothing if the drawer already exists. The newly created
  12033. drawer is immediately hidden."
  12034. (org-with-wide-buffer
  12035. ;; Set point to the position where the drawer should be inserted.
  12036. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12037. (org-back-to-heading-or-point-min t)
  12038. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12039. (if (org-before-first-heading-p)
  12040. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12041. (progn
  12042. (forward-line)
  12043. (when (looking-at-p org-planning-line-re) (forward-line))))
  12044. (unless (looking-at-p org-property-drawer-re)
  12045. ;; Make sure we start editing a line from current entry, not from
  12046. ;; next one. It prevents extending text properties or overlays
  12047. ;; belonging to the latter.
  12048. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12049. (let ((begin (if (bobp) (point) (1+ (point))))
  12050. (inhibit-read-only t))
  12051. (unless (bobp) (insert "\n"))
  12052. (insert ":PROPERTIES:\n:END:")
  12053. (org-flag-region (line-end-position 0) (point) t 'outline)
  12054. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12055. (org-indent-region begin (point))))))
  12056. (defun org-insert-drawer (&optional arg drawer)
  12057. "Insert a drawer at point.
  12058. When optional argument ARG is non-nil, insert a property drawer.
  12059. Optional argument DRAWER, when non-nil, is a string representing
  12060. drawer's name. Otherwise, the user is prompted for a name.
  12061. If a region is active, insert the drawer around that region
  12062. instead.
  12063. Point is left between drawer's boundaries."
  12064. (interactive "P")
  12065. (let* ((drawer (if arg "PROPERTIES"
  12066. (or drawer (read-from-minibuffer "Drawer: ")))))
  12067. (cond
  12068. ;; With C-u, fall back on `org-insert-property-drawer'
  12069. (arg (org-insert-property-drawer))
  12070. ;; Check validity of suggested drawer's name.
  12071. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12072. (user-error "Invalid drawer name"))
  12073. ;; With an active region, insert a drawer at point.
  12074. ((not (org-region-active-p))
  12075. (progn
  12076. (unless (bolp) (insert "\n"))
  12077. (insert (format ":%s:\n\n:END:\n" drawer))
  12078. (forward-line -2)))
  12079. ;; Otherwise, insert the drawer at point
  12080. (t
  12081. (let ((rbeg (region-beginning))
  12082. (rend (copy-marker (region-end))))
  12083. (unwind-protect
  12084. (progn
  12085. (goto-char rbeg)
  12086. (beginning-of-line)
  12087. (when (save-excursion
  12088. (re-search-forward org-outline-regexp-bol rend t))
  12089. (user-error "Drawers cannot contain headlines"))
  12090. ;; Position point at the beginning of the first
  12091. ;; non-blank line in region. Insert drawer's opening
  12092. ;; there, then indent it.
  12093. (org-skip-whitespace)
  12094. (beginning-of-line)
  12095. (insert ":" drawer ":\n")
  12096. (forward-line -1)
  12097. (indent-for-tab-command)
  12098. ;; Move point to the beginning of the first blank line
  12099. ;; after the last non-blank line in region. Insert
  12100. ;; drawer's closing, then indent it.
  12101. (goto-char rend)
  12102. (skip-chars-backward " \r\t\n")
  12103. (insert "\n:END:")
  12104. (deactivate-mark t)
  12105. (indent-for-tab-command)
  12106. (unless (eolp) (insert "\n")))
  12107. ;; Clear marker, whatever the outcome of insertion is.
  12108. (set-marker rend nil)))))))
  12109. (defvar org-property-set-functions-alist nil
  12110. "Property set function alist.
  12111. Each entry should have the following format:
  12112. (PROPERTY . READ-FUNCTION)
  12113. The read function will be called with the same argument as
  12114. `org-completing-read'.")
  12115. (defun org-set-property-function (property)
  12116. "Get the function that should be used to set PROPERTY.
  12117. This is computed according to `org-property-set-functions-alist'."
  12118. (or (cdr (assoc property org-property-set-functions-alist))
  12119. 'org-completing-read))
  12120. (defun org-read-property-value (property &optional pom default)
  12121. "Read value for PROPERTY, as a string.
  12122. When optional argument POM is non-nil, completion uses additional
  12123. information, i.e., allowed or existing values at point or marker
  12124. POM.
  12125. Optional argument DEFAULT provides a default value for PROPERTY."
  12126. (let* ((completion-ignore-case t)
  12127. (allowed
  12128. (or (org-property-get-allowed-values nil property 'table)
  12129. (and pom (org-property-get-allowed-values pom property 'table))))
  12130. (current (org-entry-get nil property))
  12131. (prompt (format "%s value%s: "
  12132. property
  12133. (if (org-string-nw-p current)
  12134. (format " [%s]" current)
  12135. "")))
  12136. (set-function (org-set-property-function property)))
  12137. (org-trim
  12138. (if allowed
  12139. (funcall set-function
  12140. prompt allowed nil
  12141. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12142. default nil default)
  12143. (let ((all (mapcar #'list
  12144. (append (org-property-values property)
  12145. (and pom
  12146. (org-with-point-at pom
  12147. (org-property-values property)))))))
  12148. (funcall set-function prompt all nil nil "" nil current))))))
  12149. (defvar org-last-set-property nil)
  12150. (defvar org-last-set-property-value nil)
  12151. (defun org-read-property-name ()
  12152. "Read a property name."
  12153. (let ((completion-ignore-case t)
  12154. (default-prop (or (and (org-at-property-p)
  12155. (match-string-no-properties 2))
  12156. org-last-set-property)))
  12157. (org-completing-read
  12158. (concat "Property"
  12159. (if default-prop (concat " [" default-prop "]") "")
  12160. ": ")
  12161. (mapcar #'list (org-buffer-property-keys nil t t))
  12162. nil nil nil nil default-prop)))
  12163. (defun org-set-property-and-value (use-last)
  12164. "Allow to set [PROPERTY]: [value] direction from prompt.
  12165. When use-default, don't even ask, just use the last
  12166. \"[PROPERTY]: [value]\" string from the history."
  12167. (interactive "P")
  12168. (let* ((completion-ignore-case t)
  12169. (pv (or (and use-last org-last-set-property-value)
  12170. (org-completing-read
  12171. "Enter a \"[Property]: [value]\" pair: "
  12172. nil nil nil nil nil
  12173. org-last-set-property-value)))
  12174. prop val)
  12175. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12176. (setq prop (match-string 1 pv)
  12177. val (match-string 2 pv))
  12178. (org-set-property prop val))))
  12179. (defun org-set-property (property value)
  12180. "In the current entry, set PROPERTY to VALUE.
  12181. When called interactively, this will prompt for a property name, offering
  12182. completion on existing and default properties. And then it will prompt
  12183. for a value, offering completion either on allowed values (via an inherited
  12184. xxx_ALL property) or on existing values in other instances of this property
  12185. in the current file.
  12186. Throw an error when trying to set a property with an invalid name."
  12187. (interactive (list nil nil))
  12188. (let ((property (or property (org-read-property-name))))
  12189. ;; `org-entry-put' also makes the following check, but this one
  12190. ;; avoids polluting `org-last-set-property' and
  12191. ;; `org-last-set-property-value' needlessly.
  12192. (unless (org--valid-property-p property)
  12193. (user-error "Invalid property name: \"%s\"" property))
  12194. (let ((value (or value (org-read-property-value property)))
  12195. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12196. (setq org-last-set-property property)
  12197. (setq org-last-set-property-value (concat property ": " value))
  12198. ;; Possibly postprocess the inserted value:
  12199. (when fn (setq value (funcall fn value)))
  12200. (unless (equal (org-entry-get nil property) value)
  12201. (org-entry-put nil property value)))))
  12202. (defun org-find-property (property &optional value)
  12203. "Find first entry in buffer that sets PROPERTY.
  12204. When optional argument VALUE is non-nil, only consider an entry
  12205. if it contains PROPERTY set to this value. If PROPERTY should be
  12206. explicitly set to nil, use string \"nil\" for VALUE.
  12207. Return position where the entry begins, or nil if there is no
  12208. such entry. If narrowing is in effect, only search the visible
  12209. part of the buffer."
  12210. (save-excursion
  12211. (goto-char (point-min))
  12212. (let ((case-fold-search t)
  12213. (re (org-re-property property nil (not value) value)))
  12214. (catch 'exit
  12215. (while (re-search-forward re nil t)
  12216. (when (if value (org-at-property-p)
  12217. (org-entry-get (point) property nil t))
  12218. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12219. (point)))))))))
  12220. (defun org-delete-property (property)
  12221. "In the current entry, delete PROPERTY."
  12222. (interactive
  12223. (let* ((completion-ignore-case t)
  12224. (cat (org-entry-get (point) "CATEGORY"))
  12225. (props0 (org-entry-properties nil 'standard))
  12226. (props (if cat props0
  12227. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12228. (prop (if (< 1 (length props))
  12229. (completing-read "Property: " props nil t)
  12230. (caar props))))
  12231. (list prop)))
  12232. (if (not property)
  12233. (message "No property to delete in this entry")
  12234. (org-entry-delete nil property)
  12235. (message "Property \"%s\" deleted" property)))
  12236. (defun org-delete-property-globally (property)
  12237. "Remove PROPERTY globally, from all entries.
  12238. This function ignores narrowing, if any."
  12239. (interactive
  12240. (let* ((completion-ignore-case t)
  12241. (prop (completing-read
  12242. "Globally remove property: "
  12243. (mapcar #'list (org-buffer-property-keys)))))
  12244. (list prop)))
  12245. (org-with-wide-buffer
  12246. (goto-char (point-min))
  12247. (let ((count 0)
  12248. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12249. (while (re-search-forward re nil t)
  12250. (when (org-entry-delete (point) property) (cl-incf count)))
  12251. (message "Property \"%s\" removed from %d entries" property count))))
  12252. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12253. (defun org-compute-property-at-point ()
  12254. "Compute the property at point.
  12255. This looks for an enclosing column format, extracts the operator and
  12256. then applies it to the property in the column format's scope."
  12257. (interactive)
  12258. (unless (org-at-property-p)
  12259. (user-error "Not at a property"))
  12260. (let ((prop (match-string-no-properties 2)))
  12261. (org-columns-get-format-and-top-level)
  12262. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12263. (user-error "No operator defined for property %s" prop))
  12264. (org-columns-compute prop)))
  12265. (defvar org-property-allowed-value-functions nil
  12266. "Hook for functions supplying allowed values for a specific property.
  12267. The functions must take a single argument, the name of the property, and
  12268. return a flat list of allowed values. If \":ETC\" is one of
  12269. the values, this means that these values are intended as defaults for
  12270. completion, but that other values should be allowed too.
  12271. The functions must return nil if they are not responsible for this
  12272. property.")
  12273. (defun org-property-get-allowed-values (pom property &optional table)
  12274. "Get allowed values for the property PROPERTY.
  12275. When TABLE is non-nil, return an alist that can directly be used for
  12276. completion."
  12277. (let (vals)
  12278. (cond
  12279. ((equal property "TODO")
  12280. (setq vals (org-with-point-at pom
  12281. (append org-todo-keywords-1 '("")))))
  12282. ((equal property "PRIORITY")
  12283. (let ((n org-priority-lowest))
  12284. (while (>= n org-priority-highest)
  12285. (push (char-to-string n) vals)
  12286. (setq n (1- n)))))
  12287. ((equal property "CATEGORY"))
  12288. ((member property org-special-properties))
  12289. ((setq vals (run-hook-with-args-until-success
  12290. 'org-property-allowed-value-functions property)))
  12291. (t
  12292. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12293. (when (and vals (string-match "\\S-" vals))
  12294. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12295. (setq vals (mapcar (lambda (x)
  12296. (cond ((stringp x) x)
  12297. ((numberp x) (number-to-string x))
  12298. ((symbolp x) (symbol-name x))
  12299. (t "???")))
  12300. vals)))))
  12301. (when (member ":ETC" vals)
  12302. (setq vals (remove ":ETC" vals))
  12303. (org-add-props (car vals) '(org-unrestricted t)))
  12304. (if table (mapcar 'list vals) vals)))
  12305. (defun org-property-previous-allowed-value (&optional _previous)
  12306. "Switch to the next allowed value for this property."
  12307. (interactive)
  12308. (org-property-next-allowed-value t))
  12309. (defun org-property-next-allowed-value (&optional previous)
  12310. "Switch to the next allowed value for this property."
  12311. (interactive)
  12312. (unless (org-at-property-p)
  12313. (user-error "Not at a property"))
  12314. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12315. (key (match-string 2))
  12316. (value (match-string 3))
  12317. (allowed (or (org-property-get-allowed-values (point) key)
  12318. (and (member value '("[ ]" "[-]" "[X]"))
  12319. '("[ ]" "[X]"))))
  12320. (heading (save-match-data (nth 4 (org-heading-components))))
  12321. nval)
  12322. (unless allowed
  12323. (user-error "Allowed values for this property have not been defined"))
  12324. (when previous (setq allowed (reverse allowed)))
  12325. (when (member value allowed)
  12326. (setq nval (car (cdr (member value allowed)))))
  12327. (setq nval (or nval (car allowed)))
  12328. (when (equal nval value)
  12329. (user-error "Only one allowed value for this property"))
  12330. (org-at-property-p)
  12331. (replace-match (concat " :" key ": " nval) t t)
  12332. (org-indent-line)
  12333. (beginning-of-line 1)
  12334. (skip-chars-forward " \t")
  12335. (when (equal prop org-effort-property)
  12336. (org-refresh-property
  12337. '((effort . identity)
  12338. (effort-minutes . org-duration-to-minutes))
  12339. nval)
  12340. (when (string= org-clock-current-task heading)
  12341. (setq org-clock-effort nval)
  12342. (org-clock-update-mode-line)))
  12343. (run-hook-with-args 'org-property-changed-functions key nval)))
  12344. (defun org-find-olp (path &optional this-buffer)
  12345. "Return a marker pointing to the entry at outline path OLP.
  12346. If anything goes wrong, throw an error, and if you need to do
  12347. something based on this error, you can catch it with
  12348. `condition-case'.
  12349. If THIS-BUFFER is set, the outline path does not contain a file,
  12350. only headings."
  12351. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12352. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12353. (level 1)
  12354. (lmin 1)
  12355. (lmax 1)
  12356. end found flevel)
  12357. (unless buffer (error "File not found :%s" file))
  12358. (with-current-buffer buffer
  12359. (unless (derived-mode-p 'org-mode)
  12360. (error "Buffer %s needs to be in Org mode" buffer))
  12361. (org-with-wide-buffer
  12362. (goto-char (point-min))
  12363. (dolist (heading path)
  12364. (let ((re (format org-complex-heading-regexp-format
  12365. (regexp-quote heading)))
  12366. (cnt 0))
  12367. (while (re-search-forward re end t)
  12368. (setq level (- (match-end 1) (match-beginning 1)))
  12369. (when (and (>= level lmin) (<= level lmax))
  12370. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12371. (when (= cnt 0)
  12372. (error "Heading not found on level %d: %s" lmax heading))
  12373. (when (> cnt 1)
  12374. (error "Heading not unique on level %d: %s" lmax heading))
  12375. (goto-char found)
  12376. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12377. (setq end (save-excursion (org-end-of-subtree t t)))))
  12378. (when (org-at-heading-p)
  12379. (point-marker))))))
  12380. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12381. "Find node HEADING in BUFFER.
  12382. Return a marker to the heading if it was found, or nil if not.
  12383. If POS-ONLY is set, return just the position instead of a marker.
  12384. The heading text must match exact, but it may have a TODO keyword,
  12385. a priority cookie and tags in the standard locations."
  12386. (with-current-buffer (or buffer (current-buffer))
  12387. (org-with-wide-buffer
  12388. (goto-char (point-min))
  12389. (let (case-fold-search)
  12390. (when (re-search-forward
  12391. (format org-complex-heading-regexp-format
  12392. (regexp-quote heading)) nil t)
  12393. (if pos-only
  12394. (match-beginning 0)
  12395. (move-marker (make-marker) (match-beginning 0))))))))
  12396. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12397. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12398. When the target headline is found, return a marker to this location."
  12399. (let ((files (directory-files (or dir default-directory)
  12400. t "\\`[^.#].*\\.org\\'"))
  12401. visiting m buffer)
  12402. (catch 'found
  12403. (dolist (file files)
  12404. (message "trying %s" file)
  12405. (setq visiting (org-find-base-buffer-visiting file))
  12406. (setq buffer (or visiting (find-file-noselect file)))
  12407. (setq m (org-find-exact-headline-in-buffer
  12408. heading buffer))
  12409. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12410. (and m (throw 'found m))))))
  12411. (defun org-find-entry-with-id (ident)
  12412. "Locate the entry that contains the ID property with exact value IDENT.
  12413. IDENT can be a string, a symbol or a number, this function will search for
  12414. the string representation of it.
  12415. Return the position where this entry starts, or nil if there is no such entry."
  12416. (interactive "sID: ")
  12417. (let ((id (cond
  12418. ((stringp ident) ident)
  12419. ((symbolp ident) (symbol-name ident))
  12420. ((numberp ident) (number-to-string ident))
  12421. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12422. (org-with-wide-buffer (org-find-property "ID" id))))
  12423. ;;;; Timestamps
  12424. (defvar org-last-changed-timestamp nil)
  12425. (defvar org-last-inserted-timestamp nil
  12426. "The last time stamp inserted with `org-insert-time-stamp'.")
  12427. (defun org-time-stamp (arg &optional inactive)
  12428. "Prompt for a date/time and insert a time stamp.
  12429. If the user specifies a time like HH:MM or if this command is
  12430. called with at least one prefix argument, the time stamp contains
  12431. the date and the time. Otherwise, only the date is included.
  12432. All parts of a date not specified by the user are filled in from
  12433. the timestamp at point, if any, or the current date/time
  12434. otherwise.
  12435. If there is already a timestamp at the cursor, it is replaced.
  12436. With two universal prefix arguments, insert an active timestamp
  12437. with the current time without prompting the user.
  12438. When called from lisp, the timestamp is inactive if INACTIVE is
  12439. non-nil."
  12440. (interactive "P")
  12441. (let* ((ts (cond
  12442. ((org-at-date-range-p t)
  12443. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12444. ((org-at-timestamp-p 'lax) (match-string 0))))
  12445. ;; Default time is either the timestamp at point or today.
  12446. ;; When entering a range, only the range start is considered.
  12447. (default-time (and ts (org-time-string-to-time ts)))
  12448. (default-input (and ts (org-get-compact-tod ts)))
  12449. (repeater (and ts
  12450. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12451. (match-string 0 ts)))
  12452. org-time-was-given
  12453. org-end-time-was-given
  12454. (time
  12455. (if (equal arg '(16)) (current-time)
  12456. ;; Preserve `this-command' and `last-command'.
  12457. (let ((this-command this-command)
  12458. (last-command last-command))
  12459. (org-read-date
  12460. arg 'totime nil nil default-time default-input
  12461. inactive)))))
  12462. (cond
  12463. ((and ts
  12464. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12465. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12466. (insert "--")
  12467. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12468. (ts
  12469. ;; Make sure we're on a timestamp. When in the middle of a date
  12470. ;; range, move arbitrarily to range end.
  12471. (unless (org-at-timestamp-p 'lax)
  12472. (skip-chars-forward "-")
  12473. (org-at-timestamp-p 'lax))
  12474. (replace-match "")
  12475. (setq org-last-changed-timestamp
  12476. (org-insert-time-stamp
  12477. time (or org-time-was-given arg)
  12478. inactive nil nil (list org-end-time-was-given)))
  12479. (when repeater
  12480. (backward-char)
  12481. (insert " " repeater)
  12482. (setq org-last-changed-timestamp
  12483. (concat (substring org-last-inserted-timestamp 0 -1)
  12484. " " repeater ">")))
  12485. (message "Timestamp updated"))
  12486. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12487. (t (org-insert-time-stamp
  12488. time (or org-time-was-given arg) inactive nil nil
  12489. (list org-end-time-was-given))))))
  12490. ;; FIXME: can we use this for something else, like computing time differences?
  12491. (defun org-get-compact-tod (s)
  12492. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12493. (let* ((t1 (match-string 1 s))
  12494. (h1 (string-to-number (match-string 2 s)))
  12495. (m1 (string-to-number (match-string 3 s)))
  12496. (t2 (and (match-end 4) (match-string 5 s)))
  12497. (h2 (and t2 (string-to-number (match-string 6 s))))
  12498. (m2 (and t2 (string-to-number (match-string 7 s))))
  12499. dh dm)
  12500. (if (not t2)
  12501. t1
  12502. (setq dh (- h2 h1) dm (- m2 m1))
  12503. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12504. (concat t1 "+" (number-to-string dh)
  12505. (and (/= 0 dm) (format ":%02d" dm)))))))
  12506. (defun org-time-stamp-inactive (&optional arg)
  12507. "Insert an inactive time stamp.
  12508. An inactive time stamp is enclosed in square brackets instead of
  12509. angle brackets. It is inactive in the sense that it does not
  12510. trigger agenda entries. So these are more for recording a
  12511. certain time/date.
  12512. If the user specifies a time like HH:MM or if this command is called with
  12513. at least one prefix argument, the time stamp contains the date and the time.
  12514. Otherwise, only the date is included.
  12515. When called with two universal prefix arguments, insert an inactive time stamp
  12516. with the current time without prompting the user."
  12517. (interactive "P")
  12518. (org-time-stamp arg 'inactive))
  12519. (defvar org-date-ovl (make-overlay 1 1))
  12520. (overlay-put org-date-ovl 'face 'org-date-selected)
  12521. (delete-overlay org-date-ovl)
  12522. (defvar org-ans1) ; dynamically scoped parameter
  12523. (defvar org-ans2) ; dynamically scoped parameter
  12524. (defvar org-plain-time-of-day-regexp) ; defined below
  12525. (defvar org-overriding-default-time nil) ; dynamically scoped
  12526. (defvar org-read-date-overlay nil)
  12527. (defvar org-read-date-history nil)
  12528. (defvar org-read-date-final-answer nil)
  12529. (defvar org-read-date-analyze-futurep nil)
  12530. (defvar org-read-date-analyze-forced-year nil)
  12531. (defvar org-read-date-inactive)
  12532. (defvar org-def)
  12533. (defvar org-defdecode)
  12534. (defvar org-with-time)
  12535. (defvar calendar-setup) ; Dynamically scoped.
  12536. (defun org-read-date (&optional with-time to-time from-string prompt
  12537. default-time default-input inactive)
  12538. "Read a date, possibly a time, and make things smooth for the user.
  12539. The prompt will suggest to enter an ISO date, but you can also enter anything
  12540. which will at least partially be understood by `parse-time-string'.
  12541. Unrecognized parts of the date will default to the current day, month, year,
  12542. hour and minute. If this command is called to replace a timestamp at point,
  12543. or to enter the second timestamp of a range, the default time is taken
  12544. from the existing stamp. Furthermore, the command prefers the future,
  12545. so if you are giving a date where the year is not given, and the day-month
  12546. combination is already past in the current year, it will assume you
  12547. mean next year. For details, see the manual. A few examples:
  12548. 3-2-5 --> 2003-02-05
  12549. feb 15 --> currentyear-02-15
  12550. 2/15 --> currentyear-02-15
  12551. sep 12 9 --> 2009-09-12
  12552. 12:45 --> today 12:45
  12553. 22 sept 0:34 --> currentyear-09-22 0:34
  12554. 12 --> currentyear-currentmonth-12
  12555. Fri --> nearest Friday after today
  12556. -Tue --> last Tuesday
  12557. etc.
  12558. Furthermore you can specify a relative date by giving, as the *first* thing
  12559. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12560. change in days weeks, months, years.
  12561. With a single plus or minus, the date is relative to today. With a double
  12562. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12563. +4d --> four days from today
  12564. +4 --> same as above
  12565. +2w --> two weeks from today
  12566. ++5 --> five days from default date
  12567. The function understands only English month and weekday abbreviations.
  12568. While prompting, a calendar is popped up - you can also select the
  12569. date with the mouse (button 1). The calendar shows a period of three
  12570. months. To scroll it to other months, use the keys `>' and `<'.
  12571. If you don't like the calendar, turn it off with
  12572. (setq org-read-date-popup-calendar nil)
  12573. With optional argument TO-TIME, the date will immediately be converted
  12574. to an internal time.
  12575. With an optional argument WITH-TIME, the prompt will suggest to
  12576. also insert a time. Note that when WITH-TIME is not set, you can
  12577. still enter a time, and this function will inform the calling routine
  12578. about this change. The calling routine may then choose to change the
  12579. format used to insert the time stamp into the buffer to include the time.
  12580. With optional argument FROM-STRING, read from this string instead from
  12581. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12582. the time/date that is used for everything that is not specified by the
  12583. user."
  12584. (require 'parse-time)
  12585. (let* ((org-with-time with-time)
  12586. (org-time-stamp-rounding-minutes
  12587. (if (equal org-with-time '(16))
  12588. '(0 0)
  12589. org-time-stamp-rounding-minutes))
  12590. (ct (org-current-time))
  12591. (org-def (or org-overriding-default-time default-time ct))
  12592. (org-defdecode (decode-time org-def))
  12593. (cur-frame (selected-frame))
  12594. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12595. (calendar-setup
  12596. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12597. (calendar-move-hook nil)
  12598. (calendar-view-diary-initially-flag nil)
  12599. (calendar-view-holidays-initially-flag nil)
  12600. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12601. ;; Rationalize `org-def' and `org-defdecode', if required.
  12602. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12603. (setf (nth 2 org-defdecode) -1)
  12604. (setf (nth 1 org-defdecode) 59)
  12605. (setq org-def (apply #'encode-time org-defdecode))
  12606. (setq org-defdecode (decode-time org-def)))
  12607. (let* ((timestr (format-time-string
  12608. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12609. org-def))
  12610. (prompt (concat (if prompt (concat prompt " ") "")
  12611. (format "Date+time [%s]: " timestr))))
  12612. (cond
  12613. (from-string (setq ans from-string))
  12614. (org-read-date-popup-calendar
  12615. (save-excursion
  12616. (save-window-excursion
  12617. (calendar)
  12618. (when (eq calendar-setup 'calendar-only)
  12619. (setq cal-frame
  12620. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12621. (select-frame cal-frame))
  12622. (org-eval-in-calendar '(setq cursor-type nil) t)
  12623. (unwind-protect
  12624. (progn
  12625. (calendar-forward-day (- (time-to-days org-def)
  12626. (calendar-absolute-from-gregorian
  12627. (calendar-current-date))))
  12628. (org-eval-in-calendar nil t)
  12629. (let* ((old-map (current-local-map))
  12630. (map (copy-keymap calendar-mode-map))
  12631. (minibuffer-local-map
  12632. (copy-keymap org-read-date-minibuffer-local-map)))
  12633. (org-defkey map (kbd "RET") 'org-calendar-select)
  12634. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12635. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12636. (unwind-protect
  12637. (progn
  12638. (use-local-map map)
  12639. (setq org-read-date-inactive inactive)
  12640. (add-hook 'post-command-hook 'org-read-date-display)
  12641. (setq org-ans0
  12642. (read-string prompt
  12643. default-input
  12644. 'org-read-date-history
  12645. nil))
  12646. ;; org-ans0: from prompt
  12647. ;; org-ans1: from mouse click
  12648. ;; org-ans2: from calendar motion
  12649. (setq ans
  12650. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12651. (remove-hook 'post-command-hook 'org-read-date-display)
  12652. (use-local-map old-map)
  12653. (when org-read-date-overlay
  12654. (delete-overlay org-read-date-overlay)
  12655. (setq org-read-date-overlay nil)))))
  12656. (bury-buffer "*Calendar*")
  12657. (when cal-frame
  12658. (delete-frame cal-frame)
  12659. (select-frame-set-input-focus cur-frame))))))
  12660. (t ; Naked prompt only
  12661. (unwind-protect
  12662. (setq ans (read-string prompt default-input
  12663. 'org-read-date-history timestr))
  12664. (when org-read-date-overlay
  12665. (delete-overlay org-read-date-overlay)
  12666. (setq org-read-date-overlay nil))))))
  12667. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12668. (when org-read-date-analyze-forced-year
  12669. (message "Year was forced into %s"
  12670. (if org-read-date-force-compatible-dates
  12671. "compatible range (1970-2037)"
  12672. "range representable on this machine"))
  12673. (ding))
  12674. (setq final (apply #'encode-time final))
  12675. (setq org-read-date-final-answer ans)
  12676. (if to-time
  12677. final
  12678. ;; This round-trip gets rid of 34th of August and stuff like that....
  12679. (setq final (decode-time final))
  12680. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12681. (format "%04d-%02d-%02d %02d:%02d"
  12682. (nth 5 final) (nth 4 final) (nth 3 final)
  12683. (nth 2 final) (nth 1 final))
  12684. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12685. (defun org-read-date-display ()
  12686. "Display the current date prompt interpretation in the minibuffer."
  12687. (when org-read-date-display-live
  12688. (when org-read-date-overlay
  12689. (delete-overlay org-read-date-overlay))
  12690. (when (minibufferp (current-buffer))
  12691. (save-excursion
  12692. (end-of-line 1)
  12693. (while (not (equal (buffer-substring
  12694. (max (point-min) (- (point) 4)) (point))
  12695. " "))
  12696. (insert " ")))
  12697. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12698. " " (or org-ans1 org-ans2)))
  12699. (org-end-time-was-given nil)
  12700. (f (org-read-date-analyze ans org-def org-defdecode))
  12701. (fmts (if org-display-custom-times
  12702. org-time-stamp-custom-formats
  12703. org-time-stamp-formats))
  12704. (fmt (if (or org-with-time
  12705. (and (boundp 'org-time-was-given) org-time-was-given))
  12706. (cdr fmts)
  12707. (car fmts)))
  12708. (txt (format-time-string fmt (apply #'encode-time f)))
  12709. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12710. (txt (concat "=> " txt)))
  12711. (when (and org-end-time-was-given
  12712. (string-match org-plain-time-of-day-regexp txt))
  12713. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12714. org-end-time-was-given
  12715. (substring txt (match-end 0)))))
  12716. (when org-read-date-analyze-futurep
  12717. (setq txt (concat txt " (=>F)")))
  12718. (setq org-read-date-overlay
  12719. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12720. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12721. (defun org-read-date-analyze (ans def defdecode)
  12722. "Analyze the combined answer of the date prompt."
  12723. ;; FIXME: cleanup and comment
  12724. (let ((org-def def)
  12725. (org-defdecode defdecode)
  12726. (nowdecode (decode-time))
  12727. delta deltan deltaw deltadef year month day
  12728. hour minute second wday pm h2 m2 tl wday1
  12729. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12730. (setq org-read-date-analyze-futurep nil
  12731. org-read-date-analyze-forced-year nil)
  12732. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12733. (setq ans "+0"))
  12734. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12735. (setq ans (replace-match "" t t ans)
  12736. deltan (car delta)
  12737. deltaw (nth 1 delta)
  12738. deltadef (nth 2 delta)))
  12739. ;; Check if there is an iso week date in there. If yes, store the
  12740. ;; info and postpone interpreting it until the rest of the parsing
  12741. ;; is done.
  12742. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12743. (setq iso-year (when (match-end 1)
  12744. (org-small-year-to-year
  12745. (string-to-number (match-string 1 ans))))
  12746. iso-weekday (when (match-end 3)
  12747. (string-to-number (match-string 3 ans)))
  12748. iso-week (string-to-number (match-string 2 ans)))
  12749. (setq ans (replace-match "" t t ans)))
  12750. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12751. (when (string-match
  12752. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12753. (setq year (if (match-end 2)
  12754. (string-to-number (match-string 2 ans))
  12755. (progn (setq kill-year t)
  12756. (string-to-number (format-time-string "%Y"))))
  12757. month (string-to-number (match-string 3 ans))
  12758. day (string-to-number (match-string 4 ans)))
  12759. (setq year (org-small-year-to-year year))
  12760. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12761. t nil ans)))
  12762. ;; Help matching dotted european dates
  12763. (when (string-match
  12764. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12765. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12766. (setq kill-year t)
  12767. (string-to-number (format-time-string "%Y")))
  12768. day (string-to-number (match-string 1 ans))
  12769. month (string-to-number (match-string 2 ans))
  12770. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12771. t nil ans)))
  12772. ;; Help matching american dates, like 5/30 or 5/30/7
  12773. (when (string-match
  12774. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12775. (setq year (if (match-end 4)
  12776. (string-to-number (match-string 4 ans))
  12777. (progn (setq kill-year t)
  12778. (string-to-number (format-time-string "%Y"))))
  12779. month (string-to-number (match-string 1 ans))
  12780. day (string-to-number (match-string 2 ans)))
  12781. (setq year (org-small-year-to-year year))
  12782. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12783. t nil ans)))
  12784. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12785. ;; If there is a time with am/pm, and *no* time without it, we convert
  12786. ;; so that matching will be successful.
  12787. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12788. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12789. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12790. (setq hour (string-to-number (match-string 1 ans))
  12791. minute (if (match-end 3)
  12792. (string-to-number (match-string 3 ans))
  12793. 0)
  12794. pm (equal ?p
  12795. (string-to-char (downcase (match-string 4 ans)))))
  12796. (if (and (= hour 12) (not pm))
  12797. (setq hour 0)
  12798. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12799. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12800. t t ans))))
  12801. ;; Check if a time range is given as a duration
  12802. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12803. (setq hour (string-to-number (match-string 1 ans))
  12804. h2 (+ hour (string-to-number (match-string 3 ans)))
  12805. minute (string-to-number (match-string 2 ans))
  12806. m2 (+ minute (if (match-end 5) (string-to-number
  12807. (match-string 5 ans))0)))
  12808. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12809. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12810. t t ans)))
  12811. ;; Check if there is a time range
  12812. (when (boundp 'org-end-time-was-given)
  12813. (setq org-time-was-given nil)
  12814. (when (and (string-match org-plain-time-of-day-regexp ans)
  12815. (match-end 8))
  12816. (setq org-end-time-was-given (match-string 8 ans))
  12817. (setq ans (concat (substring ans 0 (match-beginning 7))
  12818. (substring ans (match-end 7))))))
  12819. (setq tl (parse-time-string ans)
  12820. day (or (nth 3 tl) (nth 3 org-defdecode))
  12821. month
  12822. (cond ((nth 4 tl))
  12823. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12824. ;; Day was specified. Make sure DAY+MONTH
  12825. ;; combination happens in the future.
  12826. ((nth 3 tl)
  12827. (setq futurep t)
  12828. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12829. (nth 4 nowdecode)))
  12830. (t (nth 4 org-defdecode)))
  12831. year
  12832. (cond ((and (not kill-year) (nth 5 tl)))
  12833. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12834. ;; Month was guessed in the future and is at least
  12835. ;; equal to NOWDECODE's. Fix year accordingly.
  12836. (futurep
  12837. (if (or (> month (nth 4 nowdecode))
  12838. (>= day (nth 3 nowdecode)))
  12839. (nth 5 nowdecode)
  12840. (1+ (nth 5 nowdecode))))
  12841. ;; Month was specified. Make sure MONTH+YEAR
  12842. ;; combination happens in the future.
  12843. ((nth 4 tl)
  12844. (setq futurep t)
  12845. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12846. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12847. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12848. (t (nth 5 nowdecode))))
  12849. (t (nth 5 org-defdecode)))
  12850. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12851. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12852. second (or (nth 0 tl) 0)
  12853. wday (nth 6 tl))
  12854. (when (and (eq org-read-date-prefer-future 'time)
  12855. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12856. (equal day (nth 3 nowdecode))
  12857. (equal month (nth 4 nowdecode))
  12858. (equal year (nth 5 nowdecode))
  12859. (nth 2 tl)
  12860. (or (< (nth 2 tl) (nth 2 nowdecode))
  12861. (and (= (nth 2 tl) (nth 2 nowdecode))
  12862. (nth 1 tl)
  12863. (< (nth 1 tl) (nth 1 nowdecode)))))
  12864. (setq day (1+ day)
  12865. futurep t))
  12866. ;; Special date definitions below
  12867. (cond
  12868. (iso-week
  12869. ;; There was an iso week
  12870. (require 'cal-iso)
  12871. (setq futurep nil)
  12872. (setq year (or iso-year year)
  12873. day (or iso-weekday wday 1)
  12874. wday nil ; to make sure that the trigger below does not match
  12875. iso-date (calendar-gregorian-from-absolute
  12876. (calendar-iso-to-absolute
  12877. (list iso-week day year))))
  12878. ; FIXME: Should we also push ISO weeks into the future?
  12879. ; (when (and org-read-date-prefer-future
  12880. ; (not iso-year)
  12881. ; (< (calendar-absolute-from-gregorian iso-date)
  12882. ; (time-to-days nil)))
  12883. ; (setq year (1+ year)
  12884. ; iso-date (calendar-gregorian-from-absolute
  12885. ; (calendar-iso-to-absolute
  12886. ; (list iso-week day year)))))
  12887. (setq month (car iso-date)
  12888. year (nth 2 iso-date)
  12889. day (nth 1 iso-date)))
  12890. (deltan
  12891. (setq futurep nil)
  12892. (unless deltadef
  12893. (let ((now (decode-time)))
  12894. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12895. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12896. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12897. ((equal deltaw "m") (setq month (+ month deltan)))
  12898. ((equal deltaw "y") (setq year (+ year deltan)))))
  12899. ((and wday (not (nth 3 tl)))
  12900. ;; Weekday was given, but no day, so pick that day in the week
  12901. ;; on or after the derived date.
  12902. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12903. (unless (equal wday wday1)
  12904. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12905. (when (and (boundp 'org-time-was-given)
  12906. (nth 2 tl))
  12907. (setq org-time-was-given t))
  12908. (when (< year 100) (setq year (+ 2000 year)))
  12909. ;; Check of the date is representable
  12910. (if org-read-date-force-compatible-dates
  12911. (progn
  12912. (when (< year 1970)
  12913. (setq year 1970 org-read-date-analyze-forced-year t))
  12914. (when (> year 2037)
  12915. (setq year 2037 org-read-date-analyze-forced-year t)))
  12916. (condition-case nil
  12917. (ignore (encode-time second minute hour day month year))
  12918. (error
  12919. (setq year (nth 5 org-defdecode))
  12920. (setq org-read-date-analyze-forced-year t))))
  12921. (setq org-read-date-analyze-futurep futurep)
  12922. (list second minute hour day month year)))
  12923. (defvar parse-time-weekdays)
  12924. (defun org-read-date-get-relative (s today default)
  12925. "Check string S for special relative date string.
  12926. TODAY and DEFAULT are internal times, for today and for a default.
  12927. Return shift list (N what def-flag)
  12928. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12929. N is the number of WHATs to shift.
  12930. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12931. the DEFAULT date rather than TODAY."
  12932. (require 'parse-time)
  12933. (when (and
  12934. (string-match
  12935. (concat
  12936. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12937. "\\([0-9]+\\)?"
  12938. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12939. "\\([ \t]\\|$\\)") s)
  12940. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12941. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12942. (string-to-char (substring (match-string 1 s) -1))
  12943. ?+))
  12944. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12945. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12946. (what (if (match-end 3) (match-string 3 s) "d"))
  12947. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12948. (date (if rel default today))
  12949. (wday (nth 6 (decode-time date)))
  12950. delta)
  12951. (if wday1
  12952. (progn
  12953. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12954. (when (= delta 0) (setq delta 7))
  12955. (when (= dir ?-)
  12956. (setq delta (- delta 7))
  12957. (when (= delta 0) (setq delta -7)))
  12958. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12959. (list delta "d" rel))
  12960. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12961. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12962. "Turn a user-specified date into the internal representation.
  12963. The internal representation needed by the calendar is (month day year).
  12964. This is a wrapper to handle the brain-dead convention in calendar that
  12965. user function argument order change dependent on argument order."
  12966. (pcase calendar-date-style
  12967. (`american (list arg1 arg2 arg3))
  12968. (`european (list arg2 arg1 arg3))
  12969. (`iso (list arg2 arg3 arg1))))
  12970. (defun org-eval-in-calendar (form &optional keepdate)
  12971. "Eval FORM in the calendar window and return to current window.
  12972. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12973. (let ((sf (selected-frame))
  12974. (sw (selected-window)))
  12975. (select-window (get-buffer-window "*Calendar*" t))
  12976. (eval form)
  12977. (when (and (not keepdate) (calendar-cursor-to-date))
  12978. (let* ((date (calendar-cursor-to-date))
  12979. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12980. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12981. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12982. (select-window sw)
  12983. (select-frame-set-input-focus sf)))
  12984. (defun org-calendar-select ()
  12985. "Return to `org-read-date' with the date currently selected.
  12986. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12987. (interactive)
  12988. (when (calendar-cursor-to-date)
  12989. (let* ((date (calendar-cursor-to-date))
  12990. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12991. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12992. (when (active-minibuffer-window) (exit-minibuffer))))
  12993. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12994. "Insert a date stamp for the date given by the internal TIME.
  12995. See `format-time-string' for the format of TIME.
  12996. WITH-HM means use the stamp format that includes the time of the day.
  12997. INACTIVE means use square brackets instead of angular ones, so that the
  12998. stamp will not contribute to the agenda.
  12999. PRE and POST are optional strings to be inserted before and after the
  13000. stamp.
  13001. The command returns the inserted time stamp."
  13002. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13003. stamp)
  13004. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13005. (insert-before-markers (or pre ""))
  13006. (when (listp extra)
  13007. (setq extra (car extra))
  13008. (if (and (stringp extra)
  13009. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13010. (setq extra (format "-%02d:%02d"
  13011. (string-to-number (match-string 1 extra))
  13012. (string-to-number (match-string 2 extra))))
  13013. (setq extra nil)))
  13014. (when extra
  13015. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13016. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13017. (insert-before-markers (or post ""))
  13018. (setq org-last-inserted-timestamp stamp)))
  13019. (defun org-toggle-time-stamp-overlays ()
  13020. "Toggle the use of custom time stamp formats."
  13021. (interactive)
  13022. (setq org-display-custom-times (not org-display-custom-times))
  13023. (unless org-display-custom-times
  13024. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13025. (while (setq p (next-single-property-change p 'display))
  13026. (when (and (get-text-property p 'display)
  13027. (eq (get-text-property p 'face) 'org-date))
  13028. (remove-text-properties
  13029. p (setq p (next-single-property-change p 'display))
  13030. '(display t))))
  13031. (set-buffer-modified-p bmp)))
  13032. (org-restart-font-lock)
  13033. (setq org-table-may-need-update t)
  13034. (if org-display-custom-times
  13035. (message "Time stamps are overlaid with custom format")
  13036. (message "Time stamp overlays removed")))
  13037. (defun org-display-custom-time (beg end)
  13038. "Overlay modified time stamp format over timestamp between BEG and END."
  13039. (let* ((ts (buffer-substring beg end))
  13040. t1 with-hm tf time str (off 0))
  13041. (save-match-data
  13042. (setq t1 (org-parse-time-string ts t))
  13043. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13044. (setq off (- (match-end 0) (match-beginning 0)))))
  13045. (setq end (- end off))
  13046. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13047. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13048. time (org-fix-decoded-time t1)
  13049. str (org-add-props
  13050. (format-time-string
  13051. (substring tf 1 -1) (apply 'encode-time time))
  13052. nil 'mouse-face 'highlight))
  13053. (put-text-property beg end 'display str)))
  13054. (defun org-fix-decoded-time (time)
  13055. "Set 0 instead of nil for the first 6 elements of time.
  13056. Don't touch the rest."
  13057. (let ((n 0))
  13058. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13059. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13060. "Difference between TIMESTAMP-STRING and now in days.
  13061. If SECONDS is non-nil, return the difference in seconds."
  13062. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13063. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13064. (funcall fdiff nil))))
  13065. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13066. "Is the time in TIMESTAMP-STRING close to the current date?"
  13067. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13068. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13069. (not (org-entry-is-done-p))))
  13070. (defun org-get-wdays (ts &optional delay zero-delay)
  13071. "Get the deadline lead time appropriate for timestring TS.
  13072. When DELAY is non-nil, get the delay time for scheduled items
  13073. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13074. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13075. don't try to find the delay cookie in the scheduled timestamp."
  13076. (let ((tv (if delay org-scheduled-delay-days
  13077. org-deadline-warning-days)))
  13078. (cond
  13079. ((or (and delay (< tv 0))
  13080. (and delay zero-delay (<= tv 0))
  13081. (and (not delay) (<= tv 0)))
  13082. ;; Enforce this value no matter what
  13083. (- tv))
  13084. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13085. ;; lead time is specified.
  13086. (floor (* (string-to-number (match-string 1 ts))
  13087. (cdr (assoc (match-string 2 ts)
  13088. '(("d" . 1) ("w" . 7)
  13089. ("m" . 30.4) ("y" . 365.25)
  13090. ("h" . 0.041667)))))))
  13091. ;; go for the default.
  13092. (t tv))))
  13093. (defun org-calendar-select-mouse (ev)
  13094. "Return to `org-read-date' with the date currently selected.
  13095. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13096. (interactive "e")
  13097. (mouse-set-point ev)
  13098. (when (calendar-cursor-to-date)
  13099. (let* ((date (calendar-cursor-to-date))
  13100. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13101. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13102. (when (active-minibuffer-window) (exit-minibuffer))))
  13103. (defun org-check-deadlines (ndays)
  13104. "Check if there are any deadlines due or past due.
  13105. A deadline is considered due if it happens within `org-deadline-warning-days'
  13106. days from today's date. If the deadline appears in an entry marked DONE,
  13107. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13108. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13109. are shown."
  13110. (interactive "P")
  13111. (let* ((org-warn-days
  13112. (cond
  13113. ((equal ndays '(4)) 100000)
  13114. (ndays (prefix-numeric-value ndays))
  13115. (t (abs org-deadline-warning-days))))
  13116. (case-fold-search nil)
  13117. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13118. (callback
  13119. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13120. (message "%d deadlines past-due or due within %d days"
  13121. (org-occur regexp nil callback)
  13122. org-warn-days)))
  13123. (defsubst org-re-timestamp (type)
  13124. "Return a regexp for timestamp TYPE.
  13125. Allowed values for TYPE are:
  13126. all: all timestamps
  13127. active: only active timestamps (<...>)
  13128. inactive: only inactive timestamps ([...])
  13129. scheduled: only scheduled timestamps
  13130. deadline: only deadline timestamps
  13131. closed: only closed time-stamps
  13132. When TYPE is nil, fall back on returning a regexp that matches
  13133. both scheduled and deadline timestamps."
  13134. (cl-case type
  13135. (all org-ts-regexp-both)
  13136. (active org-ts-regexp)
  13137. (inactive org-ts-regexp-inactive)
  13138. (scheduled org-scheduled-time-regexp)
  13139. (deadline org-deadline-time-regexp)
  13140. (closed org-closed-time-regexp)
  13141. (otherwise
  13142. (concat "\\<"
  13143. (regexp-opt (list org-deadline-string org-scheduled-string))
  13144. " *<\\([^>]+\\)>"))))
  13145. (defun org-check-before-date (d)
  13146. "Check if there are deadlines or scheduled entries before date D."
  13147. (interactive (list (org-read-date)))
  13148. (let* ((case-fold-search nil)
  13149. (regexp (org-re-timestamp org-ts-type))
  13150. (ts-type org-ts-type)
  13151. (callback
  13152. (lambda ()
  13153. (let ((match (match-string 1)))
  13154. (and (if (memq ts-type '(active inactive all))
  13155. (eq (org-element-type (save-excursion
  13156. (backward-char)
  13157. (org-element-context)))
  13158. 'timestamp)
  13159. (org-at-planning-p))
  13160. (time-less-p
  13161. (org-time-string-to-time match)
  13162. (org-time-string-to-time d)))))))
  13163. (message "%d entries before %s"
  13164. (org-occur regexp nil callback)
  13165. d)))
  13166. (defun org-check-after-date (d)
  13167. "Check if there are deadlines or scheduled entries after date D."
  13168. (interactive (list (org-read-date)))
  13169. (let* ((case-fold-search nil)
  13170. (regexp (org-re-timestamp org-ts-type))
  13171. (ts-type org-ts-type)
  13172. (callback
  13173. (lambda ()
  13174. (let ((match (match-string 1)))
  13175. (and (if (memq ts-type '(active inactive all))
  13176. (eq (org-element-type (save-excursion
  13177. (backward-char)
  13178. (org-element-context)))
  13179. 'timestamp)
  13180. (org-at-planning-p))
  13181. (not (time-less-p
  13182. (org-time-string-to-time match)
  13183. (org-time-string-to-time d))))))))
  13184. (message "%d entries after %s"
  13185. (org-occur regexp nil callback)
  13186. d)))
  13187. (defun org-check-dates-range (start-date end-date)
  13188. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13189. (interactive (list (org-read-date nil nil nil "Range starts")
  13190. (org-read-date nil nil nil "Range end")))
  13191. (let ((case-fold-search nil)
  13192. (regexp (org-re-timestamp org-ts-type))
  13193. (callback
  13194. (let ((type org-ts-type))
  13195. (lambda ()
  13196. (let ((match (match-string 1)))
  13197. (and
  13198. (if (memq type '(active inactive all))
  13199. (eq (org-element-type (save-excursion
  13200. (backward-char)
  13201. (org-element-context)))
  13202. 'timestamp)
  13203. (org-at-planning-p))
  13204. (not (time-less-p
  13205. (org-time-string-to-time match)
  13206. (org-time-string-to-time start-date)))
  13207. (time-less-p
  13208. (org-time-string-to-time match)
  13209. (org-time-string-to-time end-date))))))))
  13210. (message "%d entries between %s and %s"
  13211. (org-occur regexp nil callback) start-date end-date)))
  13212. (defun org-evaluate-time-range (&optional to-buffer)
  13213. "Evaluate a time range by computing the difference between start and end.
  13214. Normally the result is just printed in the echo area, but with prefix arg
  13215. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13216. If the time range is actually in a table, the result is inserted into the
  13217. next column.
  13218. For time difference computation, a year is assumed to be exactly 365
  13219. days in order to avoid rounding problems."
  13220. (interactive "P")
  13221. (or
  13222. (org-clock-update-time-maybe)
  13223. (save-excursion
  13224. (unless (org-at-date-range-p t)
  13225. (goto-char (point-at-bol))
  13226. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13227. (unless (org-at-date-range-p t)
  13228. (user-error "Not at a time-stamp range, and none found in current line")))
  13229. (let* ((ts1 (match-string 1))
  13230. (ts2 (match-string 2))
  13231. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13232. (match-end (match-end 0))
  13233. (time1 (org-time-string-to-time ts1))
  13234. (time2 (org-time-string-to-time ts2))
  13235. (diff (abs (float-time (time-subtract time2 time1))))
  13236. (negative (time-less-p time2 time1))
  13237. ;; (ys (floor (* 365 24 60 60)))
  13238. (ds (* 24 60 60))
  13239. (hs (* 60 60))
  13240. (fy "%dy %dd %02d:%02d")
  13241. (fy1 "%dy %dd")
  13242. (fd "%dd %02d:%02d")
  13243. (fd1 "%dd")
  13244. (fh "%02d:%02d")
  13245. y d h m align)
  13246. (if havetime
  13247. (setq ; y (floor diff ys) diff (mod diff ys)
  13248. y 0
  13249. d (floor diff ds) diff (mod diff ds)
  13250. h (floor diff hs) diff (mod diff hs)
  13251. m (floor diff 60))
  13252. (setq ; y (floor diff ys) diff (mod diff ys)
  13253. y 0
  13254. d (round diff ds)
  13255. h 0 m 0))
  13256. (if (not to-buffer)
  13257. (message "%s" (org-make-tdiff-string y d h m))
  13258. (if (org-at-table-p)
  13259. (progn
  13260. (goto-char match-end)
  13261. (setq align t)
  13262. (and (looking-at " *|") (goto-char (match-end 0))))
  13263. (goto-char match-end))
  13264. (when (looking-at
  13265. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13266. (replace-match ""))
  13267. (when negative (insert " -"))
  13268. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13269. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13270. (insert " " (format fh h m))))
  13271. (when align (org-table-align))
  13272. (message "Time difference inserted")))))
  13273. (defun org-make-tdiff-string (y d h m)
  13274. (let ((fmt "")
  13275. (l nil))
  13276. (when (> y 0)
  13277. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13278. (push y l))
  13279. (when (> d 0)
  13280. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13281. (push d l))
  13282. (when (> h 0)
  13283. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13284. (push h l))
  13285. (when (> m 0)
  13286. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13287. (push m l))
  13288. (apply 'format fmt (nreverse l))))
  13289. (defun org-time-string-to-time (s)
  13290. "Convert timestamp string S into internal time."
  13291. (apply #'encode-time (org-parse-time-string s)))
  13292. (defun org-time-string-to-seconds (s)
  13293. "Convert a timestamp string S into a number of seconds."
  13294. (float-time (org-time-string-to-time s)))
  13295. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13296. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13297. "Convert time stamp S to an absolute day number.
  13298. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13299. stamp, get the closest date to DAYNR. If PREFER is
  13300. `past' (respectively `future') return a date past (respectively
  13301. after) or equal to DAYNR.
  13302. POS is the location of time stamp S, as a buffer position in
  13303. BUFFER.
  13304. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13305. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13306. signaled."
  13307. (cond
  13308. ((string-match "\\`%%\\((.*)\\)" s)
  13309. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13310. ;; only able to match individual dates. If it fails, raise an
  13311. ;; error.
  13312. (if (and daynr
  13313. (org-diary-sexp-entry
  13314. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13315. daynr
  13316. (signal 'org-diary-sexp-no-match (list s))))
  13317. (daynr (org-closest-date s daynr prefer))
  13318. (t (time-to-days
  13319. (condition-case errdata
  13320. (org-time-string-to-time s)
  13321. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13322. s
  13323. (if (not (and buffer pos)) ""
  13324. (format-message " at %d in buffer `%s'" pos buffer))
  13325. (cdr errdata))))))))
  13326. (defun org-days-to-iso-week (days)
  13327. "Return the ISO week number."
  13328. (require 'cal-iso)
  13329. (car (calendar-iso-from-absolute days)))
  13330. (defun org-small-year-to-year (year)
  13331. "Convert 2-digit years into 4-digit years.
  13332. YEAR is expanded into one of the 30 next years, if possible, or
  13333. into a past one. Any year larger than 99 is returned unchanged."
  13334. (if (>= year 100) year
  13335. (let* ((current (string-to-number (format-time-string "%Y")))
  13336. (century (/ current 100))
  13337. (offset (- year (% current 100))))
  13338. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13339. ((> offset -70) (+ (* century 100) year))
  13340. (t (+ (* (1+ century) 100) year))))))
  13341. (defun org-time-from-absolute (d)
  13342. "Return the time corresponding to date D.
  13343. D may be an absolute day number, or a calendar-type list (month day year)."
  13344. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13345. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13346. (defvar org-agenda-current-date)
  13347. (defun org-calendar-holiday ()
  13348. "List of holidays, for Diary display in Org mode."
  13349. (require 'holidays)
  13350. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13351. (and hl (mapconcat #'identity hl "; "))))
  13352. (defun org-diary-sexp-entry (sexp entry d)
  13353. "Process a SEXP diary ENTRY for date D."
  13354. (require 'diary-lib)
  13355. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13356. ;; dynamically.
  13357. (let* ((sexp `(let ((entry ,entry)
  13358. (date ',d))
  13359. ,(car (read-from-string sexp))))
  13360. (result (if calendar-debug-sexp (eval sexp)
  13361. (condition-case nil
  13362. (eval sexp)
  13363. (error
  13364. (beep)
  13365. (message "Bad sexp at line %d in %s: %s"
  13366. (org-current-line)
  13367. (buffer-file-name) sexp)
  13368. (sleep-for 2))))))
  13369. (cond ((stringp result) (split-string result "; "))
  13370. ((and (consp result)
  13371. (not (consp (cdr result)))
  13372. (stringp (cdr result))) (cdr result))
  13373. ((and (consp result)
  13374. (stringp (car result))) result)
  13375. (result entry))))
  13376. (defun org-diary-to-ical-string (frombuf)
  13377. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13378. This uses the icalendar.el library."
  13379. (let* ((tmpdir temporary-file-directory)
  13380. (tmpfile (make-temp-name
  13381. (expand-file-name "orgics" tmpdir)))
  13382. buf rtn b e)
  13383. (with-current-buffer frombuf
  13384. (icalendar-export-region (point-min) (point-max) tmpfile)
  13385. (setq buf (find-buffer-visiting tmpfile))
  13386. (set-buffer buf)
  13387. (goto-char (point-min))
  13388. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13389. (setq b (match-beginning 0)))
  13390. (goto-char (point-max))
  13391. (when (re-search-backward "^END:VEVENT" nil t)
  13392. (setq e (match-end 0)))
  13393. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13394. (kill-buffer buf)
  13395. (delete-file tmpfile)
  13396. rtn))
  13397. (defun org-closest-date (start current prefer)
  13398. "Return closest date to CURRENT starting from START.
  13399. CURRENT and START are both time stamps.
  13400. When PREFER is `past', return a date that is either CURRENT or
  13401. past. When PREFER is `future', return a date that is either
  13402. CURRENT or future.
  13403. Only time stamps with a repeater are modified. Any other time
  13404. stamp stay unchanged. In any case, return value is an absolute
  13405. day number."
  13406. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13407. ;; No repeater. Do not shift time stamp.
  13408. (time-to-days (org-time-string-to-time start))
  13409. (let ((value (string-to-number (match-string 1 start)))
  13410. (type (match-string 2 start)))
  13411. (if (= 0 value)
  13412. ;; Repeater with a 0-value is considered as void.
  13413. (time-to-days (org-time-string-to-time start))
  13414. (let* ((base (org-date-to-gregorian start))
  13415. (target (org-date-to-gregorian current))
  13416. (sday (calendar-absolute-from-gregorian base))
  13417. (cday (calendar-absolute-from-gregorian target))
  13418. n1 n2)
  13419. ;; If START is already past CURRENT, just return START.
  13420. (if (<= cday sday) sday
  13421. ;; Compute closest date before (N1) and closest date past
  13422. ;; (N2) CURRENT.
  13423. (pcase type
  13424. ("h"
  13425. (let ((missing-hours
  13426. (mod (+ (- (* 24 (- cday sday))
  13427. (nth 2 (org-parse-time-string start)))
  13428. org-extend-today-until)
  13429. value)))
  13430. (setf n1 (if (= missing-hours 0) cday
  13431. (- cday (1+ (/ missing-hours 24)))))
  13432. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13433. ((or "d" "w")
  13434. (let ((value (if (equal type "w") (* 7 value) value)))
  13435. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13436. (setf n2 (+ n1 value))))
  13437. ("m"
  13438. (let* ((add-months
  13439. (lambda (d n)
  13440. ;; Add N months to gregorian date D, i.e.,
  13441. ;; a list (MONTH DAY YEAR). Return a valid
  13442. ;; gregorian date.
  13443. (let ((m (+ (nth 0 d) n)))
  13444. (list (mod m 12)
  13445. (nth 1 d)
  13446. (+ (/ m 12) (nth 2 d))))))
  13447. (months ; Complete months to TARGET.
  13448. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13449. (- (nth 0 target) (nth 0 base))
  13450. ;; If START's day is greater than
  13451. ;; TARGET's, remove incomplete month.
  13452. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13453. value)
  13454. value))
  13455. (before (funcall add-months base months)))
  13456. (setf n1 (calendar-absolute-from-gregorian before))
  13457. (setf n2
  13458. (calendar-absolute-from-gregorian
  13459. (funcall add-months before value)))))
  13460. (_
  13461. (let* ((d (nth 1 base))
  13462. (m (nth 0 base))
  13463. (y (nth 2 base))
  13464. (years ; Complete years to TARGET.
  13465. (* (/ (- (nth 2 target)
  13466. y
  13467. ;; If START's month and day are
  13468. ;; greater than TARGET's, remove
  13469. ;; incomplete year.
  13470. (if (or (> (nth 0 target) m)
  13471. (and (= (nth 0 target) m)
  13472. (> (nth 1 target) d)))
  13473. 0
  13474. 1))
  13475. value)
  13476. value))
  13477. (before (list m d (+ y years))))
  13478. (setf n1 (calendar-absolute-from-gregorian before))
  13479. (setf n2 (calendar-absolute-from-gregorian
  13480. (list m d (+ (nth 2 before) value)))))))
  13481. ;; Handle PREFER parameter, if any.
  13482. (cond
  13483. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13484. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13485. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13486. (defun org-date-to-gregorian (d)
  13487. "Turn any specification of date D into a Gregorian date for the calendar."
  13488. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13489. ((and (listp d) (= (length d) 3)) d)
  13490. ((stringp d)
  13491. (let ((d (org-parse-time-string d)))
  13492. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13493. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13494. (defun org-timestamp-up (&optional arg)
  13495. "Increase the date item at the cursor by one.
  13496. If the cursor is on the year, change the year. If it is on the month,
  13497. the day or the time, change that. If the cursor is on the enclosing
  13498. bracket, change the timestamp type.
  13499. With prefix ARG, change by that many units."
  13500. (interactive "p")
  13501. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13502. (defun org-timestamp-down (&optional arg)
  13503. "Decrease the date item at the cursor by one.
  13504. If the cursor is on the year, change the year. If it is on the month,
  13505. the day or the time, change that. If the cursor is on the enclosing
  13506. bracket, change the timestamp type.
  13507. With prefix ARG, change by that many units."
  13508. (interactive "p")
  13509. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13510. (defun org-timestamp-up-day (&optional arg)
  13511. "Increase the date in the time stamp by one day.
  13512. With prefix ARG, change that many days."
  13513. (interactive "p")
  13514. (if (and (not (org-at-timestamp-p 'lax))
  13515. (org-at-heading-p))
  13516. (org-todo 'up)
  13517. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13518. (defun org-timestamp-down-day (&optional arg)
  13519. "Decrease the date in the time stamp by one day.
  13520. With prefix ARG, change that many days."
  13521. (interactive "p")
  13522. (if (and (not (org-at-timestamp-p 'lax))
  13523. (org-at-heading-p))
  13524. (org-todo 'down)
  13525. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13526. (defun org-at-timestamp-p (&optional extended)
  13527. "Non-nil if point is inside a timestamp.
  13528. By default, the function only consider syntactically valid active
  13529. timestamps. However, the caller may have a broader definition
  13530. for timestamps. As a consequence, optional argument EXTENDED can
  13531. be set to the following values
  13532. `inactive'
  13533. Include also syntactically valid inactive timestamps.
  13534. `agenda'
  13535. Include timestamps allowed in Agenda, i.e., those in
  13536. properties drawers, planning lines and clock lines.
  13537. `lax'
  13538. Ignore context. The function matches any part of the
  13539. document looking like a timestamp. This includes comments,
  13540. example blocks...
  13541. For backward-compatibility with Org 9.0, every other non-nil
  13542. value is equivalent to `inactive'.
  13543. When at a timestamp, return the position of the point as a symbol
  13544. among `bracket', `after', `year', `month', `hour', `minute',
  13545. `day' or a number of character from the last know part of the
  13546. time stamp.
  13547. When matching, the match groups are the following:
  13548. group 1: year
  13549. group 2: month
  13550. group 3: day number
  13551. group 4: day name
  13552. group 5: hours, if any
  13553. group 6: minutes, if any"
  13554. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13555. (pos (point))
  13556. (match?
  13557. (let ((boundaries (org-in-regexp regexp)))
  13558. (save-match-data
  13559. (cond ((null boundaries) nil)
  13560. ((eq extended 'lax) t)
  13561. (t
  13562. (or (and (eq extended 'agenda)
  13563. (or (org-at-planning-p)
  13564. (org-at-property-p)
  13565. (and (bound-and-true-p
  13566. org-agenda-include-inactive-timestamps)
  13567. (org-at-clock-log-p))))
  13568. (eq 'timestamp
  13569. (save-excursion
  13570. (when (= pos (cdr boundaries)) (forward-char -1))
  13571. (org-element-type (org-element-context)))))))))))
  13572. (cond
  13573. ((not match?) nil)
  13574. ((= pos (match-beginning 0)) 'bracket)
  13575. ;; Distinguish location right before the closing bracket from
  13576. ;; right after it.
  13577. ((= pos (1- (match-end 0))) 'bracket)
  13578. ((= pos (match-end 0)) 'after)
  13579. ((org-pos-in-match-range pos 2) 'year)
  13580. ((org-pos-in-match-range pos 3) 'month)
  13581. ((org-pos-in-match-range pos 7) 'hour)
  13582. ((org-pos-in-match-range pos 8) 'minute)
  13583. ((or (org-pos-in-match-range pos 4)
  13584. (org-pos-in-match-range pos 5)) 'day)
  13585. ((and (> pos (or (match-end 8) (match-end 5)))
  13586. (< pos (match-end 0)))
  13587. (- pos (or (match-end 8) (match-end 5))))
  13588. (t 'day))))
  13589. (defun org-toggle-timestamp-type ()
  13590. "Toggle the type (<active> or [inactive]) of a time stamp."
  13591. (interactive)
  13592. (when (org-at-timestamp-p 'lax)
  13593. (let ((beg (match-beginning 0)) (end (match-end 0))
  13594. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13595. (save-excursion
  13596. (goto-char beg)
  13597. (while (re-search-forward "[][<>]" end t)
  13598. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13599. t t)))
  13600. (message "Timestamp is now %sactive"
  13601. (if (equal (char-after beg) ?<) "" "in")))))
  13602. (defun org-at-clock-log-p ()
  13603. "Non-nil if point is on a clock log line."
  13604. (and (org-match-line org-clock-line-re)
  13605. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13606. (defvar org-clock-history) ; defined in org-clock.el
  13607. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13608. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13609. "Change the date in the time stamp at point.
  13610. The date is changed by N times WHAT. WHAT can be `day', `month',
  13611. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13612. position in the timestamp determines what is changed.
  13613. When optional argument UPDOWN is non-nil, minutes are rounded
  13614. according to `org-time-stamp-rounding-minutes'.
  13615. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13616. \"--2d\"."
  13617. (let ((origin (point))
  13618. (timestamp? (org-at-timestamp-p 'lax))
  13619. origin-cat
  13620. with-hm inactive
  13621. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13622. extra rem
  13623. ts time time0 fixnext clrgx)
  13624. (unless timestamp? (user-error "Not at a timestamp"))
  13625. (if (and (not what) (eq timestamp? 'bracket))
  13626. (org-toggle-timestamp-type)
  13627. ;; Point isn't on brackets. Remember the part of the time-stamp
  13628. ;; the point was in. Indeed, size of time-stamps may change,
  13629. ;; but point must be kept in the same category nonetheless.
  13630. (setq origin-cat timestamp?)
  13631. (when (and (not what) (not (eq timestamp? 'day))
  13632. org-display-custom-times
  13633. (get-text-property (point) 'display)
  13634. (not (get-text-property (1- (point)) 'display)))
  13635. (setq timestamp? 'day))
  13636. (setq timestamp? (or what timestamp?)
  13637. inactive (= (char-after (match-beginning 0)) ?\[)
  13638. ts (match-string 0))
  13639. (replace-match "")
  13640. (when (string-match
  13641. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13642. ts)
  13643. (setq extra (match-string 1 ts))
  13644. (when suppress-tmp-delay
  13645. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13646. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13647. (setq with-hm t))
  13648. (setq time0 (org-parse-time-string ts))
  13649. (when (and updown
  13650. (eq timestamp? 'minute)
  13651. (not current-prefix-arg))
  13652. ;; This looks like s-up and s-down. Change by one rounding step.
  13653. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13654. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13655. (setcar (cdr time0) (+ (nth 1 time0)
  13656. (if (> n 0) (- rem) (- dm rem))))))
  13657. (setq time
  13658. (apply #'encode-time
  13659. (or (car time0) 0)
  13660. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13661. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13662. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13663. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13664. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13665. (nthcdr 6 time0)))
  13666. (when (and (memq timestamp? '(hour minute))
  13667. extra
  13668. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13669. (setq extra (org-modify-ts-extra
  13670. extra
  13671. (if (eq timestamp? 'hour) 2 5)
  13672. n dm)))
  13673. (when (integerp timestamp?)
  13674. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13675. (when (eq what 'calendar)
  13676. (let ((cal-date (org-get-date-from-calendar)))
  13677. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13678. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13679. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13680. (setcar time0 (or (car time0) 0))
  13681. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13682. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13683. (setq time (apply 'encode-time time0))))
  13684. ;; Insert the new time-stamp, and ensure point stays in the same
  13685. ;; category as before (i.e. not after the last position in that
  13686. ;; category).
  13687. (let ((pos (point)))
  13688. ;; Stay before inserted string. `save-excursion' is of no use.
  13689. (setq org-last-changed-timestamp
  13690. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13691. (goto-char pos))
  13692. (save-match-data
  13693. (looking-at org-ts-regexp3)
  13694. (goto-char
  13695. (pcase origin-cat
  13696. ;; `day' category ends before `hour' if any, or at the end
  13697. ;; of the day name.
  13698. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13699. (`hour (min (match-end 7) origin))
  13700. (`minute (min (1- (match-end 8)) origin))
  13701. ((pred integerp) (min (1- (match-end 0)) origin))
  13702. ;; Point was right after the time-stamp. However, the
  13703. ;; time-stamp length might have changed, so refer to
  13704. ;; (match-end 0) instead.
  13705. (`after (match-end 0))
  13706. ;; `year' and `month' have both fixed size: point couldn't
  13707. ;; have moved into another part.
  13708. (_ origin))))
  13709. ;; Update clock if on a CLOCK line.
  13710. (org-clock-update-time-maybe)
  13711. ;; Maybe adjust the closest clock in `org-clock-history'
  13712. (when org-clock-adjust-closest
  13713. (if (not (and (org-at-clock-log-p)
  13714. (< 1 (length (delq nil (mapcar 'marker-position
  13715. org-clock-history))))))
  13716. (message "No clock to adjust")
  13717. (cond ((save-excursion ; fix previous clock?
  13718. (re-search-backward org-ts-regexp0 nil t)
  13719. (looking-back (concat org-clock-string " \\[")
  13720. (line-beginning-position)))
  13721. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13722. ((save-excursion ; fix next clock?
  13723. (re-search-backward org-ts-regexp0 nil t)
  13724. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13725. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13726. (save-window-excursion
  13727. ;; Find closest clock to point, adjust the previous/next one in history
  13728. (let* ((p (save-excursion (org-back-to-heading t)))
  13729. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13730. (clfixnth
  13731. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13732. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13733. (if (not clfixpos)
  13734. (message "No clock to adjust")
  13735. (save-excursion
  13736. (org-goto-marker-or-bmk clfixpos)
  13737. (org-show-subtree)
  13738. (when (re-search-forward clrgx nil t)
  13739. (goto-char (match-beginning 1))
  13740. (let (org-clock-adjust-closest)
  13741. (org-timestamp-change n timestamp? updown))
  13742. (message "Clock adjusted in %s for heading: %s"
  13743. (file-name-nondirectory (buffer-file-name))
  13744. (org-get-heading t t)))))))))
  13745. ;; Try to recenter the calendar window, if any.
  13746. (when (and org-calendar-follow-timestamp-change
  13747. (get-buffer-window "*Calendar*" t)
  13748. (memq timestamp? '(day month year)))
  13749. (org-recenter-calendar (time-to-days time))))))
  13750. (defun org-modify-ts-extra (s pos n dm)
  13751. "Change the different parts of the lead-time and repeat fields in timestamp."
  13752. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13753. ng h m new rem)
  13754. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13755. (cond
  13756. ((or (org-pos-in-match-range pos 2)
  13757. (org-pos-in-match-range pos 3))
  13758. (setq m (string-to-number (match-string 3 s))
  13759. h (string-to-number (match-string 2 s)))
  13760. (if (org-pos-in-match-range pos 2)
  13761. (setq h (+ h n))
  13762. (setq n (* dm (with-no-warnings (cl-signum n))))
  13763. (unless (= 0 (setq rem (% m dm)))
  13764. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13765. (setq m (+ m n)))
  13766. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13767. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13768. (setq h (mod h 24))
  13769. (setq ng 1 new (format "-%02d:%02d" h m)))
  13770. ((org-pos-in-match-range pos 6)
  13771. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13772. ((org-pos-in-match-range pos 5)
  13773. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13774. ((org-pos-in-match-range pos 9)
  13775. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13776. ((org-pos-in-match-range pos 8)
  13777. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13778. (when ng
  13779. (setq s (concat
  13780. (substring s 0 (match-beginning ng))
  13781. new
  13782. (substring s (match-end ng))))))
  13783. s))
  13784. (defun org-recenter-calendar (d)
  13785. "If the calendar is visible, recenter it to date D."
  13786. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13787. (when cwin
  13788. (let ((calendar-move-hook nil))
  13789. (with-selected-window cwin
  13790. (calendar-goto-date
  13791. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13792. (defun org-goto-calendar (&optional arg)
  13793. "Go to the Emacs calendar at the current date.
  13794. If there is a time stamp in the current line, go to that date.
  13795. A prefix ARG can be used to force the current date."
  13796. (interactive "P")
  13797. (let ((calendar-move-hook nil)
  13798. (calendar-view-holidays-initially-flag nil)
  13799. (calendar-view-diary-initially-flag nil)
  13800. diff)
  13801. (when (or (org-at-timestamp-p 'lax)
  13802. (org-match-line (concat ".*" org-ts-regexp)))
  13803. (let ((d1 (time-to-days nil))
  13804. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13805. (setq diff (- d2 d1))))
  13806. (calendar)
  13807. (calendar-goto-today)
  13808. (when (and diff (not arg)) (calendar-forward-day diff))))
  13809. (defun org-get-date-from-calendar ()
  13810. "Return a list (month day year) of date at point in calendar."
  13811. (with-current-buffer "*Calendar*"
  13812. (save-match-data
  13813. (calendar-cursor-to-date))))
  13814. (defun org-date-from-calendar ()
  13815. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13816. If there is already a time stamp at the cursor position, update it."
  13817. (interactive)
  13818. (if (org-at-timestamp-p 'lax)
  13819. (org-timestamp-change 0 'calendar)
  13820. (let ((cal-date (org-get-date-from-calendar)))
  13821. (org-insert-time-stamp
  13822. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13823. (defcustom org-image-actual-width t
  13824. "When non-nil, use the actual width of images when inlining them.
  13825. When set to a number, use imagemagick (when available) to set the
  13826. image's width to this value.
  13827. When set to a number in a list, try to get the width from any
  13828. #+ATTR.* keyword if it matches a width specification like
  13829. #+ATTR_HTML: :width 300px
  13830. and fall back on that number if none is found.
  13831. When set to nil, try to get the width from an #+ATTR.* keyword
  13832. and fall back on the original width if none is found.
  13833. When set to any other non-nil value, always use the image width.
  13834. This requires Emacs >= 24.1, built with imagemagick support."
  13835. :group 'org-appearance
  13836. :version "24.4"
  13837. :package-version '(Org . "8.0")
  13838. :type '(choice
  13839. (const :tag "Use the image width" t)
  13840. (integer :tag "Use a number of pixels")
  13841. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13842. (const :tag "Use #+ATTR* or don't resize" nil)))
  13843. (defcustom org-agenda-inhibit-startup nil
  13844. "Inhibit startup when preparing agenda buffers.
  13845. When this variable is t, the initialization of the Org agenda
  13846. buffers is inhibited: e.g. the visibility state is not set, the
  13847. tables are not re-aligned, etc."
  13848. :type 'boolean
  13849. :version "24.3"
  13850. :group 'org-agenda)
  13851. (defcustom org-agenda-ignore-properties nil
  13852. "Avoid updating text properties when building the agenda.
  13853. Properties are used to prepare buffers for effort estimates,
  13854. appointments, statistics and subtree-local categories.
  13855. If you don't use these in the agenda, you can add them to this
  13856. list and agenda building will be a bit faster.
  13857. The value is a list, with zero or more of the symbols `effort', `appt',
  13858. `stats' or `category'."
  13859. :type '(set :greedy t
  13860. (const effort)
  13861. (const appt)
  13862. (const stats)
  13863. (const category))
  13864. :version "26.1"
  13865. :package-version '(Org . "8.3")
  13866. :group 'org-agenda)
  13867. ;;;; Files
  13868. (defun org-save-all-org-buffers ()
  13869. "Save all Org buffers without user confirmation."
  13870. (interactive)
  13871. (message "Saving all Org buffers...")
  13872. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13873. (when (featurep 'org-id) (org-id-locations-save))
  13874. (message "Saving all Org buffers... done"))
  13875. (defun org-revert-all-org-buffers ()
  13876. "Revert all Org buffers.
  13877. Prompt for confirmation when there are unsaved changes.
  13878. Be sure you know what you are doing before letting this function
  13879. overwrite your changes.
  13880. This function is useful in a setup where one tracks Org files
  13881. with a version control system, to revert on one machine after pulling
  13882. changes from another. I believe the procedure must be like this:
  13883. 1. M-x org-save-all-org-buffers
  13884. 2. Pull changes from the other machine, resolve conflicts
  13885. 3. M-x org-revert-all-org-buffers"
  13886. (interactive)
  13887. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13888. (user-error "Abort"))
  13889. (save-excursion
  13890. (save-window-excursion
  13891. (dolist (b (buffer-list))
  13892. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13893. (with-current-buffer b buffer-file-name))
  13894. (pop-to-buffer-same-window b)
  13895. (revert-buffer t 'no-confirm)))
  13896. (when (and (featurep 'org-id) org-id-track-globally)
  13897. (org-id-locations-load)))))
  13898. ;;;; Agenda files
  13899. ;;;###autoload
  13900. (defun org-switchb (&optional arg)
  13901. "Switch between Org buffers.
  13902. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13903. With `\\[universal-argument] \\[universal-argument]' \
  13904. prefix, restrict available buffers to agenda files."
  13905. (interactive "P")
  13906. (let ((blist (org-buffer-list
  13907. (cond ((equal arg '(4)) 'files)
  13908. ((equal arg '(16)) 'agenda)))))
  13909. (pop-to-buffer-same-window
  13910. (completing-read "Org buffer: "
  13911. (mapcar #'list (mapcar #'buffer-name blist))
  13912. nil t))))
  13913. (defun org-buffer-list (&optional predicate exclude-tmp)
  13914. "Return a list of Org buffers.
  13915. PREDICATE can be `export', `files' or `agenda'.
  13916. export restrict the list to Export buffers.
  13917. files restrict the list to buffers visiting Org files.
  13918. agenda restrict the list to buffers visiting agenda files.
  13919. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13920. (let* ((bfn nil)
  13921. (agenda-files (and (eq predicate 'agenda)
  13922. (mapcar 'file-truename (org-agenda-files t))))
  13923. (filter
  13924. (cond
  13925. ((eq predicate 'files)
  13926. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13927. ((eq predicate 'export)
  13928. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13929. ((eq predicate 'agenda)
  13930. (lambda (b)
  13931. (with-current-buffer b
  13932. (and (derived-mode-p 'org-mode)
  13933. (setq bfn (buffer-file-name b))
  13934. (member (file-truename bfn) agenda-files)))))
  13935. (t (lambda (b) (with-current-buffer b
  13936. (or (derived-mode-p 'org-mode)
  13937. (string-match "\\*Org .*Export"
  13938. (buffer-name b)))))))))
  13939. (delq nil
  13940. (mapcar
  13941. (lambda(b)
  13942. (if (and (funcall filter b)
  13943. (or (not exclude-tmp)
  13944. (not (string-match "tmp" (buffer-name b)))))
  13945. b
  13946. nil))
  13947. (buffer-list)))))
  13948. (defun org-agenda-files (&optional unrestricted archives)
  13949. "Get the list of agenda files.
  13950. Optional UNRESTRICTED means return the full list even if a restriction
  13951. is currently in place.
  13952. When ARCHIVES is t, include all archive files that are really being
  13953. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13954. `org-agenda-archives-mode' is t."
  13955. (let ((files
  13956. (cond
  13957. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13958. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13959. ((listp org-agenda-files) org-agenda-files)
  13960. (t (error "Invalid value of `org-agenda-files'")))))
  13961. (setq files (apply 'append
  13962. (mapcar (lambda (f)
  13963. (if (file-directory-p f)
  13964. (directory-files
  13965. f t org-agenda-file-regexp)
  13966. (list f)))
  13967. files)))
  13968. (when org-agenda-skip-unavailable-files
  13969. (setq files (delq nil
  13970. (mapcar (lambda (file)
  13971. (and (file-readable-p file) file))
  13972. files))))
  13973. (when (or (eq archives t)
  13974. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13975. (setq files (org-add-archive-files files)))
  13976. files))
  13977. (defun org-agenda-file-p (&optional file)
  13978. "Return non-nil, if FILE is an agenda file.
  13979. If FILE is omitted, use the file associated with the current
  13980. buffer."
  13981. (let ((fname (or file (buffer-file-name))))
  13982. (and fname
  13983. (member (file-truename fname)
  13984. (mapcar #'file-truename (org-agenda-files t))))))
  13985. (defun org-edit-agenda-file-list ()
  13986. "Edit the list of agenda files.
  13987. Depending on setup, this either uses customize to edit the variable
  13988. `org-agenda-files', or it visits the file that is holding the list. In the
  13989. latter case, the buffer is set up in a way that saving it automatically kills
  13990. the buffer and restores the previous window configuration."
  13991. (interactive)
  13992. (if (stringp org-agenda-files)
  13993. (let ((cw (current-window-configuration)))
  13994. (find-file org-agenda-files)
  13995. (setq-local org-window-configuration cw)
  13996. (add-hook 'after-save-hook
  13997. (lambda ()
  13998. (set-window-configuration
  13999. (prog1 org-window-configuration
  14000. (kill-buffer (current-buffer))))
  14001. (org-install-agenda-files-menu)
  14002. (message "New agenda file list installed"))
  14003. nil 'local)
  14004. (message "%s" (substitute-command-keys
  14005. "Edit list and finish with \\[save-buffer]")))
  14006. (customize-variable 'org-agenda-files)))
  14007. (defun org-store-new-agenda-file-list (list)
  14008. "Set new value for the agenda file list and save it correctly."
  14009. (if (stringp org-agenda-files)
  14010. (let ((fe (org-read-agenda-file-list t)) b u)
  14011. (while (setq b (find-buffer-visiting org-agenda-files))
  14012. (kill-buffer b))
  14013. (with-temp-file org-agenda-files
  14014. (insert
  14015. (mapconcat
  14016. (lambda (f) ;; Keep un-expanded entries.
  14017. (if (setq u (assoc f fe))
  14018. (cdr u)
  14019. f))
  14020. list "\n")
  14021. "\n")))
  14022. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14023. (org-insert-mode-line-in-empty-file nil))
  14024. (setq org-agenda-files list)
  14025. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14026. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14027. "Read the list of agenda files from a file.
  14028. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14029. filenames, used by `org-store-new-agenda-file-list' to write back
  14030. un-expanded file names."
  14031. (when (file-directory-p org-agenda-files)
  14032. (error "`org-agenda-files' cannot be a single directory"))
  14033. (when (stringp org-agenda-files)
  14034. (with-temp-buffer
  14035. (insert-file-contents org-agenda-files)
  14036. (mapcar
  14037. (lambda (f)
  14038. (let ((e (expand-file-name (substitute-in-file-name f)
  14039. org-directory)))
  14040. (if pair-with-expansion
  14041. (cons e f)
  14042. e)))
  14043. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14044. ;;;###autoload
  14045. (defun org-cycle-agenda-files ()
  14046. "Cycle through the files in `org-agenda-files'.
  14047. If the current buffer visits an agenda file, find the next one in the list.
  14048. If the current buffer does not, find the first agenda file."
  14049. (interactive)
  14050. (let* ((fs (or (org-agenda-files t)
  14051. (user-error "No agenda files")))
  14052. (files (copy-sequence fs))
  14053. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14054. file)
  14055. (when tcf
  14056. (while (and (setq file (pop files))
  14057. (not (equal (file-truename file) tcf)))))
  14058. (find-file (car (or files fs)))
  14059. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14060. (defun org-agenda-file-to-front (&optional to-end)
  14061. "Move/add the current file to the top of the agenda file list.
  14062. If the file is not present in the list, it is added to the front. If it is
  14063. present, it is moved there. With optional argument TO-END, add/move to the
  14064. end of the list."
  14065. (interactive "P")
  14066. (let ((org-agenda-skip-unavailable-files nil)
  14067. (file-alist (mapcar (lambda (x)
  14068. (cons (file-truename x) x))
  14069. (org-agenda-files t)))
  14070. (ctf (file-truename
  14071. (or buffer-file-name
  14072. (user-error "Please save the current buffer to a file"))))
  14073. x had)
  14074. (setq x (assoc ctf file-alist) had x)
  14075. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14076. (if to-end
  14077. (setq file-alist (append (delq x file-alist) (list x)))
  14078. (setq file-alist (cons x (delq x file-alist))))
  14079. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14080. (org-install-agenda-files-menu)
  14081. (message "File %s to %s of agenda file list"
  14082. (if had "moved" "added") (if to-end "end" "front"))))
  14083. (defun org-remove-file (&optional file)
  14084. "Remove current file from the list of files in variable `org-agenda-files'.
  14085. These are the files which are being checked for agenda entries.
  14086. Optional argument FILE means use this file instead of the current."
  14087. (interactive)
  14088. (let* ((org-agenda-skip-unavailable-files nil)
  14089. (file (or file buffer-file-name
  14090. (user-error "Current buffer does not visit a file")))
  14091. (true-file (file-truename file))
  14092. (afile (abbreviate-file-name file))
  14093. (files (delq nil (mapcar
  14094. (lambda (x)
  14095. (unless (equal true-file
  14096. (file-truename x))
  14097. x))
  14098. (org-agenda-files t)))))
  14099. (if (not (= (length files) (length (org-agenda-files t))))
  14100. (progn
  14101. (org-store-new-agenda-file-list files)
  14102. (org-install-agenda-files-menu)
  14103. (message "Removed from Org Agenda list: %s" afile))
  14104. (message "File was not in list: %s (not removed)" afile))))
  14105. (defun org-file-menu-entry (file)
  14106. (vector file (list 'find-file file) t))
  14107. (defun org-check-agenda-file (file)
  14108. "Make sure FILE exists. If not, ask user what to do."
  14109. (unless (file-exists-p file)
  14110. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14111. (abbreviate-file-name file))
  14112. (let ((r (downcase (read-char-exclusive))))
  14113. (cond
  14114. ((equal r ?r)
  14115. (org-remove-file file)
  14116. (throw 'nextfile t))
  14117. (t (user-error "Abort"))))))
  14118. (defun org-get-agenda-file-buffer (file)
  14119. "Get an agenda buffer visiting FILE.
  14120. If the buffer needs to be created, add it to the list of buffers
  14121. which might be released later."
  14122. (let ((buf (org-find-base-buffer-visiting file)))
  14123. (if buf
  14124. buf ; just return it
  14125. ;; Make a new buffer and remember it
  14126. (setq buf (find-file-noselect file))
  14127. (when buf (push buf org-agenda-new-buffers))
  14128. buf)))
  14129. (defun org-release-buffers (blist)
  14130. "Release all buffers in list, asking the user for confirmation when needed.
  14131. When a buffer is unmodified, it is just killed. When modified, it is saved
  14132. \(if the user agrees) and then killed."
  14133. (let (file)
  14134. (dolist (buf blist)
  14135. (setq file (buffer-file-name buf))
  14136. (when (and (buffer-modified-p buf)
  14137. file
  14138. (y-or-n-p (format "Save file %s? " file)))
  14139. (with-current-buffer buf (save-buffer)))
  14140. (kill-buffer buf))))
  14141. (defun org-agenda-prepare-buffers (files)
  14142. "Create buffers for all agenda files, protect archived trees and comments."
  14143. (interactive)
  14144. (let ((pa '(:org-archived t))
  14145. (pc '(:org-comment t))
  14146. (pall '(:org-archived t :org-comment t))
  14147. (inhibit-read-only t)
  14148. (org-inhibit-startup org-agenda-inhibit-startup)
  14149. (rea (org-make-tag-string (list org-archive-tag)))
  14150. re pos)
  14151. (setq org-tag-alist-for-agenda nil
  14152. org-tag-groups-alist-for-agenda nil)
  14153. (save-excursion
  14154. (save-restriction
  14155. (dolist (file files)
  14156. (catch 'nextfile
  14157. (if (bufferp file)
  14158. (set-buffer file)
  14159. (org-check-agenda-file file)
  14160. (set-buffer (org-get-agenda-file-buffer file)))
  14161. (widen)
  14162. (org-set-regexps-and-options 'tags-only)
  14163. (setq pos (point))
  14164. (or (memq 'category org-agenda-ignore-properties)
  14165. (org-refresh-category-properties))
  14166. (or (memq 'stats org-agenda-ignore-properties)
  14167. (org-refresh-stats-properties))
  14168. (or (memq 'effort org-agenda-ignore-properties)
  14169. (org-refresh-effort-properties))
  14170. (or (memq 'appt org-agenda-ignore-properties)
  14171. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14172. (setq org-todo-keywords-for-agenda
  14173. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14174. (setq org-done-keywords-for-agenda
  14175. (append org-done-keywords-for-agenda org-done-keywords))
  14176. (setq org-todo-keyword-alist-for-agenda
  14177. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14178. (setq org-tag-alist-for-agenda
  14179. (org--tag-add-to-alist
  14180. org-tag-alist-for-agenda
  14181. org-current-tag-alist))
  14182. ;; Merge current file's tag groups into global
  14183. ;; `org-tag-groups-alist-for-agenda'.
  14184. (when org-group-tags
  14185. (dolist (alist org-tag-groups-alist)
  14186. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14187. (if old
  14188. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14189. (push alist org-tag-groups-alist-for-agenda)))))
  14190. (with-silent-modifications
  14191. (save-excursion
  14192. (remove-text-properties (point-min) (point-max) pall)
  14193. (when org-agenda-skip-archived-trees
  14194. (goto-char (point-min))
  14195. (while (re-search-forward rea nil t)
  14196. (when (org-at-heading-p t)
  14197. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14198. (goto-char (point-min))
  14199. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14200. (while (re-search-forward re nil t)
  14201. (when (save-match-data (org-in-commented-heading-p t))
  14202. (add-text-properties
  14203. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14204. (goto-char pos)))))
  14205. (setq org-todo-keywords-for-agenda
  14206. (org-uniquify org-todo-keywords-for-agenda))
  14207. (setq org-todo-keyword-alist-for-agenda
  14208. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14209. ;;;; CDLaTeX minor mode
  14210. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14211. "Keymap for the minor `org-cdlatex-mode'.")
  14212. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14213. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14214. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14215. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14216. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14217. (defvar org-cdlatex-texmathp-advice-is-done nil
  14218. "Flag remembering if we have applied the advice to texmathp already.")
  14219. (define-minor-mode org-cdlatex-mode
  14220. "Toggle the minor `org-cdlatex-mode'.
  14221. This mode supports entering LaTeX environment and math in LaTeX fragments
  14222. in Org mode.
  14223. \\{org-cdlatex-mode-map}"
  14224. nil " OCDL" nil
  14225. (when org-cdlatex-mode
  14226. (require 'cdlatex)
  14227. (run-hooks 'cdlatex-mode-hook)
  14228. (cdlatex-compute-tables))
  14229. (unless org-cdlatex-texmathp-advice-is-done
  14230. (setq org-cdlatex-texmathp-advice-is-done t)
  14231. (defadvice texmathp (around org-math-always-on activate)
  14232. "Always return t in Org buffers.
  14233. This is because we want to insert math symbols without dollars even outside
  14234. the LaTeX math segments. If Org mode thinks that point is actually inside
  14235. an embedded LaTeX fragment, let `texmathp' do its job.
  14236. `\\[org-cdlatex-mode-map]'"
  14237. (interactive)
  14238. (let (p)
  14239. (cond
  14240. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14241. ((eq this-command 'cdlatex-math-symbol)
  14242. (setq ad-return-value t
  14243. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14244. (t
  14245. (let ((p (org-inside-LaTeX-fragment-p)))
  14246. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14247. (setq ad-return-value t
  14248. texmathp-why '("Org mode embedded math" . 0))
  14249. (when p ad-do-it)))))))))
  14250. (defun turn-on-org-cdlatex ()
  14251. "Unconditionally turn on `org-cdlatex-mode'."
  14252. (org-cdlatex-mode 1))
  14253. (defun org-try-cdlatex-tab ()
  14254. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14255. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14256. - inside a LaTeX fragment, or
  14257. - after the first word in a line, where an abbreviation expansion could
  14258. insert a LaTeX environment."
  14259. (when org-cdlatex-mode
  14260. (cond
  14261. ;; Before any word on the line: No expansion possible.
  14262. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14263. ;; Just after first word on the line: Expand it. Make sure it
  14264. ;; cannot happen on headlines, though.
  14265. ((save-excursion
  14266. (skip-chars-backward "a-zA-Z0-9*")
  14267. (skip-chars-backward " \t")
  14268. (and (bolp) (not (org-at-heading-p))))
  14269. (cdlatex-tab) t)
  14270. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14271. (defun org-cdlatex-underscore-caret (&optional _arg)
  14272. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14273. Revert to the normal definition outside of these fragments."
  14274. (interactive "P")
  14275. (if (org-inside-LaTeX-fragment-p)
  14276. (call-interactively 'cdlatex-sub-superscript)
  14277. (let (org-cdlatex-mode)
  14278. (call-interactively (key-binding (vector last-input-event))))))
  14279. (defun org-cdlatex-math-modify (&optional _arg)
  14280. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14281. Revert to the normal definition outside of these fragments."
  14282. (interactive "P")
  14283. (if (org-inside-LaTeX-fragment-p)
  14284. (call-interactively 'cdlatex-math-modify)
  14285. (let (org-cdlatex-mode)
  14286. (call-interactively (key-binding (vector last-input-event))))))
  14287. (defun org-cdlatex-environment-indent (&optional environment item)
  14288. "Execute `cdlatex-environment' and indent the inserted environment.
  14289. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14290. The inserted environment is indented to current indentation
  14291. unless point is at the beginning of the line, in which the
  14292. environment remains unintended."
  14293. (interactive)
  14294. ;; cdlatex-environment always return nil. Therefore, capture output
  14295. ;; first and determine if an environment was selected.
  14296. (let* ((beg (point-marker))
  14297. (end (copy-marker (point) t))
  14298. (inserted (progn
  14299. (ignore-errors (cdlatex-environment environment item))
  14300. (< beg end)))
  14301. ;; Figure out how many lines to move forward after the
  14302. ;; environment has been inserted.
  14303. (lines (when inserted
  14304. (save-excursion
  14305. (- (cl-loop while (< beg (point))
  14306. with x = 0
  14307. do (forward-line -1)
  14308. (cl-incf x)
  14309. finally return x)
  14310. (if (progn (goto-char beg)
  14311. (and (progn (skip-chars-forward " \t") (eolp))
  14312. (progn (skip-chars-backward " \t") (bolp))))
  14313. 1 0)))))
  14314. (env (org-trim (delete-and-extract-region beg end))))
  14315. (when inserted
  14316. ;; Get indentation of next line unless at column 0.
  14317. (let ((ind (if (bolp) 0
  14318. (save-excursion
  14319. (org-return t)
  14320. (prog1 (current-indentation)
  14321. (when (progn (skip-chars-forward " \t") (eolp))
  14322. (delete-region beg (point)))))))
  14323. (bol (progn (skip-chars-backward " \t") (bolp))))
  14324. ;; Insert a newline before environment unless at column zero
  14325. ;; to "escape" the current line. Insert a newline if
  14326. ;; something is one the same line as \end{ENVIRONMENT}.
  14327. (insert
  14328. (concat (unless bol "\n") env
  14329. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14330. (unless (zerop ind)
  14331. (save-excursion
  14332. (goto-char beg)
  14333. (while (< (point) end)
  14334. (unless (eolp) (indent-line-to ind))
  14335. (forward-line))))
  14336. (goto-char beg)
  14337. (forward-line lines)
  14338. (indent-line-to ind)))
  14339. (set-marker beg nil)
  14340. (set-marker end nil)))
  14341. ;;;; LaTeX fragments
  14342. (defun org-inside-LaTeX-fragment-p ()
  14343. "Test if point is inside a LaTeX fragment.
  14344. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14345. sequence appearing also before point.
  14346. Even though the matchers for math are configurable, this function assumes
  14347. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14348. delimiters are skipped when they have been removed by customization.
  14349. The return value is nil, or a cons cell with the delimiter and the
  14350. position of this delimiter.
  14351. This function does a reasonably good job, but can locally be fooled by
  14352. for example currency specifications. For example it will assume being in
  14353. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14354. fragments that are properly closed, but during editing, we have to live
  14355. with the uncertainty caused by missing closing delimiters. This function
  14356. looks only before point, not after."
  14357. (catch 'exit
  14358. (let ((pos (point))
  14359. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14360. (lim (progn
  14361. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14362. 'move)
  14363. (point)))
  14364. dd-on str (start 0) m re)
  14365. (goto-char pos)
  14366. (when dodollar
  14367. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14368. re (nth 1 (assoc "$" org-latex-regexps)))
  14369. (while (string-match re str start)
  14370. (cond
  14371. ((= (match-end 0) (length str))
  14372. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14373. ((= (match-end 0) (- (length str) 5))
  14374. (throw 'exit nil))
  14375. (t (setq start (match-end 0))))))
  14376. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14377. (goto-char pos)
  14378. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14379. (and (match-beginning 2) (throw 'exit nil))
  14380. ;; count $$
  14381. (while (re-search-backward "\\$\\$" lim t)
  14382. (setq dd-on (not dd-on)))
  14383. (goto-char pos)
  14384. (when dd-on (cons "$$" m))))))
  14385. (defun org-inside-latex-macro-p ()
  14386. "Is point inside a LaTeX macro or its arguments?"
  14387. (save-match-data
  14388. (org-in-regexp
  14389. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14390. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14391. "Build an overlay between BEG and END using IMAGE file.
  14392. Argument IMAGETYPE is the extension of the displayed image,
  14393. as a string. It defaults to \"png\"."
  14394. (let ((ov (make-overlay beg end))
  14395. (imagetype (or (intern imagetype) 'png)))
  14396. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14397. (overlay-put ov 'evaporate t)
  14398. (overlay-put ov
  14399. 'modification-hooks
  14400. (list (lambda (o _flag _beg _end &optional _l)
  14401. (delete-overlay o))))
  14402. (overlay-put ov
  14403. 'display
  14404. (list 'image :type imagetype :file image :ascent 'center))))
  14405. (defun org-clear-latex-preview (&optional beg end)
  14406. "Remove all overlays with LaTeX fragment images in current buffer.
  14407. When optional arguments BEG and END are non-nil, remove all
  14408. overlays between them instead. Return a non-nil value when some
  14409. overlays were removed, nil otherwise."
  14410. (let ((overlays
  14411. (cl-remove-if-not
  14412. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14413. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14414. (mapc #'delete-overlay overlays)
  14415. overlays))
  14416. (defun org--latex-preview-region (beg end)
  14417. "Preview LaTeX fragments between BEG and END.
  14418. BEG and END are buffer positions."
  14419. (let ((file (buffer-file-name (buffer-base-buffer))))
  14420. (save-excursion
  14421. (org-format-latex
  14422. (concat org-preview-latex-image-directory "org-ltximg")
  14423. beg end
  14424. ;; Emacs cannot overlay images from remote hosts. Create it in
  14425. ;; `temporary-file-directory' instead.
  14426. (if (or (not file) (file-remote-p file))
  14427. temporary-file-directory
  14428. default-directory)
  14429. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14430. (defun org-latex-preview (&optional arg)
  14431. "Toggle preview of the LaTeX fragment at point.
  14432. If the cursor is on a LaTeX fragment, create the image and
  14433. overlay it over the source code, if there is none. Remove it
  14434. otherwise. If there is no fragment at point, display images for
  14435. all fragments in the current section.
  14436. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14437. for all fragments
  14438. in the current section.
  14439. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14440. argument ARG, display image for all
  14441. fragments in the buffer.
  14442. With a `\\[universal-argument] \\[universal-argument] \
  14443. \\[universal-argument]' prefix argument ARG, clear image for all
  14444. fragments in the buffer."
  14445. (interactive "P")
  14446. (cond
  14447. ((not (display-graphic-p)) nil)
  14448. ;; Clear whole buffer.
  14449. ((equal arg '(64))
  14450. (org-clear-latex-preview (point-min) (point-max))
  14451. (message "LaTeX previews removed from buffer"))
  14452. ;; Preview whole buffer.
  14453. ((equal arg '(16))
  14454. (message "Creating LaTeX previews in buffer...")
  14455. (org--latex-preview-region (point-min) (point-max))
  14456. (message "Creating LaTeX previews in buffer... done."))
  14457. ;; Clear current section.
  14458. ((equal arg '(4))
  14459. (org-clear-latex-preview
  14460. (if (org-before-first-heading-p) (point-min)
  14461. (save-excursion
  14462. (org-with-limited-levels (org-back-to-heading t) (point))))
  14463. (org-with-limited-levels (org-entry-end-position))))
  14464. ;; Toggle preview on LaTeX code at point.
  14465. ((let ((datum (org-element-context)))
  14466. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14467. (let ((beg (org-element-property :begin datum))
  14468. (end (org-element-property :end datum)))
  14469. (if (org-clear-latex-preview beg end)
  14470. (message "LaTeX preview removed")
  14471. (message "Creating LaTeX preview...")
  14472. (org--latex-preview-region beg end)
  14473. (message "Creating LaTeX preview... done."))
  14474. t))))
  14475. ;; Preview current section.
  14476. (t
  14477. (let ((beg (if (org-before-first-heading-p) (point-min)
  14478. (save-excursion
  14479. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14480. (end (org-with-limited-levels (org-entry-end-position))))
  14481. (message "Creating LaTeX previews in section...")
  14482. (org--latex-preview-region beg end)
  14483. (message "Creating LaTeX previews in section... done.")))))
  14484. (defun org-format-latex
  14485. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14486. "Replace LaTeX fragments with links to an image.
  14487. The function takes care of creating the replacement image.
  14488. Only consider fragments between BEG and END when those are
  14489. provided.
  14490. When optional argument OVERLAYS is non-nil, display the image on
  14491. top of the fragment instead of replacing it.
  14492. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14493. Some of the options can be changed using the variable
  14494. `org-format-latex-options', which see."
  14495. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14496. (unless (eq processing-type 'verbatim)
  14497. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14498. (cnt 0)
  14499. checkdir-flag)
  14500. (goto-char (or beg (point-min)))
  14501. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14502. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14503. (overlay-recenter (or end (point-max))))
  14504. (while (re-search-forward math-regexp end t)
  14505. (unless (and overlays
  14506. (eq (get-char-property (point) 'org-overlay-type)
  14507. 'org-latex-overlay))
  14508. (let* ((context (org-element-context))
  14509. (type (org-element-type context)))
  14510. (when (memq type '(latex-environment latex-fragment))
  14511. (let ((block-type (eq type 'latex-environment))
  14512. (value (org-element-property :value context))
  14513. (beg (org-element-property :begin context))
  14514. (end (save-excursion
  14515. (goto-char (org-element-property :end context))
  14516. (skip-chars-backward " \r\t\n")
  14517. (point))))
  14518. (cond
  14519. ((eq processing-type 'mathjax)
  14520. ;; Prepare for MathJax processing.
  14521. (if (not (string-match "\\`\\$\\$?" value))
  14522. (goto-char end)
  14523. (delete-region beg end)
  14524. (if (string= (match-string 0 value) "$$")
  14525. (insert "\\[" (substring value 2 -2) "\\]")
  14526. (insert "\\(" (substring value 1 -1) "\\)"))))
  14527. ((eq processing-type 'html)
  14528. (goto-char beg)
  14529. (delete-region beg end)
  14530. (insert (org-format-latex-as-html value)))
  14531. ((assq processing-type org-preview-latex-process-alist)
  14532. ;; Process to an image.
  14533. (cl-incf cnt)
  14534. (goto-char beg)
  14535. (let* ((processing-info
  14536. (cdr (assq processing-type org-preview-latex-process-alist)))
  14537. (face (face-at-point))
  14538. ;; Get the colors from the face at point.
  14539. (fg
  14540. (let ((color (plist-get org-format-latex-options
  14541. :foreground)))
  14542. (if (and forbuffer (eq color 'auto))
  14543. (face-attribute face :foreground nil 'default)
  14544. color)))
  14545. (bg
  14546. (let ((color (plist-get org-format-latex-options
  14547. :background)))
  14548. (if (and forbuffer (eq color 'auto))
  14549. (face-attribute face :background nil 'default)
  14550. color)))
  14551. (hash (sha1 (prin1-to-string
  14552. (list org-format-latex-header
  14553. org-latex-default-packages-alist
  14554. org-latex-packages-alist
  14555. org-format-latex-options
  14556. forbuffer value fg bg))))
  14557. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14558. (absprefix (expand-file-name prefix dir))
  14559. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14560. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14561. (sep (and block-type "\n\n"))
  14562. (link (concat sep "[[file:" linkfile "]]" sep))
  14563. (options
  14564. (org-combine-plists
  14565. org-format-latex-options
  14566. `(:foreground ,fg :background ,bg))))
  14567. (when msg (message msg cnt))
  14568. (unless checkdir-flag ; Ensure the directory exists.
  14569. (setq checkdir-flag t)
  14570. (let ((todir (file-name-directory absprefix)))
  14571. (unless (file-directory-p todir)
  14572. (make-directory todir t))))
  14573. (unless (file-exists-p movefile)
  14574. (org-create-formula-image
  14575. value movefile options forbuffer processing-type))
  14576. (if overlays
  14577. (progn
  14578. (dolist (o (overlays-in beg end))
  14579. (when (eq (overlay-get o 'org-overlay-type)
  14580. 'org-latex-overlay)
  14581. (delete-overlay o)))
  14582. (org--make-preview-overlay beg end movefile imagetype)
  14583. (goto-char end))
  14584. (delete-region beg end)
  14585. (insert
  14586. (org-add-props link
  14587. (list 'org-latex-src
  14588. (replace-regexp-in-string "\"" "" value)
  14589. 'org-latex-src-embed-type
  14590. (if block-type 'paragraph 'character)))))))
  14591. ((eq processing-type 'mathml)
  14592. ;; Process to MathML.
  14593. (unless (org-format-latex-mathml-available-p)
  14594. (user-error "LaTeX to MathML converter not configured"))
  14595. (cl-incf cnt)
  14596. (when msg (message msg cnt))
  14597. (goto-char beg)
  14598. (delete-region beg end)
  14599. (insert (org-format-latex-as-mathml
  14600. value block-type prefix dir)))
  14601. (t
  14602. (error "Unknown conversion process %s for LaTeX fragments"
  14603. processing-type)))))))))))
  14604. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14605. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14606. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14607. successful, return the portion between \"<math...> </math>\"
  14608. elements otherwise return nil. When MATHML-FILE is specified,
  14609. write the results in to that file. When invoked as an
  14610. interactive command, prompt for LATEX-FRAG, with initial value
  14611. set to the current active region and echo the results for user
  14612. inspection."
  14613. (interactive (list (let ((frag (when (org-region-active-p)
  14614. (buffer-substring-no-properties
  14615. (region-beginning) (region-end)))))
  14616. (read-string "LaTeX Fragment: " frag nil frag))))
  14617. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14618. (let* ((tmp-in-file
  14619. (let ((file (file-relative-name
  14620. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14621. (write-region latex-frag nil file)
  14622. file))
  14623. (tmp-out-file (file-relative-name
  14624. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14625. (cmd (format-spec
  14626. org-latex-to-mathml-convert-command
  14627. `((?j . ,(and org-latex-to-mathml-jar-file
  14628. (shell-quote-argument
  14629. (expand-file-name
  14630. org-latex-to-mathml-jar-file))))
  14631. (?I . ,(shell-quote-argument tmp-in-file))
  14632. (?i . ,latex-frag)
  14633. (?o . ,(shell-quote-argument tmp-out-file)))))
  14634. mathml shell-command-output)
  14635. (when (called-interactively-p 'any)
  14636. (unless (org-format-latex-mathml-available-p)
  14637. (user-error "LaTeX to MathML converter not configured")))
  14638. (message "Running %s" cmd)
  14639. (setq shell-command-output (shell-command-to-string cmd))
  14640. (setq mathml
  14641. (when (file-readable-p tmp-out-file)
  14642. (with-current-buffer (find-file-noselect tmp-out-file t)
  14643. (goto-char (point-min))
  14644. (when (re-search-forward
  14645. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14646. (regexp-quote
  14647. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14648. nil t)
  14649. (prog1 (match-string 0) (kill-buffer))))))
  14650. (cond
  14651. (mathml
  14652. (setq mathml
  14653. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14654. (when mathml-file
  14655. (write-region mathml nil mathml-file))
  14656. (when (called-interactively-p 'any)
  14657. (message mathml)))
  14658. ((warn "LaTeX to MathML conversion failed")
  14659. (message shell-command-output)))
  14660. (delete-file tmp-in-file)
  14661. (when (file-exists-p tmp-out-file)
  14662. (delete-file tmp-out-file))
  14663. mathml))
  14664. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14665. prefix &optional dir)
  14666. "Use `org-create-math-formula' but check local cache first."
  14667. (let* ((absprefix (expand-file-name prefix dir))
  14668. (print-length nil) (print-level nil)
  14669. (formula-id (concat
  14670. "formula-"
  14671. (sha1
  14672. (prin1-to-string
  14673. (list latex-frag
  14674. org-latex-to-mathml-convert-command)))))
  14675. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14676. (formula-cache-dir (file-name-directory formula-cache)))
  14677. (unless (file-directory-p formula-cache-dir)
  14678. (make-directory formula-cache-dir t))
  14679. (unless (file-exists-p formula-cache)
  14680. (org-create-math-formula latex-frag formula-cache))
  14681. (if (file-exists-p formula-cache)
  14682. ;; Successful conversion. Return the link to MathML file.
  14683. (org-add-props
  14684. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14685. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14686. 'org-latex-src-embed-type (if latex-frag-type
  14687. 'paragraph 'character)))
  14688. ;; Failed conversion. Return the LaTeX fragment verbatim
  14689. latex-frag)))
  14690. (defun org-format-latex-as-html (latex-fragment)
  14691. "Convert LATEX-FRAGMENT to HTML.
  14692. This uses `org-latex-to-html-convert-command', which see."
  14693. (let ((cmd (format-spec org-latex-to-html-convert-command
  14694. `((?i . ,latex-fragment)))))
  14695. (message "Running %s" cmd)
  14696. (shell-command-to-string cmd)))
  14697. (defun org--get-display-dpi ()
  14698. "Get the DPI of the display.
  14699. The function assumes that the display has the same pixel width in
  14700. the horizontal and vertical directions."
  14701. (if (display-graphic-p)
  14702. (round (/ (display-pixel-height)
  14703. (/ (display-mm-height) 25.4)))
  14704. (error "Attempt to calculate the dpi of a non-graphic display")))
  14705. (defun org-create-formula-image
  14706. (string tofile options buffer &optional processing-type)
  14707. "Create an image from LaTeX source using external processes.
  14708. The LaTeX STRING is saved to a temporary LaTeX file, then
  14709. converted to an image file by process PROCESSING-TYPE defined in
  14710. `org-preview-latex-process-alist'. A nil value defaults to
  14711. `org-preview-latex-default-process'.
  14712. The generated image file is eventually moved to TOFILE.
  14713. The OPTIONS argument controls the size, foreground color and
  14714. background color of the generated image.
  14715. When BUFFER non-nil, this function is used for LaTeX previewing.
  14716. Otherwise, it is used to deal with LaTeX snippets showed in
  14717. a HTML file."
  14718. (let* ((processing-type (or processing-type
  14719. org-preview-latex-default-process))
  14720. (processing-info
  14721. (cdr (assq processing-type org-preview-latex-process-alist)))
  14722. (programs (plist-get processing-info :programs))
  14723. (error-message (or (plist-get processing-info :message) ""))
  14724. (image-input-type (plist-get processing-info :image-input-type))
  14725. (image-output-type (plist-get processing-info :image-output-type))
  14726. (post-clean (or (plist-get processing-info :post-clean)
  14727. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14728. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14729. (latex-header
  14730. (or (plist-get processing-info :latex-header)
  14731. (org-latex-make-preamble
  14732. (org-export-get-environment (org-export-get-backend 'latex))
  14733. org-format-latex-header
  14734. 'snippet)))
  14735. (latex-compiler (plist-get processing-info :latex-compiler))
  14736. (image-converter (plist-get processing-info :image-converter))
  14737. (tmpdir temporary-file-directory)
  14738. (texfilebase (make-temp-name
  14739. (expand-file-name "orgtex" tmpdir)))
  14740. (texfile (concat texfilebase ".tex"))
  14741. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14742. '(1.0 . 1.0)))
  14743. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14744. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14745. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14746. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14747. "Black"))
  14748. (bg (or (plist-get options (if buffer :background :html-background))
  14749. "Transparent"))
  14750. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14751. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14752. (dolist (program programs)
  14753. (org-check-external-command program error-message))
  14754. (if (eq fg 'default)
  14755. (setq fg (org-latex-color :foreground))
  14756. (setq fg (org-latex-color-format fg)))
  14757. (setq bg (cond
  14758. ((eq bg 'default) (org-latex-color :background))
  14759. ((string= bg "Transparent") nil)
  14760. (t (org-latex-color-format bg))))
  14761. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14762. (if (string-suffix-p string "\n")
  14763. (aset string (1- (length string)) ?%)
  14764. (setq string (concat string "%")))
  14765. (with-temp-file texfile
  14766. (insert latex-header)
  14767. (insert "\n\\begin{document}\n"
  14768. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14769. (if bg
  14770. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14771. "\n\\pagecolor{bg}%\n")
  14772. "")
  14773. "\n{\\color{fg}\n"
  14774. string
  14775. "\n}\n"
  14776. "\n\\end{document}\n"))
  14777. (let* ((err-msg (format "Please adjust `%s' part of \
  14778. `org-preview-latex-process-alist'."
  14779. processing-type))
  14780. (image-input-file
  14781. (org-compile-file
  14782. texfile latex-compiler image-input-type err-msg log-buf))
  14783. (image-output-file
  14784. (org-compile-file
  14785. image-input-file image-converter image-output-type err-msg log-buf
  14786. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14787. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14788. (copy-file image-output-file tofile 'replace)
  14789. (dolist (e post-clean)
  14790. (when (file-exists-p (concat texfilebase e))
  14791. (delete-file (concat texfilebase e))))
  14792. image-output-file)))
  14793. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14794. "Fill a LaTeX header template TPL.
  14795. In the template, the following place holders will be recognized:
  14796. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14797. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14798. [PACKAGES] \\usepackage statements for PKG
  14799. [NO-PACKAGES] do not include PKG
  14800. [EXTRA] the string EXTRA
  14801. [NO-EXTRA] do not include EXTRA
  14802. For backward compatibility, if both the positive and the negative place
  14803. holder is missing, the positive one (without the \"NO-\") will be
  14804. assumed to be present at the end of the template.
  14805. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14806. EXTRA is a string.
  14807. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14808. (let (rpl (end ""))
  14809. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14810. (setq rpl (if (or (match-end 1) (not def-pkg))
  14811. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14812. tpl (replace-match rpl t t tpl))
  14813. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14814. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14815. (setq rpl (if (or (match-end 1) (not pkg))
  14816. "" (org-latex-packages-to-string pkg snippets-p t))
  14817. tpl (replace-match rpl t t tpl))
  14818. (when pkg (setq end
  14819. (concat end "\n"
  14820. (org-latex-packages-to-string pkg snippets-p)))))
  14821. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14822. (setq rpl (if (or (match-end 1) (not extra))
  14823. "" (concat extra "\n"))
  14824. tpl (replace-match rpl t t tpl))
  14825. (when (and extra (string-match "\\S-" extra))
  14826. (setq end (concat end "\n" extra))))
  14827. (if (string-match "\\S-" end)
  14828. (concat tpl "\n" end)
  14829. tpl)))
  14830. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14831. "Turn an alist of packages into a string with the \\usepackage macros."
  14832. (setq pkg (mapconcat (lambda(p)
  14833. (cond
  14834. ((stringp p) p)
  14835. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14836. (format "%% Package %s omitted" (cadr p)))
  14837. ((equal "" (car p))
  14838. (format "\\usepackage{%s}" (cadr p)))
  14839. (t
  14840. (format "\\usepackage[%s]{%s}"
  14841. (car p) (cadr p)))))
  14842. pkg
  14843. "\n"))
  14844. (if newline (concat pkg "\n") pkg))
  14845. (defun org-dvipng-color (attr)
  14846. "Return a RGB color specification for dvipng."
  14847. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14848. (defun org-dvipng-color-format (color-name)
  14849. "Convert COLOR-NAME to a RGB color value for dvipng."
  14850. (apply #'format "rgb %s %s %s"
  14851. (mapcar 'org-normalize-color
  14852. (color-values color-name))))
  14853. (defun org-latex-color (attr)
  14854. "Return a RGB color for the LaTeX color package."
  14855. (org-latex-color-format (face-attribute 'default attr nil)))
  14856. (defun org-latex-color-format (color-name)
  14857. "Convert COLOR-NAME to a RGB color value."
  14858. (apply #'format "%s,%s,%s"
  14859. (mapcar 'org-normalize-color
  14860. (color-values color-name))))
  14861. (defun org-normalize-color (value)
  14862. "Return string to be used as color value for an RGB component."
  14863. (format "%g" (/ value 65535.0)))
  14864. ;; Image display
  14865. (defvar-local org-inline-image-overlays nil)
  14866. (defun org-toggle-inline-images (&optional include-linked)
  14867. "Toggle the display of inline images.
  14868. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14869. (interactive "P")
  14870. (if org-inline-image-overlays
  14871. (progn
  14872. (org-remove-inline-images)
  14873. (when (called-interactively-p 'interactive)
  14874. (message "Inline image display turned off")))
  14875. (org-display-inline-images include-linked)
  14876. (when (called-interactively-p 'interactive)
  14877. (message (if org-inline-image-overlays
  14878. (format "%d images displayed inline"
  14879. (length org-inline-image-overlays))
  14880. "No images to display inline")))))
  14881. (defun org-redisplay-inline-images ()
  14882. "Assure display of inline images and refresh them."
  14883. (interactive)
  14884. (org-toggle-inline-images)
  14885. (unless org-inline-image-overlays
  14886. (org-toggle-inline-images)))
  14887. ;; For without-x builds.
  14888. (declare-function image-refresh "image" (spec &optional frame))
  14889. (defcustom org-display-remote-inline-images 'skip
  14890. "How to display remote inline images.
  14891. Possible values of this option are:
  14892. skip Don't display remote images.
  14893. download Always download and display remote images.
  14894. cache Display remote images, and open them in separate buffers
  14895. for caching. Silently update the image buffer when a file
  14896. change is detected."
  14897. :group 'org-appearance
  14898. :package-version '(Org . "9.4")
  14899. :type '(choice
  14900. (const :tag "Ignore remote images" skip)
  14901. (const :tag "Always display remote images" download)
  14902. (const :tag "Display and silently update remote images" cache))
  14903. :safe #'symbolp)
  14904. (defun org--create-inline-image (file width)
  14905. "Create image located at FILE, or return nil.
  14906. WIDTH is the width of the image. The image may not be created
  14907. according to the value of `org-display-remote-inline-images'."
  14908. (let* ((remote? (file-remote-p file))
  14909. (file-or-data
  14910. (pcase org-display-remote-inline-images
  14911. ((guard (not remote?)) file)
  14912. (`download (with-temp-buffer
  14913. (set-buffer-multibyte nil)
  14914. (insert-file-contents-literally file)
  14915. (buffer-string)))
  14916. (`cache (let ((revert-without-query '(".")))
  14917. (with-current-buffer (find-file-noselect file)
  14918. (buffer-string))))
  14919. (`skip nil)
  14920. (other
  14921. (message "Invalid value of `org-display-remote-inline-images': %S"
  14922. other)
  14923. nil))))
  14924. (when file-or-data
  14925. (create-image file-or-data
  14926. (and (image-type-available-p 'imagemagick)
  14927. width
  14928. 'imagemagick)
  14929. remote?
  14930. :width width))))
  14931. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14932. "Display inline images.
  14933. An inline image is a link which follows either of these
  14934. conventions:
  14935. 1. Its path is a file with an extension matching return value
  14936. from `image-file-name-regexp' and it has no contents.
  14937. 2. Its description consists in a single link of the previous
  14938. type. In this case, that link must be a well-formed plain
  14939. or angle link, i.e., it must have an explicit \"file\" type.
  14940. Equip each image with the key-map `image-map'.
  14941. When optional argument INCLUDE-LINKED is non-nil, also links with
  14942. a text description part will be inlined. This can be nice for
  14943. a quick look at those images, but it does not reflect what
  14944. exported files will look like.
  14945. When optional argument REFRESH is non-nil, refresh existing
  14946. images between BEG and END. This will create new image displays
  14947. only if necessary.
  14948. BEG and END define the considered part. They default to the
  14949. buffer boundaries with possible narrowing."
  14950. (interactive "P")
  14951. (when (display-graphic-p)
  14952. (unless refresh
  14953. (org-remove-inline-images)
  14954. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14955. (let ((end (or end (point-max))))
  14956. (org-with-point-at (or beg (point-min))
  14957. (let* ((case-fold-search t)
  14958. (file-extension-re (image-file-name-regexp))
  14959. (link-abbrevs (mapcar #'car
  14960. (append org-link-abbrev-alist-local
  14961. org-link-abbrev-alist)))
  14962. ;; Check absolute, relative file names and explicit
  14963. ;; "file:" links. Also check link abbreviations since
  14964. ;; some might expand to "file" links.
  14965. (file-types-re
  14966. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14967. (if (not link-abbrevs) ""
  14968. (concat "\\|" (regexp-opt link-abbrevs))))))
  14969. (while (re-search-forward file-types-re end t)
  14970. (let* ((link (org-element-lineage
  14971. (save-match-data (org-element-context))
  14972. '(link) t))
  14973. (linktype (org-element-property :type link))
  14974. (inner-start (match-beginning 1))
  14975. (path
  14976. (cond
  14977. ;; No link at point; no inline image.
  14978. ((not link) nil)
  14979. ;; File link without a description. Also handle
  14980. ;; INCLUDE-LINKED here since it should have
  14981. ;; precedence over the next case. I.e., if link
  14982. ;; contains filenames in both the path and the
  14983. ;; description, prioritize the path only when
  14984. ;; INCLUDE-LINKED is non-nil.
  14985. ((or (not (org-element-property :contents-begin link))
  14986. include-linked)
  14987. (and (or (equal "file" linktype)
  14988. (equal "attachment" linktype))
  14989. (org-element-property :path link)))
  14990. ;; Link with a description. Check if description
  14991. ;; is a filename. Even if Org doesn't have syntax
  14992. ;; for those -- clickable image -- constructs, fake
  14993. ;; them, as in `org-export-insert-image-links'.
  14994. ((not inner-start) nil)
  14995. (t
  14996. (org-with-point-at inner-start
  14997. (and (looking-at
  14998. (if (char-equal ?< (char-after inner-start))
  14999. org-link-angle-re
  15000. org-link-plain-re))
  15001. ;; File name must fill the whole
  15002. ;; description.
  15003. (= (org-element-property :contents-end link)
  15004. (match-end 0))
  15005. (match-string 2)))))))
  15006. (when (and path (string-match-p file-extension-re path))
  15007. (let ((file (if (equal "attachment" linktype)
  15008. (progn
  15009. (require 'org-attach)
  15010. (ignore-errors (org-attach-expand path)))
  15011. (expand-file-name path))))
  15012. (when (and file (file-exists-p file))
  15013. (let ((width
  15014. ;; Apply `org-image-actual-width' specifications.
  15015. (cond
  15016. ((eq org-image-actual-width t) nil)
  15017. ((listp org-image-actual-width)
  15018. (or
  15019. ;; First try to find a width among
  15020. ;; attributes associated to the paragraph
  15021. ;; containing link.
  15022. (pcase (org-element-lineage link '(paragraph))
  15023. (`nil nil)
  15024. (p
  15025. (let* ((case-fold-search t)
  15026. (end (org-element-property :post-affiliated p))
  15027. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15028. (when (org-with-point-at
  15029. (org-element-property :begin p)
  15030. (re-search-forward re end t))
  15031. (string-to-number (match-string 1))))))
  15032. ;; Otherwise, fall-back to provided number.
  15033. (car org-image-actual-width)))
  15034. ((numberp org-image-actual-width)
  15035. org-image-actual-width)
  15036. (t nil)))
  15037. (old (get-char-property-and-overlay
  15038. (org-element-property :begin link)
  15039. 'org-image-overlay)))
  15040. (if (and (car-safe old) refresh)
  15041. (image-refresh (overlay-get (cdr old) 'display))
  15042. (let ((image (org--create-inline-image file width)))
  15043. (when image
  15044. (let ((ov (make-overlay
  15045. (org-element-property :begin link)
  15046. (progn
  15047. (goto-char
  15048. (org-element-property :end link))
  15049. (skip-chars-backward " \t")
  15050. (point)))))
  15051. (overlay-put ov 'display image)
  15052. (overlay-put ov 'face 'default)
  15053. (overlay-put ov 'org-image-overlay t)
  15054. (overlay-put
  15055. ov 'modification-hooks
  15056. (list 'org-display-inline-remove-overlay))
  15057. (when (<= 26 emacs-major-version)
  15058. (cl-assert (boundp 'image-map))
  15059. (overlay-put ov 'keymap image-map))
  15060. (push ov org-inline-image-overlays))))))))))))))))
  15061. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15062. "Remove inline-display overlay if a corresponding region is modified."
  15063. (let ((inhibit-modification-hooks t))
  15064. (when (and ov after)
  15065. (delete ov org-inline-image-overlays)
  15066. (delete-overlay ov))))
  15067. (defun org-remove-inline-images ()
  15068. "Remove inline display of images."
  15069. (interactive)
  15070. (mapc #'delete-overlay org-inline-image-overlays)
  15071. (setq org-inline-image-overlays nil))
  15072. (defvar org-self-insert-command-undo-counter 0)
  15073. (defvar org-speed-command nil)
  15074. (defun org-self-insert-command (N)
  15075. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15076. If the cursor is in a table looking at whitespace, the whitespace is
  15077. overwritten, and the table is not marked as requiring realignment."
  15078. (interactive "p")
  15079. (org-check-before-invisible-edit 'insert)
  15080. (cond
  15081. ((and org-use-speed-commands
  15082. (let ((kv (this-command-keys-vector)))
  15083. (setq org-speed-command
  15084. (run-hook-with-args-until-success
  15085. 'org-speed-command-hook
  15086. (make-string 1 (aref kv (1- (length kv))))))))
  15087. (cond
  15088. ((commandp org-speed-command)
  15089. (setq this-command org-speed-command)
  15090. (call-interactively org-speed-command))
  15091. ((functionp org-speed-command)
  15092. (funcall org-speed-command))
  15093. ((and org-speed-command (listp org-speed-command))
  15094. (eval org-speed-command))
  15095. (t (let (org-use-speed-commands)
  15096. (call-interactively 'org-self-insert-command)))))
  15097. ((and
  15098. (= N 1)
  15099. (not (org-region-active-p))
  15100. (org-at-table-p)
  15101. (progn
  15102. ;; Check if we blank the field, and if that triggers align.
  15103. (and (featurep 'org-table)
  15104. org-table-auto-blank-field
  15105. (memq last-command
  15106. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15107. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15108. ;; Got extra space, this field does not determine
  15109. ;; column width.
  15110. (let (org-table-may-need-update) (org-table-blank-field))
  15111. ;; No extra space, this field may determine column
  15112. ;; width.
  15113. (org-table-blank-field)))
  15114. t)
  15115. (looking-at "[^|\n]* |"))
  15116. ;; There is room for insertion without re-aligning the table.
  15117. (self-insert-command N)
  15118. (org-table-with-shrunk-field
  15119. (save-excursion
  15120. (skip-chars-forward "^|")
  15121. ;; Do not delete last space, which is
  15122. ;; `org-table-separator-space', but the regular space before
  15123. ;; it.
  15124. (delete-region (- (point) 2) (1- (point))))))
  15125. (t
  15126. (setq org-table-may-need-update t)
  15127. (self-insert-command N)
  15128. (org-fix-tags-on-the-fly)
  15129. (when org-self-insert-cluster-for-undo
  15130. (if (not (eq last-command 'org-self-insert-command))
  15131. (setq org-self-insert-command-undo-counter 1)
  15132. (if (>= org-self-insert-command-undo-counter 20)
  15133. (setq org-self-insert-command-undo-counter 1)
  15134. (and (> org-self-insert-command-undo-counter 0)
  15135. buffer-undo-list (listp buffer-undo-list)
  15136. (not (cadr buffer-undo-list)) ; remove nil entry
  15137. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15138. (setq org-self-insert-command-undo-counter
  15139. (1+ org-self-insert-command-undo-counter))))))))
  15140. (defun org-check-before-invisible-edit (kind)
  15141. "Check if editing kind KIND would be dangerous with invisible text around.
  15142. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15143. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15144. (when (and org-catch-invisible-edits
  15145. (or (not (boundp 'visible-mode)) (not visible-mode))
  15146. (or (get-char-property (point) 'invisible)
  15147. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15148. ;; OK, we need to take a closer look. Do not consider
  15149. ;; invisibility obtained through text properties (e.g., link
  15150. ;; fontification), as it cannot be toggled.
  15151. (let* ((invisible-at-point
  15152. (pcase (get-char-property-and-overlay (point) 'invisible)
  15153. (`(,_ . ,(and (pred overlayp) o)) o)))
  15154. ;; Assume that point cannot land in the middle of an
  15155. ;; overlay, or between two overlays.
  15156. (invisible-before-point
  15157. (and (not invisible-at-point)
  15158. (not (bobp))
  15159. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15160. (`(,_ . ,(and (pred overlayp) o)) o))))
  15161. (border-and-ok-direction
  15162. (or
  15163. ;; Check if we are acting predictably before invisible
  15164. ;; text.
  15165. (and invisible-at-point
  15166. (memq kind '(insert delete-backward)))
  15167. ;; Check if we are acting predictably after invisible text
  15168. ;; This works not well, and I have turned it off. It seems
  15169. ;; better to always show and stop after invisible text.
  15170. ;; (and (not invisible-at-point) invisible-before-point
  15171. ;; (memq kind '(insert delete)))
  15172. )))
  15173. (when (or invisible-at-point invisible-before-point)
  15174. (when (eq org-catch-invisible-edits 'error)
  15175. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15176. (if (and org-custom-properties-overlays
  15177. (y-or-n-p "Display invisible properties in this buffer? "))
  15178. (org-toggle-custom-properties-visibility)
  15179. ;; Make the area visible
  15180. (save-excursion
  15181. (when invisible-before-point
  15182. (goto-char
  15183. (previous-single-char-property-change (point) 'invisible)))
  15184. ;; Remove whatever overlay is currently making yet-to-be
  15185. ;; edited text invisible. Also remove nested invisibility
  15186. ;; related overlays.
  15187. (delete-overlay (or invisible-at-point invisible-before-point))
  15188. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15189. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15190. (`(,_ . ,(and (pred overlayp) o))
  15191. (delete-overlay o)
  15192. t)))))
  15193. (cond
  15194. ((eq org-catch-invisible-edits 'show)
  15195. ;; That's it, we do the edit after showing
  15196. (message
  15197. "Unfolding invisible region around point before editing")
  15198. (sit-for 1))
  15199. ((and (eq org-catch-invisible-edits 'smart)
  15200. border-and-ok-direction)
  15201. (message "Unfolding invisible region around point before editing"))
  15202. (t
  15203. ;; Don't do the edit, make the user repeat it in full visibility
  15204. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15205. (defun org-fix-tags-on-the-fly ()
  15206. "Align tags in headline at point.
  15207. Unlike `org-align-tags', this function does nothing if point is
  15208. either not currently on a tagged headline or on a tag."
  15209. (when (and (org-match-line org-tag-line-re)
  15210. (< (point) (match-beginning 1)))
  15211. (org-align-tags)))
  15212. (defun org-delete-backward-char (N)
  15213. "Like `delete-backward-char', insert whitespace at field end in tables.
  15214. When deleting backwards, in tables this function will insert whitespace in
  15215. front of the next \"|\" separator, to keep the table aligned. The table will
  15216. still be marked for re-alignment if the field did fill the entire column,
  15217. because, in this case the deletion might narrow the column."
  15218. (interactive "p")
  15219. (save-match-data
  15220. (org-check-before-invisible-edit 'delete-backward)
  15221. (if (and (= N 1)
  15222. (not overwrite-mode)
  15223. (not (org-region-active-p))
  15224. (not (eq (char-before) ?|))
  15225. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15226. (looking-at-p ".*?|")
  15227. (org-at-table-p))
  15228. (progn (forward-char -1) (org-delete-char 1))
  15229. (backward-delete-char N)
  15230. (org-fix-tags-on-the-fly))))
  15231. (defun org-delete-char (N)
  15232. "Like `delete-char', but insert whitespace at field end in tables.
  15233. When deleting characters, in tables this function will insert whitespace in
  15234. front of the next \"|\" separator, to keep the table aligned. The table will
  15235. still be marked for re-alignment if the field did fill the entire column,
  15236. because, in this case the deletion might narrow the column."
  15237. (interactive "p")
  15238. (save-match-data
  15239. (org-check-before-invisible-edit 'delete)
  15240. (cond
  15241. ((or (/= N 1)
  15242. (eq (char-after) ?|)
  15243. (save-excursion (skip-chars-backward " \t") (bolp))
  15244. (not (org-at-table-p)))
  15245. (delete-char N)
  15246. (org-fix-tags-on-the-fly))
  15247. ((looking-at ".\\(.*?\\)|")
  15248. (let* ((update? org-table-may-need-update)
  15249. (noalign (looking-at-p ".*? |")))
  15250. (delete-char 1)
  15251. (org-table-with-shrunk-field
  15252. (save-excursion
  15253. ;; Last space is `org-table-separator-space', so insert
  15254. ;; a regular one before it instead.
  15255. (goto-char (- (match-end 0) 2))
  15256. (insert " ")))
  15257. ;; If there were two spaces at the end, this field does not
  15258. ;; determine the width of the column.
  15259. (when noalign (setq org-table-may-need-update update?))))
  15260. (t
  15261. (delete-char N)))))
  15262. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15263. (put 'org-self-insert-command 'delete-selection
  15264. (lambda ()
  15265. (not (run-hook-with-args-until-success
  15266. 'self-insert-uses-region-functions))))
  15267. (put 'orgtbl-self-insert-command 'delete-selection
  15268. (lambda ()
  15269. (not (run-hook-with-args-until-success
  15270. 'self-insert-uses-region-functions))))
  15271. (put 'org-delete-char 'delete-selection 'supersede)
  15272. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15273. (put 'org-yank 'delete-selection 'yank)
  15274. ;; Make `flyspell-mode' delay after some commands
  15275. (put 'org-self-insert-command 'flyspell-delayed t)
  15276. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15277. (put 'org-delete-char 'flyspell-delayed t)
  15278. (put 'org-delete-backward-char 'flyspell-delayed t)
  15279. ;; Make pabbrev-mode expand after Org mode commands
  15280. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15281. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15282. (defun org-transpose-words ()
  15283. "Transpose words for Org.
  15284. This uses the `org-mode-transpose-word-syntax-table' syntax
  15285. table, which interprets characters in `org-emphasis-alist' as
  15286. word constituents."
  15287. (interactive)
  15288. (with-syntax-table org-mode-transpose-word-syntax-table
  15289. (call-interactively 'transpose-words)))
  15290. (defvar org-ctrl-c-ctrl-c-hook nil
  15291. "Hook for functions attaching themselves to `C-c C-c'.
  15292. This can be used to add additional functionality to the `C-c C-c'
  15293. key which executes context-dependent commands. This hook is run
  15294. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15295. run after the last test.
  15296. Each function will be called with no arguments. The function
  15297. must check if the context is appropriate for it to act. If yes,
  15298. it should do its thing and then return a non-nil value. If the
  15299. context is wrong, just do nothing and return nil.")
  15300. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15301. "Hook for functions attaching themselves to `C-c C-c'.
  15302. This can be used to add additional functionality to the `C-c C-c'
  15303. key which executes context-dependent commands. This hook is run
  15304. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15305. before the first test.
  15306. Each function will be called with no arguments. The function
  15307. must check if the context is appropriate for it to act. If yes,
  15308. it should do its thing and then return a non-nil value. If the
  15309. context is wrong, just do nothing and return nil.")
  15310. (defvar org-tab-first-hook nil
  15311. "Hook for functions to attach themselves to TAB.
  15312. See `org-ctrl-c-ctrl-c-hook' for more information.
  15313. This hook runs as the first action when TAB is pressed, even before
  15314. `org-cycle' messes around with the `outline-regexp' to cater for
  15315. inline tasks and plain list item folding.
  15316. If any function in this hook returns t, any other actions that
  15317. would have been caused by TAB (such as table field motion or visibility
  15318. cycling) will not occur.")
  15319. (defvar org-tab-after-check-for-table-hook nil
  15320. "Hook for functions to attach themselves to TAB.
  15321. See `org-ctrl-c-ctrl-c-hook' for more information.
  15322. This hook runs after it has been established that the cursor is not in a
  15323. table, but before checking if the cursor is in a headline or if global cycling
  15324. should be done.
  15325. If any function in this hook returns t, not other actions like visibility
  15326. cycling will be done.")
  15327. (defvar org-tab-after-check-for-cycling-hook nil
  15328. "Hook for functions to attach themselves to TAB.
  15329. See `org-ctrl-c-ctrl-c-hook' for more information.
  15330. This hook runs after it has been established that not table field motion and
  15331. not visibility should be done because of current context. This is probably
  15332. the place where a package like yasnippets can hook in.")
  15333. (defvar org-tab-before-tab-emulation-hook nil
  15334. "Hook for functions to attach themselves to TAB.
  15335. See `org-ctrl-c-ctrl-c-hook' for more information.
  15336. This hook runs after every other options for TAB have been exhausted, but
  15337. before indentation and \t insertion takes place.")
  15338. (defvar org-metaleft-hook nil
  15339. "Hook for functions attaching themselves to `M-left'.
  15340. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15341. (defvar org-metaright-hook nil
  15342. "Hook for functions attaching themselves to `M-right'.
  15343. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15344. (defvar org-metaup-hook nil
  15345. "Hook for functions attaching themselves to `M-up'.
  15346. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15347. (defvar org-metadown-hook nil
  15348. "Hook for functions attaching themselves to `M-down'.
  15349. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15350. (defvar org-shiftmetaleft-hook nil
  15351. "Hook for functions attaching themselves to `M-S-left'.
  15352. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15353. (defvar org-shiftmetaright-hook nil
  15354. "Hook for functions attaching themselves to `M-S-right'.
  15355. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15356. (defvar org-shiftmetaup-hook nil
  15357. "Hook for functions attaching themselves to `M-S-up'.
  15358. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15359. (defvar org-shiftmetadown-hook nil
  15360. "Hook for functions attaching themselves to `M-S-down'.
  15361. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15362. (defvar org-metareturn-hook nil
  15363. "Hook for functions attaching themselves to `M-RET'.
  15364. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15365. (defvar org-shiftup-hook nil
  15366. "Hook for functions attaching themselves to `S-up'.
  15367. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15368. (defvar org-shiftup-final-hook nil
  15369. "Hook for functions attaching themselves to `S-up'.
  15370. This one runs after all other options except shift-select have been excluded.
  15371. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15372. (defvar org-shiftdown-hook nil
  15373. "Hook for functions attaching themselves to `S-down'.
  15374. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15375. (defvar org-shiftdown-final-hook nil
  15376. "Hook for functions attaching themselves to `S-down'.
  15377. This one runs after all other options except shift-select have been excluded.
  15378. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15379. (defvar org-shiftleft-hook nil
  15380. "Hook for functions attaching themselves to `S-left'.
  15381. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15382. (defvar org-shiftleft-final-hook nil
  15383. "Hook for functions attaching themselves to `S-left'.
  15384. This one runs after all other options except shift-select have been excluded.
  15385. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15386. (defvar org-shiftright-hook nil
  15387. "Hook for functions attaching themselves to `S-right'.
  15388. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15389. (defvar org-shiftright-final-hook nil
  15390. "Hook for functions attaching themselves to `S-right'.
  15391. This one runs after all other options except shift-select have been excluded.
  15392. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15393. (defun org-modifier-cursor-error ()
  15394. "Throw an error, a modified cursor command was applied in wrong context."
  15395. (user-error "This command is active in special context like tables, headlines or items"))
  15396. (defun org-shiftselect-error ()
  15397. "Throw an error because Shift-Cursor command was applied in wrong context."
  15398. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15399. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15400. (user-error "This command works only in special context like headlines or timestamps")))
  15401. (defun org-call-for-shift-select (cmd)
  15402. (let ((this-command-keys-shift-translated t))
  15403. (call-interactively cmd)))
  15404. (defun org-shifttab (&optional arg)
  15405. "Global visibility cycling or move to previous table field.
  15406. Call `org-table-previous-field' within a table.
  15407. When ARG is nil, cycle globally through visibility states.
  15408. When ARG is a numeric prefix, show contents of this level."
  15409. (interactive "P")
  15410. (cond
  15411. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15412. ((integerp arg)
  15413. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15414. (message "Content view to level: %d" arg)
  15415. (org-content (prefix-numeric-value arg2))
  15416. (org-cycle-show-empty-lines t)
  15417. (setq org-cycle-global-status 'overview)
  15418. (run-hook-with-args 'org-cycle-hook 'overview)))
  15419. (t (call-interactively 'org-global-cycle))))
  15420. (defun org-shiftmetaleft ()
  15421. "Promote subtree or delete table column.
  15422. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15423. `org-table-delete-column', depending on context. See the
  15424. individual commands for more information."
  15425. (interactive)
  15426. (cond
  15427. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15428. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15429. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15430. ((if (not (org-region-active-p)) (org-at-item-p)
  15431. (save-excursion (goto-char (region-beginning))
  15432. (org-at-item-p)))
  15433. (call-interactively 'org-outdent-item-tree))
  15434. (t (org-modifier-cursor-error))))
  15435. (defun org-shiftmetaright ()
  15436. "Demote subtree or insert table column.
  15437. Calls `org-demote-subtree', `org-indent-item-tree', or
  15438. `org-table-insert-column', depending on context. See the
  15439. individual commands for more information."
  15440. (interactive)
  15441. (cond
  15442. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15443. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15444. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15445. ((if (not (org-region-active-p)) (org-at-item-p)
  15446. (save-excursion (goto-char (region-beginning))
  15447. (org-at-item-p)))
  15448. (call-interactively 'org-indent-item-tree))
  15449. (t (org-modifier-cursor-error))))
  15450. (defun org-shiftmetaup (&optional _arg)
  15451. "Drag the line at point up.
  15452. In a table, kill the current row.
  15453. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15454. but also adjust the previous clocked item in the clock history.
  15455. Everywhere else, drag the line at point up."
  15456. (interactive "P")
  15457. (cond
  15458. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15459. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15460. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15461. (call-interactively 'org-timestamp-up)))
  15462. (t (call-interactively 'org-drag-line-backward))))
  15463. (defun org-shiftmetadown (&optional _arg)
  15464. "Drag the line at point down.
  15465. In a table, insert an empty row at the current line.
  15466. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15467. but also adjust the previous clocked item in the clock history.
  15468. Everywhere else, drag the line at point down."
  15469. (interactive "P")
  15470. (cond
  15471. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15472. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15473. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15474. (call-interactively 'org-timestamp-down)))
  15475. (t (call-interactively 'org-drag-line-forward))))
  15476. (defsubst org-hidden-tree-error ()
  15477. (user-error
  15478. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15479. (defun org-metaleft (&optional _arg)
  15480. "Promote heading, list item at point or move table column left.
  15481. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15482. depending on context. With no specific context, calls the Emacs
  15483. default `backward-word'. See the individual commands for more
  15484. information.
  15485. This function runs the hook `org-metaleft-hook' as a first step,
  15486. and returns at first non-nil value."
  15487. (interactive "P")
  15488. (cond
  15489. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15490. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15491. ((org-with-limited-levels
  15492. (or (org-at-heading-p)
  15493. (and (org-region-active-p)
  15494. (save-excursion
  15495. (goto-char (region-beginning))
  15496. (org-at-heading-p)))))
  15497. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15498. (call-interactively 'org-do-promote))
  15499. ;; At an inline task.
  15500. ((org-at-heading-p)
  15501. (call-interactively 'org-inlinetask-promote))
  15502. ((or (org-at-item-p)
  15503. (and (org-region-active-p)
  15504. (save-excursion
  15505. (goto-char (region-beginning))
  15506. (org-at-item-p))))
  15507. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15508. (call-interactively 'org-outdent-item))
  15509. (t (call-interactively 'backward-word))))
  15510. (defun org-metaright (&optional _arg)
  15511. "Demote heading, list item at point or move table column right.
  15512. In front of a drawer or a block keyword, indent it correctly.
  15513. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15514. `org-indent-drawer' or `org-indent-block' depending on context.
  15515. With no specific context, calls the Emacs default `forward-word'.
  15516. See the individual commands for more information.
  15517. This function runs the hook `org-metaright-hook' as a first step,
  15518. and returns at first non-nil value."
  15519. (interactive "P")
  15520. (cond
  15521. ((run-hook-with-args-until-success 'org-metaright-hook))
  15522. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15523. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15524. ((org-at-block-p) (call-interactively 'org-indent-block))
  15525. ((org-with-limited-levels
  15526. (or (org-at-heading-p)
  15527. (and (org-region-active-p)
  15528. (save-excursion
  15529. (goto-char (region-beginning))
  15530. (org-at-heading-p)))))
  15531. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15532. (call-interactively 'org-do-demote))
  15533. ;; At an inline task.
  15534. ((org-at-heading-p)
  15535. (call-interactively 'org-inlinetask-demote))
  15536. ((or (org-at-item-p)
  15537. (and (org-region-active-p)
  15538. (save-excursion
  15539. (goto-char (region-beginning))
  15540. (org-at-item-p))))
  15541. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15542. (call-interactively 'org-indent-item))
  15543. (t (call-interactively 'forward-word))))
  15544. (defun org-check-for-hidden (what)
  15545. "Check if there are hidden headlines/items in the current visual line.
  15546. WHAT can be either `headlines' or `items'. If the current line is
  15547. an outline or item heading and it has a folded subtree below it,
  15548. this function returns t, nil otherwise."
  15549. (let ((re (cond
  15550. ((eq what 'headlines) org-outline-regexp-bol)
  15551. ((eq what 'items) (org-item-beginning-re))
  15552. (t (error "This should not happen"))))
  15553. beg end)
  15554. (save-excursion
  15555. (catch 'exit
  15556. (unless (org-region-active-p)
  15557. (setq beg (point-at-bol))
  15558. (beginning-of-line 2)
  15559. (while (and (not (eobp)) ;; this is like `next-line'
  15560. (get-char-property (1- (point)) 'invisible))
  15561. (beginning-of-line 2))
  15562. (setq end (point))
  15563. (goto-char beg)
  15564. (goto-char (point-at-eol))
  15565. (setq end (max end (point)))
  15566. (while (re-search-forward re end t)
  15567. (when (get-char-property (match-beginning 0) 'invisible)
  15568. (throw 'exit t))))
  15569. nil))))
  15570. (defun org-metaup (&optional _arg)
  15571. "Move subtree up or move table row up.
  15572. Calls `org-move-subtree-up' or `org-table-move-row' or
  15573. `org-move-item-up', depending on context. See the individual commands
  15574. for more information."
  15575. (interactive "P")
  15576. (cond
  15577. ((run-hook-with-args-until-success 'org-metaup-hook))
  15578. ((org-region-active-p)
  15579. (let* ((a (save-excursion
  15580. (goto-char (min (region-beginning) (region-end)))
  15581. (line-beginning-position)))
  15582. (b (save-excursion
  15583. (goto-char (max (region-beginning) (region-end)))
  15584. (if (bolp) (1- (point)) (line-end-position))))
  15585. (c (save-excursion
  15586. (goto-char a)
  15587. (move-beginning-of-line 0)
  15588. (point)))
  15589. (d (save-excursion
  15590. (goto-char a)
  15591. (move-end-of-line 0)
  15592. (point))))
  15593. (transpose-regions a b c d)
  15594. (goto-char c)))
  15595. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15596. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15597. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15598. (t (org-drag-element-backward))))
  15599. (defun org-metadown (&optional _arg)
  15600. "Move subtree down or move table row down.
  15601. Calls `org-move-subtree-down' or `org-table-move-row' or
  15602. `org-move-item-down', depending on context. See the individual
  15603. commands for more information."
  15604. (interactive "P")
  15605. (cond
  15606. ((run-hook-with-args-until-success 'org-metadown-hook))
  15607. ((org-region-active-p)
  15608. (let* ((a (save-excursion
  15609. (goto-char (min (region-beginning) (region-end)))
  15610. (line-beginning-position)))
  15611. (b (save-excursion
  15612. (goto-char (max (region-beginning) (region-end)))
  15613. (if (bolp) (1- (point)) (line-end-position))))
  15614. (c (save-excursion
  15615. (goto-char b)
  15616. (move-beginning-of-line (if (bolp) 1 2))
  15617. (point)))
  15618. (d (save-excursion
  15619. (goto-char b)
  15620. (move-end-of-line (if (bolp) 1 2))
  15621. (point))))
  15622. (transpose-regions a b c d)
  15623. (goto-char d)))
  15624. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15625. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15626. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15627. (t (org-drag-element-forward))))
  15628. (defun org-shiftup (&optional arg)
  15629. "Act on current element according to context.
  15630. Call `org-timestamp-up' or `org-priority-up', or
  15631. `org-previous-item', or `org-table-move-cell-up'. See the
  15632. individual commands for more information."
  15633. (interactive "P")
  15634. (cond
  15635. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15636. ((and org-support-shift-select (org-region-active-p))
  15637. (org-call-for-shift-select 'previous-line))
  15638. ((org-at-timestamp-p 'lax)
  15639. (call-interactively (if org-edit-timestamp-down-means-later
  15640. 'org-timestamp-down 'org-timestamp-up)))
  15641. ((and (not (eq org-support-shift-select 'always))
  15642. org-priority-enable-commands
  15643. (org-at-heading-p))
  15644. (call-interactively 'org-priority-up))
  15645. ((and (not org-support-shift-select) (org-at-item-p))
  15646. (call-interactively 'org-previous-item))
  15647. ((org-clocktable-try-shift 'up arg))
  15648. ((and (not (eq org-support-shift-select 'always))
  15649. (org-at-table-p))
  15650. (org-table-move-cell-up))
  15651. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15652. (org-support-shift-select
  15653. (org-call-for-shift-select 'previous-line))
  15654. (t (org-shiftselect-error))))
  15655. (defun org-shiftdown (&optional arg)
  15656. "Act on current element according to context.
  15657. Call `org-timestamp-down' or `org-priority-down', or
  15658. `org-next-item', or `org-table-move-cell-down'. See the
  15659. individual commands for more information."
  15660. (interactive "P")
  15661. (cond
  15662. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15663. ((and org-support-shift-select (org-region-active-p))
  15664. (org-call-for-shift-select 'next-line))
  15665. ((org-at-timestamp-p 'lax)
  15666. (call-interactively (if org-edit-timestamp-down-means-later
  15667. 'org-timestamp-up 'org-timestamp-down)))
  15668. ((and (not (eq org-support-shift-select 'always))
  15669. org-priority-enable-commands
  15670. (org-at-heading-p))
  15671. (call-interactively 'org-priority-down))
  15672. ((and (not org-support-shift-select) (org-at-item-p))
  15673. (call-interactively 'org-next-item))
  15674. ((org-clocktable-try-shift 'down arg))
  15675. ((and (not (eq org-support-shift-select 'always))
  15676. (org-at-table-p))
  15677. (org-table-move-cell-down))
  15678. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15679. (org-support-shift-select
  15680. (org-call-for-shift-select 'next-line))
  15681. (t (org-shiftselect-error))))
  15682. (defun org-shiftright (&optional arg)
  15683. "Act on the current element according to context.
  15684. This does one of the following:
  15685. - switch a timestamp at point one day into the future
  15686. - on a headline, switch to the next TODO keyword
  15687. - on an item, switch entire list to the next bullet type
  15688. - on a property line, switch to the next allowed value
  15689. - on a clocktable definition line, move time block into the future
  15690. - in a table, move a single cell right"
  15691. (interactive "P")
  15692. (cond
  15693. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15694. ((and org-support-shift-select (org-region-active-p))
  15695. (org-call-for-shift-select 'forward-char))
  15696. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15697. ((and (not (eq org-support-shift-select 'always))
  15698. (org-at-heading-p))
  15699. (let ((org-inhibit-logging
  15700. (not org-treat-S-cursor-todo-selection-as-state-change))
  15701. (org-inhibit-blocking
  15702. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15703. (org-call-with-arg 'org-todo 'right)))
  15704. ((or (and org-support-shift-select
  15705. (not (eq org-support-shift-select 'always))
  15706. (org-at-item-bullet-p))
  15707. (and (not org-support-shift-select) (org-at-item-p)))
  15708. (org-call-with-arg 'org-cycle-list-bullet nil))
  15709. ((and (not (eq org-support-shift-select 'always))
  15710. (org-at-property-p))
  15711. (call-interactively 'org-property-next-allowed-value))
  15712. ((org-clocktable-try-shift 'right arg))
  15713. ((and (not (eq org-support-shift-select 'always))
  15714. (org-at-table-p))
  15715. (org-table-move-cell-right))
  15716. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15717. (org-support-shift-select
  15718. (org-call-for-shift-select 'forward-char))
  15719. (t (org-shiftselect-error))))
  15720. (defun org-shiftleft (&optional arg)
  15721. "Act on current element according to context.
  15722. This does one of the following:
  15723. - switch a timestamp at point one day into the past
  15724. - on a headline, switch to the previous TODO keyword.
  15725. - on an item, switch entire list to the previous bullet type
  15726. - on a property line, switch to the previous allowed value
  15727. - on a clocktable definition line, move time block into the past
  15728. - in a table, move a single cell left"
  15729. (interactive "P")
  15730. (cond
  15731. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15732. ((and org-support-shift-select (org-region-active-p))
  15733. (org-call-for-shift-select 'backward-char))
  15734. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15735. ((and (not (eq org-support-shift-select 'always))
  15736. (org-at-heading-p))
  15737. (let ((org-inhibit-logging
  15738. (not org-treat-S-cursor-todo-selection-as-state-change))
  15739. (org-inhibit-blocking
  15740. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15741. (org-call-with-arg 'org-todo 'left)))
  15742. ((or (and org-support-shift-select
  15743. (not (eq org-support-shift-select 'always))
  15744. (org-at-item-bullet-p))
  15745. (and (not org-support-shift-select) (org-at-item-p)))
  15746. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15747. ((and (not (eq org-support-shift-select 'always))
  15748. (org-at-property-p))
  15749. (call-interactively 'org-property-previous-allowed-value))
  15750. ((org-clocktable-try-shift 'left arg))
  15751. ((and (not (eq org-support-shift-select 'always))
  15752. (org-at-table-p))
  15753. (org-table-move-cell-left))
  15754. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15755. (org-support-shift-select
  15756. (org-call-for-shift-select 'backward-char))
  15757. (t (org-shiftselect-error))))
  15758. (defun org-shiftcontrolright ()
  15759. "Switch to next TODO set."
  15760. (interactive)
  15761. (cond
  15762. ((and org-support-shift-select (org-region-active-p))
  15763. (org-call-for-shift-select 'forward-word))
  15764. ((and (not (eq org-support-shift-select 'always))
  15765. (org-at-heading-p))
  15766. (org-call-with-arg 'org-todo 'nextset))
  15767. (org-support-shift-select
  15768. (org-call-for-shift-select 'forward-word))
  15769. (t (org-shiftselect-error))))
  15770. (defun org-shiftcontrolleft ()
  15771. "Switch to previous TODO set."
  15772. (interactive)
  15773. (cond
  15774. ((and org-support-shift-select (org-region-active-p))
  15775. (org-call-for-shift-select 'backward-word))
  15776. ((and (not (eq org-support-shift-select 'always))
  15777. (org-at-heading-p))
  15778. (org-call-with-arg 'org-todo 'previousset))
  15779. (org-support-shift-select
  15780. (org-call-for-shift-select 'backward-word))
  15781. (t (org-shiftselect-error))))
  15782. (defun org-shiftcontrolup (&optional n)
  15783. "Change timestamps synchronously up in CLOCK log lines.
  15784. Optional argument N tells to change by that many units."
  15785. (interactive "P")
  15786. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15787. (let (org-support-shift-select)
  15788. (org-clock-timestamps-up n))
  15789. (user-error "Not at a clock log")))
  15790. (defun org-shiftcontroldown (&optional n)
  15791. "Change timestamps synchronously down in CLOCK log lines.
  15792. Optional argument N tells to change by that many units."
  15793. (interactive "P")
  15794. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15795. (let (org-support-shift-select)
  15796. (org-clock-timestamps-down n))
  15797. (user-error "Not at a clock log")))
  15798. (defun org-increase-number-at-point (&optional inc)
  15799. "Increment the number at point.
  15800. With an optional prefix numeric argument INC, increment using
  15801. this numeric value."
  15802. (interactive "p")
  15803. (if (not (number-at-point))
  15804. (user-error "Not on a number")
  15805. (unless inc (setq inc 1))
  15806. (let ((pos (point))
  15807. (beg (skip-chars-backward "-+^/*0-9eE."))
  15808. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15809. (setq nap (buffer-substring-no-properties
  15810. (+ pos beg) (+ pos beg end)))
  15811. (delete-region (+ pos beg) (+ pos beg end))
  15812. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15813. (when (org-at-table-p)
  15814. (org-table-align)
  15815. (org-table-end-of-field 1))))
  15816. (defun org-decrease-number-at-point (&optional inc)
  15817. "Decrement the number at point.
  15818. With an optional prefix numeric argument INC, decrement using
  15819. this numeric value."
  15820. (interactive "p")
  15821. (org-increase-number-at-point (- (or inc 1))))
  15822. (defun org-ctrl-c-ret ()
  15823. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15824. (interactive)
  15825. (cond
  15826. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15827. (t (call-interactively 'org-insert-heading))))
  15828. (defun org-copy-visible (beg end)
  15829. "Copy the visible parts of the region."
  15830. (interactive "r")
  15831. (let ((result ""))
  15832. (while (/= beg end)
  15833. (when (get-char-property beg 'invisible)
  15834. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15835. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15836. (setq result (concat result (buffer-substring beg next)))
  15837. (setq beg next)))
  15838. (setq deactivate-mark t)
  15839. (kill-new result)
  15840. (message "Visible strings have been copied to the kill ring.")))
  15841. (defun org-copy-special ()
  15842. "Copy region in table or copy current subtree.
  15843. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15844. context. See the individual commands for more information."
  15845. (interactive)
  15846. (call-interactively
  15847. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15848. (defun org-cut-special ()
  15849. "Cut region in table or cut current subtree.
  15850. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15851. context. See the individual commands for more information."
  15852. (interactive)
  15853. (call-interactively
  15854. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15855. (defun org-paste-special (arg)
  15856. "Paste rectangular region into table, or past subtree relative to level.
  15857. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15858. See the individual commands for more information."
  15859. (interactive "P")
  15860. (if (org-at-table-p)
  15861. (org-table-paste-rectangle)
  15862. (org-paste-subtree arg)))
  15863. (defun org-edit-special (&optional arg)
  15864. "Call a special editor for the element at point.
  15865. When at a table, call the formula editor with `org-table-edit-formulas'.
  15866. When in a source code block, call `org-edit-src-code'.
  15867. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15868. When in an export block, call `org-edit-export-block'.
  15869. When in a LaTeX environment, call `org-edit-latex-environment'.
  15870. When at an #+INCLUDE keyword, visit the included file.
  15871. When at a footnote reference, call `org-edit-footnote-reference'.
  15872. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15873. When at an active timestamp, call `org-time-stamp'.
  15874. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15875. On a link, call `ffap' to visit the link at point.
  15876. Otherwise, return a user error."
  15877. (interactive "P")
  15878. (let ((element (org-element-at-point)))
  15879. (barf-if-buffer-read-only)
  15880. (pcase (org-element-type element)
  15881. (`src-block
  15882. (if (not arg) (org-edit-src-code)
  15883. (let* ((info (org-babel-get-src-block-info))
  15884. (lang (nth 0 info))
  15885. (params (nth 2 info))
  15886. (session (cdr (assq :session params))))
  15887. (if (not session) (org-edit-src-code)
  15888. ;; At a source block with a session and function called
  15889. ;; with an ARG: switch to the buffer related to the
  15890. ;; inferior process.
  15891. (switch-to-buffer
  15892. (funcall (intern (concat "org-babel-prep-session:" lang))
  15893. session params))))))
  15894. (`keyword
  15895. (unless (member (org-element-property :key element)
  15896. '("INCLUDE" "SETUPFILE"))
  15897. (user-error "No special environment to edit here"))
  15898. (let ((value (org-element-property :value element)))
  15899. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15900. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15901. (or (match-string 1 value)
  15902. (match-string 0 value)))))
  15903. (when (org-file-url-p file)
  15904. (user-error "Files located with a URL cannot be edited"))
  15905. (org-link-open-from-string
  15906. (format "[[%s]]" (expand-file-name file))))))
  15907. (`table
  15908. (if (eq (org-element-property :type element) 'table.el)
  15909. (org-edit-table.el)
  15910. (call-interactively 'org-table-edit-formulas)))
  15911. ;; Only Org tables contain `table-row' type elements.
  15912. (`table-row (call-interactively 'org-table-edit-formulas))
  15913. (`example-block (org-edit-src-code))
  15914. (`export-block (org-edit-export-block))
  15915. (`fixed-width (org-edit-fixed-width-region))
  15916. (`latex-environment (org-edit-latex-environment))
  15917. (`planning
  15918. (let ((proplist (cadr element)))
  15919. (mapc #'call-interactively
  15920. (remq nil
  15921. (list
  15922. (when (plist-get proplist :deadline) #'org-deadline)
  15923. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15924. (_
  15925. ;; No notable element at point. Though, we may be at a link or
  15926. ;; a footnote reference, which are objects. Thus, scan deeper.
  15927. (let ((context (org-element-context element)))
  15928. (pcase (org-element-type context)
  15929. (`footnote-reference (org-edit-footnote-reference))
  15930. (`inline-src-block (org-edit-inline-src-code))
  15931. (`latex-fragment (org-edit-latex-fragment))
  15932. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15933. (call-interactively #'org-time-stamp-inactive)
  15934. (call-interactively #'org-time-stamp)))
  15935. (`link (call-interactively #'ffap))
  15936. (_ (user-error "No special environment to edit here"))))))))
  15937. (defun org-ctrl-c-ctrl-c (&optional arg)
  15938. "Set tags in headline, or update according to changed information at point.
  15939. This command does many different things, depending on context:
  15940. - If column view is active, in agenda or org buffers, quit it.
  15941. - If there are highlights, remove them.
  15942. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15943. this is what we do.
  15944. - If the cursor is on a statistics cookie, update it.
  15945. - If the cursor is in a headline, in an agenda or an org buffer,
  15946. prompt for tags and insert them into the current line, aligned
  15947. to `org-tags-column'. When called with prefix arg, realign all
  15948. tags in the current buffer.
  15949. - If the cursor is in one of the special #+KEYWORD lines, this
  15950. triggers scanning the buffer for these lines and updating the
  15951. information.
  15952. - If the cursor is inside a table, realign the table. This command
  15953. works even if the automatic table editor has been turned off.
  15954. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15955. the entire table.
  15956. - If the cursor is at a footnote reference or definition, jump to
  15957. the corresponding definition or references, respectively.
  15958. - If the cursor is a the beginning of a dynamic block, update it.
  15959. - If the current buffer is a capture buffer, close note and file it.
  15960. - If the cursor is on a <<<target>>>, update radio targets and
  15961. corresponding links in this buffer.
  15962. - If the cursor is on a numbered item in a plain list, renumber the
  15963. ordered list.
  15964. - If the cursor is on a checkbox, toggle it.
  15965. - If the cursor is on a code block, evaluate it. The variable
  15966. `org-confirm-babel-evaluate' can be used to control prompting
  15967. before code block evaluation, by default every code block
  15968. evaluation requires confirmation. Code block evaluation can be
  15969. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15970. (interactive "P")
  15971. (cond
  15972. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15973. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15974. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15975. (org-remove-occur-highlights)
  15976. (message "Temporary highlights/overlays removed from current buffer"))
  15977. ((and (local-variable-p 'org-finish-function)
  15978. (fboundp org-finish-function))
  15979. (funcall org-finish-function))
  15980. ((org-babel-hash-at-point))
  15981. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15982. (t
  15983. (let* ((context
  15984. (org-element-lineage
  15985. (org-element-context)
  15986. ;; Limit to supported contexts.
  15987. '(babel-call clock dynamic-block footnote-definition
  15988. footnote-reference inline-babel-call inline-src-block
  15989. inlinetask item keyword node-property paragraph
  15990. plain-list planning property-drawer radio-target
  15991. src-block statistics-cookie table table-cell table-row
  15992. timestamp)
  15993. t))
  15994. (radio-list-p (org-at-radio-list-p))
  15995. (type (org-element-type context)))
  15996. ;; For convenience: at the first line of a paragraph on the same
  15997. ;; line as an item, apply function on that item instead.
  15998. (when (eq type 'paragraph)
  15999. (let ((parent (org-element-property :parent context)))
  16000. (when (and (eq (org-element-type parent) 'item)
  16001. (= (line-beginning-position)
  16002. (org-element-property :begin parent)))
  16003. (setq context parent)
  16004. (setq type 'item))))
  16005. ;; Act according to type of element or object at point.
  16006. ;;
  16007. ;; Do nothing on a blank line, except if it is contained in
  16008. ;; a source block. Hence, we first check if point is in such
  16009. ;; a block and then if it is at a blank line.
  16010. (pcase type
  16011. ((or `inline-src-block `src-block)
  16012. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16013. (org-babel-eval-wipe-error-buffer)
  16014. (org-babel-execute-src-block
  16015. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16016. ((guard (org-match-line "[ \t]*$"))
  16017. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16018. (user-error
  16019. (substitute-command-keys
  16020. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16021. ((or `babel-call `inline-babel-call)
  16022. (let ((info (org-babel-lob-get-info context)))
  16023. (when info (org-babel-execute-src-block nil info))))
  16024. (`clock (org-clock-update-time-maybe))
  16025. (`dynamic-block
  16026. (save-excursion
  16027. (goto-char (org-element-property :post-affiliated context))
  16028. (org-update-dblock)))
  16029. (`footnote-definition
  16030. (goto-char (org-element-property :post-affiliated context))
  16031. (call-interactively 'org-footnote-action))
  16032. (`footnote-reference (call-interactively #'org-footnote-action))
  16033. ((or `headline `inlinetask)
  16034. (save-excursion (goto-char (org-element-property :begin context))
  16035. (call-interactively #'org-set-tags-command)))
  16036. (`item
  16037. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16038. ;; unconditionally, whereas `C-u' will toggle its presence.
  16039. ;; Without a universal argument, if the item has a checkbox,
  16040. ;; toggle it. Otherwise repair the list.
  16041. (if (or radio-list-p
  16042. (and (boundp org-list-checkbox-radio-mode)
  16043. org-list-checkbox-radio-mode))
  16044. (org-toggle-radio-button arg)
  16045. (let* ((box (org-element-property :checkbox context))
  16046. (struct (org-element-property :structure context))
  16047. (old-struct (copy-tree struct))
  16048. (parents (org-list-parents-alist struct))
  16049. (prevs (org-list-prevs-alist struct))
  16050. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16051. (org-list-set-checkbox
  16052. (org-element-property :begin context) struct
  16053. (cond ((equal arg '(16)) "[-]")
  16054. ((and (not box) (equal arg '(4))) "[ ]")
  16055. ((or (not box) (equal arg '(4))) nil)
  16056. ((eq box 'on) "[ ]")
  16057. (t "[X]")))
  16058. ;; Mimic `org-list-write-struct' but with grabbing a return
  16059. ;; value from `org-list-struct-fix-box'.
  16060. (org-list-struct-fix-ind struct parents 2)
  16061. (org-list-struct-fix-item-end struct)
  16062. (org-list-struct-fix-bul struct prevs)
  16063. (org-list-struct-fix-ind struct parents)
  16064. (let ((block-item
  16065. (org-list-struct-fix-box struct parents prevs orderedp)))
  16066. (if (and box (equal struct old-struct))
  16067. (if (equal arg '(16))
  16068. (message "Checkboxes already reset")
  16069. (user-error "Cannot toggle this checkbox: %s"
  16070. (if (eq box 'on)
  16071. "all subitems checked"
  16072. "unchecked subitems")))
  16073. (org-list-struct-apply-struct struct old-struct)
  16074. (org-update-checkbox-count-maybe))
  16075. (when block-item
  16076. (message "Checkboxes were removed due to empty box at line %d"
  16077. (org-current-line block-item)))))))
  16078. (`plain-list
  16079. ;; At a plain list, with a double C-u argument, set
  16080. ;; checkboxes of each item to "[-]", whereas a single one
  16081. ;; will toggle their presence according to the state of the
  16082. ;; first item in the list. Without an argument, repair the
  16083. ;; list.
  16084. (if (or radio-list-p
  16085. (and (boundp org-list-checkbox-radio-mode)
  16086. org-list-checkbox-radio-mode))
  16087. (org-toggle-radio-button arg)
  16088. (let* ((begin (org-element-property :contents-begin context))
  16089. (struct (org-element-property :structure context))
  16090. (old-struct (copy-tree struct))
  16091. (first-box (save-excursion
  16092. (goto-char begin)
  16093. (looking-at org-list-full-item-re)
  16094. (match-string-no-properties 3)))
  16095. (new-box (cond ((equal arg '(16)) "[-]")
  16096. ((equal arg '(4)) (unless first-box "[ ]"))
  16097. ((equal first-box "[X]") "[ ]")
  16098. (t "[X]"))))
  16099. (cond
  16100. (arg
  16101. (dolist (pos
  16102. (org-list-get-all-items
  16103. begin struct (org-list-prevs-alist struct)))
  16104. (org-list-set-checkbox pos struct new-box)))
  16105. ((and first-box (eq (point) begin))
  16106. ;; For convenience, when point is at bol on the first
  16107. ;; item of the list and no argument is provided, simply
  16108. ;; toggle checkbox of that item, if any.
  16109. (org-list-set-checkbox begin struct new-box)))
  16110. (when (equal
  16111. (org-list-write-struct
  16112. struct (org-list-parents-alist struct) old-struct)
  16113. old-struct)
  16114. (message "Cannot update this checkbox"))
  16115. (org-update-checkbox-count-maybe))))
  16116. (`keyword
  16117. (let ((org-inhibit-startup-visibility-stuff t)
  16118. (org-startup-align-all-tables nil))
  16119. (when (boundp 'org-table-coordinate-overlays)
  16120. (mapc #'delete-overlay org-table-coordinate-overlays)
  16121. (setq org-table-coordinate-overlays nil))
  16122. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16123. (message "Local setup has been refreshed"))
  16124. ((or `property-drawer `node-property)
  16125. (call-interactively #'org-property-action))
  16126. (`radio-target
  16127. (call-interactively #'org-update-radio-target-regexp))
  16128. (`statistics-cookie
  16129. (call-interactively #'org-update-statistics-cookies))
  16130. ((or `table `table-cell `table-row)
  16131. ;; At a table, recalculate every field and align it. Also
  16132. ;; send the table if necessary. If the table has
  16133. ;; a `table.el' type, just give up. At a table row or cell,
  16134. ;; maybe recalculate line but always align table.
  16135. (if (eq (org-element-property :type context) 'table.el)
  16136. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16137. Use `\\[org-edit-special]' to edit table.el tables"))
  16138. (if (or (eq type 'table)
  16139. ;; Check if point is at a TBLFM line.
  16140. (and (eq type 'table-row)
  16141. (= (point) (org-element-property :end context))))
  16142. (save-excursion
  16143. (if (org-at-TBLFM-p)
  16144. (progn (require 'org-table)
  16145. (org-table-calc-current-TBLFM))
  16146. (goto-char (org-element-property :contents-begin context))
  16147. (org-call-with-arg 'org-table-recalculate (or arg t))
  16148. (orgtbl-send-table 'maybe)))
  16149. (org-table-maybe-eval-formula)
  16150. (cond (arg (call-interactively #'org-table-recalculate))
  16151. ((org-table-maybe-recalculate-line))
  16152. (t (org-table-align))))))
  16153. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16154. (org-timestamp-change 0 'day))
  16155. ((and `nil (guard (org-at-heading-p)))
  16156. ;; When point is on an unsupported object type, we can miss
  16157. ;; the fact that it also is at a heading. Handle it here.
  16158. (call-interactively #'org-set-tags-command))
  16159. ((guard
  16160. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16161. (_
  16162. (user-error
  16163. (substitute-command-keys
  16164. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16165. (defun org-mode-restart ()
  16166. "Restart `org-mode'."
  16167. (interactive)
  16168. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16169. (funcall major-mode)
  16170. (hack-local-variables)
  16171. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16172. (org-indent-mode -1))
  16173. (org-reset-file-cache))
  16174. (message "%s restarted" major-mode))
  16175. (defun org-flag-above-first-heading (&optional arg)
  16176. "Hide from bob up to the first heading.
  16177. Move point to the beginning of first heading or end of buffer."
  16178. (goto-char (point-min))
  16179. (unless (org-at-heading-p)
  16180. (outline-next-heading))
  16181. (unless (bobp)
  16182. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16183. (defun org-show-branches-buffer ()
  16184. "Show all branches in the buffer."
  16185. (org-flag-above-first-heading)
  16186. (outline-hide-sublevels 1)
  16187. (unless (eobp)
  16188. (outline-show-branches)
  16189. (while (outline-get-next-sibling)
  16190. (outline-show-branches)))
  16191. (goto-char (point-min)))
  16192. (defun org-kill-note-or-show-branches ()
  16193. "Abort storing current note, or show just branches."
  16194. (interactive)
  16195. (cond (org-finish-function
  16196. (let ((org-note-abort t)) (funcall org-finish-function)))
  16197. ((org-before-first-heading-p)
  16198. (org-show-branches-buffer)
  16199. (org-hide-archived-subtrees (point-min) (point-max)))
  16200. (t
  16201. (let ((beg (progn (org-back-to-heading) (point)))
  16202. (end (save-excursion (org-end-of-subtree t t) (point))))
  16203. (outline-hide-subtree)
  16204. (outline-show-branches)
  16205. (org-hide-archived-subtrees beg end)))))
  16206. (defun org-delete-indentation (&optional arg)
  16207. "Join current line to previous and fix whitespace at join.
  16208. If previous line is a headline add to headline title. Otherwise
  16209. the function calls `delete-indentation'.
  16210. I.e. with a non-nil optional argument, join the line with the
  16211. following one. If there is a region then join the lines in that
  16212. region."
  16213. (interactive "*P")
  16214. (if (save-excursion
  16215. (beginning-of-line (if arg 1 0))
  16216. (let ((case-fold-search nil))
  16217. (looking-at org-complex-heading-regexp)))
  16218. ;; At headline.
  16219. (let ((tags-column (when (match-beginning 5)
  16220. (save-excursion (goto-char (match-beginning 5))
  16221. (current-column))))
  16222. (string (concat " " (progn (when arg (forward-line 1))
  16223. (org-trim (delete-and-extract-region
  16224. (line-beginning-position)
  16225. (line-end-position)))))))
  16226. (unless (bobp) (delete-region (point) (1- (point))))
  16227. (goto-char (or (match-end 4)
  16228. (match-beginning 5)
  16229. (match-end 0)))
  16230. (skip-chars-backward " \t")
  16231. (save-excursion (insert string))
  16232. ;; Adjust alignment of tags.
  16233. (cond
  16234. ((not tags-column)) ;no tags
  16235. (org-auto-align-tags (org-align-tags))
  16236. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16237. (let ((current-prefix-arg arg))
  16238. (call-interactively #'delete-indentation))))
  16239. (defun org-open-line (n)
  16240. "Insert a new row in tables, call `open-line' elsewhere.
  16241. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16242. As a special case, when a document starts with a table, allow to
  16243. call `open-line' on the very first character."
  16244. (interactive "*p")
  16245. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16246. (org-table-insert-row)
  16247. (open-line n)))
  16248. (defun org--newline (indent arg interactive)
  16249. "Call `newline-and-indent' or just `newline'.
  16250. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16251. indent unconditionally; otherwise, call `newline' with ARG and
  16252. INTERACTIVE, which can trigger indentation if
  16253. `electric-indent-mode' is enabled."
  16254. (if indent
  16255. (org-newline-and-indent arg)
  16256. (newline arg interactive)))
  16257. (defun org-return (&optional indent arg interactive)
  16258. "Goto next table row or insert a newline.
  16259. Calls `org-table-next-row' or `newline', depending on context.
  16260. When optional INDENT argument is non-nil, call
  16261. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16262. and INTERACTIVE.
  16263. When `org-return-follows-link' is non-nil and point is on
  16264. a timestamp or a link, call `org-open-at-point'. However, it
  16265. will not happen if point is in a table or on a \"dead\"
  16266. object (e.g., within a comment). In these case, you need to use
  16267. `org-open-at-point' directly."
  16268. (interactive "i\nP\np")
  16269. (let ((context (if org-return-follows-link (org-element-context)
  16270. (org-element-at-point))))
  16271. (cond
  16272. ;; In a table, call `org-table-next-row'. However, before first
  16273. ;; column or after last one, split the table.
  16274. ((or (and (eq 'table (org-element-type context))
  16275. (not (eq 'table.el (org-element-property :type context)))
  16276. (>= (point) (org-element-property :contents-begin context))
  16277. (< (point) (org-element-property :contents-end context)))
  16278. (org-element-lineage context '(table-row table-cell) t))
  16279. (if (or (looking-at-p "[ \t]*$")
  16280. (save-excursion (skip-chars-backward " \t") (bolp)))
  16281. (insert "\n")
  16282. (org-table-justify-field-maybe)
  16283. (call-interactively #'org-table-next-row)))
  16284. ;; On a link or a timestamp, call `org-open-at-point' if
  16285. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16286. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16287. ((and org-return-follows-link
  16288. (or (and (eq 'link (org-element-type context))
  16289. ;; Ensure point is not on the white spaces after
  16290. ;; the link.
  16291. (let ((origin (point)))
  16292. (org-with-point-at (org-element-property :end context)
  16293. (skip-chars-backward " \t")
  16294. (> (point) origin))))
  16295. (org-in-regexp org-ts-regexp-both nil t)
  16296. (org-in-regexp org-tsr-regexp-both nil t)
  16297. (org-in-regexp org-link-any-re nil t)))
  16298. (call-interactively #'org-open-at-point))
  16299. ;; Insert newline in heading, but preserve tags.
  16300. ((and (not (bolp))
  16301. (let ((case-fold-search nil))
  16302. (org-match-line org-complex-heading-regexp)))
  16303. ;; At headline. Split line. However, if point is on keyword,
  16304. ;; priority cookie or tags, do not break any of them: add
  16305. ;; a newline after the headline instead.
  16306. (let ((tags-column (and (match-beginning 5)
  16307. (save-excursion (goto-char (match-beginning 5))
  16308. (current-column))))
  16309. (string
  16310. (when (and (match-end 4) (org-point-in-group (point) 4))
  16311. (delete-and-extract-region (point) (match-end 4)))))
  16312. ;; Adjust tag alignment.
  16313. (cond
  16314. ((not (and tags-column string)))
  16315. (org-auto-align-tags (org-align-tags))
  16316. (t (org--align-tags-here tags-column))) ;preserve tags column
  16317. (end-of-line)
  16318. (org-show-entry)
  16319. (org--newline indent arg interactive)
  16320. (when string (save-excursion (insert (org-trim string))))))
  16321. ;; In a list, make sure indenting keeps trailing text within.
  16322. ((and (not (eolp))
  16323. (org-element-lineage context '(item)))
  16324. (let ((trailing-data
  16325. (delete-and-extract-region (point) (line-end-position))))
  16326. (org--newline indent arg interactive)
  16327. (save-excursion (insert trailing-data))))
  16328. (t
  16329. ;; Do not auto-fill when point is in an Org property drawer.
  16330. (let ((auto-fill-function (and (not (org-at-property-p))
  16331. auto-fill-function)))
  16332. (org--newline indent arg interactive))))))
  16333. (defun org-return-and-maybe-indent ()
  16334. "Goto next table row, or insert a newline.
  16335. Call `org-table-next-row' or `org-return', depending on context.
  16336. See the individual commands for more information.
  16337. When inserting a newline, indent the new line if
  16338. `electric-indent-mode' is disabled."
  16339. (interactive)
  16340. (org-return (not electric-indent-mode)))
  16341. (defun org-ctrl-c-tab (&optional arg)
  16342. "Toggle columns width in a table, or show children.
  16343. Call `org-table-toggle-column-width' if point is in a table.
  16344. Otherwise provide a compact view of the children. ARG is the
  16345. level to hide."
  16346. (interactive "p")
  16347. (cond
  16348. ((org-at-table-p)
  16349. (call-interactively #'org-table-toggle-column-width))
  16350. ((org-before-first-heading-p)
  16351. (save-excursion
  16352. (org-flag-above-first-heading)
  16353. (outline-hide-sublevels (or arg 1))))
  16354. (t
  16355. (outline-hide-subtree)
  16356. (org-show-children arg))))
  16357. (defun org-ctrl-c-star ()
  16358. "Compute table, or change heading status of lines.
  16359. Calls `org-table-recalculate' or `org-toggle-heading',
  16360. depending on context."
  16361. (interactive)
  16362. (cond
  16363. ((org-at-table-p)
  16364. (call-interactively 'org-table-recalculate))
  16365. (t
  16366. ;; Convert all lines in region to list items
  16367. (call-interactively 'org-toggle-heading))))
  16368. (defun org-ctrl-c-minus ()
  16369. "Insert separator line in table or modify bullet status of line.
  16370. Also turns a plain line or a region of lines into list items.
  16371. Calls `org-table-insert-hline', `org-toggle-item', or
  16372. `org-cycle-list-bullet', depending on context."
  16373. (interactive)
  16374. (cond
  16375. ((org-at-table-p)
  16376. (call-interactively 'org-table-insert-hline))
  16377. ((org-region-active-p)
  16378. (call-interactively 'org-toggle-item))
  16379. ((org-in-item-p)
  16380. (call-interactively 'org-cycle-list-bullet))
  16381. (t
  16382. (call-interactively 'org-toggle-item))))
  16383. (defun org-toggle-heading (&optional nstars)
  16384. "Convert headings to normal text, or items or text to headings.
  16385. If there is no active region, only convert the current line.
  16386. With a `\\[universal-argument]' prefix, convert the whole list at
  16387. point into heading.
  16388. In a region:
  16389. - If the first non blank line is a headline, remove the stars
  16390. from all headlines in the region.
  16391. - If it is a normal line, turn each and every normal line (i.e.,
  16392. not an heading or an item) in the region into headings. If you
  16393. want to convert only the first line of this region, use one
  16394. universal prefix argument.
  16395. - If it is a plain list item, turn all plain list items into headings.
  16396. When converting a line into a heading, the number of stars is chosen
  16397. such that the lines become children of the current entry. However,
  16398. when a numeric prefix argument is given, its value determines the
  16399. number of stars to add."
  16400. (interactive "P")
  16401. (let ((skip-blanks
  16402. ;; Return beginning of first non-blank line, starting from
  16403. ;; line at POS.
  16404. (lambda (pos)
  16405. (save-excursion
  16406. (goto-char pos)
  16407. (while (org-at-comment-p) (forward-line))
  16408. (skip-chars-forward " \r\t\n")
  16409. (point-at-bol))))
  16410. beg end toggled)
  16411. ;; Determine boundaries of changes. If a universal prefix has
  16412. ;; been given, put the list in a region. If region ends at a bol,
  16413. ;; do not consider the last line to be in the region.
  16414. (when (and current-prefix-arg (org-at-item-p))
  16415. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16416. (org-mark-element))
  16417. (if (org-region-active-p)
  16418. (setq beg (funcall skip-blanks (region-beginning))
  16419. end (copy-marker (save-excursion
  16420. (goto-char (region-end))
  16421. (if (bolp) (point) (point-at-eol)))))
  16422. (setq beg (funcall skip-blanks (point-at-bol))
  16423. end (copy-marker (point-at-eol))))
  16424. ;; Ensure inline tasks don't count as headings.
  16425. (org-with-limited-levels
  16426. (save-excursion
  16427. (goto-char beg)
  16428. (cond
  16429. ;; Case 1. Started at an heading: de-star headings.
  16430. ((org-at-heading-p)
  16431. (while (< (point) end)
  16432. (when (org-at-heading-p t)
  16433. (looking-at org-outline-regexp) (replace-match "")
  16434. (setq toggled t))
  16435. (forward-line)))
  16436. ;; Case 2. Started at an item: change items into headlines.
  16437. ;; One star will be added by `org-list-to-subtree'.
  16438. ((org-at-item-p)
  16439. (while (< (point) end)
  16440. (when (org-at-item-p)
  16441. ;; Pay attention to cases when region ends before list.
  16442. (let* ((struct (org-list-struct))
  16443. (list-end
  16444. (min (org-list-get-bottom-point struct) (1+ end))))
  16445. (save-restriction
  16446. (narrow-to-region (point) list-end)
  16447. (insert (org-list-to-subtree
  16448. (org-list-to-lisp t)
  16449. (pcase (org-current-level)
  16450. (`nil 1)
  16451. (l (1+ (org-reduced-level l)))))
  16452. "\n")))
  16453. (setq toggled t))
  16454. (forward-line)))
  16455. ;; Case 3. Started at normal text: make every line an heading,
  16456. ;; skipping headlines and items.
  16457. (t (let* ((stars
  16458. (make-string
  16459. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16460. (add-stars
  16461. (cond (nstars "") ; stars from prefix only
  16462. ((equal stars "") "*") ; before first heading
  16463. (org-odd-levels-only "**") ; inside heading, odd
  16464. (t "*"))) ; inside heading, oddeven
  16465. (rpl (concat stars add-stars " "))
  16466. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16467. (while (< (point) (if (equal nstars '(4)) lend end))
  16468. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16469. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16470. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16471. (forward-line)))))))
  16472. (unless toggled (message "Cannot toggle heading from here"))))
  16473. (defun org-meta-return (&optional arg)
  16474. "Insert a new heading or wrap a region in a table.
  16475. Calls `org-insert-heading', `org-insert-item' or
  16476. `org-table-wrap-region', depending on context. When called with
  16477. an argument, unconditionally call `org-insert-heading'."
  16478. (interactive "P")
  16479. (org-check-before-invisible-edit 'insert)
  16480. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16481. (call-interactively (cond (arg #'org-insert-heading)
  16482. ((org-at-table-p) #'org-table-wrap-region)
  16483. ((org-in-item-p) #'org-insert-item)
  16484. (t #'org-insert-heading)))))
  16485. ;;; Menu entries
  16486. (defsubst org-in-subtree-not-table-p ()
  16487. "Are we in a subtree and not in a table?"
  16488. (and (not (org-before-first-heading-p))
  16489. (not (org-at-table-p))))
  16490. ;; Define the Org mode menus
  16491. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16492. `("Org"
  16493. ("Show/Hide"
  16494. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16495. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16496. ["Sparse Tree..." org-sparse-tree t]
  16497. ["Reveal Context" org-reveal t]
  16498. ["Show All" org-show-all t]
  16499. "--"
  16500. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16501. "--"
  16502. ["New Heading" org-insert-heading t]
  16503. ("Navigate Headings"
  16504. ["Up" outline-up-heading t]
  16505. ["Next" outline-next-visible-heading t]
  16506. ["Previous" outline-previous-visible-heading t]
  16507. ["Next Same Level" outline-forward-same-level t]
  16508. ["Previous Same Level" outline-backward-same-level t]
  16509. "--"
  16510. ["Jump" org-goto t])
  16511. ("Edit Structure"
  16512. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16513. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16514. "--"
  16515. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16516. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16517. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16518. "--"
  16519. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16520. "--"
  16521. ["Copy visible text" org-copy-visible t]
  16522. "--"
  16523. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16524. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16525. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16526. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16527. "--"
  16528. ["Sort Region/Children" org-sort t]
  16529. "--"
  16530. ["Convert to odd levels" org-convert-to-odd-levels t]
  16531. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16532. ("Editing"
  16533. ["Emphasis..." org-emphasize t]
  16534. ["Add block structure" org-insert-structure-template t]
  16535. ["Edit Source Example" org-edit-special t]
  16536. "--"
  16537. ["Footnote new/jump" org-footnote-action t]
  16538. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16539. ("Archive"
  16540. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16541. "--"
  16542. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16543. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16544. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16545. "--"
  16546. ("Hyperlinks"
  16547. ["Store Link (Global)" org-store-link t]
  16548. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16549. ["Insert Link" org-insert-link t]
  16550. ["Follow Link" org-open-at-point t]
  16551. "--"
  16552. ["Next link" org-next-link t]
  16553. ["Previous link" org-previous-link t]
  16554. "--"
  16555. ["Descriptive Links"
  16556. org-toggle-link-display
  16557. :style radio
  16558. :selected org-descriptive-links
  16559. ]
  16560. ["Literal Links"
  16561. org-toggle-link-display
  16562. :style radio
  16563. :selected (not org-descriptive-links)])
  16564. "--"
  16565. ("TODO Lists"
  16566. ["TODO/DONE/-" org-todo t]
  16567. ("Select keyword"
  16568. ["Next keyword" org-shiftright (org-at-heading-p)]
  16569. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16570. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16571. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16572. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16573. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16574. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16575. "--"
  16576. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16577. :selected org-enforce-todo-dependencies :style toggle :active t]
  16578. "Settings for tree at point"
  16579. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16580. :selected (org-entry-get nil "ORDERED")
  16581. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16582. ["Do Children parallel" org-toggle-ordered-property :style radio
  16583. :selected (not (org-entry-get nil "ORDERED"))
  16584. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16585. "--"
  16586. ["Set Priority" org-priority t]
  16587. ["Priority Up" org-shiftup t]
  16588. ["Priority Down" org-shiftdown t]
  16589. "--"
  16590. ["Get news from all feeds" org-feed-update-all t]
  16591. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16592. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16593. ("TAGS and Properties"
  16594. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16595. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16596. "--"
  16597. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16598. ["Column view of properties" org-columns t]
  16599. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16600. ("Dates and Scheduling"
  16601. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16602. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16603. ("Change Date"
  16604. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16605. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16606. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16607. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16608. ["Compute Time Range" org-evaluate-time-range t]
  16609. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16610. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16611. "--"
  16612. ["Custom time format" org-toggle-time-stamp-overlays
  16613. :style radio :selected org-display-custom-times]
  16614. "--"
  16615. ["Goto Calendar" org-goto-calendar t]
  16616. ["Date from Calendar" org-date-from-calendar t]
  16617. "--"
  16618. ["Start/Restart Timer" org-timer-start t]
  16619. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16620. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16621. ["Insert Timer String" org-timer t]
  16622. ["Insert Timer Item" org-timer-item t])
  16623. ("Logging work"
  16624. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16625. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16626. ["Clock out" org-clock-out t]
  16627. ["Clock cancel" org-clock-cancel t]
  16628. "--"
  16629. ["Mark as default task" org-clock-mark-default-task t]
  16630. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16631. ["Goto running clock" org-clock-goto t]
  16632. "--"
  16633. ["Display times" org-clock-display t]
  16634. ["Create clock table" org-clock-report t]
  16635. "--"
  16636. ["Record DONE time"
  16637. (progn (setq org-log-done (not org-log-done))
  16638. (message "Switching to %s will %s record a timestamp"
  16639. (car org-done-keywords)
  16640. (if org-log-done "automatically" "not")))
  16641. :style toggle :selected org-log-done])
  16642. "--"
  16643. ["Agenda Command..." org-agenda t]
  16644. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16645. ("File List for Agenda")
  16646. ("Special views current file"
  16647. ["TODO Tree" org-show-todo-tree t]
  16648. ["Check Deadlines" org-check-deadlines t]
  16649. ["Tags/Property tree" org-match-sparse-tree t])
  16650. "--"
  16651. ["Export/Publish..." org-export-dispatch t]
  16652. ("LaTeX"
  16653. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16654. :style toggle :selected org-cdlatex-mode]
  16655. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16656. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16657. ["Modify math symbol" org-cdlatex-math-modify
  16658. (org-inside-LaTeX-fragment-p)]
  16659. ["Insert citation" org-reftex-citation t])
  16660. "--"
  16661. ("Documentation"
  16662. ["Show Version" org-version t]
  16663. ["Info Documentation" org-info t]
  16664. ["Browse Org News" org-browse-news t])
  16665. ("Customize"
  16666. ["Browse Org Group" org-customize t]
  16667. "--"
  16668. ["Expand This Menu" org-create-customize-menu t])
  16669. ["Send bug report" org-submit-bug-report t]
  16670. "--"
  16671. ("Refresh/Reload"
  16672. ["Refresh setup current buffer" org-mode-restart t]
  16673. ["Reload Org (after update)" org-reload t]
  16674. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16675. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16676. '("Table"
  16677. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16678. ["Next Field" org-cycle (org-at-table-p)]
  16679. ["Previous Field" org-shifttab (org-at-table-p)]
  16680. ["Next Row" org-return (org-at-table-p)]
  16681. "--"
  16682. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16683. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16684. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16685. "--"
  16686. ("Column"
  16687. ["Move Column Left" org-metaleft (org-at-table-p)]
  16688. ["Move Column Right" org-metaright (org-at-table-p)]
  16689. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16690. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16691. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16692. ("Row"
  16693. ["Move Row Up" org-metaup (org-at-table-p)]
  16694. ["Move Row Down" org-metadown (org-at-table-p)]
  16695. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16696. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16697. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16698. "--"
  16699. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16700. ("Rectangle"
  16701. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16702. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16703. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16704. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16705. "--"
  16706. ("Calculate"
  16707. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16708. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16709. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16710. "--"
  16711. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16712. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16713. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16714. "--"
  16715. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16716. "--"
  16717. ["Sum Column/Rectangle" org-table-sum
  16718. (or (org-at-table-p) (org-region-active-p))]
  16719. ["Which Column?" org-table-current-column (org-at-table-p)])
  16720. ["Debug Formulas"
  16721. org-table-toggle-formula-debugger
  16722. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16723. ["Show Col/Row Numbers"
  16724. org-table-toggle-coordinate-overlays
  16725. :style toggle
  16726. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16727. "--"
  16728. ["Create" org-table-create (not (org-at-table-p))]
  16729. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16730. ["Import from File" org-table-import (not (org-at-table-p))]
  16731. ["Export to File" org-table-export (org-at-table-p)]
  16732. "--"
  16733. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16734. "--"
  16735. ("Plot"
  16736. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16737. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16738. (defun org-info (&optional node)
  16739. "Read documentation for Org in the info system.
  16740. With optional NODE, go directly to that node."
  16741. (interactive)
  16742. (info (format "(org)%s" (or node ""))))
  16743. (defun org-browse-news ()
  16744. "Browse the news for the latest major release."
  16745. (interactive)
  16746. (browse-url "https://orgmode.org/Changes.html"))
  16747. ;;;###autoload
  16748. (defun org-submit-bug-report ()
  16749. "Submit a bug report on Org via mail.
  16750. Don't hesitate to report any problems or inaccurate documentation.
  16751. If you don't have setup sending mail from (X)Emacs, please copy the
  16752. output buffer into your mail program, as it gives us important
  16753. information about your Org version and configuration."
  16754. (interactive)
  16755. (require 'reporter)
  16756. (defvar reporter-prompt-for-summary-p)
  16757. (org-load-modules-maybe)
  16758. (org-require-autoloaded-modules)
  16759. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16760. (reporter-submit-bug-report
  16761. "emacs-orgmode@gnu.org"
  16762. (org-version nil 'full)
  16763. (let (list)
  16764. (save-window-excursion
  16765. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16766. (delete-other-windows)
  16767. (erase-buffer)
  16768. (insert "You are about to submit a bug report to the Org mailing list.
  16769. If your report is about Org installation, please read this section:
  16770. https://orgmode.org/org.html#Installation
  16771. Please read https://orgmode.org/org.html#Feedback on how to make
  16772. a good report, it will help Org contributors fixing your problem.
  16773. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16774. if the issue you are about to raise has already been dealt with.
  16775. We also would like to add your full Org and Outline configuration
  16776. to the bug report. It will help us debugging the issue.
  16777. *HOWEVER*, some variables you have customized may contain private
  16778. information. The names of customers, colleagues, or friends, might
  16779. appear in the form of file names, tags, todo states or search strings.
  16780. If you answer \"yes\" to the prompt, you might want to check and remove
  16781. such private information before sending the email.")
  16782. (add-text-properties (point-min) (point-max) '(face org-warning))
  16783. (when (yes-or-no-p "Include your Org configuration ")
  16784. (mapatoms
  16785. (lambda (v)
  16786. (and (boundp v)
  16787. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16788. (or (and (symbol-value v)
  16789. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16790. (and
  16791. (get v 'custom-type) (get v 'standard-value)
  16792. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16793. (push v list)))))
  16794. (kill-buffer (get-buffer "*Warn about privacy*"))
  16795. list))
  16796. nil nil
  16797. "Remember to cover the basics, that is, what you expected to happen and
  16798. what in fact did happen. You don't know how to make a good report? See
  16799. https://orgmode.org/manual/Feedback.html#Feedback
  16800. Your bug report will be posted to the Org mailing list.
  16801. ------------------------------------------------------------------------")
  16802. (save-excursion
  16803. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16804. (replace-match "\\1Bug: \\3 [\\2]")))))
  16805. (defun org-install-agenda-files-menu ()
  16806. "Install agenda file menu."
  16807. (let ((bl (buffer-list)))
  16808. (save-excursion
  16809. (while bl
  16810. (set-buffer (pop bl))
  16811. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16812. (when (derived-mode-p 'org-mode)
  16813. (easy-menu-change
  16814. '("Org") "File List for Agenda"
  16815. (append
  16816. (list
  16817. ["Edit File List" (org-edit-agenda-file-list) t]
  16818. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16819. ["Remove Current File from List" org-remove-file t]
  16820. ["Cycle through agenda files" org-cycle-agenda-files t]
  16821. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16822. "--")
  16823. (mapcar 'org-file-menu-entry
  16824. ;; Prevent initialization from failing.
  16825. (ignore-errors (org-agenda-files t)))))))))
  16826. ;;;; Documentation
  16827. (defun org-require-autoloaded-modules ()
  16828. (interactive)
  16829. (mapc #'require
  16830. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16831. org-table org-timer)))
  16832. ;;;###autoload
  16833. (defun org-reload (&optional uncompiled)
  16834. "Reload all Org Lisp files.
  16835. With prefix arg UNCOMPILED, load the uncompiled versions."
  16836. (interactive "P")
  16837. (require 'loadhist)
  16838. (let* ((org-dir (org-find-library-dir "org"))
  16839. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16840. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16841. (remove-re (format "\\`%s\\'"
  16842. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16843. (feats (delete-dups
  16844. (mapcar 'file-name-sans-extension
  16845. (mapcar 'file-name-nondirectory
  16846. (delq nil
  16847. (mapcar 'feature-file
  16848. features))))))
  16849. (lfeat (append
  16850. (sort
  16851. (setq feats
  16852. (delq nil (mapcar
  16853. (lambda (f)
  16854. (if (and (string-match feature-re f)
  16855. (not (string-match remove-re f)))
  16856. f nil))
  16857. feats)))
  16858. 'string-lessp)
  16859. (list "org-version" "org")))
  16860. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16861. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16862. load-uncore load-misses)
  16863. (setq load-misses
  16864. (delq 't
  16865. (mapcar (lambda (f)
  16866. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16867. (and (string= org-dir contrib-dir)
  16868. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16869. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16870. (push f load-uncore)
  16871. 't)
  16872. f))
  16873. lfeat)))
  16874. (when load-uncore
  16875. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16876. (if (> (length load-uncore) 1) "s were" " was")
  16877. (reverse load-uncore)))
  16878. (if load-misses
  16879. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16880. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16881. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16882. ;;;###autoload
  16883. (defun org-customize ()
  16884. "Call the customize function with org as argument."
  16885. (interactive)
  16886. (org-load-modules-maybe)
  16887. (org-require-autoloaded-modules)
  16888. (customize-browse 'org))
  16889. (defun org-create-customize-menu ()
  16890. "Create a full customization menu for Org mode, insert it into the menu."
  16891. (interactive)
  16892. (org-load-modules-maybe)
  16893. (org-require-autoloaded-modules)
  16894. (easy-menu-change
  16895. '("Org") "Customize"
  16896. `(["Browse Org group" org-customize t]
  16897. "--"
  16898. ,(customize-menu-create 'org)
  16899. ["Set" Custom-set t]
  16900. ["Save" Custom-save t]
  16901. ["Reset to Current" Custom-reset-current t]
  16902. ["Reset to Saved" Custom-reset-saved t]
  16903. ["Reset to Standard Settings" Custom-reset-standard t]))
  16904. (message "\"Org\"-menu now contains full customization menu"))
  16905. ;;;; Miscellaneous stuff
  16906. ;;; Generally useful functions
  16907. (defun org-in-clocktable-p ()
  16908. "Check if the cursor is in a clocktable."
  16909. (let ((pos (point)) start)
  16910. (save-excursion
  16911. (end-of-line 1)
  16912. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16913. (setq start (match-beginning 0))
  16914. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16915. (>= (match-end 0) pos)
  16916. start))))
  16917. (defun org-in-verbatim-emphasis ()
  16918. (save-match-data
  16919. (and (org-in-regexp org-verbatim-re 2)
  16920. (>= (point) (match-beginning 3))
  16921. (<= (point) (match-end 4)))))
  16922. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16923. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16924. (if (and marker (marker-buffer marker)
  16925. (buffer-live-p (marker-buffer marker)))
  16926. (progn
  16927. (pop-to-buffer-same-window (marker-buffer marker))
  16928. (when (or (> marker (point-max)) (< marker (point-min)))
  16929. (widen))
  16930. (goto-char marker)
  16931. (org-show-context 'org-goto))
  16932. (if bookmark
  16933. (bookmark-jump bookmark)
  16934. (error "Cannot find location"))))
  16935. (defun org-quote-csv-field (s)
  16936. "Quote field for inclusion in CSV material."
  16937. (if (string-match "[\",]" s)
  16938. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16939. s))
  16940. (defun org-force-self-insert (N)
  16941. "Needed to enforce self-insert under remapping."
  16942. (interactive "p")
  16943. (self-insert-command N))
  16944. (defun org-quote-vert (s)
  16945. "Replace \"|\" with \"\\vert\"."
  16946. (while (string-match "|" s)
  16947. (setq s (replace-match "\\vert" t t s)))
  16948. s)
  16949. (defun org-uuidgen-p (s)
  16950. "Is S an ID created by UUIDGEN?"
  16951. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16952. (defun org-in-src-block-p (&optional inside)
  16953. "Whether point is in a code source block.
  16954. When INSIDE is non-nil, don't consider we are within a source
  16955. block when point is at #+BEGIN_SRC or #+END_SRC."
  16956. (let ((case-fold-search t))
  16957. (or (and (eq (get-char-property (point) 'src-block) t))
  16958. (and (not inside)
  16959. (save-match-data
  16960. (save-excursion
  16961. (beginning-of-line)
  16962. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16963. (defun org-context ()
  16964. "Return a list of contexts of the current cursor position.
  16965. If several contexts apply, all are returned.
  16966. Each context entry is a list with a symbol naming the context, and
  16967. two positions indicating start and end of the context. Possible
  16968. contexts are:
  16969. :headline anywhere in a headline
  16970. :headline-stars on the leading stars in a headline
  16971. :todo-keyword on a TODO keyword (including DONE) in a headline
  16972. :tags on the TAGS in a headline
  16973. :priority on the priority cookie in a headline
  16974. :item on the first line of a plain list item
  16975. :item-bullet on the bullet/number of a plain list item
  16976. :checkbox on the checkbox in a plain list item
  16977. :table in an Org table
  16978. :table-special on a special filed in a table
  16979. :table-table in a table.el table
  16980. :clocktable in a clocktable
  16981. :src-block in a source block
  16982. :link on a hyperlink
  16983. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16984. :latex-fragment on a LaTeX fragment
  16985. :latex-preview on a LaTeX fragment with overlaid preview image
  16986. This function expects the position to be visible because it uses font-lock
  16987. faces as a help to recognize the following contexts: :table-special, :link,
  16988. and :keyword."
  16989. (let* ((f (get-text-property (point) 'face))
  16990. (faces (if (listp f) f (list f)))
  16991. (case-fold-search t)
  16992. (p (point)) clist o)
  16993. ;; First the large context
  16994. (cond
  16995. ((org-at-heading-p t)
  16996. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16997. (when (progn
  16998. (beginning-of-line 1)
  16999. (looking-at org-todo-line-tags-regexp))
  17000. (push (org-point-in-group p 1 :headline-stars) clist)
  17001. (push (org-point-in-group p 2 :todo-keyword) clist)
  17002. (push (org-point-in-group p 4 :tags) clist))
  17003. (goto-char p)
  17004. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17005. (when (looking-at "\\[#[A-Z0-9]\\]")
  17006. (push (org-point-in-group p 0 :priority) clist)))
  17007. ((org-at-item-p)
  17008. (push (org-point-in-group p 2 :item-bullet) clist)
  17009. (push (list :item (point-at-bol)
  17010. (save-excursion (org-end-of-item) (point)))
  17011. clist)
  17012. (and (org-at-item-checkbox-p)
  17013. (push (org-point-in-group p 0 :checkbox) clist)))
  17014. ((org-at-table-p)
  17015. (push (list :table (org-table-begin) (org-table-end)) clist)
  17016. (when (memq 'org-formula faces)
  17017. (push (list :table-special
  17018. (previous-single-property-change p 'face)
  17019. (next-single-property-change p 'face))
  17020. clist)))
  17021. ((org-at-table-p 'any)
  17022. (push (list :table-table) clist)))
  17023. (goto-char p)
  17024. (let ((case-fold-search t))
  17025. ;; New the "medium" contexts: clocktables, source blocks
  17026. (cond ((org-in-clocktable-p)
  17027. (push (list :clocktable
  17028. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17029. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17030. (match-beginning 1))
  17031. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17032. (match-end 0)))
  17033. clist))
  17034. ((org-in-src-block-p)
  17035. (push (list :src-block
  17036. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17037. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17038. (match-beginning 1))
  17039. (and (search-forward "#+END_SRC" nil t)
  17040. (match-beginning 0)))
  17041. clist))))
  17042. (goto-char p)
  17043. ;; Now the small context
  17044. (cond
  17045. ((org-at-timestamp-p)
  17046. (push (org-point-in-group p 0 :timestamp) clist))
  17047. ((memq 'org-link faces)
  17048. (push (list :link
  17049. (previous-single-property-change p 'face)
  17050. (next-single-property-change p 'face))
  17051. clist))
  17052. ((memq 'org-special-keyword faces)
  17053. (push (list :keyword
  17054. (previous-single-property-change p 'face)
  17055. (next-single-property-change p 'face))
  17056. clist))
  17057. ((setq o (cl-some
  17058. (lambda (o)
  17059. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17060. o))
  17061. (overlays-at (point))))
  17062. (push (list :latex-fragment
  17063. (overlay-start o) (overlay-end o))
  17064. clist)
  17065. (push (list :latex-preview
  17066. (overlay-start o) (overlay-end o))
  17067. clist))
  17068. ((org-inside-LaTeX-fragment-p)
  17069. ;; FIXME: positions wrong.
  17070. (push (list :latex-fragment (point) (point)) clist)))
  17071. (setq clist (nreverse (delq nil clist)))
  17072. clist))
  17073. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17074. "Non-nil when point is between matches of START-RE and END-RE.
  17075. Also return a non-nil value when point is on one of the matches.
  17076. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17077. buffer positions. Default values are the positions of headlines
  17078. surrounding the point.
  17079. The functions returns a cons cell whose car (resp. cdr) is the
  17080. position before START-RE (resp. after END-RE)."
  17081. (save-match-data
  17082. (let ((pos (point))
  17083. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17084. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17085. beg end)
  17086. (save-excursion
  17087. ;; Point is on a block when on START-RE or if START-RE can be
  17088. ;; found before it...
  17089. (and (or (org-in-regexp start-re)
  17090. (re-search-backward start-re limit-up t))
  17091. (setq beg (match-beginning 0))
  17092. ;; ... and END-RE after it...
  17093. (goto-char (match-end 0))
  17094. (re-search-forward end-re limit-down t)
  17095. (> (setq end (match-end 0)) pos)
  17096. ;; ... without another START-RE in-between.
  17097. (goto-char (match-beginning 0))
  17098. (not (re-search-backward start-re (1+ beg) t))
  17099. ;; Return value.
  17100. (cons beg end))))))
  17101. (defun org-in-block-p (names)
  17102. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17103. NAMES is a list of strings containing names of blocks.
  17104. Return first block name matched, or nil. Beware that in case of
  17105. nested blocks, the returned name may not belong to the closest
  17106. block from point."
  17107. (save-match-data
  17108. (catch 'exit
  17109. (let ((case-fold-search t)
  17110. (lim-up (save-excursion (outline-previous-heading)))
  17111. (lim-down (save-excursion (outline-next-heading))))
  17112. (dolist (name names)
  17113. (let ((n (regexp-quote name)))
  17114. (when (org-between-regexps-p
  17115. (concat "^[ \t]*#\\+begin_" n)
  17116. (concat "^[ \t]*#\\+end_" n)
  17117. lim-up lim-down)
  17118. (throw 'exit n)))))
  17119. nil)))
  17120. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17121. "Call `multi-occur' with buffers for all agenda files."
  17122. (interactive "sOrg-files matching: ")
  17123. (let* ((files (org-agenda-files))
  17124. (tnames (mapcar #'file-truename files))
  17125. (extra org-agenda-text-search-extra-files))
  17126. (when (eq (car extra) 'agenda-archives)
  17127. (setq extra (cdr extra))
  17128. (setq files (org-add-archive-files files)))
  17129. (dolist (f extra)
  17130. (unless (member (file-truename f) tnames)
  17131. (unless (member f files) (setq files (append files (list f))))
  17132. (setq tnames (append tnames (list (file-truename f))))))
  17133. (multi-occur
  17134. (mapcar (lambda (x)
  17135. (with-current-buffer
  17136. ;; FIXME: Why not just (find-file-noselect x)?
  17137. ;; Is it to avoid the "revert buffer" prompt?
  17138. (or (get-file-buffer x) (find-file-noselect x))
  17139. (widen)
  17140. (current-buffer)))
  17141. files)
  17142. regexp)))
  17143. (add-hook 'occur-mode-find-occurrence-hook
  17144. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17145. (defun org-occur-link-in-agenda-files ()
  17146. "Create a link and search for it in the agendas.
  17147. The link is not stored in `org-stored-links', it is just created
  17148. for the search purpose."
  17149. (interactive)
  17150. (let ((link (condition-case nil
  17151. (org-store-link nil)
  17152. (error "Unable to create a link to here"))))
  17153. (org-occur-in-agenda-files (regexp-quote link))))
  17154. (defun org-back-over-empty-lines ()
  17155. "Move backwards over whitespace, to the beginning of the first empty line.
  17156. Returns the number of empty lines passed."
  17157. (let ((pos (point)))
  17158. (if (cdr (assq 'heading org-blank-before-new-entry))
  17159. (skip-chars-backward " \t\n\r")
  17160. (unless (eobp)
  17161. (forward-line -1)))
  17162. (beginning-of-line 2)
  17163. (goto-char (min (point) pos))
  17164. (count-lines (point) pos)))
  17165. ;;; TODO: Only called once, from ox-odt which should probably use
  17166. ;;; org-export-inline-image-p or something.
  17167. (defun org-file-image-p (file)
  17168. "Return non-nil if FILE is an image."
  17169. (save-match-data
  17170. (string-match (image-file-name-regexp) file)))
  17171. (defun org-get-cursor-date (&optional with-time)
  17172. "Return the date at cursor in as a time.
  17173. This works in the calendar and in the agenda, anywhere else it just
  17174. returns the current time.
  17175. If WITH-TIME is non-nil, returns the time of the event at point (in
  17176. the agenda) or the current time of the day; otherwise returns the
  17177. earliest time on the cursor date that Org treats as that date
  17178. (bearing in mind `org-extend-today-until')."
  17179. (let (date day defd tp hod mod)
  17180. (when with-time
  17181. (setq tp (get-text-property (point) 'time))
  17182. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17183. (setq hod (string-to-number (match-string 1 tp))
  17184. mod (string-to-number (match-string 2 tp))))
  17185. (or tp (let ((now (decode-time)))
  17186. (setq hod (nth 2 now)
  17187. mod (nth 1 now)))))
  17188. (cond
  17189. ((eq major-mode 'calendar-mode)
  17190. (setq date (calendar-cursor-to-date)
  17191. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17192. (nth 1 date) (nth 0 date) (nth 2 date))))
  17193. ((eq major-mode 'org-agenda-mode)
  17194. (setq day (get-text-property (point) 'day))
  17195. (when day
  17196. (setq date (calendar-gregorian-from-absolute day)
  17197. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17198. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17199. (or defd (current-time))))
  17200. (defun org-mark-subtree (&optional up)
  17201. "Mark the current subtree.
  17202. This puts point at the start of the current subtree, and mark at
  17203. the end. If a numeric prefix UP is given, move up into the
  17204. hierarchy of headlines by UP levels before marking the subtree."
  17205. (interactive "P")
  17206. (org-with-limited-levels
  17207. (cond ((org-at-heading-p) (beginning-of-line))
  17208. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17209. (t (outline-previous-visible-heading 1))))
  17210. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17211. (if (called-interactively-p 'any)
  17212. (call-interactively 'org-mark-element)
  17213. (org-mark-element)))
  17214. ;;; Indentation
  17215. (defvar org-element-greater-elements)
  17216. (defun org--get-expected-indentation (element contentsp)
  17217. "Expected indentation column for current line, according to ELEMENT.
  17218. ELEMENT is an element containing point. CONTENTSP is non-nil
  17219. when indentation is to be computed according to contents of
  17220. ELEMENT."
  17221. (let ((type (org-element-type element))
  17222. (start (org-element-property :begin element))
  17223. (post-affiliated (org-element-property :post-affiliated element)))
  17224. (org-with-wide-buffer
  17225. (cond
  17226. (contentsp
  17227. (cl-case type
  17228. ((diary-sexp footnote-definition) 0)
  17229. ((headline inlinetask nil)
  17230. (if (not org-adapt-indentation) 0
  17231. (let ((level (org-current-level)))
  17232. (if level (1+ level) 0))))
  17233. ((item plain-list) (org-list-item-body-column post-affiliated))
  17234. (t
  17235. (goto-char start)
  17236. (current-indentation))))
  17237. ((and
  17238. (eq org-adapt-indentation 'headline-data)
  17239. (memq type '(planning clock node-property property-drawer drawer)))
  17240. (org--get-expected-indentation
  17241. (org-element-property :parent element) t))
  17242. ((memq type '(headline inlinetask nil))
  17243. (if (org-match-line "[ \t]*$")
  17244. (org--get-expected-indentation element t)
  17245. 0))
  17246. ((memq type '(diary-sexp footnote-definition)) 0)
  17247. ;; First paragraph of a footnote definition or an item.
  17248. ;; Indent like parent.
  17249. ((< (line-beginning-position) start)
  17250. (org--get-expected-indentation
  17251. (org-element-property :parent element) t))
  17252. ;; At first line: indent according to previous sibling, if any,
  17253. ;; ignoring footnote definitions and inline tasks, or parent's
  17254. ;; contents.
  17255. ((and ( = (line-beginning-position) start)
  17256. (eq org-adapt-indentation t))
  17257. (catch 'exit
  17258. (while t
  17259. (if (= (point-min) start) (throw 'exit 0)
  17260. (goto-char (1- start))
  17261. (let* ((previous (org-element-at-point))
  17262. (parent previous))
  17263. (while (and parent (<= (org-element-property :end parent) start))
  17264. (setq previous parent
  17265. parent (org-element-property :parent parent)))
  17266. (cond
  17267. ((not previous) (throw 'exit 0))
  17268. ((> (org-element-property :end previous) start)
  17269. (throw 'exit (org--get-expected-indentation previous t)))
  17270. ((memq (org-element-type previous)
  17271. '(footnote-definition inlinetask))
  17272. (setq start (org-element-property :begin previous)))
  17273. (t (goto-char (org-element-property :begin previous))
  17274. (throw 'exit
  17275. (if (bolp) (current-indentation)
  17276. ;; At first paragraph in an item or
  17277. ;; a footnote definition.
  17278. (org--get-expected-indentation
  17279. (org-element-property :parent previous) t))))))))))
  17280. ;; Otherwise, move to the first non-blank line above.
  17281. ((not (eq org-adapt-indentation 'headline-data))
  17282. (beginning-of-line)
  17283. (let ((pos (point)))
  17284. (skip-chars-backward " \r\t\n")
  17285. (cond
  17286. ;; Two blank lines end a footnote definition or a plain
  17287. ;; list. When we indent an empty line after them, the
  17288. ;; containing list or footnote definition is over, so it
  17289. ;; qualifies as a previous sibling. Therefore, we indent
  17290. ;; like its first line.
  17291. ((and (memq type '(footnote-definition plain-list))
  17292. (> (count-lines (point) pos) 2))
  17293. (goto-char start)
  17294. (current-indentation))
  17295. ;; Line above is the first one of a paragraph at the
  17296. ;; beginning of an item or a footnote definition. Indent
  17297. ;; like parent.
  17298. ((< (line-beginning-position) start)
  17299. (org--get-expected-indentation
  17300. (org-element-property :parent element) t))
  17301. ;; Line above is the beginning of an element, i.e., point
  17302. ;; was originally on the blank lines between element's start
  17303. ;; and contents.
  17304. ((= (line-beginning-position) post-affiliated)
  17305. (org--get-expected-indentation element t))
  17306. ;; POS is after contents in a greater element. Indent like
  17307. ;; the beginning of the element.
  17308. ((and (memq type org-element-greater-elements)
  17309. (let ((cend (org-element-property :contents-end element)))
  17310. (and cend (<= cend pos))))
  17311. ;; As a special case, if point is at the end of a footnote
  17312. ;; definition or an item, indent like the very last element
  17313. ;; within. If that last element is an item, indent like
  17314. ;; its contents.
  17315. (if (memq type '(footnote-definition item plain-list))
  17316. (let ((last (org-element-at-point)))
  17317. (goto-char pos)
  17318. (org--get-expected-indentation
  17319. last (eq (org-element-type last) 'item)))
  17320. (goto-char start)
  17321. (current-indentation)))
  17322. ;; In any other case, indent like the current line.
  17323. (t (current-indentation)))))
  17324. ;; Finally, no indentation is needed, fall back to 0.
  17325. (t (current-indentation))))))
  17326. (defun org--align-node-property ()
  17327. "Align node property at point.
  17328. Alignment is done according to `org-property-format', which see."
  17329. (when (save-excursion
  17330. (beginning-of-line)
  17331. (looking-at org-property-re))
  17332. (replace-match
  17333. (concat (match-string 4)
  17334. (org-trim
  17335. (format org-property-format (match-string 1) (match-string 3))))
  17336. t t)))
  17337. (defun org-indent-line ()
  17338. "Indent line depending on context.
  17339. Indentation is done according to the following rules:
  17340. - Footnote definitions, diary sexps, headlines and inline tasks
  17341. have to start at column 0.
  17342. - On the very first line of an element, consider, in order, the
  17343. next rules until one matches:
  17344. 1. If there's a sibling element before, ignoring footnote
  17345. definitions and inline tasks, indent like its first line.
  17346. 2. If element has a parent, indent like its contents. More
  17347. precisely, if parent is an item, indent after the bullet.
  17348. Else, indent like parent's first line.
  17349. 3. Otherwise, indent relatively to current level, if
  17350. `org-adapt-indentation' is non-nil, or to left margin.
  17351. - On a blank line at the end of an element, indent according to
  17352. the type of the element. More precisely
  17353. 1. If element is a plain list, an item, or a footnote
  17354. definition, indent like the very last element within.
  17355. 2. If element is a paragraph, indent like its last non blank
  17356. line.
  17357. 3. Otherwise, indent like its very first line.
  17358. - In the code part of a source block, use language major mode
  17359. to indent current line if `org-src-tab-acts-natively' is
  17360. non-nil. If it is nil, do nothing.
  17361. - Otherwise, indent like the first non-blank line above.
  17362. The function doesn't indent an item as it could break the whole
  17363. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17364. `\\[org-shiftmetaright]'.
  17365. Also align node properties according to `org-property-format'."
  17366. (interactive)
  17367. (unless (org-at-heading-p)
  17368. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17369. (type (org-element-type element)))
  17370. (cond ((and (memq type '(plain-list item))
  17371. (= (line-beginning-position)
  17372. (org-element-property :post-affiliated element)))
  17373. nil)
  17374. ((and (eq type 'latex-environment)
  17375. (>= (point) (org-element-property :post-affiliated element))
  17376. (< (point)
  17377. (org-with-point-at (org-element-property :end element)
  17378. (skip-chars-backward " \t\n")
  17379. (line-beginning-position 2))))
  17380. nil)
  17381. ((and (eq type 'src-block)
  17382. org-src-tab-acts-natively
  17383. (> (line-beginning-position)
  17384. (org-element-property :post-affiliated element))
  17385. (< (line-beginning-position)
  17386. (org-with-point-at (org-element-property :end element)
  17387. (skip-chars-backward " \t\n")
  17388. (line-beginning-position))))
  17389. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17390. (t
  17391. (let ((column (org--get-expected-indentation element nil)))
  17392. ;; Preserve current column.
  17393. (if (<= (current-column) (current-indentation))
  17394. (indent-line-to column)
  17395. (save-excursion (indent-line-to column))))
  17396. ;; Align node property. Also preserve current column.
  17397. (when (eq type 'node-property)
  17398. (let ((column (current-column)))
  17399. (org--align-node-property)
  17400. (org-move-to-column column))))))))
  17401. (defun org-indent-region (start end)
  17402. "Indent each non-blank line in the region.
  17403. Called from a program, START and END specify the region to
  17404. indent. The function will not indent contents of example blocks,
  17405. verse blocks and export blocks as leading white spaces are
  17406. assumed to be significant there."
  17407. (interactive "r")
  17408. (save-excursion
  17409. (goto-char start)
  17410. (skip-chars-forward " \r\t\n")
  17411. (unless (eobp) (beginning-of-line))
  17412. (let ((indent-to
  17413. (lambda (ind pos)
  17414. ;; Set IND as indentation for all lines between point and
  17415. ;; POS. Blank lines are ignored. Leave point after POS
  17416. ;; once done.
  17417. (let ((limit (copy-marker pos)))
  17418. (while (< (point) limit)
  17419. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17420. (forward-line))
  17421. (set-marker limit nil))))
  17422. (end (copy-marker end)))
  17423. (while (< (point) end)
  17424. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17425. (let* ((element (org-element-at-point))
  17426. (type (org-element-type element))
  17427. (element-end (copy-marker (org-element-property :end element)))
  17428. (ind (org--get-expected-indentation element nil)))
  17429. (cond
  17430. ;; Element indented as a single block. Example blocks
  17431. ;; preserving indentation are a special case since the
  17432. ;; "contents" must not be indented whereas the block
  17433. ;; boundaries can.
  17434. ((or (memq type '(export-block latex-environment))
  17435. (and (eq type 'example-block)
  17436. (not
  17437. (or org-src-preserve-indentation
  17438. (org-element-property :preserve-indent element)))))
  17439. (let ((offset (- ind (current-indentation))))
  17440. (unless (zerop offset)
  17441. (indent-rigidly (org-element-property :begin element)
  17442. (org-element-property :end element)
  17443. offset)))
  17444. (goto-char element-end))
  17445. ;; Elements indented line wise. Be sure to exclude
  17446. ;; example blocks (preserving indentation) and source
  17447. ;; blocks from this category as they are treated
  17448. ;; specially later.
  17449. ((or (memq type '(paragraph table table-row))
  17450. (not (or (org-element-property :contents-begin element)
  17451. (memq type '(example-block src-block)))))
  17452. (when (eq type 'node-property)
  17453. (org--align-node-property)
  17454. (beginning-of-line))
  17455. (funcall indent-to ind (min element-end end)))
  17456. ;; Elements consisting of three parts: before the
  17457. ;; contents, the contents, and after the contents. The
  17458. ;; contents are treated specially, according to the
  17459. ;; element type, or not indented at all. Other parts are
  17460. ;; indented as a single block.
  17461. (t
  17462. (let* ((post (copy-marker
  17463. (org-element-property :post-affiliated element)))
  17464. (cbeg
  17465. (copy-marker
  17466. (cond
  17467. ((not (org-element-property :contents-begin element))
  17468. ;; Fake contents for source blocks.
  17469. (org-with-wide-buffer
  17470. (goto-char post)
  17471. (line-beginning-position 2)))
  17472. ((memq type '(footnote-definition item plain-list))
  17473. ;; Contents in these elements could start on
  17474. ;; the same line as the beginning of the
  17475. ;; element. Make sure we start indenting
  17476. ;; from the second line.
  17477. (org-with-wide-buffer
  17478. (goto-char post)
  17479. (end-of-line)
  17480. (skip-chars-forward " \r\t\n")
  17481. (if (eobp) (point) (line-beginning-position))))
  17482. (t (org-element-property :contents-begin element)))))
  17483. (cend (copy-marker
  17484. (or (org-element-property :contents-end element)
  17485. ;; Fake contents for source blocks.
  17486. (org-with-wide-buffer
  17487. (goto-char element-end)
  17488. (skip-chars-backward " \r\t\n")
  17489. (line-beginning-position)))
  17490. t)))
  17491. ;; Do not change items indentation individually as it
  17492. ;; might break the list as a whole. On the other
  17493. ;; hand, when at a plain list, indent it as a whole.
  17494. (cond ((eq type 'plain-list)
  17495. (let ((offset (- ind (current-indentation))))
  17496. (unless (zerop offset)
  17497. (indent-rigidly (org-element-property :begin element)
  17498. (org-element-property :end element)
  17499. offset))
  17500. (goto-char cbeg)))
  17501. ((eq type 'item) (goto-char cbeg))
  17502. (t (funcall indent-to ind (min cbeg end))))
  17503. (when (< (point) end)
  17504. (cl-case type
  17505. ((example-block verse-block))
  17506. (src-block
  17507. ;; In a source block, indent source code
  17508. ;; according to language major mode, but only if
  17509. ;; `org-src-tab-acts-natively' is non-nil.
  17510. (when (and (< (point) end) org-src-tab-acts-natively)
  17511. (ignore-errors
  17512. (org-babel-do-in-edit-buffer
  17513. (indent-region (point-min) (point-max))))))
  17514. (t (org-indent-region (point) (min cend end))))
  17515. (goto-char (min cend end))
  17516. (when (< (point) end)
  17517. (funcall indent-to ind (min element-end end))))
  17518. (set-marker post nil)
  17519. (set-marker cbeg nil)
  17520. (set-marker cend nil))))
  17521. (set-marker element-end nil))))
  17522. (set-marker end nil))))
  17523. (defun org-indent-drawer ()
  17524. "Indent the drawer at point."
  17525. (interactive)
  17526. (unless (save-excursion
  17527. (beginning-of-line)
  17528. (looking-at-p org-drawer-regexp))
  17529. (user-error "Not at a drawer"))
  17530. (let ((element (org-element-at-point)))
  17531. (unless (memq (org-element-type element) '(drawer property-drawer))
  17532. (user-error "Not at a drawer"))
  17533. (org-with-wide-buffer
  17534. (org-indent-region (org-element-property :begin element)
  17535. (org-element-property :end element))))
  17536. (message "Drawer at point indented"))
  17537. (defun org-indent-block ()
  17538. "Indent the block at point."
  17539. (interactive)
  17540. (unless (save-excursion
  17541. (beginning-of-line)
  17542. (let ((case-fold-search t))
  17543. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17544. (user-error "Not at a block"))
  17545. (let ((element (org-element-at-point)))
  17546. (unless (memq (org-element-type element)
  17547. '(comment-block center-block dynamic-block example-block
  17548. export-block quote-block special-block
  17549. src-block verse-block))
  17550. (user-error "Not at a block"))
  17551. (org-with-wide-buffer
  17552. (org-indent-region (org-element-property :begin element)
  17553. (org-element-property :end element))))
  17554. (message "Block at point indented"))
  17555. ;;; Filling
  17556. ;; We use our own fill-paragraph and auto-fill functions.
  17557. ;; `org-fill-paragraph' relies on adaptive filling and context
  17558. ;; checking. Appropriate `fill-prefix' is computed with
  17559. ;; `org-adaptive-fill-function'.
  17560. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17561. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17562. ;; `org-adaptive-fill-function' value. Internally,
  17563. ;; `org-comment-line-break-function' breaks the line.
  17564. ;; `org-setup-filling' installs filling and auto-filling related
  17565. ;; variables during `org-mode' initialization.
  17566. (defun org-setup-filling ()
  17567. (require 'org-element)
  17568. ;; Prevent auto-fill from inserting unwanted new items.
  17569. (when (boundp 'fill-nobreak-predicate)
  17570. (setq-local
  17571. fill-nobreak-predicate
  17572. (org-uniquify
  17573. (append fill-nobreak-predicate
  17574. '(org-fill-line-break-nobreak-p
  17575. org-fill-n-macro-as-item-nobreak-p
  17576. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17577. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17578. (setq-local paragraph-start paragraph-ending)
  17579. (setq-local paragraph-separate paragraph-ending))
  17580. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17581. (setq-local auto-fill-inhibit-regexp nil)
  17582. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17583. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17584. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17585. (defun org-fill-line-break-nobreak-p ()
  17586. "Non-nil when a new line at point would create an Org line break."
  17587. (save-excursion
  17588. (skip-chars-backward " \t")
  17589. (skip-chars-backward "\\\\")
  17590. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17591. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17592. "Non-nil when a new line at point would split a timestamp."
  17593. (and (org-at-timestamp-p 'lax)
  17594. (not (looking-at org-ts-regexp-both))))
  17595. (defun org-fill-n-macro-as-item-nobreak-p ()
  17596. "Non-nil when a new line at point would create a new list."
  17597. ;; During export, a "n" macro followed by a dot or a closing
  17598. ;; parenthesis can end up being parsed as a new list item.
  17599. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17600. (defun org-adaptive-fill-function ()
  17601. "Compute a fill prefix for the current line.
  17602. Return fill prefix, as a string, or nil if current line isn't
  17603. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17604. matches in paragraphs or comments, use it."
  17605. (org-with-wide-buffer
  17606. (unless (org-at-heading-p)
  17607. (let* ((p (line-beginning-position))
  17608. (element (save-excursion
  17609. (beginning-of-line)
  17610. (org-element-at-point)))
  17611. (type (org-element-type element))
  17612. (post-affiliated (org-element-property :post-affiliated element)))
  17613. (unless (< p post-affiliated)
  17614. (cl-case type
  17615. (comment
  17616. (save-excursion
  17617. (beginning-of-line)
  17618. (looking-at "[ \t]*")
  17619. (concat (match-string 0) "# ")))
  17620. (footnote-definition "")
  17621. ((item plain-list)
  17622. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17623. (paragraph
  17624. ;; Fill prefix is usually the same as the current line,
  17625. ;; unless the paragraph is at the beginning of an item.
  17626. (let ((parent (org-element-property :parent element)))
  17627. (save-excursion
  17628. (beginning-of-line)
  17629. (cond ((eq (org-element-type parent) 'item)
  17630. (make-string (org-list-item-body-column
  17631. (org-element-property :begin parent))
  17632. ?\s))
  17633. ((and adaptive-fill-regexp
  17634. ;; Locally disable
  17635. ;; `adaptive-fill-function' to let
  17636. ;; `fill-context-prefix' handle
  17637. ;; `adaptive-fill-regexp' variable.
  17638. (let (adaptive-fill-function)
  17639. (fill-context-prefix
  17640. post-affiliated
  17641. (org-element-property :end element)))))
  17642. ((looking-at "[ \t]+") (match-string 0))
  17643. (t "")))))
  17644. (comment-block
  17645. ;; Only fill contents if P is within block boundaries.
  17646. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17647. (forward-line)
  17648. (point)))
  17649. (cend (save-excursion
  17650. (goto-char (org-element-property :end element))
  17651. (skip-chars-backward " \r\t\n")
  17652. (line-beginning-position))))
  17653. (when (and (>= p cbeg) (< p cend))
  17654. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17655. (match-string 0)
  17656. ""))))))))))
  17657. (defun org-fill-element (&optional justify)
  17658. "Fill element at point, when applicable.
  17659. This function only applies to comment blocks, comments, example
  17660. blocks and paragraphs. Also, as a special case, re-align table
  17661. when point is at one.
  17662. If JUSTIFY is non-nil (interactively, with prefix argument),
  17663. justify as well. If `sentence-end-double-space' is non-nil, then
  17664. period followed by one space does not end a sentence, so don't
  17665. break a line there. The variable `fill-column' controls the
  17666. width for filling.
  17667. For convenience, when point is at a plain list, an item or
  17668. a footnote definition, try to fill the first paragraph within."
  17669. (with-syntax-table org-mode-transpose-word-syntax-table
  17670. ;; Move to end of line in order to get the first paragraph within
  17671. ;; a plain list or a footnote definition.
  17672. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17673. ;; First check if point is in a blank line at the beginning of
  17674. ;; the buffer. In that case, ignore filling.
  17675. (cl-case (org-element-type element)
  17676. ;; Use major mode filling function is source blocks.
  17677. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17678. ;; Align Org tables, leave table.el tables as-is.
  17679. (table-row (org-table-align) t)
  17680. (table
  17681. (when (eq (org-element-property :type element) 'org)
  17682. (save-excursion
  17683. (goto-char (org-element-property :post-affiliated element))
  17684. (org-table-align)))
  17685. t)
  17686. (paragraph
  17687. ;; Paragraphs may contain `line-break' type objects.
  17688. (let ((beg (max (point-min)
  17689. (org-element-property :contents-begin element)))
  17690. (end (min (point-max)
  17691. (org-element-property :contents-end element))))
  17692. ;; Do nothing if point is at an affiliated keyword.
  17693. (if (< (line-end-position) beg) t
  17694. ;; Fill paragraph, taking line breaks into account.
  17695. (save-excursion
  17696. (goto-char beg)
  17697. (let ((cuts (list beg)))
  17698. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17699. (when (eq 'line-break
  17700. (org-element-type
  17701. (save-excursion (backward-char)
  17702. (org-element-context))))
  17703. (push (point) cuts)))
  17704. (dolist (c (delq end cuts))
  17705. (fill-region-as-paragraph c end justify)
  17706. (setq end c))))
  17707. t)))
  17708. ;; Contents of `comment-block' type elements should be
  17709. ;; filled as plain text, but only if point is within block
  17710. ;; markers.
  17711. (comment-block
  17712. (let* ((case-fold-search t)
  17713. (beg (save-excursion
  17714. (goto-char (org-element-property :begin element))
  17715. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17716. (forward-line)
  17717. (point)))
  17718. (end (save-excursion
  17719. (goto-char (org-element-property :end element))
  17720. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17721. (line-beginning-position))))
  17722. (if (or (< (point) beg) (> (point) end)) t
  17723. (fill-region-as-paragraph
  17724. (save-excursion (end-of-line)
  17725. (re-search-backward "^[ \t]*$" beg 'move)
  17726. (line-beginning-position))
  17727. (save-excursion (beginning-of-line)
  17728. (re-search-forward "^[ \t]*$" end 'move)
  17729. (line-beginning-position))
  17730. justify))))
  17731. ;; Fill comments.
  17732. (comment
  17733. (let ((begin (org-element-property :post-affiliated element))
  17734. (end (org-element-property :end element)))
  17735. (when (and (>= (point) begin) (<= (point) end))
  17736. (let ((begin (save-excursion
  17737. (end-of-line)
  17738. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17739. (progn (forward-line) (point))
  17740. begin)))
  17741. (end (save-excursion
  17742. (end-of-line)
  17743. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17744. (1- (line-beginning-position))
  17745. (skip-chars-backward " \r\t\n")
  17746. (line-end-position)))))
  17747. ;; Do not fill comments when at a blank line.
  17748. (when (> end begin)
  17749. (let ((fill-prefix
  17750. (save-excursion
  17751. (beginning-of-line)
  17752. (looking-at "[ \t]*#")
  17753. (let ((comment-prefix (match-string 0)))
  17754. (goto-char (match-end 0))
  17755. (if (looking-at adaptive-fill-regexp)
  17756. (concat comment-prefix (match-string 0))
  17757. (concat comment-prefix " "))))))
  17758. (save-excursion
  17759. (fill-region-as-paragraph begin end justify))))))
  17760. t))
  17761. ;; Ignore every other element.
  17762. (otherwise t)))))
  17763. (defun org-fill-paragraph (&optional justify region)
  17764. "Fill element at point, when applicable.
  17765. This function only applies to comment blocks, comments, example
  17766. blocks and paragraphs. Also, as a special case, re-align table
  17767. when point is at one.
  17768. For convenience, when point is at a plain list, an item or
  17769. a footnote definition, try to fill the first paragraph within.
  17770. If JUSTIFY is non-nil (interactively, with prefix argument),
  17771. justify as well. If `sentence-end-double-space' is non-nil, then
  17772. period followed by one space does not end a sentence, so don't
  17773. break a line there. The variable `fill-column' controls the
  17774. width for filling.
  17775. The REGION argument is non-nil if called interactively; in that
  17776. case, if Transient Mark mode is enabled and the mark is active,
  17777. fill each of the elements in the active region, instead of just
  17778. filling the current element."
  17779. (interactive (progn
  17780. (barf-if-buffer-read-only)
  17781. (list (when current-prefix-arg 'full) t)))
  17782. (let ((hash (and (not (buffer-modified-p))
  17783. (org-buffer-hash))))
  17784. (cond
  17785. ((and region transient-mark-mode mark-active
  17786. (not (eq (region-beginning) (region-end))))
  17787. (let ((origin (point-marker))
  17788. (start (region-beginning)))
  17789. (unwind-protect
  17790. (progn
  17791. (goto-char (region-end))
  17792. (skip-chars-backward " \t\n")
  17793. (while (> (point) start)
  17794. (org-fill-element justify)
  17795. (org-backward-paragraph)))
  17796. (goto-char origin)
  17797. (set-marker origin nil))))
  17798. (t
  17799. (save-excursion
  17800. (when (org-match-line "[ \t]*$")
  17801. (skip-chars-forward " \t\n"))
  17802. (org-fill-element justify))))
  17803. ;; If we didn't change anything in the buffer (and the buffer was
  17804. ;; previously unmodified), then flip the modification status back
  17805. ;; to "unchanged".
  17806. (when (and hash (equal hash (org-buffer-hash)))
  17807. (set-buffer-modified-p nil))))
  17808. (defun org-auto-fill-function ()
  17809. "Auto-fill function."
  17810. ;; Check if auto-filling is meaningful.
  17811. (let ((fc (current-fill-column)))
  17812. (when (and fc (> (current-column) fc))
  17813. (let* ((fill-prefix (org-adaptive-fill-function))
  17814. ;; Enforce empty fill prefix, if required. Otherwise, it
  17815. ;; will be computed again.
  17816. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17817. (when fill-prefix (do-auto-fill))))))
  17818. (defun org-comment-line-break-function (&optional soft)
  17819. "Break line at point and indent, continuing comment if within one.
  17820. The inserted newline is marked hard if variable
  17821. `use-hard-newlines' is true, unless optional argument SOFT is
  17822. non-nil."
  17823. (if soft (insert-and-inherit ?\n) (newline 1))
  17824. (save-excursion (forward-char -1) (delete-horizontal-space))
  17825. (delete-horizontal-space)
  17826. (indent-to-left-margin)
  17827. (insert-before-markers-and-inherit fill-prefix))
  17828. ;;; Fixed Width Areas
  17829. (defun org-toggle-fixed-width ()
  17830. "Toggle fixed-width markup.
  17831. Add or remove fixed-width markup on current line, whenever it
  17832. makes sense. Return an error otherwise.
  17833. If a region is active and if it contains only fixed-width areas
  17834. or blank lines, remove all fixed-width markup in it. If the
  17835. region contains anything else, convert all non-fixed-width lines
  17836. to fixed-width ones.
  17837. Blank lines at the end of the region are ignored unless the
  17838. region only contains such lines."
  17839. (interactive)
  17840. (if (not (org-region-active-p))
  17841. ;; No region:
  17842. ;;
  17843. ;; Remove fixed width marker only in a fixed-with element.
  17844. ;;
  17845. ;; Add fixed width maker in paragraphs, in blank lines after
  17846. ;; elements or at the beginning of a headline or an inlinetask,
  17847. ;; and before any one-line elements (e.g., a clock).
  17848. (progn
  17849. (beginning-of-line)
  17850. (let* ((element (org-element-at-point))
  17851. (type (org-element-type element)))
  17852. (cond
  17853. ((and (eq type 'fixed-width)
  17854. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17855. (replace-match
  17856. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17857. ((and (memq type '(babel-call clock comment diary-sexp headline
  17858. horizontal-rule keyword paragraph
  17859. planning))
  17860. (<= (org-element-property :post-affiliated element) (point)))
  17861. (skip-chars-forward " \t")
  17862. (insert ": "))
  17863. ((and (looking-at-p "[ \t]*$")
  17864. (or (eq type 'inlinetask)
  17865. (save-excursion
  17866. (skip-chars-forward " \r\t\n")
  17867. (<= (org-element-property :end element) (point)))))
  17868. (delete-region (point) (line-end-position))
  17869. (org-indent-line)
  17870. (insert ": "))
  17871. (t (user-error "Cannot insert a fixed-width line here")))))
  17872. ;; Region active.
  17873. (let* ((begin (save-excursion
  17874. (goto-char (region-beginning))
  17875. (line-beginning-position)))
  17876. (end (copy-marker
  17877. (save-excursion
  17878. (goto-char (region-end))
  17879. (unless (eolp) (beginning-of-line))
  17880. (if (save-excursion (re-search-backward "\\S-" begin t))
  17881. (progn (skip-chars-backward " \r\t\n") (point))
  17882. (point)))))
  17883. (all-fixed-width-p
  17884. (catch 'not-all-p
  17885. (save-excursion
  17886. (goto-char begin)
  17887. (skip-chars-forward " \r\t\n")
  17888. (when (eobp) (throw 'not-all-p nil))
  17889. (while (< (point) end)
  17890. (let ((element (org-element-at-point)))
  17891. (if (eq (org-element-type element) 'fixed-width)
  17892. (goto-char (org-element-property :end element))
  17893. (throw 'not-all-p nil))))
  17894. t))))
  17895. (if all-fixed-width-p
  17896. (save-excursion
  17897. (goto-char begin)
  17898. (while (< (point) end)
  17899. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17900. (replace-match
  17901. "" nil nil nil
  17902. (if (= (line-end-position) (match-end 0)) 0 1)))
  17903. (forward-line)))
  17904. (let ((min-ind (point-max)))
  17905. ;; Find minimum indentation across all lines.
  17906. (save-excursion
  17907. (goto-char begin)
  17908. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17909. (setq min-ind 0)
  17910. (catch 'zerop
  17911. (while (< (point) end)
  17912. (unless (looking-at-p "[ \t]*$")
  17913. (let ((ind (current-indentation)))
  17914. (setq min-ind (min min-ind ind))
  17915. (when (zerop ind) (throw 'zerop t))))
  17916. (forward-line)))))
  17917. ;; Loop over all lines and add fixed-width markup everywhere
  17918. ;; but in fixed-width lines.
  17919. (save-excursion
  17920. (goto-char begin)
  17921. (while (< (point) end)
  17922. (cond
  17923. ((org-at-heading-p)
  17924. (insert ": ")
  17925. (forward-line)
  17926. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17927. (insert ":")
  17928. (forward-line)))
  17929. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17930. (let* ((element (org-element-at-point))
  17931. (element-end (org-element-property :end element)))
  17932. (if (eq (org-element-type element) 'fixed-width)
  17933. (progn (goto-char element-end)
  17934. (skip-chars-backward " \r\t\n")
  17935. (forward-line))
  17936. (let ((limit (min end element-end)))
  17937. (while (< (point) limit)
  17938. (org-move-to-column min-ind t)
  17939. (insert ": ")
  17940. (forward-line))))))
  17941. (t
  17942. (org-move-to-column min-ind t)
  17943. (insert ": ")
  17944. (forward-line)))))))
  17945. (set-marker end nil))))
  17946. ;;; Blocks
  17947. (defun org-block-map (function &optional start end)
  17948. "Call FUNCTION at the head of all source blocks in the current buffer.
  17949. Optional arguments START and END can be used to limit the range."
  17950. (let ((start (or start (point-min)))
  17951. (end (or end (point-max))))
  17952. (save-excursion
  17953. (goto-char start)
  17954. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17955. (save-excursion
  17956. (save-match-data
  17957. (goto-char (match-beginning 0))
  17958. (funcall function)))))))
  17959. (defun org-next-block (arg &optional backward block-regexp)
  17960. "Jump to the next block.
  17961. With a prefix argument ARG, jump forward ARG many blocks.
  17962. When BACKWARD is non-nil, jump to the previous block.
  17963. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17964. Match data is set according to this regexp when the function
  17965. returns.
  17966. Return point at beginning of the opening line of found block.
  17967. Throw an error if no block is found."
  17968. (interactive "p")
  17969. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17970. (case-fold-search t)
  17971. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17972. (count (or arg 1))
  17973. (origin (point))
  17974. last-element)
  17975. (if backward (beginning-of-line) (end-of-line))
  17976. (while (and (> count 0) (funcall search-fn re nil t))
  17977. (let ((element (save-excursion
  17978. (goto-char (match-beginning 0))
  17979. (save-match-data (org-element-at-point)))))
  17980. (when (and (memq (org-element-type element)
  17981. '(center-block comment-block dynamic-block
  17982. example-block export-block quote-block
  17983. special-block src-block verse-block))
  17984. (<= (match-beginning 0)
  17985. (org-element-property :post-affiliated element)))
  17986. (setq last-element element)
  17987. (cl-decf count))))
  17988. (if (= count 0)
  17989. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17990. (save-match-data (org-show-context)))
  17991. (goto-char origin)
  17992. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17993. (defun org-previous-block (arg &optional block-regexp)
  17994. "Jump to the previous block.
  17995. With a prefix argument ARG, jump backward ARG many source blocks.
  17996. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17997. (interactive "p")
  17998. (org-next-block arg t block-regexp))
  17999. ;;; Comments
  18000. ;; Org comments syntax is quite complex. It requires the entire line
  18001. ;; to be just a comment. Also, even with the right syntax at the
  18002. ;; beginning of line, some elements (e.g., verse-block or
  18003. ;; example-block) don't accept comments. Usual Emacs comment commands
  18004. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18005. ;; Org still relies on `comment-dwim', but cannot trust
  18006. ;; `comment-only-p'. So, `comment-region-function' and
  18007. ;; `uncomment-region-function' both point
  18008. ;; to`org-comment-or-uncomment-region'. Eventually,
  18009. ;; `org-insert-comment' takes care of insertion of comments at the
  18010. ;; beginning of line.
  18011. ;; `org-setup-comments-handling' install comments related variables
  18012. ;; during `org-mode' initialization.
  18013. (defun org-setup-comments-handling ()
  18014. (interactive)
  18015. (setq-local comment-use-syntax nil)
  18016. (setq-local comment-start "# ")
  18017. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18018. (setq-local comment-insert-comment-function 'org-insert-comment)
  18019. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18020. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18021. (defun org-insert-comment ()
  18022. "Insert an empty comment above current line.
  18023. If the line is empty, insert comment at its beginning. When
  18024. point is within a source block, comment according to the related
  18025. major mode."
  18026. (if (let ((element (org-element-at-point)))
  18027. (and (eq (org-element-type element) 'src-block)
  18028. (< (save-excursion
  18029. (goto-char (org-element-property :post-affiliated element))
  18030. (line-end-position))
  18031. (point))
  18032. (> (save-excursion
  18033. (goto-char (org-element-property :end element))
  18034. (skip-chars-backward " \r\t\n")
  18035. (line-beginning-position))
  18036. (point))))
  18037. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18038. (beginning-of-line)
  18039. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18040. (open-line 1))
  18041. (org-indent-line)
  18042. (insert "# ")))
  18043. (defvar comment-empty-lines) ; From newcomment.el.
  18044. (defun org-comment-or-uncomment-region (beg end &rest _)
  18045. "Comment or uncomment each non-blank line in the region.
  18046. Uncomment each non-blank line between BEG and END if it only
  18047. contains commented lines. Otherwise, comment them. If region is
  18048. strictly within a source block, use appropriate comment syntax."
  18049. (if (let ((element (org-element-at-point)))
  18050. (and (eq (org-element-type element) 'src-block)
  18051. (< (save-excursion
  18052. (goto-char (org-element-property :post-affiliated element))
  18053. (line-end-position))
  18054. beg)
  18055. (>= (save-excursion
  18056. (goto-char (org-element-property :end element))
  18057. (skip-chars-backward " \r\t\n")
  18058. (line-beginning-position))
  18059. end)))
  18060. ;; Translate region boundaries for the Org buffer to the source
  18061. ;; buffer.
  18062. (let ((offset (- end beg)))
  18063. (save-excursion
  18064. (goto-char beg)
  18065. (org-babel-do-in-edit-buffer
  18066. (comment-or-uncomment-region (point) (+ offset (point))))))
  18067. (save-restriction
  18068. ;; Restrict region
  18069. (narrow-to-region (save-excursion (goto-char beg)
  18070. (skip-chars-forward " \r\t\n" end)
  18071. (line-beginning-position))
  18072. (save-excursion (goto-char end)
  18073. (skip-chars-backward " \r\t\n" beg)
  18074. (line-end-position)))
  18075. (let ((uncommentp
  18076. ;; UNCOMMENTP is non-nil when every non blank line between
  18077. ;; BEG and END is a comment.
  18078. (save-excursion
  18079. (goto-char (point-min))
  18080. (while (and (not (eobp))
  18081. (let ((element (org-element-at-point)))
  18082. (and (eq (org-element-type element) 'comment)
  18083. (goto-char (min (point-max)
  18084. (org-element-property
  18085. :end element)))))))
  18086. (eobp))))
  18087. (if uncommentp
  18088. ;; Only blank lines and comments in region: uncomment it.
  18089. (save-excursion
  18090. (goto-char (point-min))
  18091. (while (not (eobp))
  18092. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18093. (replace-match "" nil nil nil 1))
  18094. (forward-line)))
  18095. ;; Comment each line in region.
  18096. (let ((min-indent (point-max)))
  18097. ;; First find the minimum indentation across all lines.
  18098. (save-excursion
  18099. (goto-char (point-min))
  18100. (while (and (not (eobp)) (not (zerop min-indent)))
  18101. (unless (looking-at "[ \t]*$")
  18102. (setq min-indent (min min-indent (current-indentation))))
  18103. (forward-line)))
  18104. ;; Then loop over all lines.
  18105. (save-excursion
  18106. (goto-char (point-min))
  18107. (while (not (eobp))
  18108. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18109. ;; Don't get fooled by invisible text (e.g. link path)
  18110. ;; when moving to column MIN-INDENT.
  18111. (let ((buffer-invisibility-spec nil))
  18112. (org-move-to-column min-indent t))
  18113. (insert comment-start))
  18114. (forward-line)))))))))
  18115. (defun org-comment-dwim (_arg)
  18116. "Call the comment command you mean.
  18117. Call `org-toggle-comment' if on a heading, otherwise call
  18118. `comment-dwim', within a source edit buffer if needed."
  18119. (interactive "*P")
  18120. (cond ((org-at-heading-p)
  18121. (call-interactively #'org-toggle-comment))
  18122. ((org-in-src-block-p)
  18123. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18124. (t (call-interactively #'comment-dwim))))
  18125. ;;; Timestamps API
  18126. ;; This section contains tools to operate on, or create, timestamp
  18127. ;; objects, as returned by, e.g. `org-element-context'.
  18128. (defun org-timestamp-from-string (s)
  18129. "Convert Org timestamp S, as a string, into a timestamp object.
  18130. Return nil if S is not a valid timestamp string."
  18131. (when (org-string-nw-p s)
  18132. (with-temp-buffer
  18133. (save-excursion (insert s))
  18134. (org-element-timestamp-parser))))
  18135. (defun org-timestamp-from-time (time &optional with-time inactive)
  18136. "Convert a time value into a timestamp object.
  18137. TIME is an Emacs internal time representation, as returned, e.g.,
  18138. by `current-time'.
  18139. When optional argument WITH-TIME is non-nil, return a timestamp
  18140. object with a time part, i.e., with hours and minutes.
  18141. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18142. return an active timestamp."
  18143. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18144. (org-element-create 'timestamp
  18145. (list :type (if inactive 'inactive 'active)
  18146. :year-start year
  18147. :month-start month
  18148. :day-start day
  18149. :hour-start (and with-time hour)
  18150. :minute-start (and with-time minute)))))
  18151. (defun org-timestamp-to-time (timestamp &optional end)
  18152. "Convert TIMESTAMP object into an Emacs internal time value.
  18153. Use end of date range or time range when END is non-nil.
  18154. Otherwise, use its start."
  18155. (apply #'encode-time 0
  18156. (mapcar
  18157. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18158. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18159. '(:minute-start :hour-start :day-start :month-start
  18160. :year-start)))))
  18161. (defun org-timestamp-has-time-p (timestamp)
  18162. "Non-nil when TIMESTAMP has a time specified."
  18163. (org-element-property :hour-start timestamp))
  18164. (defun org-timestamp-format (timestamp format &optional end utc)
  18165. "Format a TIMESTAMP object into a string.
  18166. FORMAT is a format specifier to be passed to
  18167. `format-time-string'.
  18168. When optional argument END is non-nil, use end of date-range or
  18169. time-range, if possible.
  18170. When optional argument UTC is non-nil, time is be expressed as
  18171. Universal Time."
  18172. (format-time-string format (org-timestamp-to-time timestamp end)
  18173. (and utc t)))
  18174. (defun org-timestamp-split-range (timestamp &optional end)
  18175. "Extract a TIMESTAMP object from a date or time range.
  18176. END, when non-nil, means extract the end of the range.
  18177. Otherwise, extract its start.
  18178. Return a new timestamp object."
  18179. (let ((type (org-element-property :type timestamp)))
  18180. (if (memq type '(active inactive diary)) timestamp
  18181. (let ((split-ts (org-element-copy timestamp)))
  18182. ;; Set new type.
  18183. (org-element-put-property
  18184. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18185. ;; Copy start properties over end properties if END is
  18186. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18187. (let ((p-alist '((:minute-start . :minute-end)
  18188. (:hour-start . :hour-end)
  18189. (:day-start . :day-end)
  18190. (:month-start . :month-end)
  18191. (:year-start . :year-end))))
  18192. (dolist (p-cell p-alist)
  18193. (org-element-put-property
  18194. split-ts
  18195. (funcall (if end #'car #'cdr) p-cell)
  18196. (org-element-property
  18197. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18198. ;; Eventually refresh `:raw-value'.
  18199. (org-element-put-property split-ts :raw-value nil)
  18200. (org-element-put-property
  18201. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18202. (defun org-timestamp-translate (timestamp &optional boundary)
  18203. "Translate TIMESTAMP object to custom format.
  18204. Format string is defined in `org-time-stamp-custom-formats',
  18205. which see.
  18206. When optional argument BOUNDARY is non-nil, it is either the
  18207. symbol `start' or `end'. In this case, only translate the
  18208. starting or ending part of TIMESTAMP if it is a date or time
  18209. range. Otherwise, translate both parts.
  18210. Return timestamp as-is if `org-display-custom-times' is nil or if
  18211. it has a `diary' type."
  18212. (let ((type (org-element-property :type timestamp)))
  18213. (if (or (not org-display-custom-times) (eq type 'diary))
  18214. (org-element-interpret-data timestamp)
  18215. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18216. org-time-stamp-custom-formats)))
  18217. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18218. (concat (org-timestamp-format timestamp fmt)
  18219. "--"
  18220. (org-timestamp-format timestamp fmt t))
  18221. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18222. ;;; Other stuff
  18223. (defvar reftex-docstruct-symbol)
  18224. (defvar org--rds)
  18225. (defun org-reftex-citation ()
  18226. "Use reftex-citation to insert a citation into the buffer.
  18227. This looks for a line like
  18228. #+BIBLIOGRAPHY: foo plain option:-d
  18229. and derives from it that foo.bib is the bibliography file relevant
  18230. for this document. It then installs the necessary environment for RefTeX
  18231. to work in this buffer and calls `reftex-citation' to insert a citation
  18232. into the buffer.
  18233. Export of such citations to both LaTeX and HTML is handled by the contributed
  18234. package ox-bibtex by Taru Karttunen."
  18235. (interactive)
  18236. (let ((reftex-docstruct-symbol 'org--rds)
  18237. org--rds bib)
  18238. (org-with-wide-buffer
  18239. (let ((case-fold-search t)
  18240. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18241. (if (not (save-excursion
  18242. (or (re-search-forward re nil t)
  18243. (re-search-backward re nil t))))
  18244. (user-error "No bibliography defined in file")
  18245. (setq bib (concat (match-string 1) ".bib")
  18246. org--rds (list (list 'bib bib))))))
  18247. (call-interactively 'reftex-citation)))
  18248. ;;;; Functions extending outline functionality
  18249. (defun org-beginning-of-line (&optional n)
  18250. "Go to the beginning of the current visible line.
  18251. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18252. symbol `reversed', on the first attempt move to where the
  18253. headline text starts, and only move to beginning of line when the
  18254. cursor is already before the start of the text of the headline.
  18255. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18256. start of the text on the second attempt.
  18257. With argument N not nil or 1, move forward N - 1 lines first."
  18258. (interactive "^p")
  18259. (let ((origin (point))
  18260. (special (pcase org-special-ctrl-a/e
  18261. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18262. deactivate-mark)
  18263. ;; First move to a visible line.
  18264. (if (bound-and-true-p visual-line-mode)
  18265. (beginning-of-visual-line n)
  18266. (move-beginning-of-line n)
  18267. ;; `move-beginning-of-line' may leave point after invisible
  18268. ;; characters if line starts with such of these (e.g., with
  18269. ;; a link at column 0). Really move to the beginning of the
  18270. ;; current visible line.
  18271. (beginning-of-line))
  18272. (cond
  18273. ;; No special behavior. Point is already at the beginning of
  18274. ;; a line, logical or visual.
  18275. ((not special))
  18276. ;; `beginning-of-visual-line' left point before logical beginning
  18277. ;; of line: point is at the beginning of a visual line. Bail
  18278. ;; out.
  18279. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18280. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18281. ;; At a headline, special position is before the title, but
  18282. ;; after any TODO keyword or priority cookie.
  18283. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18284. (line-end-position)))
  18285. (bol (point)))
  18286. (if (eq special 'reversed)
  18287. (when (and (= origin bol) (eq last-command this-command))
  18288. (goto-char refpos))
  18289. (when (or (> origin refpos) (= origin bol))
  18290. (goto-char refpos)))))
  18291. ((and (looking-at org-list-full-item-re)
  18292. (memq (org-element-type (save-match-data (org-element-at-point)))
  18293. '(item plain-list)))
  18294. ;; Set special position at first white space character after
  18295. ;; bullet, and check-box, if any.
  18296. (let ((after-bullet
  18297. (let ((box (match-end 3)))
  18298. (cond ((not box) (match-end 1))
  18299. ((eq (char-after box) ?\s) (1+ box))
  18300. (t box)))))
  18301. (if (eq special 'reversed)
  18302. (when (and (= (point) origin) (eq last-command this-command))
  18303. (goto-char after-bullet))
  18304. (when (or (> origin after-bullet) (= (point) origin))
  18305. (goto-char after-bullet)))))
  18306. ;; No special context. Point is already at beginning of line.
  18307. (t nil))))
  18308. (defun org-end-of-line (&optional n)
  18309. "Go to the end of the line, but before ellipsis, if any.
  18310. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18311. symbol `reversed', ignore tags on the first attempt, and only
  18312. move to after the tags when the cursor is already beyond the end
  18313. of the headline.
  18314. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18315. on the second attempt.
  18316. With argument N not nil or 1, move forward N - 1 lines first."
  18317. (interactive "^p")
  18318. (let ((origin (point))
  18319. (special (pcase org-special-ctrl-a/e
  18320. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18321. deactivate-mark)
  18322. ;; First move to a visible line.
  18323. (if (bound-and-true-p visual-line-mode)
  18324. (beginning-of-visual-line n)
  18325. (move-beginning-of-line n))
  18326. (cond
  18327. ;; At a headline, with tags.
  18328. ((and special
  18329. (save-excursion
  18330. (beginning-of-line)
  18331. (let ((case-fold-search nil))
  18332. (looking-at org-complex-heading-regexp)))
  18333. (match-end 5))
  18334. (let ((tags (save-excursion
  18335. (goto-char (match-beginning 5))
  18336. (skip-chars-backward " \t")
  18337. (point)))
  18338. (visual-end (and (bound-and-true-p visual-line-mode)
  18339. (save-excursion
  18340. (end-of-visual-line)
  18341. (point)))))
  18342. ;; If `end-of-visual-line' brings us before end of line or
  18343. ;; even tags, i.e., the headline spans over multiple visual
  18344. ;; lines, move there.
  18345. (cond ((and visual-end
  18346. (< visual-end tags)
  18347. (<= origin visual-end))
  18348. (goto-char visual-end))
  18349. ((eq special 'reversed)
  18350. (if (and (= origin (line-end-position))
  18351. (eq this-command last-command))
  18352. (goto-char tags)
  18353. (end-of-line)))
  18354. (t
  18355. (if (or (< origin tags) (= origin (line-end-position)))
  18356. (goto-char tags)
  18357. (end-of-line))))))
  18358. ((bound-and-true-p visual-line-mode)
  18359. (let ((bol (line-beginning-position)))
  18360. (end-of-visual-line)
  18361. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18362. ;; end of a line, backtrack and use `end-of-line' instead.
  18363. (when (/= bol (line-beginning-position))
  18364. (goto-char bol)
  18365. (end-of-line))))
  18366. (t (end-of-line)))))
  18367. (defun org-backward-sentence (&optional _arg)
  18368. "Go to beginning of sentence, or beginning of table field.
  18369. This will call `backward-sentence' or `org-table-beginning-of-field',
  18370. depending on context."
  18371. (interactive)
  18372. (let* ((element (org-element-at-point))
  18373. (contents-begin (org-element-property :contents-begin element))
  18374. (table (org-element-lineage element '(table) t)))
  18375. (if (and table
  18376. (> (point) contents-begin)
  18377. (<= (point) (org-element-property :contents-end table)))
  18378. (call-interactively #'org-table-beginning-of-field)
  18379. (save-restriction
  18380. (when (and contents-begin
  18381. (< (point-min) contents-begin)
  18382. (> (point) contents-begin))
  18383. (narrow-to-region contents-begin
  18384. (org-element-property :contents-end element)))
  18385. (call-interactively #'backward-sentence)))))
  18386. (defun org-forward-sentence (&optional _arg)
  18387. "Go to end of sentence, or end of table field.
  18388. This will call `forward-sentence' or `org-table-end-of-field',
  18389. depending on context."
  18390. (interactive)
  18391. (if (and (org-at-heading-p)
  18392. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18393. (save-restriction
  18394. (narrow-to-region (line-beginning-position) (line-end-position))
  18395. (call-interactively #'forward-sentence))
  18396. (let* ((element (org-element-at-point))
  18397. (contents-end (org-element-property :contents-end element))
  18398. (table (org-element-lineage element '(table) t)))
  18399. (if (and table
  18400. (>= (point) (org-element-property :contents-begin table))
  18401. (< (point) contents-end))
  18402. (call-interactively #'org-table-end-of-field)
  18403. (save-restriction
  18404. (when (and contents-end
  18405. (> (point-max) contents-end)
  18406. ;; Skip blank lines between elements.
  18407. (< (org-element-property :end element)
  18408. (save-excursion (goto-char contents-end)
  18409. (skip-chars-forward " \r\t\n"))))
  18410. (narrow-to-region (org-element-property :contents-begin element)
  18411. contents-end))
  18412. ;; End of heading is considered as the end of a sentence.
  18413. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18414. (call-interactively #'forward-sentence)))))))
  18415. (defun org-kill-line (&optional _arg)
  18416. "Kill line, to tags or end of line."
  18417. (interactive)
  18418. (cond
  18419. ((or (not org-special-ctrl-k)
  18420. (bolp)
  18421. (not (org-at-heading-p)))
  18422. (when (and (get-char-property (line-end-position) 'invisible)
  18423. org-ctrl-k-protect-subtree
  18424. (or (eq org-ctrl-k-protect-subtree 'error)
  18425. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18426. (user-error
  18427. (substitute-command-keys
  18428. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18429. (call-interactively
  18430. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18431. ((org-match-line org-tag-line-re)
  18432. (let ((end (save-excursion
  18433. (goto-char (match-beginning 1))
  18434. (skip-chars-backward " \t")
  18435. (point))))
  18436. (if (<= end (point)) ;on tags part
  18437. (kill-region (point) (line-end-position))
  18438. (kill-region (point) end)))
  18439. ;; Only align tags when we are still on a heading:
  18440. (if (org-at-heading-p) (org-align-tags)))
  18441. (t (kill-region (point) (line-end-position)))))
  18442. (defun org-yank (&optional arg)
  18443. "Yank. If the kill is a subtree, treat it specially.
  18444. This command will look at the current kill and check if is a single
  18445. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18446. cursor is at the beginning of a line or after the stars of a currently
  18447. empty headline, then the yank is handled specially. How exactly depends
  18448. on the value of the following variables.
  18449. `org-yank-folded-subtrees'
  18450. By default, this variable is non-nil, which results in
  18451. subtree(s) being folded after insertion, except if doing so
  18452. would swallow text after the yanked text.
  18453. `org-yank-adjusted-subtrees'
  18454. When non-nil (the default value is nil), the subtree will be
  18455. promoted or demoted in order to fit into the local outline tree
  18456. structure, which means that the level will be adjusted so that it
  18457. becomes the smaller one of the two *visible* surrounding headings.
  18458. Any prefix to this command will cause `yank' to be called directly with
  18459. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18460. will just
  18461. plainly yank the text as it is.
  18462. \[1] The test checks if the first non-white line is a heading
  18463. and if there are no other headings with fewer stars."
  18464. (interactive "P")
  18465. (org-yank-generic 'yank arg))
  18466. (defun org-yank-generic (command arg)
  18467. "Perform some yank-like command.
  18468. This function implements the behavior described in the `org-yank'
  18469. documentation. However, it has been generalized to work for any
  18470. interactive command with similar behavior."
  18471. ;; pretend to be command COMMAND
  18472. (setq this-command command)
  18473. (if arg
  18474. (call-interactively command)
  18475. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18476. (and (org-kill-is-subtree-p)
  18477. (or (bolp)
  18478. (and (looking-at "[ \t]*$")
  18479. (string-match
  18480. "\\`\\*+\\'"
  18481. (buffer-substring (point-at-bol) (point)))))))
  18482. swallowp)
  18483. (cond
  18484. ((and subtreep org-yank-folded-subtrees)
  18485. (let ((beg (point))
  18486. end)
  18487. (if (and subtreep org-yank-adjusted-subtrees)
  18488. (org-paste-subtree nil nil 'for-yank)
  18489. (call-interactively command))
  18490. (setq end (point))
  18491. (goto-char beg)
  18492. (when (and (bolp) subtreep
  18493. (not (setq swallowp
  18494. (org-yank-folding-would-swallow-text beg end))))
  18495. (org-with-limited-levels
  18496. (or (looking-at org-outline-regexp)
  18497. (re-search-forward org-outline-regexp-bol end t))
  18498. (while (and (< (point) end) (looking-at org-outline-regexp))
  18499. (org-flag-subtree t)
  18500. (org-cycle-show-empty-lines 'folded)
  18501. (condition-case nil
  18502. (outline-forward-same-level 1)
  18503. (error (goto-char end))))))
  18504. (when swallowp
  18505. (message
  18506. "Inserted text not folded because that would swallow text"))
  18507. (goto-char end)
  18508. (skip-chars-forward " \t\n\r")
  18509. (beginning-of-line 1)
  18510. (push-mark beg 'nomsg)))
  18511. ((and subtreep org-yank-adjusted-subtrees)
  18512. (let ((beg (point-at-bol)))
  18513. (org-paste-subtree nil nil 'for-yank)
  18514. (push-mark beg 'nomsg)))
  18515. (t
  18516. (call-interactively command))))))
  18517. (defun org-yank-folding-would-swallow-text (beg end)
  18518. "Would hide-subtree at BEG swallow any text after END?"
  18519. (let (level)
  18520. (org-with-limited-levels
  18521. (save-excursion
  18522. (goto-char beg)
  18523. (when (or (looking-at org-outline-regexp)
  18524. (re-search-forward org-outline-regexp-bol end t))
  18525. (setq level (org-outline-level)))
  18526. (goto-char end)
  18527. (skip-chars-forward " \t\r\n\v\f")
  18528. (not (or (eobp)
  18529. (and (bolp) (looking-at-p org-outline-regexp)
  18530. (<= (org-outline-level) level))))))))
  18531. (defun org-back-to-heading (&optional invisible-ok)
  18532. "Call `outline-back-to-heading', but provide a better error message."
  18533. (condition-case nil
  18534. (outline-back-to-heading invisible-ok)
  18535. (error
  18536. (user-error "Before first headline at position %d in buffer %s"
  18537. (point) (current-buffer)))))
  18538. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18539. "Go back to heading or first point in buffer.
  18540. If point is before first heading go to first point in buffer
  18541. instead of back to heading."
  18542. (condition-case nil
  18543. (outline-back-to-heading invisible-ok)
  18544. (error
  18545. (goto-char (point-min)))))
  18546. (defun org-before-first-heading-p ()
  18547. "Before first heading?"
  18548. (org-with-limited-levels
  18549. (save-excursion
  18550. (end-of-line)
  18551. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18552. (defun org-at-heading-p (&optional _)
  18553. "Non-nil when on a headline."
  18554. (outline-on-heading-p t))
  18555. (defun org-in-commented-heading-p (&optional no-inheritance)
  18556. "Non-nil if point is under a commented heading.
  18557. This function also checks ancestors of the current headline,
  18558. unless optional argument NO-INHERITANCE is non-nil."
  18559. (cond
  18560. ((org-before-first-heading-p) nil)
  18561. ((let ((headline (nth 4 (org-heading-components))))
  18562. (and headline
  18563. (let ((case-fold-search nil))
  18564. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18565. headline)))))
  18566. (no-inheritance nil)
  18567. (t
  18568. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18569. (defun org-in-archived-heading-p (&optional no-inheritance)
  18570. "Non-nil if point is under an archived heading.
  18571. This function also checks ancestors of the current headline,
  18572. unless optional argument NO-INHERITANCE is non-nil."
  18573. (cond
  18574. ((org-before-first-heading-p) nil)
  18575. ((let ((tags (org-get-tags nil 'local)))
  18576. (and tags
  18577. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18578. (no-inheritance nil)
  18579. (t
  18580. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18581. (defun org-at-comment-p nil
  18582. "Return t if cursor is in a commented line."
  18583. (save-excursion
  18584. (save-match-data
  18585. (beginning-of-line)
  18586. (looking-at org-comment-regexp))))
  18587. (defun org-at-keyword-p nil
  18588. "Return t if cursor is at a keyword-line."
  18589. (save-excursion
  18590. (move-beginning-of-line 1)
  18591. (looking-at org-keyword-regexp)))
  18592. (defun org-at-drawer-p nil
  18593. "Return t if cursor is at a drawer keyword."
  18594. (save-excursion
  18595. (move-beginning-of-line 1)
  18596. (looking-at org-drawer-regexp)))
  18597. (defun org-at-block-p nil
  18598. "Return t if cursor is at a block keyword."
  18599. (save-excursion
  18600. (move-beginning-of-line 1)
  18601. (looking-at org-block-regexp)))
  18602. (defun org-point-at-end-of-empty-headline ()
  18603. "If point is at the end of an empty headline, return t, else nil.
  18604. If the heading only contains a TODO keyword, it is still still considered
  18605. empty."
  18606. (let ((case-fold-search nil))
  18607. (and (looking-at "[ \t]*$")
  18608. org-todo-line-regexp
  18609. (save-excursion
  18610. (beginning-of-line)
  18611. (looking-at org-todo-line-regexp)
  18612. (string= (match-string 3) "")))))
  18613. (defun org-at-heading-or-item-p ()
  18614. (or (org-at-heading-p) (org-at-item-p)))
  18615. (defun org-up-heading-all (arg)
  18616. "Move to the heading line of which the present line is a subheading.
  18617. This function considers both visible and invisible heading lines.
  18618. With argument, move up ARG levels."
  18619. (outline-up-heading arg t))
  18620. (defun org-up-heading-safe ()
  18621. "Move to the heading line of which the present line is a subheading.
  18622. This version will not throw an error. It will return the level of the
  18623. headline found, or nil if no higher level is found.
  18624. Also, this function will be a lot faster than `outline-up-heading',
  18625. because it relies on stars being the outline starters. This can really
  18626. make a significant difference in outlines with very many siblings."
  18627. (when (ignore-errors (org-back-to-heading t))
  18628. (let ((level-up (1- (funcall outline-level))))
  18629. (and (> level-up 0)
  18630. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18631. (funcall outline-level)))))
  18632. (defun org-up-heading-or-point-min ()
  18633. "Move to the heading line of which the present is a subheading, or point-min.
  18634. This version is needed to make point-min behave like a virtual
  18635. heading of level 0 for property-inheritance. It will return the
  18636. level of the headline found (down to 0) or nil if already at a
  18637. point before the first headline or at point-min."
  18638. (when (ignore-errors (org-back-to-heading t))
  18639. (if (< 1 (funcall outline-level))
  18640. (org-up-heading-safe)
  18641. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18642. (defun org-first-sibling-p ()
  18643. "Is this heading the first child of its parents?"
  18644. (interactive)
  18645. (let ((re org-outline-regexp-bol)
  18646. level l)
  18647. (unless (org-at-heading-p t)
  18648. (user-error "Not at a heading"))
  18649. (setq level (funcall outline-level))
  18650. (save-excursion
  18651. (if (not (re-search-backward re nil t))
  18652. t
  18653. (setq l (funcall outline-level))
  18654. (< l level)))))
  18655. (defun org-goto-sibling (&optional previous)
  18656. "Goto the next sibling, even if it is invisible.
  18657. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18658. when a sibling was found. When none is found, return nil and don't
  18659. move point."
  18660. (let ((fun (if previous 're-search-backward 're-search-forward))
  18661. (pos (point))
  18662. (re org-outline-regexp-bol)
  18663. level l)
  18664. (when (ignore-errors (org-back-to-heading t))
  18665. (setq level (funcall outline-level))
  18666. (catch 'exit
  18667. (or previous (forward-char 1))
  18668. (while (funcall fun re nil t)
  18669. (setq l (funcall outline-level))
  18670. (when (< l level) (goto-char pos) (throw 'exit nil))
  18671. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18672. (goto-char pos)
  18673. nil))))
  18674. (defun org-show-siblings ()
  18675. "Show all siblings of the current headline."
  18676. (save-excursion
  18677. (while (org-goto-sibling) (org-flag-heading nil)))
  18678. (save-excursion
  18679. (while (org-goto-sibling 'previous)
  18680. (org-flag-heading nil))))
  18681. (defun org-goto-first-child ()
  18682. "Goto the first child, even if it is invisible.
  18683. Return t when a child was found. Otherwise don't move point and
  18684. return nil."
  18685. (let (level (pos (point)) (re org-outline-regexp-bol))
  18686. (when (org-back-to-heading-or-point-min t)
  18687. (setq level (org-outline-level))
  18688. (forward-char 1)
  18689. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18690. (progn (goto-char (match-beginning 0)) t)
  18691. (goto-char pos) nil))))
  18692. (defun org-show-hidden-entry ()
  18693. "Show an entry where even the heading is hidden."
  18694. (save-excursion
  18695. (org-show-entry)))
  18696. (defun org-flag-heading (flag &optional entry)
  18697. "Flag the current heading. FLAG non-nil means make invisible.
  18698. When ENTRY is non-nil, show the entire entry."
  18699. (save-excursion
  18700. (org-back-to-heading t)
  18701. ;; Check if we should show the entire entry
  18702. (if (not entry)
  18703. (org-flag-region
  18704. (line-end-position 0) (line-end-position) flag 'outline)
  18705. (org-show-entry)
  18706. (save-excursion
  18707. (and (outline-next-heading)
  18708. (org-flag-heading nil))))))
  18709. (defun org-get-next-sibling ()
  18710. "Move to next heading of the same level, and return point.
  18711. If there is no such heading, return nil.
  18712. This is like outline-next-sibling, but invisible headings are ok."
  18713. (let ((level (funcall outline-level)))
  18714. (outline-next-heading)
  18715. (while (and (not (eobp)) (> (funcall outline-level) level))
  18716. (outline-next-heading))
  18717. (unless (or (eobp) (< (funcall outline-level) level))
  18718. (point))))
  18719. (defun org-get-last-sibling ()
  18720. "Move to previous heading of the same level, and return point.
  18721. If there is no such heading, return nil."
  18722. (let ((opoint (point))
  18723. (level (funcall outline-level)))
  18724. (outline-previous-heading)
  18725. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18726. (while (and (> (funcall outline-level) level)
  18727. (not (bobp)))
  18728. (outline-previous-heading))
  18729. (unless (< (funcall outline-level) level)
  18730. (point)))))
  18731. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18732. "Goto to the end of a subtree."
  18733. ;; This contains an exact copy of the original function, but it uses
  18734. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18735. ;; trees and before first headline. And is uses an invisible-ok argument.
  18736. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18737. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18738. ;; with many children and grandchildren etc, this can be much faster
  18739. ;; than the outline version.
  18740. (org-back-to-heading-or-point-min invisible-ok)
  18741. (let ((first t)
  18742. (level (funcall outline-level)))
  18743. (cond ((= level 0)
  18744. (goto-char (point-max)))
  18745. ((and (derived-mode-p 'org-mode) (< level 1000))
  18746. ;; A true heading (not a plain list item), in Org
  18747. ;; This means we can easily find the end by looking
  18748. ;; only for the right number of stars. Using a regexp to do
  18749. ;; this is so much faster than using a Lisp loop.
  18750. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18751. (forward-char 1)
  18752. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18753. (t
  18754. ;; something else, do it the slow way
  18755. (while (and (not (eobp))
  18756. (or first (> (funcall outline-level) level)))
  18757. (setq first nil)
  18758. (outline-next-heading))))
  18759. (unless to-heading
  18760. (when (memq (preceding-char) '(?\n ?\^M))
  18761. ;; Go to end of line before heading
  18762. (forward-char -1)
  18763. (when (memq (preceding-char) '(?\n ?\^M))
  18764. ;; leave blank line before heading
  18765. (forward-char -1)))))
  18766. (point))
  18767. (defun org-end-of-meta-data (&optional full)
  18768. "Skip planning line and properties drawer in current entry.
  18769. When optional argument FULL is t, also skip planning information,
  18770. clocking lines and any kind of drawer.
  18771. When FULL is non-nil but not t, skip planning information,
  18772. clocking lines and only non-regular drawers, i.e. properties and
  18773. logbook drawers."
  18774. (org-back-to-heading t)
  18775. (forward-line)
  18776. ;; Skip planning information.
  18777. (when (looking-at-p org-planning-line-re) (forward-line))
  18778. ;; Skip property drawer.
  18779. (when (looking-at org-property-drawer-re)
  18780. (goto-char (match-end 0))
  18781. (forward-line))
  18782. ;; When FULL is not nil, skip more.
  18783. (when (and full (not (org-at-heading-p)))
  18784. (catch 'exit
  18785. (let ((end (save-excursion (outline-next-heading) (point)))
  18786. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18787. (while (not (eobp))
  18788. (cond ;; Skip clock lines.
  18789. ((looking-at-p re) (forward-line))
  18790. ;; Skip logbook drawer.
  18791. ((looking-at-p org-logbook-drawer-re)
  18792. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18793. (forward-line)
  18794. (throw 'exit t)))
  18795. ;; When FULL is t, skip regular drawer too.
  18796. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18797. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18798. (forward-line)
  18799. (throw 'exit t)))
  18800. (t (throw 'exit t))))))))
  18801. (defun org--line-fully-invisible-p ()
  18802. "Return non-nil if the current line is fully invisible."
  18803. (let ((line-beg (line-beginning-position))
  18804. (line-pos (1- (line-end-position)))
  18805. (is-invisible t))
  18806. (while (and (< line-beg line-pos) is-invisible)
  18807. (setq is-invisible (org-invisible-p line-pos))
  18808. (setq line-pos (1- line-pos)))
  18809. is-invisible))
  18810. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18811. "Move forward to the ARG'th subheading at same level as this one.
  18812. Stop at the first and last subheadings of a superior heading.
  18813. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18814. non-nil it will also look at invisible ones."
  18815. (interactive "p")
  18816. (let ((backward? (and arg (< arg 0))))
  18817. (if (org-before-first-heading-p)
  18818. (if backward? (goto-char (point-min)) (outline-next-heading))
  18819. (org-back-to-heading invisible-ok)
  18820. (unless backward? (end-of-line)) ;do not match current headline
  18821. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18822. (f (if backward? #'re-search-backward #'re-search-forward))
  18823. (count (if arg (abs arg) 1))
  18824. (result (point)))
  18825. (while (and (> count 0)
  18826. (funcall f org-outline-regexp-bol nil 'move))
  18827. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18828. (cond ((< l level) (setq count 0))
  18829. ((and (= l level)
  18830. (or invisible-ok
  18831. ;; FIXME: See commit a700fadd72 and the
  18832. ;; related discussion on why using
  18833. ;; `org--line-fully-invisible-p' is needed
  18834. ;; here, which is to serve the needs of an
  18835. ;; external package. If the change is
  18836. ;; wrong regarding Org itself, it should
  18837. ;; be removed.
  18838. (not (org--line-fully-invisible-p))))
  18839. (cl-decf count)
  18840. (when (= l level) (setq result (point)))))))
  18841. (goto-char result))
  18842. (beginning-of-line))))
  18843. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18844. "Move backward to the ARG'th subheading at same level as this one.
  18845. Stop at the first and last subheadings of a superior heading."
  18846. (interactive "p")
  18847. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18848. (defun org-next-visible-heading (arg)
  18849. "Move to the next visible heading line.
  18850. With ARG, repeats or can move backward if negative."
  18851. (interactive "p")
  18852. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18853. (if (< arg 0)
  18854. (beginning-of-line)
  18855. (end-of-line))
  18856. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18857. (unless (bobp)
  18858. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18859. (`(outline . ,o)
  18860. (goto-char (overlay-start o))
  18861. (re-search-backward regexp nil :move))
  18862. (_ nil))))
  18863. (cl-incf arg))
  18864. (while (and (> arg 0) (re-search-forward regexp nil t))
  18865. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18866. (`(outline . ,o)
  18867. (goto-char (overlay-end o))
  18868. (re-search-forward regexp nil :move))
  18869. (_
  18870. (end-of-line)
  18871. nil))) ;leave the loop
  18872. (cl-decf arg))
  18873. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18874. (defun org-previous-visible-heading (arg)
  18875. "Move to the previous visible heading.
  18876. With ARG, repeats or can move forward if negative."
  18877. (interactive "p")
  18878. (org-next-visible-heading (- arg)))
  18879. (defun org-forward-paragraph (&optional arg)
  18880. "Move forward by a paragraph, or equivalent, unit.
  18881. With argument ARG, do it ARG times;
  18882. a negative argument ARG = -N means move backward N paragraphs.
  18883. The function moves point between two structural
  18884. elements (paragraphs, tables, lists, etc.).
  18885. It also provides the following special moves for convenience:
  18886. - on a table or a property drawer, move to its beginning;
  18887. - on comment, example, export, source and verse blocks, stop
  18888. at blank lines;
  18889. - skip consecutive clocks, diary S-exps, and keywords."
  18890. (interactive "^p")
  18891. (unless arg (setq arg 1))
  18892. (if (< arg 0) (org-backward-paragraph (- arg))
  18893. (while (and (> arg 0) (not (eobp)))
  18894. (org--forward-paragraph-once)
  18895. (cl-decf arg))
  18896. ;; Return moves left.
  18897. arg))
  18898. (defun org-backward-paragraph (&optional arg)
  18899. "Move backward by a paragraph, or equivalent, unit.
  18900. With argument ARG, do it ARG times;
  18901. a negative argument ARG = -N means move forward N paragraphs.
  18902. The function moves point between two structural
  18903. elements (paragraphs, tables, lists, etc.).
  18904. It also provides the following special moves for convenience:
  18905. - on a table or a property drawer, move to its beginning;
  18906. - on comment, example, export, source and verse blocks, stop
  18907. at blank lines;
  18908. - skip consecutive clocks, diary S-exps, and keywords."
  18909. (interactive "^p")
  18910. (unless arg (setq arg 1))
  18911. (if (< arg 0) (org-forward-paragraph (- arg))
  18912. (while (and (> arg 0) (not (bobp)))
  18913. (org--backward-paragraph-once)
  18914. (cl-decf arg))
  18915. ;; Return moves left.
  18916. arg))
  18917. (defun org--paragraph-at-point ()
  18918. "Return paragraph, or equivalent, element at point.
  18919. Paragraph element at point is the element at point, with the
  18920. following special cases:
  18921. - treat table rows (resp. node properties) as the table
  18922. \(resp. property drawer) containing them.
  18923. - treat plain lists with an item every line as a whole.
  18924. - treat consecutive keywords, clocks, and diary-sexps as a single
  18925. block.
  18926. Function may return a real element, or a pseudo-element with type
  18927. `pseudo-paragraph'."
  18928. (let* ((e (org-element-at-point))
  18929. (type (org-element-type e))
  18930. ;; If we need to fake a new pseudo-element, triplet is
  18931. ;;
  18932. ;; (BEG END PARENT)
  18933. ;;
  18934. ;; where BEG and END are element boundaries, and PARENT the
  18935. ;; element containing it, or nil.
  18936. (triplet
  18937. (cond
  18938. ((memq type '(table property-drawer))
  18939. (list (org-element-property :begin e)
  18940. (org-element-property :end e)
  18941. (org-element-property :parent e)))
  18942. ((memq type '(node-property table-row))
  18943. (let ((e (org-element-property :parent e)))
  18944. (list (org-element-property :begin e)
  18945. (org-element-property :end e)
  18946. (org-element-property :parent e))))
  18947. ((memq type '(clock diary-sexp keyword))
  18948. (let* ((regexp (pcase type
  18949. (`clock org-clock-line-re)
  18950. (`diary-sexp "%%(")
  18951. (_ org-keyword-regexp)))
  18952. (end (if (< 0 (org-element-property :post-blank e))
  18953. (org-element-property :end e)
  18954. (org-with-wide-buffer
  18955. (forward-line)
  18956. (while (looking-at regexp) (forward-line))
  18957. (skip-chars-forward " \t\n")
  18958. (line-beginning-position))))
  18959. (begin (org-with-point-at (org-element-property :begin e)
  18960. (while (and (not (bobp)) (looking-at regexp))
  18961. (forward-line -1))
  18962. ;; We may have gotten one line too far.
  18963. (if (looking-at regexp)
  18964. (point)
  18965. (line-beginning-position 2)))))
  18966. (list begin end (org-element-property :parent e))))
  18967. ;; Find the full plain list containing point, the check it
  18968. ;; contains exactly one line per item.
  18969. ((let ((l (org-element-lineage e '(plain-list) t)))
  18970. (while (memq (org-element-type (org-element-property :parent l))
  18971. '(item plain-list))
  18972. (setq l (org-element-property :parent l)))
  18973. (and l
  18974. (org-with-point-at (org-element-property :post-affiliated l)
  18975. (forward-line (length (org-element-property :structure l)))
  18976. (= (point) (org-element-property :contents-end l)))
  18977. ;; Return value.
  18978. (list (org-element-property :begin l)
  18979. (org-element-property :end l)
  18980. (org-element-property :parent l)))))
  18981. (t nil)))) ;no triplet: return element
  18982. (pcase triplet
  18983. (`(,b ,e ,p)
  18984. (org-element-create
  18985. 'pseudo-paragraph
  18986. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18987. (_ e))))
  18988. (defun org--forward-paragraph-once ()
  18989. "Move forward to end of paragraph or equivalent, once.
  18990. See `org-forward-paragraph'."
  18991. (interactive)
  18992. (save-restriction
  18993. (widen)
  18994. (skip-chars-forward " \t\n")
  18995. (cond
  18996. ((eobp) nil)
  18997. ;; When inside a folded part, move out of it.
  18998. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18999. (`(,(or `outline `org-hide-block) . ,o)
  19000. (goto-char (overlay-end o))
  19001. (forward-line)
  19002. t)
  19003. (_ nil)))
  19004. (t
  19005. (let* ((element (org--paragraph-at-point))
  19006. (type (org-element-type element))
  19007. (contents-begin (org-element-property :contents-begin element))
  19008. (end (org-element-property :end element))
  19009. (post-affiliated (org-element-property :post-affiliated element)))
  19010. (cond
  19011. ((eq type 'plain-list)
  19012. (forward-char)
  19013. (org--forward-paragraph-once))
  19014. ;; If the element is folded, skip it altogether.
  19015. ((pcase (org-with-point-at post-affiliated
  19016. (get-char-property-and-overlay (line-end-position)
  19017. 'invisible))
  19018. (`(,(or `outline `org-hide-block) . ,o)
  19019. (goto-char (overlay-end o))
  19020. (forward-line)
  19021. t)
  19022. (_ nil)))
  19023. ;; At a greater element, move inside.
  19024. ((and contents-begin
  19025. (> contents-begin (point))
  19026. (not (eq type 'paragraph)))
  19027. (goto-char contents-begin)
  19028. ;; Items and footnote definitions contents may not start at
  19029. ;; the beginning of the line. In this case, skip until the
  19030. ;; next paragraph.
  19031. (cond
  19032. ((not (bolp)) (org--forward-paragraph-once))
  19033. ((org-previous-line-empty-p) (forward-line -1))
  19034. (t nil)))
  19035. ;; Move between empty lines in some blocks.
  19036. ((memq type '(comment-block example-block export-block src-block
  19037. verse-block))
  19038. (let ((contents-start
  19039. (org-with-point-at post-affiliated
  19040. (line-beginning-position 2))))
  19041. (if (< (point) contents-start)
  19042. (goto-char contents-start)
  19043. (let ((contents-end
  19044. (org-with-point-at end
  19045. (skip-chars-backward " \t\n")
  19046. (line-beginning-position))))
  19047. (cond
  19048. ((>= (point) contents-end)
  19049. (goto-char end)
  19050. (skip-chars-backward " \t\n")
  19051. (forward-line))
  19052. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19053. (forward-line -1))
  19054. (t nil))))))
  19055. (t
  19056. ;; Move to element's end.
  19057. (goto-char end)
  19058. (skip-chars-backward " \t\n")
  19059. (forward-line))))))))
  19060. (defun org--backward-paragraph-once ()
  19061. "Move backward to start of paragraph or equivalent, once.
  19062. See `org-backward-paragraph'."
  19063. (interactive)
  19064. (save-restriction
  19065. (widen)
  19066. (cond
  19067. ((bobp) nil)
  19068. ;; Blank lines at the beginning of the buffer.
  19069. ((and (org-match-line "^[ \t]*$")
  19070. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19071. (goto-char (point-min)))
  19072. ;; When inside a folded part, move out of it.
  19073. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19074. (`(,(or `outline `org-hide-block) . ,o)
  19075. (goto-char (1- (overlay-start o)))
  19076. (org--backward-paragraph-once)
  19077. t)
  19078. (_ nil)))
  19079. (t
  19080. (let* ((element (org--paragraph-at-point))
  19081. (type (org-element-type element))
  19082. (begin (org-element-property :begin element))
  19083. (post-affiliated (org-element-property :post-affiliated element))
  19084. (contents-end (org-element-property :contents-end element))
  19085. (end (org-element-property :end element))
  19086. (parent (org-element-property :parent element))
  19087. (reach
  19088. ;; Move to the visible empty line above position P, or
  19089. ;; to position P. Return t.
  19090. (lambda (p)
  19091. (goto-char p)
  19092. (when (and (org-previous-line-empty-p)
  19093. (let ((end (line-end-position 0)))
  19094. (or (= end (point-min))
  19095. (not (org-invisible-p (1- end))))))
  19096. (forward-line -1))
  19097. t)))
  19098. (cond
  19099. ;; Already at the beginning of an element.
  19100. ((= begin (point))
  19101. (cond
  19102. ;; There is a blank line above. Move there.
  19103. ((and (org-previous-line-empty-p)
  19104. (not (org-invisible-p (1- (line-end-position 0)))))
  19105. (forward-line -1))
  19106. ;; At the beginning of the first element within a greater
  19107. ;; element. Move to the beginning of the greater element.
  19108. ((and parent (= begin (org-element-property :contents-begin parent)))
  19109. (funcall reach (org-element-property :begin parent)))
  19110. ;; Since we have to move anyway, find the beginning
  19111. ;; position of the element above.
  19112. (t
  19113. (forward-char -1)
  19114. (org--backward-paragraph-once))))
  19115. ;; Skip paragraphs at the very beginning of footnote
  19116. ;; definitions or items.
  19117. ((and (eq type 'paragraph)
  19118. (org-with-point-at begin (not (bolp))))
  19119. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19120. ;; If the element is folded, skip it altogether.
  19121. ((org-with-point-at post-affiliated
  19122. (org-invisible-p (line-end-position) t))
  19123. (funcall reach begin))
  19124. ;; At the end of a greater element, move inside.
  19125. ((and contents-end
  19126. (<= contents-end (point))
  19127. (not (eq type 'paragraph)))
  19128. (cond
  19129. ((memq type '(footnote-definition plain-list))
  19130. (skip-chars-backward " \t\n")
  19131. (org--backward-paragraph-once))
  19132. ((= contents-end (point))
  19133. (forward-char -1)
  19134. (org--backward-paragraph-once))
  19135. (t
  19136. (goto-char contents-end))))
  19137. ;; Move between empty lines in some blocks.
  19138. ((and (memq type '(comment-block example-block export-block src-block
  19139. verse-block))
  19140. (let ((contents-start
  19141. (org-with-point-at post-affiliated
  19142. (line-beginning-position 2))))
  19143. (when (> (point) contents-start)
  19144. (let ((contents-end
  19145. (org-with-point-at end
  19146. (skip-chars-backward " \t\n")
  19147. (line-beginning-position))))
  19148. (if (> (point) contents-end)
  19149. (progn (goto-char contents-end) t)
  19150. (skip-chars-backward " \t\n" begin)
  19151. (re-search-backward "^[ \t]*\n" contents-start :move)
  19152. t))))))
  19153. ;; Move to element's start.
  19154. (t
  19155. (funcall reach begin))))))))
  19156. (defun org-forward-element ()
  19157. "Move forward by one element.
  19158. Move to the next element at the same level, when possible."
  19159. (interactive)
  19160. (cond ((eobp) (user-error "Cannot move further down"))
  19161. ((org-with-limited-levels (org-at-heading-p))
  19162. (let ((origin (point)))
  19163. (goto-char (org-end-of-subtree nil t))
  19164. (unless (org-with-limited-levels (org-at-heading-p))
  19165. (goto-char origin)
  19166. (user-error "Cannot move further down"))))
  19167. (t
  19168. (let* ((elem (org-element-at-point))
  19169. (end (org-element-property :end elem))
  19170. (parent (org-element-property :parent elem)))
  19171. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19172. (goto-char (org-element-property :end parent)))
  19173. ((integer-or-marker-p end) (goto-char end))
  19174. (t (message "No element at point")))))))
  19175. (defun org-backward-element ()
  19176. "Move backward by one element.
  19177. Move to the previous element at the same level, when possible."
  19178. (interactive)
  19179. (cond ((bobp) (user-error "Cannot move further up"))
  19180. ((org-with-limited-levels (org-at-heading-p))
  19181. ;; At a headline, move to the previous one, if any, or stay
  19182. ;; here.
  19183. (let ((origin (point)))
  19184. (org-with-limited-levels (org-backward-heading-same-level 1))
  19185. ;; When current headline has no sibling above, move to its
  19186. ;; parent.
  19187. (when (= (point) origin)
  19188. (or (org-with-limited-levels (org-up-heading-safe))
  19189. (progn (goto-char origin)
  19190. (user-error "Cannot move further up"))))))
  19191. (t
  19192. (let* ((elem (org-element-at-point))
  19193. (beg (org-element-property :begin elem)))
  19194. (cond
  19195. ;; Move to beginning of current element if point isn't
  19196. ;; there already.
  19197. ((null beg) (message "No element at point"))
  19198. ((/= (point) beg) (goto-char beg))
  19199. (t (goto-char beg)
  19200. (skip-chars-backward " \r\t\n")
  19201. (unless (bobp)
  19202. (let ((prev (org-element-at-point)))
  19203. (goto-char (org-element-property :begin prev))
  19204. (while (and (setq prev (org-element-property :parent prev))
  19205. (<= (org-element-property :end prev) beg))
  19206. (goto-char (org-element-property :begin prev)))))))))))
  19207. (defun org-up-element ()
  19208. "Move to upper element."
  19209. (interactive)
  19210. (if (org-with-limited-levels (org-at-heading-p))
  19211. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19212. (let* ((elem (org-element-at-point))
  19213. (parent (org-element-property :parent elem)))
  19214. (if parent (goto-char (org-element-property :begin parent))
  19215. (if (org-with-limited-levels (org-before-first-heading-p))
  19216. (user-error "No surrounding element")
  19217. (org-with-limited-levels (org-back-to-heading)))))))
  19218. (defun org-down-element ()
  19219. "Move to inner element."
  19220. (interactive)
  19221. (let ((element (org-element-at-point)))
  19222. (cond
  19223. ((memq (org-element-type element) '(plain-list table))
  19224. (goto-char (org-element-property :contents-begin element))
  19225. (forward-char))
  19226. ((memq (org-element-type element) org-element-greater-elements)
  19227. ;; If contents are hidden, first disclose them.
  19228. (when (org-invisible-p (line-end-position)) (org-cycle))
  19229. (goto-char (or (org-element-property :contents-begin element)
  19230. (user-error "No content for this element"))))
  19231. (t (user-error "No inner element")))))
  19232. (defun org-drag-element-backward ()
  19233. "Move backward element at point."
  19234. (interactive)
  19235. (let ((elem (or (org-element-at-point)
  19236. (user-error "No element at point"))))
  19237. (if (eq (org-element-type elem) 'headline)
  19238. ;; Preserve point when moving a whole tree, even if point was
  19239. ;; on blank lines below the headline.
  19240. (let ((offset (skip-chars-backward " \t\n")))
  19241. (unwind-protect (org-move-subtree-up)
  19242. (forward-char (- offset))))
  19243. (let ((prev-elem
  19244. (save-excursion
  19245. (goto-char (org-element-property :begin elem))
  19246. (skip-chars-backward " \r\t\n")
  19247. (unless (bobp)
  19248. (let* ((beg (org-element-property :begin elem))
  19249. (prev (org-element-at-point))
  19250. (up prev))
  19251. (while (and (setq up (org-element-property :parent up))
  19252. (<= (org-element-property :end up) beg))
  19253. (setq prev up))
  19254. prev)))))
  19255. ;; Error out if no previous element or previous element is
  19256. ;; a parent of the current one.
  19257. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19258. (user-error "Cannot drag element backward")
  19259. (let ((pos (point)))
  19260. (org-element-swap-A-B prev-elem elem)
  19261. (goto-char (+ (org-element-property :begin prev-elem)
  19262. (- pos (org-element-property :begin elem))))))))))
  19263. (defun org-drag-element-forward ()
  19264. "Move forward element at point."
  19265. (interactive)
  19266. (let* ((pos (point))
  19267. (elem (or (org-element-at-point)
  19268. (user-error "No element at point"))))
  19269. (when (= (point-max) (org-element-property :end elem))
  19270. (user-error "Cannot drag element forward"))
  19271. (goto-char (org-element-property :end elem))
  19272. (let ((next-elem (org-element-at-point)))
  19273. (when (or (org-element-nested-p elem next-elem)
  19274. (and (eq (org-element-type next-elem) 'headline)
  19275. (not (eq (org-element-type elem) 'headline))))
  19276. (goto-char pos)
  19277. (user-error "Cannot drag element forward"))
  19278. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19279. ;; body's length (without final blanks) and by the length of
  19280. ;; blanks between ELEM and NEXT-ELEM.
  19281. (let ((size-next (- (save-excursion
  19282. (goto-char (org-element-property :end next-elem))
  19283. (skip-chars-backward " \r\t\n")
  19284. (forward-line)
  19285. ;; Small correction if buffer doesn't end
  19286. ;; with a newline character.
  19287. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19288. (org-element-property :begin next-elem)))
  19289. (size-blank (- (org-element-property :end elem)
  19290. (save-excursion
  19291. (goto-char (org-element-property :end elem))
  19292. (skip-chars-backward " \r\t\n")
  19293. (forward-line)
  19294. (point)))))
  19295. (org-element-swap-A-B elem next-elem)
  19296. (goto-char (+ pos size-next size-blank))))))
  19297. (defun org-drag-line-forward (arg)
  19298. "Drag the line at point ARG lines forward."
  19299. (interactive "p")
  19300. (dotimes (_ (abs arg))
  19301. (let ((c (current-column)))
  19302. (if (< 0 arg)
  19303. (progn
  19304. (beginning-of-line 2)
  19305. (transpose-lines 1)
  19306. (beginning-of-line 0))
  19307. (transpose-lines 1)
  19308. (beginning-of-line -1))
  19309. (org-move-to-column c))))
  19310. (defun org-drag-line-backward (arg)
  19311. "Drag the line at point ARG lines backward."
  19312. (interactive "p")
  19313. (org-drag-line-forward (- arg)))
  19314. (defun org-mark-element ()
  19315. "Put point at beginning of this element, mark at end.
  19316. Interactively, if this command is repeated or (in Transient Mark
  19317. mode) if the mark is active, it marks the next element after the
  19318. ones already marked."
  19319. (interactive)
  19320. (let (deactivate-mark)
  19321. (if (and (called-interactively-p 'any)
  19322. (or (and (eq last-command this-command) (mark t))
  19323. (and transient-mark-mode mark-active)))
  19324. (set-mark
  19325. (save-excursion
  19326. (goto-char (mark))
  19327. (goto-char (org-element-property :end (org-element-at-point)))
  19328. (point)))
  19329. (let ((element (org-element-at-point)))
  19330. (end-of-line)
  19331. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19332. (goto-char (org-element-property :begin element))))))
  19333. (defun org-narrow-to-element ()
  19334. "Narrow buffer to current element."
  19335. (interactive)
  19336. (let ((elem (org-element-at-point)))
  19337. (cond
  19338. ((eq (car elem) 'headline)
  19339. (narrow-to-region
  19340. (org-element-property :begin elem)
  19341. (org-element-property :end elem)))
  19342. ((memq (car elem) org-element-greater-elements)
  19343. (narrow-to-region
  19344. (org-element-property :contents-begin elem)
  19345. (org-element-property :contents-end elem)))
  19346. (t
  19347. (narrow-to-region
  19348. (org-element-property :begin elem)
  19349. (org-element-property :end elem))))))
  19350. (defun org-transpose-element ()
  19351. "Transpose current and previous elements, keeping blank lines between.
  19352. Point is moved after both elements."
  19353. (interactive)
  19354. (org-skip-whitespace)
  19355. (let ((end (org-element-property :end (org-element-at-point))))
  19356. (org-drag-element-backward)
  19357. (goto-char end)))
  19358. (defun org-unindent-buffer ()
  19359. "Un-indent the visible part of the buffer.
  19360. Relative indentation (between items, inside blocks, etc.) isn't
  19361. modified."
  19362. (interactive)
  19363. (unless (eq major-mode 'org-mode)
  19364. (user-error "Cannot un-indent a buffer not in Org mode"))
  19365. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19366. (unindent-tree
  19367. (lambda (contents)
  19368. (dolist (element (reverse contents))
  19369. (if (memq (org-element-type element) '(headline section))
  19370. (funcall unindent-tree (org-element-contents element))
  19371. (save-excursion
  19372. (save-restriction
  19373. (narrow-to-region
  19374. (org-element-property :begin element)
  19375. (org-element-property :end element))
  19376. (org-do-remove-indentation))))))))
  19377. (funcall unindent-tree (org-element-contents parse-tree))))
  19378. (defun org-make-options-regexp (kwds &optional extra)
  19379. "Make a regular expression for keyword lines.
  19380. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19381. when non-nil, is a regexp matching keywords names."
  19382. (concat "^[ \t]*#\\+\\("
  19383. (regexp-opt kwds)
  19384. (and extra (concat (and kwds "\\|") extra))
  19385. "\\):[ \t]*\\(.*\\)"))
  19386. ;;; Conveniently switch to Info nodes
  19387. (defun org-info-find-node (&optional nodename)
  19388. "Find Info documentation NODENAME or Org documentation according context.
  19389. Started from `gnus-info-find-node'."
  19390. (interactive)
  19391. (Info-goto-node
  19392. (or nodename
  19393. (let ((default-org-info-node "(org) Top"))
  19394. (cond
  19395. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19396. ((eq 'org-mode major-mode)
  19397. (let* ((context (org-element-at-point))
  19398. (element-info-nodes ; compare to `org-element-all-elements'.
  19399. `((babel-call . "(org) Evaluating Code Blocks")
  19400. (center-block . "(org) Paragraphs")
  19401. (clock . ,default-org-info-node)
  19402. (comment . "(org) Comment Lines")
  19403. (comment-block . "(org) Comment Lines")
  19404. (diary-sexp . ,default-org-info-node)
  19405. (drawer . "(org) Drawers")
  19406. (dynamic-block . "(org) Dynamic Blocks")
  19407. (example-block . "(org) Literal Examples")
  19408. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19409. (fixed-width . ,default-org-info-node)
  19410. (footnote-definition . "(org) Creating Footnotes")
  19411. (headline . "(org) Document Structure")
  19412. (horizontal-rule . "(org) Built-in Table Editor")
  19413. (inlinetask . ,default-org-info-node)
  19414. (item . "(org) Plain Lists")
  19415. (keyword . "(org) Per-file keywords")
  19416. (latex-environment . "(org) LaTeX Export")
  19417. (node-property . "(org) Properties and Columns")
  19418. (paragraph . "(org) Paragraphs")
  19419. (plain-list . "(org) Plain Lists")
  19420. (planning . "(org) Deadlines and Scheduling")
  19421. (property-drawer . "(org) Properties and Columns")
  19422. (quote-block . "(org) Paragraphs")
  19423. (section . ,default-org-info-node)
  19424. (special-block . ,default-org-info-node)
  19425. (src-block . "(org) Working with Source Code")
  19426. (table . "(org) Tables")
  19427. (table-row . "(org) Tables")
  19428. (verse-block . "(org) Paragraphs"))))
  19429. (or (cdr (assoc (car context) element-info-nodes))
  19430. default-org-info-node)))
  19431. (t default-org-info-node))))))
  19432. ;;; Finish up
  19433. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19434. (lambda () (add-hook 'change-major-mode-hook
  19435. 'org-show-all 'append 'local)))
  19436. (provide 'org)
  19437. (run-hooks 'org-load-hook)
  19438. ;; Local variables:
  19439. ;; generated-autoload-file: "org-loaddefs.el"
  19440. ;; End:
  19441. ;;; org.el ends here