org.el 803 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257
  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-2021 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-duration-to-minutes "org-duration" (duration &optional canonical))
  137. (declare-function org-element-at-point "org-element" ())
  138. (declare-function org-element-cache-refresh "org-element" (pos))
  139. (declare-function org-element-cache-reset "org-element" (&optional all))
  140. (declare-function org-element-contents "org-element" (element))
  141. (declare-function org-element-context "org-element" (&optional element))
  142. (declare-function org-element-copy "org-element" (datum))
  143. (declare-function org-element-create "org-element" (type &optional props &rest children))
  144. (declare-function org-element-interpret-data "org-element" (data))
  145. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  146. (declare-function org-element-link-parser "org-element" ())
  147. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  148. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  149. (declare-function org-element-property "org-element" (property element))
  150. (declare-function org-element-put-property "org-element" (element property value))
  151. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  152. (declare-function org-element-timestamp-parser "org-element" ())
  153. (declare-function org-element-type "org-element" (element))
  154. (declare-function org-export-dispatch "ox" (&optional arg))
  155. (declare-function org-export-get-backend "ox" (name))
  156. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  157. (declare-function org-feed-goto-inbox "org-feed" (feed))
  158. (declare-function org-feed-update-all "org-feed" ())
  159. (declare-function org-goto "org-goto" (&optional alternative-interface))
  160. (declare-function org-id-find-id-file "org-id" (id))
  161. (declare-function org-id-get-create "org-id" (&optional force))
  162. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  163. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  164. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-num-mode "org-num" (&optional arg))
  167. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  168. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  169. (declare-function org-timer "org-timer" (&optional restart no-insert))
  170. (declare-function org-timer-item "org-timer" (&optional arg))
  171. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  172. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  173. (declare-function org-timer-start "org-timer" (&optional offset))
  174. (declare-function org-timer-stop "org-timer" ())
  175. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  176. (declare-function org-update-radio-target-regexp "ol" ())
  177. (defvar ffap-url-regexp)
  178. (defvar org-element-paragraph-separate)
  179. (defvar org-indent-indentation-per-level)
  180. (defvar org-radio-target-regexp)
  181. (defvar org-target-link-regexp)
  182. (defvar org-target-regexp)
  183. (defvar org-id-overriding-file-name)
  184. ;; load languages based on value of `org-babel-load-languages'
  185. (defvar org-babel-load-languages)
  186. ;;;###autoload
  187. (defun org-babel-do-load-languages (sym value)
  188. "Load the languages defined in `org-babel-load-languages'."
  189. (set-default sym value)
  190. (dolist (pair org-babel-load-languages)
  191. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  192. (if active
  193. (require (intern (concat "ob-" lang)))
  194. (fmakunbound
  195. (intern (concat "org-babel-execute:" lang)))
  196. (fmakunbound
  197. (intern (concat "org-babel-expand-body:" lang)))))))
  198. ;;;###autoload
  199. (defun org-babel-load-file (file &optional compile)
  200. "Load Emacs Lisp source code blocks in the Org FILE.
  201. This function exports the source code using `org-babel-tangle'
  202. and then loads the resulting file using `load-file'. With
  203. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  204. byte-compiled before it is loaded."
  205. (interactive "fFile to load: \nP")
  206. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  207. ;; Tangle only if the Org file is newer than the Elisp file.
  208. (unless (org-file-newer-than-p
  209. tangled-file
  210. (file-attribute-modification-time
  211. (file-attributes (file-truename file))))
  212. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  213. (if compile
  214. (progn
  215. (byte-compile-file tangled-file)
  216. (load tangled-file)
  217. (message "Compiled and loaded %s" tangled-file))
  218. (load-file tangled-file)
  219. (message "Loaded %s" tangled-file))))
  220. (defcustom org-babel-load-languages '((emacs-lisp . t))
  221. "Languages which can be evaluated in Org buffers.
  222. \\<org-mode-map>
  223. This list can be used to load support for any of the languages
  224. below. Each language will depend on a different set of system
  225. executables and/or Emacs modes.
  226. When a language is \"loaded\", code blocks in that language can
  227. be evaluated with `org-babel-execute-src-block', which is bound
  228. by default to \\[org-ctrl-c-ctrl-c].
  229. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  230. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  231. default, only Emacs Lisp is loaded, since it has no specific
  232. requirement."
  233. :group 'org-babel
  234. :set 'org-babel-do-load-languages
  235. :version "24.1"
  236. :type '(alist :tag "Babel Languages"
  237. :key-type
  238. (choice
  239. (const :tag "Awk" awk)
  240. (const :tag "C" C)
  241. (const :tag "R" R)
  242. (const :tag "Asymptote" asymptote)
  243. (const :tag "Calc" calc)
  244. (const :tag "Clojure" clojure)
  245. (const :tag "CSS" css)
  246. (const :tag "Ditaa" ditaa)
  247. (const :tag "Dot" dot)
  248. (const :tag "Ebnf2ps" ebnf2ps)
  249. (const :tag "Emacs Lisp" emacs-lisp)
  250. (const :tag "Forth" forth)
  251. (const :tag "Fortran" fortran)
  252. (const :tag "Gnuplot" gnuplot)
  253. (const :tag "Haskell" haskell)
  254. (const :tag "hledger" hledger)
  255. (const :tag "IO" io)
  256. (const :tag "J" J)
  257. (const :tag "Java" java)
  258. (const :tag "Javascript" js)
  259. (const :tag "LaTeX" latex)
  260. (const :tag "Ledger" ledger)
  261. (const :tag "Lilypond" lilypond)
  262. (const :tag "Lisp" lisp)
  263. (const :tag "Makefile" makefile)
  264. (const :tag "Maxima" maxima)
  265. (const :tag "Matlab" matlab)
  266. (const :tag "Mscgen" mscgen)
  267. (const :tag "Ocaml" ocaml)
  268. (const :tag "Octave" octave)
  269. (const :tag "Org" org)
  270. (const :tag "Perl" perl)
  271. (const :tag "Pico Lisp" picolisp)
  272. (const :tag "PlantUML" plantuml)
  273. (const :tag "Python" python)
  274. (const :tag "Ruby" ruby)
  275. (const :tag "Sass" sass)
  276. (const :tag "Scala" scala)
  277. (const :tag "Scheme" scheme)
  278. (const :tag "Screen" screen)
  279. (const :tag "Shell Script" shell)
  280. (const :tag "Shen" shen)
  281. (const :tag "Sql" sql)
  282. (const :tag "Sqlite" sqlite)
  283. (const :tag "Stan" stan)
  284. (const :tag "Vala" vala))
  285. :value-type (boolean :tag "Activate" :value t)))
  286. ;;;; Customization variables
  287. (defcustom org-clone-delete-id nil
  288. "Remove ID property of clones of a subtree.
  289. When non-nil, clones of a subtree don't inherit the ID property.
  290. Otherwise they inherit the ID property with a new unique
  291. identifier."
  292. :type 'boolean
  293. :version "24.1"
  294. :group 'org-id)
  295. ;;; Version
  296. (org-check-version)
  297. ;;;###autoload
  298. (defun org-version (&optional here full message)
  299. "Show the Org version.
  300. Interactively, or when MESSAGE is non-nil, show it in echo area.
  301. With prefix argument, or when HERE is non-nil, insert it at point.
  302. In non-interactive uses, a reduced version string is output unless
  303. FULL is given."
  304. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  305. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  306. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  307. (load-suffixes (list ".el"))
  308. (org-install-dir
  309. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  310. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  311. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  312. (let* ((load-suffixes save-load-suffixes)
  313. (release (org-release))
  314. (git-version (org-git-version))
  315. (version (format "Org mode version %s (%s @ %s)"
  316. release
  317. git-version
  318. (if org-install-dir
  319. (if (string= org-dir org-install-dir)
  320. org-install-dir
  321. (concat "mixed installation! "
  322. org-install-dir
  323. " and "
  324. org-dir))
  325. "org-loaddefs.el can not be found!")))
  326. (version1 (if full version release)))
  327. (when here (insert version1))
  328. (when message (message "%s" version1))
  329. version1)))
  330. (defconst org-version (org-version))
  331. ;;; Syntax Constants
  332. ;;;; Comments
  333. (defconst org-comment-regexp
  334. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  335. "Regular expression for comment lines.")
  336. ;;;; Keyword
  337. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  338. "Regular expression for keyword-lines.")
  339. ;;;; Block
  340. (defconst org-block-regexp
  341. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  342. "Regular expression for hiding blocks.")
  343. (defconst org-dblock-start-re
  344. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  345. "Matches the start line of a dynamic block, with parameters.")
  346. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  347. "Matches the end of a dynamic block.")
  348. ;;;; Timestamp
  349. (defconst org-ts--internal-regexp
  350. (rx (seq
  351. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  352. (optional " " (*? nonl))))
  353. "Regular expression matching the innards of a time stamp.")
  354. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  355. "Regular expression for fast time stamp matching.")
  356. (defconst org-ts-regexp-inactive
  357. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  358. "Regular expression for fast inactive time stamp matching.")
  359. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  360. "Regular expression for fast time stamp matching.")
  361. (defconst org-ts-regexp0
  362. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  363. "Regular expression matching time strings for analysis.
  364. This one does not require the space after the date, so it can be used
  365. on a string that terminates immediately after the date.")
  366. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  367. "Regular expression matching time strings for analysis.")
  368. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  369. "Regular expression matching time stamps, with groups.")
  370. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  371. "Regular expression matching time stamps (also [..]), with groups.")
  372. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  373. "Regular expression matching a time stamp range.")
  374. (defconst org-tr-regexp-both
  375. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  376. "Regular expression matching a time stamp range.")
  377. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  378. org-ts-regexp "\\)?")
  379. "Regular expression matching a time stamp or time stamp range.")
  380. (defconst org-tsr-regexp-both
  381. (concat org-ts-regexp-both "\\(--?-?"
  382. org-ts-regexp-both "\\)?")
  383. "Regular expression matching a time stamp or time stamp range.
  384. The time stamps may be either active or inactive.")
  385. (defconst org-repeat-re
  386. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  387. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  388. "Regular expression for specifying repeated events.
  389. After a match, group 1 contains the repeat expression.")
  390. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  391. "Formats for `format-time-string' which are used for time stamps.")
  392. ;;;; Clock and Planning
  393. (defconst org-clock-string "CLOCK:"
  394. "String used as prefix for timestamps clocking work hours on an item.")
  395. (defvar org-closed-string "CLOSED:"
  396. "String used as the prefix for timestamps logging closing a TODO entry.")
  397. (defvar org-deadline-string "DEADLINE:"
  398. "String to mark deadline entries.
  399. \\<org-mode-map>
  400. A deadline is this string, followed by a time stamp. It must be
  401. a word, terminated by a colon. You can insert a schedule keyword
  402. and a timestamp with `\\[org-deadline]'.")
  403. (defvar org-scheduled-string "SCHEDULED:"
  404. "String to mark scheduled TODO entries.
  405. \\<org-mode-map>
  406. A schedule is this string, followed by a time stamp. It must be
  407. a word, terminated by a colon. You can insert a schedule keyword
  408. and a timestamp with `\\[org-schedule]'.")
  409. (defconst org-ds-keyword-length
  410. (+ 2
  411. (apply #'max
  412. (mapcar #'length
  413. (list org-deadline-string org-scheduled-string
  414. org-clock-string org-closed-string))))
  415. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  416. (defconst org-planning-line-re
  417. (concat "^[ \t]*"
  418. (regexp-opt
  419. (list org-closed-string org-deadline-string org-scheduled-string)
  420. t))
  421. "Matches a line with planning info.
  422. Matched keyword is in group 1.")
  423. (defconst org-clock-line-re
  424. (concat "^[ \t]*" org-clock-string)
  425. "Matches a line with clock info.")
  426. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  427. "Matches the DEADLINE keyword.")
  428. (defconst org-deadline-time-regexp
  429. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  430. "Matches the DEADLINE keyword together with a time stamp.")
  431. (defconst org-deadline-time-hour-regexp
  432. (concat "\\<" org-deadline-string
  433. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  434. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  435. (defconst org-deadline-line-regexp
  436. (concat "\\<\\(" org-deadline-string "\\).*")
  437. "Matches the DEADLINE keyword and the rest of the line.")
  438. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  439. "Matches the SCHEDULED keyword.")
  440. (defconst org-scheduled-time-regexp
  441. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  442. "Matches the SCHEDULED keyword together with a time stamp.")
  443. (defconst org-scheduled-time-hour-regexp
  444. (concat "\\<" org-scheduled-string
  445. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  446. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  447. (defconst org-closed-time-regexp
  448. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  449. "Matches the CLOSED keyword together with a time stamp.")
  450. (defconst org-keyword-time-regexp
  451. (concat "\\<"
  452. (regexp-opt
  453. (list org-scheduled-string org-deadline-string org-closed-string
  454. org-clock-string)
  455. t)
  456. " *[[<]\\([^]>]+\\)[]>]")
  457. "Matches any of the 4 keywords, together with the time stamp.")
  458. (defconst org-keyword-time-not-clock-regexp
  459. (concat
  460. "\\<"
  461. (regexp-opt
  462. (list org-scheduled-string org-deadline-string org-closed-string) t)
  463. " *[[<]\\([^]>]+\\)[]>]")
  464. "Matches any of the 3 keywords, together with the time stamp.")
  465. (defconst org-all-time-keywords
  466. (mapcar (lambda (w) (substring w 0 -1))
  467. (list org-scheduled-string org-deadline-string
  468. org-clock-string org-closed-string))
  469. "List of time keywords.")
  470. ;;;; Drawer
  471. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  472. "Matches first or last line of a hidden block.
  473. Group 1 contains drawer's name or \"END\".")
  474. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  475. "Regular expression matching the first line of a property drawer.")
  476. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  477. "Regular expression matching the last line of a property drawer.")
  478. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  479. "Regular expression matching the first line of a clock drawer.")
  480. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  481. "Regular expression matching the last line of a clock drawer.")
  482. (defconst org-logbook-drawer-re
  483. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  484. (*? (0+ nonl) "\n")
  485. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  486. "Matches an entire LOGBOOK drawer.")
  487. (defconst org-property-drawer-re
  488. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  489. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  490. "[ \t]*:END:[ \t]*$")
  491. "Matches an entire property drawer.")
  492. (defconst org-clock-drawer-re
  493. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  494. org-clock-drawer-end-re "\\)\n?")
  495. "Matches an entire clock drawer.")
  496. ;;;; Headline
  497. (defconst org-heading-keyword-regexp-format
  498. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  499. "Printf format for a regexp matching a headline with some keyword.
  500. This regexp will match the headline of any node which has the
  501. exact keyword that is put into the format. The keyword isn't in
  502. any group by default, but the stars and the body are.")
  503. (defconst org-heading-keyword-maybe-regexp-format
  504. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  505. "Printf format for a regexp matching a headline, possibly with some keyword.
  506. This regexp can match any headline with the specified keyword, or
  507. without a keyword. The keyword isn't in any group by default,
  508. but the stars and the body are.")
  509. (defconst org-archive-tag "ARCHIVE"
  510. "The tag that marks a subtree as archived.
  511. An archived subtree does not open during visibility cycling, and does
  512. not contribute to the agenda listings.")
  513. (defconst org-tag-re "[[:alnum:]_@#%]+"
  514. "Regexp matching a single tag.")
  515. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  516. "Regexp matching the tag group at the end of a line, with leading spaces.
  517. Tags are stored in match group 1. Match group 2 stores the tags
  518. without the enclosing colons.")
  519. (defconst org-tag-line-re
  520. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  521. "Regexp matching tags in a headline.
  522. Tags are stored in match group 1. Match group 2 stores the tags
  523. without the enclosing colons.")
  524. (eval-and-compile
  525. (defconst org-comment-string "COMMENT"
  526. "Entries starting with this keyword will never be exported.
  527. \\<org-mode-map>
  528. An entry can be toggled between COMMENT and normal with
  529. `\\[org-toggle-comment]'."))
  530. ;;;; LaTeX Environments and Fragments
  531. (defconst org-latex-regexps
  532. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  533. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  534. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  535. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  536. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  537. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  538. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  539. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  540. "Regular expressions for matching embedded LaTeX.")
  541. ;;;; Node Property
  542. (defconst org-effort-property "Effort"
  543. "The property that is being used to keep track of effort estimates.
  544. Effort estimates given in this property need to be in the format
  545. defined in org-duration.el.")
  546. ;;; The custom variables
  547. (defgroup org nil
  548. "Outline-based notes management and organizer."
  549. :tag "Org"
  550. :group 'outlines
  551. :group 'calendar)
  552. (defcustom org-mode-hook nil
  553. "Mode hook for Org mode, run after the mode was turned on."
  554. :group 'org
  555. :type 'hook)
  556. (defcustom org-load-hook nil
  557. "Hook that is run after org.el has been loaded."
  558. :group 'org
  559. :type 'hook)
  560. (defcustom org-log-buffer-setup-hook nil
  561. "Hook that is run after an Org log buffer is created."
  562. :group 'org
  563. :version "24.1"
  564. :type 'hook)
  565. (defvar org-modules) ; defined below
  566. (defvar org-modules-loaded nil
  567. "Have the modules been loaded already?")
  568. ;;;###autoload
  569. (defun org-load-modules-maybe (&optional force)
  570. "Load all extensions listed in `org-modules'."
  571. (when (or force (not org-modules-loaded))
  572. (dolist (ext org-modules)
  573. (condition-case nil (require ext)
  574. (error (message "Problems while trying to load feature `%s'" ext))))
  575. (setq org-modules-loaded t)))
  576. (defun org-set-modules (var value)
  577. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  578. (set var value)
  579. (when (featurep 'org)
  580. (org-load-modules-maybe 'force)
  581. (org-element-cache-reset 'all)))
  582. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  583. "Modules that should always be loaded together with org.el.
  584. If a description starts with <C>, the file is not part of Emacs
  585. and loading it will require that you have downloaded and properly
  586. installed the Org mode distribution.
  587. You can also use this system to load external packages (i.e. neither Org
  588. core modules, nor modules from the CONTRIB directory). Just add symbols
  589. to the end of the list. If the package is called org-xyz.el, then you need
  590. to add the symbol `xyz', and the package must have a call to:
  591. (provide \\='org-xyz)
  592. For export specific modules, see also `org-export-backends'."
  593. :group 'org
  594. :set 'org-set-modules
  595. :version "26.1"
  596. :package-version '(Org . "9.2")
  597. :type
  598. '(set :greedy t
  599. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  600. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  601. (const :tag " crypt: Encryption of subtrees" org-crypt)
  602. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  603. (const :tag " docview: Links to Docview buffers" ol-docview)
  604. (const :tag " eww: Store link to URL of Eww" ol-eww)
  605. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  606. (const :tag " habit: Track your consistency with habits" org-habit)
  607. (const :tag " id: Global IDs for identifying entries" org-id)
  608. (const :tag " info: Links to Info nodes" ol-info)
  609. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  610. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  611. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  612. (const :tag " mouse: Additional mouse support" org-mouse)
  613. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  614. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  615. (const :tag " tempo: Fast completion for structures" org-tempo)
  616. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  617. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  618. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  619. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  620. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  621. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  622. (const :tag "C collector: Collect properties into tables" org-collector)
  623. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  624. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  625. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  626. (const :tag "C eval: Include command output as text" org-eval)
  627. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  628. (const :tag "C git-link: Links to specific file version" ol-git-link)
  629. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  630. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  631. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  632. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  633. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  634. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  635. (const :tag "C man: Links to man pages in Org mode" ol-man)
  636. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  637. (const :tag "C notify: Notifications for Org mode" org-notify)
  638. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  639. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  640. (const :tag "C registry: A registry for Org links" org-registry)
  641. (const :tag "C screen: Visit screen sessions through links" org-screen)
  642. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  643. (const :tag "C secretary: Team management with Org" org-secretary)
  644. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  645. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  646. (const :tag "C track: Keep up with Org mode development" org-track)
  647. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  648. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  649. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  650. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  651. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  652. (defvar org-export-registered-backends) ; From ox.el.
  653. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  654. (declare-function org-export-backend-name "ox" (backend) t)
  655. (defcustom org-export-backends '(ascii html icalendar latex odt)
  656. "List of export back-ends that should be always available.
  657. If a description starts with <C>, the file is not part of Emacs
  658. and loading it will require that you have downloaded and properly
  659. installed the Org mode distribution.
  660. Unlike to `org-modules', libraries in this list will not be
  661. loaded along with Org, but only once the export framework is
  662. needed.
  663. This variable needs to be set before org.el is loaded. If you
  664. need to make a change while Emacs is running, use the customize
  665. interface or run the following code, where VAL stands for the new
  666. value of the variable, after updating it:
  667. (progn
  668. (setq org-export-registered-backends
  669. (cl-remove-if-not
  670. (lambda (backend)
  671. (let ((name (org-export-backend-name backend)))
  672. (or (memq name val)
  673. (catch \\='parentp
  674. (dolist (b val)
  675. (and (org-export-derived-backend-p b name)
  676. (throw \\='parentp t)))))))
  677. org-export-registered-backends))
  678. (let ((new-list (mapcar #\\='org-export-backend-name
  679. org-export-registered-backends)))
  680. (dolist (backend val)
  681. (cond
  682. ((not (load (format \"ox-%s\" backend) t t))
  683. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  684. backend))
  685. ((not (memq backend new-list)) (push backend new-list))))
  686. (set-default \\='org-export-backends new-list)))
  687. Adding a back-end to this list will also pull the back-end it
  688. depends on, if any."
  689. :group 'org
  690. :group 'org-export
  691. :version "26.1"
  692. :package-version '(Org . "9.0")
  693. :initialize 'custom-initialize-set
  694. :set (lambda (var val)
  695. (if (not (featurep 'ox)) (set-default var val)
  696. ;; Any back-end not required anymore (not present in VAL and not
  697. ;; a parent of any back-end in the new value) is removed from the
  698. ;; list of registered back-ends.
  699. (setq org-export-registered-backends
  700. (cl-remove-if-not
  701. (lambda (backend)
  702. (let ((name (org-export-backend-name backend)))
  703. (or (memq name val)
  704. (catch 'parentp
  705. (dolist (b val)
  706. (and (org-export-derived-backend-p b name)
  707. (throw 'parentp t)))))))
  708. org-export-registered-backends))
  709. ;; Now build NEW-LIST of both new back-ends and required
  710. ;; parents.
  711. (let ((new-list (mapcar #'org-export-backend-name
  712. org-export-registered-backends)))
  713. (dolist (backend val)
  714. (cond
  715. ((not (load (format "ox-%s" backend) t t))
  716. (message "Problems while trying to load export back-end `%s'"
  717. backend))
  718. ((not (memq backend new-list)) (push backend new-list))))
  719. ;; Set VAR to that list with fixed dependencies.
  720. (set-default var new-list))))
  721. :type '(set :greedy t
  722. (const :tag " ascii Export buffer to ASCII format" ascii)
  723. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  724. (const :tag " html Export buffer to HTML format" html)
  725. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  726. (const :tag " latex Export buffer to LaTeX format" latex)
  727. (const :tag " man Export buffer to MAN format" man)
  728. (const :tag " md Export buffer to Markdown format" md)
  729. (const :tag " odt Export buffer to ODT format" odt)
  730. (const :tag " org Export buffer to Org format" org)
  731. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  732. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  733. (const :tag "C deck Export buffer to deck.js presentations" deck)
  734. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  735. (const :tag "C groff Export buffer to Groff format" groff)
  736. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  737. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  738. (const :tag "C s5 Export buffer to s5 presentations" s5)
  739. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  740. (eval-after-load 'ox
  741. '(dolist (backend org-export-backends)
  742. (condition-case nil (require (intern (format "ox-%s" backend)))
  743. (error (message "Problems while trying to load export back-end `%s'"
  744. backend)))))
  745. (defcustom org-support-shift-select nil
  746. "Non-nil means make shift-cursor commands select text when possible.
  747. \\<org-mode-map>
  748. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  749. start selecting a region, or enlarge regions started in this way.
  750. In Org mode, in special contexts, these same keys are used for
  751. other purposes, important enough to compete with shift selection.
  752. Org tries to balance these needs by supporting `shift-select-mode'
  753. outside these special contexts, under control of this variable.
  754. The default of this variable is nil, to avoid confusing behavior. Shifted
  755. cursor keys will then execute Org commands in the following contexts:
  756. - on a headline, changing TODO state (left/right) and priority (up/down)
  757. - on a time stamp, changing the time
  758. - in a plain list item, changing the bullet type
  759. - in a property definition line, switching between allowed values
  760. - in the BEGIN line of a clock table (changing the time block).
  761. - in a table, moving the cell in the specified direction.
  762. Outside these contexts, the commands will throw an error.
  763. When this variable is t and the cursor is not in a special
  764. context, Org mode will support shift-selection for making and
  765. enlarging regions. To make this more effective, the bullet
  766. cycling will no longer happen anywhere in an item line, but only
  767. if the cursor is exactly on the bullet.
  768. If you set this variable to the symbol `always', then the keys
  769. will not be special in headlines, property lines, item lines, and
  770. table cells, to make shift selection work there as well. If this is
  771. what you want, you can use the following alternative commands:
  772. `\\[org-todo]' and `\\[org-priority]' \
  773. to change TODO state and priority,
  774. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  775. can be used to switch TODO sets,
  776. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  777. and properties can be edited by hand or in column view.
  778. However, when the cursor is on a timestamp, shift-cursor commands
  779. will still edit the time stamp - this is just too good to give up."
  780. :group 'org
  781. :type '(choice
  782. (const :tag "Never" nil)
  783. (const :tag "When outside special context" t)
  784. (const :tag "Everywhere except timestamps" always)))
  785. (defcustom org-loop-over-headlines-in-active-region t
  786. "Shall some commands act upon headlines in the active region?
  787. When set to t, some commands will be performed in all headlines
  788. within the active region.
  789. When set to `start-level', some commands will be performed in all
  790. headlines within the active region, provided that these headlines
  791. are of the same level than the first one.
  792. When set to a string, those commands will be performed on the
  793. matching headlines within the active region. Such string must be
  794. a tags/property/todo match as it is used in the agenda tags view.
  795. The list of commands is: `org-schedule', `org-deadline',
  796. `org-todo', `org-set-tags-command', `org-archive-subtree',
  797. `org-archive-set-tag', `org-toggle-archive-tag' and
  798. `org-archive-to-archive-sibling'. The archiving commands skip
  799. already archived entries.
  800. See `org-agenda-loop-over-headlines-in-active-region' for the
  801. equivalent option for agenda views."
  802. :type '(choice (const :tag "Don't loop" nil)
  803. (const :tag "All headlines in active region" t)
  804. (const :tag "In active region, headlines at the same level than the first one" start-level)
  805. (string :tag "Tags/Property/Todo matcher"))
  806. :package-version '(Org . "9.4")
  807. :group 'org-todo
  808. :group 'org-archive)
  809. (defcustom org-startup-folded 'showeverything
  810. "Non-nil means entering Org mode will switch to OVERVIEW.
  811. This can also be configured on a per-file basis by adding one of
  812. the following lines anywhere in the buffer:
  813. #+STARTUP: fold (or `overview', this is equivalent)
  814. #+STARTUP: nofold (or `showall', this is equivalent)
  815. #+STARTUP: content
  816. #+STARTUP: show<n>levels (<n> = 2..5)
  817. #+STARTUP: showeverything
  818. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  819. to ignore this option when Org opens agenda files for the first
  820. time."
  821. :group 'org-startup
  822. :package-version '(Org . "9.4")
  823. :type '(choice
  824. (const :tag "nofold: show all" nil)
  825. (const :tag "fold: overview" t)
  826. (const :tag "fold: show two levels" show2levels)
  827. (const :tag "fold: show three levels" show3levels)
  828. (const :tag "fold: show four levels" show4evels)
  829. (const :tag "fold: show five levels" show5levels)
  830. (const :tag "content: all headlines" content)
  831. (const :tag "show everything, even drawers" showeverything)))
  832. (defcustom org-startup-truncated t
  833. "Non-nil means entering Org mode will set `truncate-lines'.
  834. This is useful since some lines containing links can be very long and
  835. uninteresting. Also tables look terrible when wrapped.
  836. The variable `org-startup-truncated' allows to configure
  837. truncation for Org mode different to the other modes that use the
  838. variable `truncate-lines' and as a shortcut instead of putting
  839. the variable `truncate-lines' into the `org-mode-hook'. If one
  840. wants to configure truncation for Org mode not statically but
  841. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  842. the variable `truncate-lines' has to be used because in such a
  843. case it is too late to set the variable `org-startup-truncated'."
  844. :group 'org-startup
  845. :type 'boolean)
  846. (defcustom org-startup-indented nil
  847. "Non-nil means turn on `org-indent-mode' on startup.
  848. This can also be configured on a per-file basis by adding one of
  849. the following lines anywhere in the buffer:
  850. #+STARTUP: indent
  851. #+STARTUP: noindent"
  852. :group 'org-structure
  853. :type '(choice
  854. (const :tag "Not" nil)
  855. (const :tag "Globally (slow on startup in large files)" t)))
  856. (defcustom org-startup-numerated nil
  857. "Non-nil means turn on `org-num-mode' on startup.
  858. This can also be configured on a per-file basis by adding one of
  859. the following lines anywhere in the buffer:
  860. #+STARTUP: num
  861. #+STARTUP: nonum"
  862. :group 'org-structure
  863. :package-version '(Org . "9.4")
  864. :type '(choice
  865. (const :tag "Not" nil)
  866. (const :tag "Globally" t)))
  867. (defcustom org-use-sub-superscripts t
  868. "Non-nil means interpret \"_\" and \"^\" for display.
  869. If you want to control how Org exports those characters, see
  870. `org-export-with-sub-superscripts'.
  871. When this option is turned on, you can use TeX-like syntax for
  872. sub- and superscripts within the buffer. Several characters after
  873. \"_\" or \"^\" will be considered as a single item - so grouping
  874. with {} is normally not needed. For example, the following things
  875. will be parsed as single sub- or superscripts:
  876. 10^24 or 10^tau several digits will be considered 1 item.
  877. 10^-12 or 10^-tau a leading sign with digits or a word
  878. x^2-y^3 will be read as x^2 - y^3, because items are
  879. terminated by almost any nonword/nondigit char.
  880. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  881. Still, ambiguity is possible. So when in doubt, use {} to enclose
  882. the sub/superscript. If you set this variable to the symbol `{}',
  883. the braces are *required* in order to trigger interpretations as
  884. sub/superscript. This can be helpful in documents that need \"_\"
  885. frequently in plain text."
  886. :group 'org-startup
  887. :version "24.4"
  888. :package-version '(Org . "8.0")
  889. :type '(choice
  890. (const :tag "Always interpret" t)
  891. (const :tag "Only with braces" {})
  892. (const :tag "Never interpret" nil)))
  893. (defcustom org-startup-with-beamer-mode nil
  894. "Non-nil means turn on `org-beamer-mode' on startup.
  895. This can also be configured on a per-file basis by adding one of
  896. the following lines anywhere in the buffer:
  897. #+STARTUP: beamer"
  898. :group 'org-startup
  899. :version "24.1"
  900. :type 'boolean)
  901. (defcustom org-startup-align-all-tables nil
  902. "Non-nil means align all tables when visiting a file.
  903. This can also be configured on a per-file basis by adding one of
  904. the following lines anywhere in the buffer:
  905. #+STARTUP: align
  906. #+STARTUP: noalign"
  907. :group 'org-startup
  908. :type 'boolean)
  909. (defcustom org-startup-shrink-all-tables nil
  910. "Non-nil means shrink all table columns with a width cookie.
  911. This can also be configured on a per-file basis by adding one of
  912. the following lines anywhere in the buffer:
  913. #+STARTUP: shrink"
  914. :group 'org-startup
  915. :type 'boolean
  916. :version "27.1"
  917. :package-version '(Org . "9.2")
  918. :safe #'booleanp)
  919. (defcustom org-startup-with-inline-images nil
  920. "Non-nil means show inline images when loading a new Org file.
  921. This can also be configured on a per-file basis by adding one of
  922. the following lines anywhere in the buffer:
  923. #+STARTUP: inlineimages
  924. #+STARTUP: noinlineimages"
  925. :group 'org-startup
  926. :version "24.1"
  927. :type 'boolean)
  928. (defcustom org-startup-with-latex-preview nil
  929. "Non-nil means preview LaTeX fragments when loading a new Org file.
  930. This can also be configured on a per-file basis by adding one of
  931. the following lines anywhere in the buffer:
  932. #+STARTUP: latexpreview
  933. #+STARTUP: nolatexpreview"
  934. :group 'org-startup
  935. :version "24.4"
  936. :package-version '(Org . "8.0")
  937. :type 'boolean)
  938. (defcustom org-insert-mode-line-in-empty-file nil
  939. "Non-nil means insert the first line setting Org mode in empty files.
  940. When the function `org-mode' is called interactively in an empty file, this
  941. normally means that the file name does not automatically trigger Org mode.
  942. To ensure that the file will always be in Org mode in the future, a
  943. line enforcing Org mode will be inserted into the buffer, if this option
  944. has been set."
  945. :group 'org-startup
  946. :type 'boolean)
  947. (defcustom org-ellipsis nil
  948. "The ellipsis to use in the Org mode outline.
  949. When nil, just use the standard three dots. When a non-empty string,
  950. use that string instead.
  951. The change affects only Org mode (which will then use its own display table).
  952. Changing this requires executing `\\[org-mode]' in a buffer to become
  953. effective. It cannot be set as a local variable."
  954. :group 'org-startup
  955. :type '(choice (const :tag "Default" nil)
  956. (string :tag "String" :value "...#")))
  957. (defvar org-display-table nil
  958. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  959. (defcustom org-directory "~/org"
  960. "Directory with Org files.
  961. This is just a default location to look for Org files. There is no need
  962. at all to put your files into this directory. It is used in the
  963. following situations:
  964. 1. When a capture template specifies a target file that is not an
  965. absolute path. The path will then be interpreted relative to
  966. `org-directory'
  967. 2. When the value of variable `org-agenda-files' is a single file, any
  968. relative paths in this file will be taken as relative to
  969. `org-directory'."
  970. :group 'org-refile
  971. :group 'org-capture
  972. :type 'directory)
  973. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  974. "Default target for storing notes.
  975. Used as a fall back file for org-capture.el, for templates that
  976. do not specify a target file."
  977. :group 'org-refile
  978. :group 'org-capture
  979. :type 'file)
  980. (defcustom org-reverse-note-order nil
  981. "Non-nil means store new notes at the beginning of a file or entry.
  982. When nil, new notes will be filed to the end of a file or entry.
  983. This can also be a list with cons cells of regular expressions that
  984. are matched against file names, and values."
  985. :group 'org-capture
  986. :group 'org-refile
  987. :type '(choice
  988. (const :tag "Reverse always" t)
  989. (const :tag "Reverse never" nil)
  990. (repeat :tag "By file name regexp"
  991. (cons regexp boolean))))
  992. (defgroup org-keywords nil
  993. "Keywords in Org mode."
  994. :tag "Org Keywords"
  995. :group 'org)
  996. (defcustom org-closed-keep-when-no-todo nil
  997. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  998. :group 'org-todo
  999. :group 'org-keywords
  1000. :version "24.4"
  1001. :package-version '(Org . "8.0")
  1002. :type 'boolean)
  1003. (defgroup org-structure nil
  1004. "Options concerning the general structure of Org files."
  1005. :tag "Org Structure"
  1006. :group 'org)
  1007. (defgroup org-reveal-location nil
  1008. "Options about how to make context of a location visible."
  1009. :tag "Org Reveal Location"
  1010. :group 'org-structure)
  1011. (defcustom org-show-context-detail '((agenda . local)
  1012. (bookmark-jump . lineage)
  1013. (isearch . lineage)
  1014. (default . ancestors))
  1015. "Alist between context and visibility span when revealing a location.
  1016. \\<org-mode-map>Some actions may move point into invisible
  1017. locations. As a consequence, Org always exposes a neighborhood
  1018. around point. How much is shown depends on the initial action,
  1019. or context. Valid contexts are
  1020. agenda when exposing an entry from the agenda
  1021. org-goto when using the command `org-goto' (`\\[org-goto]')
  1022. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1023. tags-tree when constructing a sparse tree based on tags matches
  1024. link-search when exposing search matches associated with a link
  1025. mark-goto when exposing the jump goal of a mark
  1026. bookmark-jump when exposing a bookmark location
  1027. isearch when exiting from an incremental search
  1028. default default for all contexts not set explicitly
  1029. Allowed visibility spans are
  1030. minimal show current headline; if point is not on headline,
  1031. also show entry
  1032. local show current headline, entry and next headline
  1033. ancestors show current headline and its direct ancestors; if
  1034. point is not on headline, also show entry
  1035. lineage show current headline, its direct ancestors and all
  1036. their children; if point is not on headline, also show
  1037. entry and first child
  1038. tree show current headline, its direct ancestors and all
  1039. their children; if point is not on headline, also show
  1040. entry and all children
  1041. canonical show current headline, its direct ancestors along with
  1042. their entries and children; if point is not located on
  1043. the headline, also show current entry and all children
  1044. As special cases, a nil or t value means show all contexts in
  1045. `minimal' or `canonical' view, respectively.
  1046. Some views can make displayed information very compact, but also
  1047. make it harder to edit the location of the match. In such
  1048. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1049. more context."
  1050. :group 'org-reveal-location
  1051. :version "26.1"
  1052. :package-version '(Org . "9.0")
  1053. :type '(choice
  1054. (const :tag "Canonical" t)
  1055. (const :tag "Minimal" nil)
  1056. (repeat :greedy t :tag "Individual contexts"
  1057. (cons
  1058. (choice :tag "Context"
  1059. (const agenda)
  1060. (const org-goto)
  1061. (const occur-tree)
  1062. (const tags-tree)
  1063. (const link-search)
  1064. (const mark-goto)
  1065. (const bookmark-jump)
  1066. (const isearch)
  1067. (const default))
  1068. (choice :tag "Detail level"
  1069. (const minimal)
  1070. (const local)
  1071. (const ancestors)
  1072. (const lineage)
  1073. (const tree)
  1074. (const canonical))))))
  1075. (defcustom org-indirect-buffer-display 'other-window
  1076. "How should indirect tree buffers be displayed?
  1077. This applies to indirect buffers created with the commands
  1078. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1079. Valid values are:
  1080. current-window Display in the current window
  1081. other-window Just display in another window.
  1082. dedicated-frame Create one new frame, and re-use it each time.
  1083. new-frame Make a new frame each time. Note that in this case
  1084. previously-made indirect buffers are kept, and you need to
  1085. kill these buffers yourself."
  1086. :group 'org-structure
  1087. :group 'org-agenda-windows
  1088. :type '(choice
  1089. (const :tag "In current window" current-window)
  1090. (const :tag "In current frame, other window" other-window)
  1091. (const :tag "Each time a new frame" new-frame)
  1092. (const :tag "One dedicated frame" dedicated-frame)))
  1093. (defconst org-file-apps-gnu
  1094. '((remote . emacs)
  1095. (system . mailcap)
  1096. (t . mailcap))
  1097. "Default file applications on a UNIX or GNU/Linux system.
  1098. See `org-file-apps'.")
  1099. (defconst org-file-apps-macos
  1100. '((remote . emacs)
  1101. (system . "open %s")
  1102. ("ps.gz" . "gv %s")
  1103. ("eps.gz" . "gv %s")
  1104. ("dvi" . "xdvi %s")
  1105. ("fig" . "xfig %s")
  1106. (t . "open %s"))
  1107. "Default file applications on a macOS system.
  1108. The system \"open\" is known as a default, but we use X11 applications
  1109. for some files for which the OS does not have a good default.
  1110. See `org-file-apps'.")
  1111. (defconst org-file-apps-windowsnt
  1112. (list '(remote . emacs)
  1113. (cons 'system (lambda (file _path)
  1114. (with-no-warnings (w32-shell-execute "open" file))))
  1115. (cons t (lambda (file _path)
  1116. (with-no-warnings (w32-shell-execute "open" file)))))
  1117. "Default file applications on a Windows NT system.
  1118. The system \"open\" is used for most files.
  1119. See `org-file-apps'.")
  1120. (defcustom org-file-apps
  1121. '((auto-mode . emacs)
  1122. (directory . emacs)
  1123. ("\\.mm\\'" . default)
  1124. ("\\.x?html?\\'" . default)
  1125. ("\\.pdf\\'" . default))
  1126. "Applications for opening `file:path' items in a document.
  1127. \\<org-mode-map>
  1128. Org mode uses system defaults for different file types, but you
  1129. can use this variable to set the application for a given file
  1130. extension. The entries in this list are cons cells where the car
  1131. identifies files and the cdr the corresponding command.
  1132. Possible values for the file identifier are:
  1133. \"string\" A string as a file identifier can be interpreted in different
  1134. ways, depending on its contents:
  1135. - Alphanumeric characters only:
  1136. Match links with this file extension.
  1137. Example: (\"pdf\" . \"evince %s\")
  1138. to open PDFs with evince.
  1139. - Regular expression: Match links where the
  1140. filename matches the regexp. If you want to
  1141. use groups here, use shy groups.
  1142. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1143. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1144. to open *.html and *.xhtml with firefox.
  1145. - Regular expression which contains (non-shy) groups:
  1146. Match links where the whole link, including \"::\", and
  1147. anything after that, matches the regexp.
  1148. In a custom command string, %1, %2, etc. are replaced with
  1149. the parts of the link that were matched by the groups.
  1150. For backwards compatibility, if a command string is given
  1151. that does not use any of the group matches, this case is
  1152. handled identically to the second one (i.e. match against
  1153. file name only).
  1154. In a custom function, you can access the group matches with
  1155. (match-string n link).
  1156. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1157. \"evince -p %1 %s\")
  1158. to open [[file:document.pdf::5]] with evince at page 5.
  1159. `directory' Matches a directory
  1160. `remote' Matches a remote file, accessible through tramp or efs.
  1161. Remote files most likely should be visited through Emacs
  1162. because external applications cannot handle such paths.
  1163. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1164. so all files Emacs knows how to handle. Using this with
  1165. command `emacs' will open most files in Emacs. Beware that this
  1166. will also open html files inside Emacs, unless you add
  1167. (\"html\" . default) to the list as well.
  1168. `system' The system command to open files, like `open' on Windows
  1169. and macOS, and mailcap under GNU/Linux. This is the command
  1170. that will be selected if you call `org-open-at-point' with a
  1171. double prefix argument (`\\[universal-argument] \
  1172. \\[universal-argument] \\[org-open-at-point]').
  1173. t Default for files not matched by any of the other options.
  1174. Possible values for the command are:
  1175. `emacs' The file will be visited by the current Emacs process.
  1176. `default' Use the default application for this file type, which is the
  1177. association for t in the list, most likely in the system-specific
  1178. part. This can be used to overrule an unwanted setting in the
  1179. system-specific variable.
  1180. `system' Use the system command for opening files, like \"open\".
  1181. This command is specified by the entry whose car is `system'.
  1182. Most likely, the system-specific version of this variable
  1183. does define this command, but you can overrule/replace it
  1184. here.
  1185. `mailcap' Use command specified in the mailcaps.
  1186. string A command to be executed by a shell; %s will be replaced
  1187. by the path to the file.
  1188. function A Lisp function, which will be called with two arguments:
  1189. the file path and the original link string, without the
  1190. \"file:\" prefix.
  1191. For more examples, see the system specific constants
  1192. `org-file-apps-macos'
  1193. `org-file-apps-windowsnt'
  1194. `org-file-apps-gnu'."
  1195. :group 'org
  1196. :package-version '(Org . "9.4")
  1197. :type '(repeat
  1198. (cons (choice :value ""
  1199. (string :tag "Extension")
  1200. (const :tag "System command to open files" system)
  1201. (const :tag "Default for unrecognized files" t)
  1202. (const :tag "Remote file" remote)
  1203. (const :tag "Links to a directory" directory)
  1204. (const :tag "Any files that have Emacs modes"
  1205. auto-mode))
  1206. (choice :value ""
  1207. (const :tag "Visit with Emacs" emacs)
  1208. (const :tag "Use default" default)
  1209. (const :tag "Use the system command" system)
  1210. (string :tag "Command")
  1211. (function :tag "Function")))))
  1212. (defcustom org-open-non-existing-files nil
  1213. "Non-nil means `org-open-file' opens non-existing files.
  1214. When nil, an error is thrown.
  1215. This variable applies only to external applications because they
  1216. might choke on non-existing files. If the link is to a file that
  1217. will be opened in Emacs, the variable is ignored."
  1218. :group 'org
  1219. :type 'boolean
  1220. :safe #'booleanp)
  1221. (defcustom org-open-directory-means-index-dot-org nil
  1222. "When non-nil a link to a directory really means to \"index.org\".
  1223. When nil, following a directory link runs Dired or opens
  1224. a finder/explorer window on that directory."
  1225. :group 'org
  1226. :type 'boolean
  1227. :safe #'booleanp)
  1228. (defcustom org-bookmark-names-plist
  1229. '(:last-capture "org-capture-last-stored"
  1230. :last-refile "org-refile-last-stored"
  1231. :last-capture-marker "org-capture-last-stored-marker")
  1232. "Names for bookmarks automatically set by some Org commands.
  1233. This can provide strings as names for a number of bookmarks Org sets
  1234. automatically. The following keys are currently implemented:
  1235. :last-capture
  1236. :last-capture-marker
  1237. :last-refile
  1238. When a key does not show up in the property list, the corresponding bookmark
  1239. is not set."
  1240. :group 'org-structure
  1241. :type 'plist)
  1242. (defgroup org-cycle nil
  1243. "Options concerning visibility cycling in Org mode."
  1244. :tag "Org Cycle"
  1245. :group 'org-structure)
  1246. (defcustom org-cycle-skip-children-state-if-no-children t
  1247. "Non-nil means skip CHILDREN state in entries that don't have any."
  1248. :group 'org-cycle
  1249. :type 'boolean)
  1250. (defcustom org-cycle-max-level nil
  1251. "Maximum level which should still be subject to visibility cycling.
  1252. Levels higher than this will, for cycling, be treated as text, not a headline.
  1253. When `org-odd-levels-only' is set, a value of N in this variable actually
  1254. means 2N-1 stars as the limiting headline.
  1255. When nil, cycle all levels.
  1256. Note that the limiting level of cycling is also influenced by
  1257. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1258. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1259. than its value."
  1260. :group 'org-cycle
  1261. :type '(choice
  1262. (const :tag "No limit" nil)
  1263. (integer :tag "Maximum level")))
  1264. (defcustom org-hide-block-startup nil
  1265. "Non-nil means entering Org mode will fold all blocks.
  1266. This can also be set in on a per-file basis with
  1267. #+STARTUP: hideblocks
  1268. #+STARTUP: showblocks"
  1269. :group 'org-startup
  1270. :group 'org-cycle
  1271. :type 'boolean)
  1272. (defcustom org-cycle-global-at-bob nil
  1273. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1274. This makes it possible to do global cycling without having to use `S-TAB'
  1275. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1276. line of the buffer
  1277. must not be a headline -- it may be empty or some other text.
  1278. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1279. sure the cursor stays at the beginning of the buffer.
  1280. When this option is nil, don't do anything special at the beginning of
  1281. the buffer."
  1282. :group 'org-cycle
  1283. :type 'boolean)
  1284. (defcustom org-cycle-level-after-item/entry-creation t
  1285. "Non-nil means cycle entry level or item indentation in new empty entries.
  1286. When the cursor is at the end of an empty headline, i.e., with only stars
  1287. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1288. and then all possible ancestor states, before returning to the original state.
  1289. This makes data entry extremely fast: M-RET to create a new headline,
  1290. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1291. When the cursor is at the end of an empty plain list item, one TAB will
  1292. make it a subitem, two or more tabs will back up to make this an item
  1293. higher up in the item hierarchy."
  1294. :group 'org-cycle
  1295. :type 'boolean)
  1296. (defcustom org-cycle-emulate-tab t
  1297. "Where should `org-cycle' emulate TAB.
  1298. nil Never
  1299. white Only in completely white lines
  1300. whitestart Only at the beginning of lines, before the first non-white char
  1301. t Everywhere except in headlines
  1302. exc-hl-bol Everywhere except at the start of a headline
  1303. If TAB is used in a place where it does not emulate TAB, the current subtree
  1304. visibility is cycled."
  1305. :group 'org-cycle
  1306. :type '(choice (const :tag "Never" nil)
  1307. (const :tag "Only in completely white lines" white)
  1308. (const :tag "Before first char in a line" whitestart)
  1309. (const :tag "Everywhere except in headlines" t)
  1310. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1311. (defcustom org-cycle-separator-lines 2
  1312. "Number of empty lines needed to keep an empty line between collapsed trees.
  1313. If you leave an empty line between the end of a subtree and the following
  1314. headline, this empty line is hidden when the subtree is folded.
  1315. Org mode will leave (exactly) one empty line visible if the number of
  1316. empty lines is equal or larger to the number given in this variable.
  1317. So the default 2 means at least 2 empty lines after the end of a subtree
  1318. are needed to produce free space between a collapsed subtree and the
  1319. following headline.
  1320. If the number is negative, and the number of empty lines is at least -N,
  1321. all empty lines are shown.
  1322. Special case: when 0, never leave empty lines in collapsed view."
  1323. :group 'org-cycle
  1324. :type 'integer)
  1325. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1326. (defcustom org-pre-cycle-hook nil
  1327. "Hook that is run before visibility cycling is happening.
  1328. The function(s) in this hook must accept a single argument which indicates
  1329. the new state that will be set right after running this hook. The
  1330. argument is a symbol. Before a global state change, it can have the values
  1331. `overview', `content', or `all'. Before a local state change, it can have
  1332. the values `folded', `children', or `subtree'."
  1333. :group 'org-cycle
  1334. :type 'hook)
  1335. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1336. org-cycle-hide-drawers
  1337. org-cycle-show-empty-lines
  1338. org-optimize-window-after-visibility-change)
  1339. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1340. The function(s) in this hook must accept a single argument which indicates
  1341. the new state that was set by the most recent `org-cycle' command. The
  1342. argument is a symbol. After a global state change, it can have the values
  1343. `overview', `contents', or `all'. After a local state change, it can have
  1344. the values `folded', `children', or `subtree'."
  1345. :group 'org-cycle
  1346. :package-version '(Org . "9.4")
  1347. :type 'hook)
  1348. (defgroup org-edit-structure nil
  1349. "Options concerning structure editing in Org mode."
  1350. :tag "Org Edit Structure"
  1351. :group 'org-structure)
  1352. (defcustom org-odd-levels-only nil
  1353. "Non-nil means skip even levels and only use odd levels for the outline.
  1354. This has the effect that two stars are being added/taken away in
  1355. promotion/demotion commands. It also influences how levels are
  1356. handled by the exporters.
  1357. Changing it requires restart of `font-lock-mode' to become effective
  1358. for fontification also in regions already fontified.
  1359. You may also set this on a per-file basis by adding one of the following
  1360. lines to the buffer:
  1361. #+STARTUP: odd
  1362. #+STARTUP: oddeven"
  1363. :group 'org-edit-structure
  1364. :group 'org-appearance
  1365. :type 'boolean)
  1366. (defcustom org-adapt-indentation t
  1367. "Non-nil means adapt indentation to outline node level.
  1368. When this variable is set to t, Org assumes that you write
  1369. outlines by indenting text in each node to align with the
  1370. headline (after the stars).
  1371. When this variable is set to `headline-data', only adapt the
  1372. indentation of the data lines right below the headline, such as
  1373. planning/clock lines and property/logbook drawers.
  1374. The following issues are influenced by this variable:
  1375. - The indentation is increased by one space in a demotion
  1376. command, and decreased by one in a promotion command. However,
  1377. in the latter case, if shifting some line in the entry body
  1378. would alter document structure (e.g., insert a new headline),
  1379. indentation is not changed at all.
  1380. - Property drawers and planning information is inserted indented
  1381. when this variable is set. When nil, they will not be indented.
  1382. - TAB indents a line relative to current level. The lines below
  1383. a headline will be indented when this variable is set to t.
  1384. Note that this is all about true indentation, by adding and
  1385. removing space characters. See also \"org-indent.el\" which does
  1386. level-dependent indentation in a virtual way, i.e. at display
  1387. time in Emacs."
  1388. :group 'org-edit-structure
  1389. :type '(choice
  1390. (const :tag "Adapt indentation for all lines" t)
  1391. (const :tag "Adapt indentation for headline data lines"
  1392. headline-data)
  1393. (const :tag "Do not adapt indentation at all" nil))
  1394. :safe (lambda (x) (memq x '(t nil headline-data))))
  1395. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1396. (defcustom org-special-ctrl-a/e nil
  1397. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1398. When t, `C-a' will bring back the cursor to the beginning of the
  1399. headline text, i.e. after the stars and after a possible TODO
  1400. keyword. In an item, this will be the position after bullet and
  1401. check-box, if any. When the cursor is already at that position,
  1402. another `C-a' will bring it to the beginning of the line.
  1403. `C-e' will jump to the end of the headline, ignoring the presence
  1404. of tags in the headline. A second `C-e' will then jump to the
  1405. true end of the line, after any tags. This also means that, when
  1406. this variable is non-nil, `C-e' also will never jump beyond the
  1407. end of the heading of a folded section, i.e. not after the
  1408. ellipses.
  1409. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1410. normally, going to the true line boundary first. Only a directly
  1411. following, identical keypress will bring the cursor to the
  1412. special positions.
  1413. This may also be a cons cell where the behavior for `C-a' and
  1414. `C-e' is set separately."
  1415. :group 'org-edit-structure
  1416. :type '(choice
  1417. (const :tag "off" nil)
  1418. (const :tag "on: after stars/bullet and before tags first" t)
  1419. (const :tag "reversed: true line boundary first" reversed)
  1420. (cons :tag "Set C-a and C-e separately"
  1421. (choice :tag "Special C-a"
  1422. (const :tag "off" nil)
  1423. (const :tag "on: after stars/bullet first" t)
  1424. (const :tag "reversed: before stars/bullet first" reversed))
  1425. (choice :tag "Special C-e"
  1426. (const :tag "off" nil)
  1427. (const :tag "on: before tags first" t)
  1428. (const :tag "reversed: after tags first" reversed)))))
  1429. (defcustom org-special-ctrl-k nil
  1430. "Non-nil means `C-k' will behave specially in headlines.
  1431. When nil, `C-k' will call the default `kill-line' command.
  1432. When t, the following will happen while the cursor is in the headline:
  1433. - When at the beginning of a headline, kill the entire subtree.
  1434. - When in the middle of the headline text, kill the text up to the tags.
  1435. - When after the headline text and before the tags, kill all the tags."
  1436. :group 'org-edit-structure
  1437. :type 'boolean)
  1438. (defcustom org-ctrl-k-protect-subtree nil
  1439. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1440. When set to the symbol `error', simply throw an error when `C-k' is
  1441. used to kill (part-of) a headline that has hidden text behind it.
  1442. Any other non-nil value will result in a query to the user, if it is
  1443. OK to kill that hidden subtree. When nil, kill without remorse."
  1444. :group 'org-edit-structure
  1445. :version "24.1"
  1446. :type '(choice
  1447. (const :tag "Do not protect hidden subtrees" nil)
  1448. (const :tag "Protect hidden subtrees with a security query" t)
  1449. (const :tag "Never kill a hidden subtree with C-k" error)))
  1450. (defcustom org-special-ctrl-o t
  1451. "Non-nil means, make `C-o' insert a row in tables."
  1452. :group 'org-edit-structure
  1453. :type 'boolean)
  1454. (defcustom org-catch-invisible-edits nil
  1455. "Check if in invisible region before inserting or deleting a character.
  1456. Valid values are:
  1457. nil Do not check, so just do invisible edits.
  1458. error Throw an error and do nothing.
  1459. show Make point visible, and do the requested edit.
  1460. show-and-error Make point visible, then throw an error and abort the edit.
  1461. smart Make point visible, and do insertion/deletion if it is
  1462. adjacent to visible text and the change feels predictable.
  1463. Never delete a previously invisible character or add in the
  1464. middle or right after an invisible region. Basically, this
  1465. allows insertion and backward-delete right before ellipses.
  1466. FIXME: maybe in this case we should not even show?"
  1467. :group 'org-edit-structure
  1468. :version "24.1"
  1469. :type '(choice
  1470. (const :tag "Do not check" nil)
  1471. (const :tag "Throw error when trying to edit" error)
  1472. (const :tag "Unhide, but do not do the edit" show-and-error)
  1473. (const :tag "Show invisible part and do the edit" show)
  1474. (const :tag "Be smart and do the right thing" smart)))
  1475. (defcustom org-yank-folded-subtrees t
  1476. "Non-nil means when yanking subtrees, fold them.
  1477. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1478. it starts with a heading and all other headings in it are either children
  1479. or siblings, then fold all the subtrees. However, do this only if no
  1480. text after the yank would be swallowed into a folded tree by this action."
  1481. :group 'org-edit-structure
  1482. :type 'boolean)
  1483. (defcustom org-yank-adjusted-subtrees nil
  1484. "Non-nil means when yanking subtrees, adjust the level.
  1485. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1486. this function for details."
  1487. :group 'org-edit-structure
  1488. :type 'boolean)
  1489. (defcustom org-M-RET-may-split-line '((default . t))
  1490. "Non-nil means M-RET will split the line at the cursor position.
  1491. When nil, it will go to the end of the line before making a
  1492. new line.
  1493. You may also set this option in a different way for different
  1494. contexts. Valid contexts are:
  1495. headline when creating a new headline
  1496. item when creating a new item
  1497. table in a table field
  1498. default the value to be used for all contexts not explicitly
  1499. customized"
  1500. :group 'org-structure
  1501. :group 'org-table
  1502. :type '(choice
  1503. (const :tag "Always" t)
  1504. (const :tag "Never" nil)
  1505. (repeat :greedy t :tag "Individual contexts"
  1506. (cons
  1507. (choice :tag "Context"
  1508. (const headline)
  1509. (const item)
  1510. (const table)
  1511. (const default))
  1512. (boolean)))))
  1513. (defcustom org-insert-heading-respect-content nil
  1514. "Non-nil means insert new headings after the current subtree.
  1515. \\<org-mode-map>
  1516. When nil, the new heading is created directly after the current line.
  1517. The commands `\\[org-insert-heading-respect-content]' and \
  1518. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1519. for the duration of the command."
  1520. :group 'org-structure
  1521. :type 'boolean)
  1522. (defcustom org-blank-before-new-entry '((heading . auto)
  1523. (plain-list-item . auto))
  1524. "Should `org-insert-heading' leave a blank line before new heading/item?
  1525. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1526. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1527. which case Org will look at the surrounding headings/items and try to
  1528. make an intelligent decision whether to insert a blank line or not."
  1529. :group 'org-edit-structure
  1530. :type '(list
  1531. (cons (const heading)
  1532. (choice (const :tag "Never" nil)
  1533. (const :tag "Always" t)
  1534. (const :tag "Auto" auto)))
  1535. (cons (const plain-list-item)
  1536. (choice (const :tag "Never" nil)
  1537. (const :tag "Always" t)
  1538. (const :tag "Auto" auto)))))
  1539. (defcustom org-insert-heading-hook nil
  1540. "Hook being run after inserting a new heading."
  1541. :group 'org-edit-structure
  1542. :type 'hook)
  1543. (defgroup org-sparse-trees nil
  1544. "Options concerning sparse trees in Org mode."
  1545. :tag "Org Sparse Trees"
  1546. :group 'org-structure)
  1547. (defcustom org-highlight-sparse-tree-matches t
  1548. "Non-nil means highlight all matches that define a sparse tree.
  1549. The highlights will automatically disappear the next time the buffer is
  1550. changed by an edit command."
  1551. :group 'org-sparse-trees
  1552. :type 'boolean)
  1553. (defcustom org-remove-highlights-with-change t
  1554. "Non-nil means any change to the buffer will remove temporary highlights.
  1555. \\<org-mode-map>\
  1556. Such highlights are created by `org-occur' and `org-clock-display'.
  1557. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1558. to get rid of the highlights.
  1559. The highlights created by `org-latex-preview' always need
  1560. `\\[org-latex-preview]' to be removed."
  1561. :group 'org-sparse-trees
  1562. :group 'org-time
  1563. :type 'boolean)
  1564. (defcustom org-occur-case-fold-search t
  1565. "Non-nil means `org-occur' should be case-insensitive.
  1566. If set to `smart' the search will be case-insensitive only if it
  1567. doesn't specify any upper case character."
  1568. :group 'org-sparse-trees
  1569. :version "26.1"
  1570. :type '(choice
  1571. (const :tag "Case-sensitive" nil)
  1572. (const :tag "Case-insensitive" t)
  1573. (const :tag "Case-insensitive for lower case searches only" smart)))
  1574. (defcustom org-occur-hook '(org-first-headline-recenter)
  1575. "Hook that is run after `org-occur' has constructed a sparse tree.
  1576. This can be used to recenter the window to show as much of the structure
  1577. as possible."
  1578. :group 'org-sparse-trees
  1579. :type 'hook)
  1580. (defcustom org-self-insert-cluster-for-undo nil
  1581. "Non-nil means cluster self-insert commands for undo when possible.
  1582. If this is set, then, like in the Emacs command loop, 20 consecutive
  1583. characters will be undone together.
  1584. This is configurable, because there is some impact on typing performance."
  1585. :group 'org-table
  1586. :type 'boolean)
  1587. (defvaralias 'org-activate-links 'org-highlight-links)
  1588. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1589. "Types of links that should be highlighted in Org files.
  1590. This is a list of symbols, each one of them leading to the
  1591. highlighting of a certain link type.
  1592. You can still open links that are not highlighted.
  1593. In principle, it does not hurt to turn on highlighting for all
  1594. link types. There may be a small gain when turning off unused
  1595. link types. The types are:
  1596. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1597. angle Links in angular brackets that may contain whitespace like
  1598. <bbdb:Carsten Dominik>.
  1599. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1600. radio Text that is matched by a radio target, see manual for details.
  1601. tag Tag settings in a headline (link to tag search).
  1602. date Time stamps (link to calendar).
  1603. footnote Footnote labels.
  1604. If you set this variable during an Emacs session, use `org-mode-restart'
  1605. in the Org buffer so that the change takes effect."
  1606. :group 'org-appearance
  1607. :type '(set :greedy t
  1608. (const :tag "Double bracket links" bracket)
  1609. (const :tag "Angular bracket links" angle)
  1610. (const :tag "Plain text links" plain)
  1611. (const :tag "Radio target matches" radio)
  1612. (const :tag "Tags" tag)
  1613. (const :tag "Timestamps" date)
  1614. (const :tag "Footnotes" footnote)))
  1615. (defcustom org-mark-ring-length 4
  1616. "Number of different positions to be recorded in the ring.
  1617. Changing this requires a restart of Emacs to work correctly."
  1618. :group 'org-link-follow
  1619. :type 'integer)
  1620. (defgroup org-todo nil
  1621. "Options concerning TODO items in Org mode."
  1622. :tag "Org TODO"
  1623. :group 'org)
  1624. (defgroup org-progress nil
  1625. "Options concerning Progress logging in Org mode."
  1626. :tag "Org Progress"
  1627. :group 'org-time)
  1628. (defvar org-todo-interpretation-widgets
  1629. '((:tag "Sequence (cycling hits every state)" sequence)
  1630. (:tag "Type (cycling directly to DONE)" type))
  1631. "The available interpretation symbols for customizing `org-todo-keywords'.
  1632. Interested libraries should add to this list.")
  1633. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1634. "List of TODO entry keyword sequences and their interpretation.
  1635. \\<org-mode-map>This is a list of sequences.
  1636. Each sequence starts with a symbol, either `sequence' or `type',
  1637. indicating if the keywords should be interpreted as a sequence of
  1638. action steps, or as different types of TODO items. The first
  1639. keywords are states requiring action - these states will select a headline
  1640. for inclusion into the global TODO list Org produces. If one of the
  1641. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1642. signify that no further action is necessary. If \"|\" is not found,
  1643. the last keyword is treated as the only DONE state of the sequence.
  1644. The command `\\[org-todo]' cycles an entry through these states, and one
  1645. additional state where no keyword is present. For details about this
  1646. cycling, see the manual.
  1647. TODO keywords and interpretation can also be set on a per-file basis with
  1648. the special #+SEQ_TODO and #+TYP_TODO lines.
  1649. Each keyword can optionally specify a character for fast state selection
  1650. \(in combination with the variable `org-use-fast-todo-selection')
  1651. and specifiers for state change logging, using the same syntax that
  1652. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1653. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1654. indicates to record a time stamp each time this state is selected.
  1655. Each keyword may also specify if a timestamp or a note should be
  1656. recorded when entering or leaving the state, by adding additional
  1657. characters in the parenthesis after the keyword. This looks like this:
  1658. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1659. record only the time of the state change. With X and Y being either
  1660. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1661. Y when leaving the state if and only if the *target* state does not
  1662. define X. You may omit any of the fast-selection key or X or /Y,
  1663. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1664. For backward compatibility, this variable may also be just a list
  1665. of keywords. In this case the interpretation (sequence or type) will be
  1666. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1667. :group 'org-todo
  1668. :group 'org-keywords
  1669. :type '(choice
  1670. (repeat :tag "Old syntax, just keywords"
  1671. (string :tag "Keyword"))
  1672. (repeat :tag "New syntax"
  1673. (cons
  1674. (choice
  1675. :tag "Interpretation"
  1676. ;;Quick and dirty way to see
  1677. ;;`org-todo-interpretation'. This takes the
  1678. ;;place of item arguments
  1679. :convert-widget
  1680. (lambda (widget)
  1681. (widget-put widget
  1682. :args (mapcar
  1683. (lambda (x)
  1684. (widget-convert
  1685. (cons 'const x)))
  1686. org-todo-interpretation-widgets))
  1687. widget))
  1688. (repeat
  1689. (string :tag "Keyword"))))))
  1690. (defvar-local org-todo-keywords-1 nil
  1691. "All TODO and DONE keywords active in a buffer.")
  1692. (defvar org-todo-keywords-for-agenda nil)
  1693. (defvar org-done-keywords-for-agenda nil)
  1694. (defvar org-todo-keyword-alist-for-agenda nil)
  1695. (defvar org-tag-alist-for-agenda nil
  1696. "Alist of all tags from all agenda files.")
  1697. (defvar org-tag-groups-alist-for-agenda nil
  1698. "Alist of all groups tags from all current agenda files.")
  1699. (defvar-local org-tag-groups-alist nil)
  1700. (defvar org-agenda-contributing-files nil)
  1701. (defvar-local org-current-tag-alist nil
  1702. "Alist of all tag groups in current buffer.
  1703. This variable takes into consideration `org-tag-alist',
  1704. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1705. (defvar-local org-not-done-keywords nil)
  1706. (defvar-local org-done-keywords nil)
  1707. (defvar-local org-todo-heads nil)
  1708. (defvar-local org-todo-sets nil)
  1709. (defvar-local org-todo-log-states nil)
  1710. (defvar-local org-todo-kwd-alist nil)
  1711. (defvar-local org-todo-key-alist nil)
  1712. (defvar-local org-todo-key-trigger nil)
  1713. (defcustom org-todo-interpretation 'sequence
  1714. "Controls how TODO keywords are interpreted.
  1715. This variable is in principle obsolete and is only used for
  1716. backward compatibility, if the interpretation of todo keywords is
  1717. not given already in `org-todo-keywords'. See that variable for
  1718. more information."
  1719. :group 'org-todo
  1720. :group 'org-keywords
  1721. :type '(choice (const sequence)
  1722. (const type)))
  1723. (defcustom org-use-fast-todo-selection 'auto
  1724. "\\<org-mode-map>\
  1725. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1726. This variable describes if and under what circumstances the cycling
  1727. mechanism for TODO keywords will be replaced by a single-key, direct
  1728. selection scheme, where the choices are displayed in a little window.
  1729. When nil, fast selection is never used. This means that the command
  1730. will always switch to the next state.
  1731. When it is the symbol `auto', fast selection is whenever selection
  1732. keys have been defined.
  1733. `expert' is like `auto', but no special window with the keyword
  1734. will be shown, choices will only be listed in the prompt.
  1735. In all cases, the special interface is only used if access keys have
  1736. actually been assigned by the user, i.e. if keywords in the configuration
  1737. are followed by a letter in parenthesis, like TODO(t)."
  1738. :group 'org-todo
  1739. :set (lambda (var val)
  1740. (cond
  1741. ((eq var t) (set var 'auto))
  1742. ((eq var 'prefix) (set var nil))
  1743. (t (set var val))))
  1744. :type '(choice
  1745. (const :tag "Never" nil)
  1746. (const :tag "Automatically, when key letter have been defined" auto)
  1747. (const :tag "Automatically, but don't show the selection window" expert)))
  1748. (defcustom org-provide-todo-statistics t
  1749. "Non-nil means update todo statistics after insert and toggle.
  1750. ALL-HEADLINES means update todo statistics by including headlines
  1751. with no TODO keyword as well, counting them as not done.
  1752. A list of TODO keywords means the same, but skip keywords that are
  1753. not in this list.
  1754. When set to a list of two lists, the first list contains keywords
  1755. to consider as TODO keywords, the second list contains keywords
  1756. to consider as DONE keywords.
  1757. When this is set, todo statistics is updated in the parent of the
  1758. current entry each time a todo state is changed."
  1759. :group 'org-todo
  1760. :type '(choice
  1761. (const :tag "Yes, only for TODO entries" t)
  1762. (const :tag "Yes, including all entries" all-headlines)
  1763. (repeat :tag "Yes, for TODOs in this list"
  1764. (string :tag "TODO keyword"))
  1765. (list :tag "Yes, for TODOs and DONEs in these lists"
  1766. (repeat (string :tag "TODO keyword"))
  1767. (repeat (string :tag "DONE keyword")))
  1768. (other :tag "No TODO statistics" nil)))
  1769. (defcustom org-hierarchical-todo-statistics t
  1770. "Non-nil means TODO statistics covers just direct children.
  1771. When nil, all entries in the subtree are considered.
  1772. This has only an effect if `org-provide-todo-statistics' is set.
  1773. To set this to nil for only a single subtree, use a COOKIE_DATA
  1774. property and include the word \"recursive\" into the value."
  1775. :group 'org-todo
  1776. :type 'boolean)
  1777. (defcustom org-after-todo-state-change-hook nil
  1778. "Hook which is run after the state of a TODO item was changed.
  1779. The new state (a string with a TODO keyword, or nil) is available in the
  1780. Lisp variable `org-state'."
  1781. :group 'org-todo
  1782. :type 'hook)
  1783. (defvar org-blocker-hook nil
  1784. "Hook for functions that are allowed to block a state change.
  1785. Functions in this hook should not modify the buffer.
  1786. Each function gets as its single argument a property list,
  1787. see `org-trigger-hook' for more information about this list.
  1788. If any of the functions in this hook returns nil, the state change
  1789. is blocked.")
  1790. (defvar org-trigger-hook nil
  1791. "Hook for functions that are triggered by a state change.
  1792. Each function gets as its single argument a property list with at
  1793. least the following elements:
  1794. (:type type-of-change :position pos-at-entry-start
  1795. :from old-state :to new-state)
  1796. Depending on the type, more properties may be present.
  1797. This mechanism is currently implemented for:
  1798. TODO state changes
  1799. ------------------
  1800. :type todo-state-change
  1801. :from previous state (keyword as a string), or nil, or a symbol
  1802. `todo' or `done', to indicate the general type of state.
  1803. :to new state, like in :from")
  1804. (defcustom org-enforce-todo-dependencies nil
  1805. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1806. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1807. be blocked if any prior sibling is not yet done.
  1808. Finally, if the parent is blocked because of ordered siblings of its own,
  1809. the child will also be blocked."
  1810. :set (lambda (var val)
  1811. (set var val)
  1812. (if val
  1813. (add-hook 'org-blocker-hook
  1814. 'org-block-todo-from-children-or-siblings-or-parent)
  1815. (remove-hook 'org-blocker-hook
  1816. 'org-block-todo-from-children-or-siblings-or-parent)))
  1817. :group 'org-todo
  1818. :type 'boolean)
  1819. (defcustom org-enforce-todo-checkbox-dependencies nil
  1820. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1821. When this is nil, checkboxes have no influence on switching TODO states.
  1822. When non-nil, you first need to check off all check boxes before the TODO
  1823. entry can be switched to DONE.
  1824. This variable needs to be set before org.el is loaded, and you need to
  1825. restart Emacs after a change to make the change effective. The only way
  1826. to change it while Emacs is running is through the customize interface."
  1827. :set (lambda (var val)
  1828. (set var val)
  1829. (if val
  1830. (add-hook 'org-blocker-hook
  1831. 'org-block-todo-from-checkboxes)
  1832. (remove-hook 'org-blocker-hook
  1833. 'org-block-todo-from-checkboxes)))
  1834. :group 'org-todo
  1835. :type 'boolean)
  1836. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1837. "Non-nil means inserting a TODO heading is treated as state change.
  1838. So when the command `\\[org-insert-todo-heading]' is used, state change
  1839. logging will apply if appropriate. When nil, the new TODO item will
  1840. be inserted directly, and no logging will take place."
  1841. :group 'org-todo
  1842. :type 'boolean)
  1843. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1844. "Non-nil means switching TODO states with S-cursor counts as state change.
  1845. This is the default behavior. However, setting this to nil allows a
  1846. convenient way to select a TODO state and bypass any logging associated
  1847. with that."
  1848. :group 'org-todo
  1849. :type 'boolean)
  1850. (defcustom org-todo-state-tags-triggers nil
  1851. "Tag changes that should be triggered by TODO state changes.
  1852. This is a list. Each entry is
  1853. (state-change (tag . flag) .......)
  1854. State-change can be a string with a state, and empty string to indicate the
  1855. state that has no TODO keyword, or it can be one of the symbols `todo'
  1856. or `done', meaning any not-done or done state, respectively."
  1857. :group 'org-todo
  1858. :group 'org-tags
  1859. :type '(repeat
  1860. (cons (choice :tag "When changing to"
  1861. (const :tag "Not-done state" todo)
  1862. (const :tag "Done state" done)
  1863. (string :tag "State"))
  1864. (repeat
  1865. (cons :tag "Tag action"
  1866. (string :tag "Tag")
  1867. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1868. (defcustom org-log-done nil
  1869. "Information to record when a task moves to the DONE state.
  1870. Possible values are:
  1871. nil Don't add anything, just change the keyword
  1872. time Add a time stamp to the task
  1873. note Prompt for a note and add it with template `org-log-note-headings'
  1874. This option can also be set with on a per-file-basis with
  1875. #+STARTUP: nologdone
  1876. #+STARTUP: logdone
  1877. #+STARTUP: lognotedone
  1878. You can have local logging settings for a subtree by setting the LOGGING
  1879. property to one or more of these keywords."
  1880. :group 'org-todo
  1881. :group 'org-progress
  1882. :type '(choice
  1883. (const :tag "No logging" nil)
  1884. (const :tag "Record CLOSED timestamp" time)
  1885. (const :tag "Record CLOSED timestamp with note." note)))
  1886. ;; Normalize old uses of org-log-done.
  1887. (cond
  1888. ((eq org-log-done t) (setq org-log-done 'time))
  1889. ((and (listp org-log-done) (memq 'done org-log-done))
  1890. (setq org-log-done 'note)))
  1891. (defcustom org-log-reschedule nil
  1892. "Information to record when the scheduling date of a task is modified.
  1893. Possible values are:
  1894. nil Don't add anything, just change the date
  1895. time Add a time stamp to the task
  1896. note Prompt for a note and add it with template `org-log-note-headings'
  1897. This option can also be set with on a per-file-basis with
  1898. #+STARTUP: nologreschedule
  1899. #+STARTUP: logreschedule
  1900. #+STARTUP: lognotereschedule
  1901. You can have local logging settings for a subtree by setting the LOGGING
  1902. property to one or more of these keywords.
  1903. This variable has an effect when calling `org-schedule' or
  1904. `org-agenda-schedule' only."
  1905. :group 'org-todo
  1906. :group 'org-progress
  1907. :type '(choice
  1908. (const :tag "No logging" nil)
  1909. (const :tag "Record timestamp" time)
  1910. (const :tag "Record timestamp with note" note)))
  1911. (defcustom org-log-redeadline nil
  1912. "Information to record when the deadline date of a task is modified.
  1913. Possible values are:
  1914. nil Don't add anything, just change the date
  1915. time Add a time stamp to the task
  1916. note Prompt for a note and add it with template `org-log-note-headings'
  1917. This option can also be set with on a per-file-basis with
  1918. #+STARTUP: nologredeadline
  1919. #+STARTUP: logredeadline
  1920. #+STARTUP: lognoteredeadline
  1921. You can have local logging settings for a subtree by setting the LOGGING
  1922. property to one or more of these keywords.
  1923. This variable has an effect when calling `org-deadline' or
  1924. `org-agenda-deadline' only."
  1925. :group 'org-todo
  1926. :group 'org-progress
  1927. :type '(choice
  1928. (const :tag "No logging" nil)
  1929. (const :tag "Record timestamp" time)
  1930. (const :tag "Record timestamp with note." note)))
  1931. (defcustom org-log-note-clock-out nil
  1932. "Non-nil means record a note when clocking out of an item.
  1933. This can also be configured on a per-file basis by adding one of
  1934. the following lines anywhere in the buffer:
  1935. #+STARTUP: lognoteclock-out
  1936. #+STARTUP: nolognoteclock-out"
  1937. :group 'org-todo
  1938. :group 'org-progress
  1939. :type 'boolean)
  1940. (defcustom org-log-done-with-time t
  1941. "Non-nil means the CLOSED time stamp will contain date and time.
  1942. When nil, only the date will be recorded."
  1943. :group 'org-progress
  1944. :type 'boolean)
  1945. (defcustom org-log-note-headings
  1946. '((done . "CLOSING NOTE %t")
  1947. (state . "State %-12s from %-12S %t")
  1948. (note . "Note taken on %t")
  1949. (reschedule . "Rescheduled from %S on %t")
  1950. (delschedule . "Not scheduled, was %S on %t")
  1951. (redeadline . "New deadline from %S on %t")
  1952. (deldeadline . "Removed deadline, was %S on %t")
  1953. (refile . "Refiled on %t")
  1954. (clock-out . ""))
  1955. "Headings for notes added to entries.
  1956. The value is an alist, with the car being a symbol indicating the
  1957. note context, and the cdr is the heading to be used. The heading
  1958. may also be the empty string. The following placeholders can be
  1959. used:
  1960. %t a time stamp.
  1961. %T an active time stamp instead the default inactive one
  1962. %d a short-format time stamp.
  1963. %D an active short-format time stamp.
  1964. %s the new TODO state or time stamp (inactive), in double quotes.
  1965. %S the old TODO state or time stamp (inactive), in double quotes.
  1966. %u the user name.
  1967. %U full user name.
  1968. In fact, it is not a good idea to change the `state' entry,
  1969. because Agenda Log mode depends on the format of these entries."
  1970. :group 'org-todo
  1971. :group 'org-progress
  1972. :type '(list :greedy t
  1973. (cons (const :tag "Heading when closing an item" done) string)
  1974. (cons (const :tag
  1975. "Heading when changing todo state (todo sequence only)"
  1976. state) string)
  1977. (cons (const :tag "Heading when just taking a note" note) string)
  1978. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1979. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1980. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1981. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1982. (cons (const :tag "Heading when refiling" refile) string)
  1983. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1984. (unless (assq 'note org-log-note-headings)
  1985. (push '(note . "%t") org-log-note-headings))
  1986. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1987. (defcustom org-log-into-drawer nil
  1988. "Non-nil means insert state change notes and time stamps into a drawer.
  1989. When nil, state changes notes will be inserted after the headline and
  1990. any scheduling and clock lines, but not inside a drawer.
  1991. The value of this variable should be the name of the drawer to use.
  1992. LOGBOOK is proposed as the default drawer for this purpose, you can
  1993. also set this to a string to define the drawer of your choice.
  1994. A value of t is also allowed, representing \"LOGBOOK\".
  1995. A value of t or nil can also be set with on a per-file-basis with
  1996. #+STARTUP: logdrawer
  1997. #+STARTUP: nologdrawer
  1998. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1999. will be ignored.
  2000. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2001. a subtree.
  2002. Do not check directly this variable in a Lisp program. Call
  2003. function `org-log-into-drawer' instead."
  2004. :group 'org-todo
  2005. :group 'org-progress
  2006. :type '(choice
  2007. (const :tag "Not into a drawer" nil)
  2008. (const :tag "LOGBOOK" t)
  2009. (string :tag "Other")))
  2010. (defun org-log-into-drawer ()
  2011. "Name of the log drawer, as a string, or nil.
  2012. This is the value of `org-log-into-drawer'. However, if the
  2013. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2014. be used instead of the default value."
  2015. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2016. (cond ((equal p "nil") nil)
  2017. ((equal p "t") "LOGBOOK")
  2018. ((stringp p) p)
  2019. (p "LOGBOOK")
  2020. ((stringp org-log-into-drawer) org-log-into-drawer)
  2021. (org-log-into-drawer "LOGBOOK"))))
  2022. (defcustom org-log-state-notes-insert-after-drawers nil
  2023. "Non-nil means insert state change notes after any drawers in entry.
  2024. Only the drawers that *immediately* follow the headline and the
  2025. deadline/scheduled line are skipped.
  2026. When nil, insert notes right after the heading and perhaps the line
  2027. with deadline/scheduling if present.
  2028. This variable will have no effect if `org-log-into-drawer' is
  2029. set."
  2030. :group 'org-todo
  2031. :group 'org-progress
  2032. :type 'boolean)
  2033. (defcustom org-log-states-order-reversed t
  2034. "Non-nil means the latest state note will be directly after heading.
  2035. When nil, the state change notes will be ordered according to time.
  2036. This option can also be set with on a per-file-basis with
  2037. #+STARTUP: logstatesreversed
  2038. #+STARTUP: nologstatesreversed"
  2039. :group 'org-todo
  2040. :group 'org-progress
  2041. :type 'boolean)
  2042. (defcustom org-todo-repeat-to-state nil
  2043. "The TODO state to which a repeater should return the repeating task.
  2044. By default this is the first task of a TODO sequence or the
  2045. previous state of a TYPE_TODO set. But you can specify to use
  2046. the previous state in a TODO sequence or a string.
  2047. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2048. entry, which has precedence over this option."
  2049. :group 'org-todo
  2050. :version "24.1"
  2051. :type '(choice (const :tag "Use the previous TODO state" t)
  2052. (const :tag "Use the head of the TODO sequence" nil)
  2053. (string :tag "Use a specific TODO state")))
  2054. (defcustom org-log-repeat 'time
  2055. "Non-nil means record moving through the DONE state when triggering repeat.
  2056. An auto-repeating task is immediately switched back to TODO when
  2057. marked DONE. If you are not logging state changes (by adding \"@\"
  2058. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2059. record a closing note, there will be no record of the task moving
  2060. through DONE. This variable forces taking a note anyway.
  2061. nil Don't force a record
  2062. time Record a time stamp
  2063. note Prompt for a note and add it with template `org-log-note-headings'
  2064. This option can also be set with on a per-file-basis with
  2065. #+STARTUP: nologrepeat
  2066. #+STARTUP: logrepeat
  2067. #+STARTUP: lognoterepeat
  2068. You can have local logging settings for a subtree by setting the LOGGING
  2069. property to one or more of these keywords."
  2070. :group 'org-todo
  2071. :group 'org-progress
  2072. :type '(choice
  2073. (const :tag "Don't force a record" nil)
  2074. (const :tag "Force recording the DONE state" time)
  2075. (const :tag "Force recording a note with the DONE state" note)))
  2076. (defcustom org-todo-repeat-hook nil
  2077. "Hook that is run after a task has been repeated."
  2078. :package-version '(Org . "9.2")
  2079. :group 'org-todo
  2080. :type 'hook)
  2081. (defgroup org-priorities nil
  2082. "Priorities in Org mode."
  2083. :tag "Org Priorities"
  2084. :group 'org-todo)
  2085. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2086. (defcustom org-priority-enable-commands t
  2087. "Non-nil means priority commands are active.
  2088. When nil, these commands will be disabled, so that you never accidentally
  2089. set a priority."
  2090. :group 'org-priorities
  2091. :type 'boolean)
  2092. (defvaralias 'org-highest-priority 'org-priority-highest)
  2093. (defcustom org-priority-highest ?A
  2094. "The highest priority of TODO items.
  2095. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2096. Must be smaller than `org-priority-lowest'."
  2097. :group 'org-priorities
  2098. :type '(choice
  2099. (character :tag "Character")
  2100. (integer :tag "Integer (< 65)")))
  2101. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2102. (defcustom org-priority-lowest ?C
  2103. "The lowest priority of TODO items.
  2104. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2105. Must be higher than `org-priority-highest'."
  2106. :group 'org-priorities
  2107. :type '(choice
  2108. (character :tag "Character")
  2109. (integer :tag "Integer (< 65)")))
  2110. (defvaralias 'org-default-priority 'org-priority-default)
  2111. (defcustom org-priority-default ?B
  2112. "The default priority of TODO items.
  2113. This is the priority an item gets if no explicit priority is given.
  2114. When starting to cycle on an empty priority the first step in the cycle
  2115. depends on `org-priority-start-cycle-with-default'. The resulting first
  2116. step priority must not exceed the range from `org-priority-highest' to
  2117. `org-priority-lowest' which means that `org-priority-default' has to be
  2118. in this range exclusive or inclusive to the range boundaries. Else the
  2119. first step refuses to set the default and the second will fall back on
  2120. \(depending on the command used) the highest or lowest priority."
  2121. :group 'org-priorities
  2122. :type '(choice
  2123. (character :tag "Character")
  2124. (integer :tag "Integer (< 65)")))
  2125. (defcustom org-priority-start-cycle-with-default t
  2126. "Non-nil means start with default priority when starting to cycle.
  2127. When this is nil, the first step in the cycle will be (depending on the
  2128. command used) one higher or lower than the default priority.
  2129. See also `org-priority-default'."
  2130. :group 'org-priorities
  2131. :type 'boolean)
  2132. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2133. (defcustom org-priority-get-priority-function nil
  2134. "Function to extract the priority from a string.
  2135. The string is normally the headline. If this is nil, Org
  2136. computes the priority from the priority cookie like [#A] in the
  2137. headline. It returns an integer, increasing by 1000 for each
  2138. priority level.
  2139. The user can set a different function here, which should take a
  2140. string as an argument and return the numeric priority."
  2141. :group 'org-priorities
  2142. :version "24.1"
  2143. :type '(choice
  2144. (const nil)
  2145. (function)))
  2146. (defgroup org-time nil
  2147. "Options concerning time stamps and deadlines in Org mode."
  2148. :tag "Org Time"
  2149. :group 'org)
  2150. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2151. "Number of minutes to round time stamps to.
  2152. \\<org-mode-map>\
  2153. These are two values, the first applies when first creating a time stamp.
  2154. The second applies when changing it with the commands `S-up' and `S-down'.
  2155. When changing the time stamp, this means that it will change in steps
  2156. of N minutes, as given by the second value.
  2157. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2158. numbers should be factors of 60, so for example 5, 10, 15.
  2159. When this is larger than 1, you can still force an exact time stamp by using
  2160. a double prefix argument to a time stamp command like \
  2161. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2162. and by using a prefix arg to `S-up/down' to specify the exact number
  2163. of minutes to shift."
  2164. :group 'org-time
  2165. :get (lambda (var) ; Make sure both elements are there
  2166. (if (integerp (default-value var))
  2167. (list (default-value var) 5)
  2168. (default-value var)))
  2169. :type '(list
  2170. (integer :tag "when inserting times")
  2171. (integer :tag "when modifying times")))
  2172. ;; Normalize old customizations of this variable.
  2173. (when (integerp org-time-stamp-rounding-minutes)
  2174. (setq org-time-stamp-rounding-minutes
  2175. (list org-time-stamp-rounding-minutes
  2176. org-time-stamp-rounding-minutes)))
  2177. (defcustom org-display-custom-times nil
  2178. "Non-nil means overlay custom formats over all time stamps.
  2179. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2180. To turn this on on a per-file basis, insert anywhere in the file:
  2181. #+STARTUP: customtime"
  2182. :group 'org-time
  2183. :set 'set-default
  2184. :type 'sexp)
  2185. (make-variable-buffer-local 'org-display-custom-times)
  2186. (defcustom org-time-stamp-custom-formats
  2187. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2188. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2189. These are overlaid over the default ISO format if the variable
  2190. `org-display-custom-times' is set. Time like %H:%M should be at the
  2191. end of the second format. The custom formats are also honored by export
  2192. commands, if custom time display is turned on at the time of export."
  2193. :group 'org-time
  2194. :type 'sexp)
  2195. (defun org-time-stamp-format (&optional long inactive)
  2196. "Get the right format for a time string."
  2197. (let ((f (if long (cdr org-time-stamp-formats)
  2198. (car org-time-stamp-formats))))
  2199. (if inactive
  2200. (concat "[" (substring f 1 -1) "]")
  2201. f)))
  2202. (defcustom org-deadline-warning-days 14
  2203. "Number of days before expiration during which a deadline becomes active.
  2204. This variable governs the display in sparse trees and in the agenda.
  2205. When 0 or negative, it means use this number (the absolute value of it)
  2206. even if a deadline has a different individual lead time specified.
  2207. Custom commands can set this variable in the options section."
  2208. :group 'org-time
  2209. :group 'org-agenda-daily/weekly
  2210. :type 'integer)
  2211. (defcustom org-scheduled-delay-days 0
  2212. "Number of days before a scheduled item becomes active.
  2213. This variable governs the display in sparse trees and in the agenda.
  2214. The default value (i.e. 0) means: don't delay scheduled item.
  2215. When negative, it means use this number (the absolute value of it)
  2216. even if a scheduled item has a different individual delay time
  2217. specified.
  2218. Custom commands can set this variable in the options section."
  2219. :group 'org-time
  2220. :group 'org-agenda-daily/weekly
  2221. :version "24.4"
  2222. :package-version '(Org . "8.0")
  2223. :type 'integer)
  2224. (defcustom org-read-date-prefer-future t
  2225. "Non-nil means assume future for incomplete date input from user.
  2226. This affects the following situations:
  2227. 1. The user gives a month but not a year.
  2228. For example, if it is April and you enter \"feb 2\", this will be read
  2229. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2230. 2. The user gives a day, but no month.
  2231. For example, if today is the 15th, and you enter \"3\", Org will read
  2232. this as the third of *next* month. However, if you enter \"17\",
  2233. it will be considered as *this* month.
  2234. If you set this variable to the symbol `time', then also the following
  2235. will work:
  2236. 3. If the user gives a time.
  2237. If the time is before now, it will be interpreted as tomorrow.
  2238. Currently none of this works for ISO week specifications.
  2239. When this option is nil, the current day, month and year will always be
  2240. used as defaults.
  2241. See also `org-agenda-jump-prefer-future'."
  2242. :group 'org-time
  2243. :type '(choice
  2244. (const :tag "Never" nil)
  2245. (const :tag "Check month and day" t)
  2246. (const :tag "Check month, day, and time" time)))
  2247. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2248. "Should the agenda jump command prefer the future for incomplete dates?
  2249. The default is to do the same as configured in `org-read-date-prefer-future'.
  2250. But you can also set a deviating value here.
  2251. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2252. :group 'org-agenda
  2253. :group 'org-time
  2254. :version "24.1"
  2255. :type '(choice
  2256. (const :tag "Use org-read-date-prefer-future"
  2257. org-read-date-prefer-future)
  2258. (const :tag "Never" nil)
  2259. (const :tag "Always" t)))
  2260. (defcustom org-read-date-force-compatible-dates t
  2261. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2262. Depending on the system Emacs is running on, certain dates cannot
  2263. be represented with the type used internally to represent time.
  2264. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2265. correctly. Some systems allow for earlier dates, some for later,
  2266. some for both. One way to find out is to insert any date into an
  2267. Org buffer, putting the cursor on the year and hitting S-up and
  2268. S-down to test the range.
  2269. When this variable is set to t, the date/time prompt will not let
  2270. you specify dates outside the 1970-2037 range, so it is certain that
  2271. these dates will work in whatever version of Emacs you are
  2272. running, and also that you can move a file from one Emacs implementation
  2273. to another. Whenever Org is forcing the year for you, it will display
  2274. a message and beep.
  2275. When this variable is nil, Org will check if the date is
  2276. representable in the specific Emacs implementation you are using.
  2277. If not, it will force a year, usually the current year, and beep
  2278. to remind you. Currently this setting is not recommended because
  2279. the likelihood that you will open your Org files in an Emacs that
  2280. has limited date range is not negligible.
  2281. A workaround for this problem is to use diary sexp dates for time
  2282. stamps outside of this range."
  2283. :group 'org-time
  2284. :version "24.1"
  2285. :type 'boolean)
  2286. (defcustom org-read-date-display-live t
  2287. "Non-nil means display current interpretation of date prompt live.
  2288. This display will be in an overlay, in the minibuffer. Note that
  2289. live display is only active when `org-read-date-popup-calendar'
  2290. is non-nil."
  2291. :group 'org-time
  2292. :type 'boolean)
  2293. (defvaralias 'org-popup-calendar-for-date-prompt
  2294. 'org-read-date-popup-calendar)
  2295. (defcustom org-read-date-popup-calendar t
  2296. "Non-nil means pop up a calendar when prompting for a date.
  2297. In the calendar, the date can be selected with mouse-1. However, the
  2298. minibuffer will also be active, and you can simply enter the date as well.
  2299. When nil, only the minibuffer will be available."
  2300. :group 'org-time
  2301. :type 'boolean)
  2302. (defcustom org-extend-today-until 0
  2303. "The hour when your day really ends. Must be an integer.
  2304. This has influence for the following applications:
  2305. - When switching the agenda to \"today\". If it is still earlier than
  2306. the time given here, the day recognized as TODAY is actually yesterday.
  2307. - When a date is read from the user and it is still before the time given
  2308. here, the current date and time will be assumed to be yesterday, 23:59.
  2309. Also, timestamps inserted in capture templates follow this rule.
  2310. IMPORTANT: This is a feature whose implementation is and likely will
  2311. remain incomplete. Really, it is only here because past midnight seems to
  2312. be the favorite working time of John Wiegley :-)"
  2313. :group 'org-time
  2314. :type 'integer)
  2315. (defcustom org-use-effective-time nil
  2316. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2317. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2318. \"effective time\" of any timestamps between midnight and 8am will be
  2319. 23:59 of the previous day."
  2320. :group 'org-time
  2321. :version "24.1"
  2322. :type 'boolean)
  2323. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2324. "When non-nil, use the last clock out time for `org-todo'.
  2325. Note that this option has precedence over the combined use of
  2326. `org-use-effective-time' and `org-extend-today-until'."
  2327. :group 'org-time
  2328. :version "24.4"
  2329. :package-version '(Org . "8.0")
  2330. :type 'boolean)
  2331. (defcustom org-edit-timestamp-down-means-later nil
  2332. "Non-nil means S-down will increase the time in a time stamp.
  2333. When nil, S-up will increase."
  2334. :group 'org-time
  2335. :type 'boolean)
  2336. (defcustom org-calendar-follow-timestamp-change t
  2337. "Non-nil means make the calendar window follow timestamp changes.
  2338. When a timestamp is modified and the calendar window is visible, it will be
  2339. moved to the new date."
  2340. :group 'org-time
  2341. :type 'boolean)
  2342. (defgroup org-tags nil
  2343. "Options concerning tags in Org mode."
  2344. :tag "Org Tags"
  2345. :group 'org)
  2346. (defcustom org-tag-alist nil
  2347. "Default tags available in Org files.
  2348. The value of this variable is an alist. Associations either:
  2349. (TAG)
  2350. (TAG . SELECT)
  2351. (SPECIAL)
  2352. where TAG is a tag as a string, SELECT is character, used to
  2353. select that tag through the fast tag selection interface, and
  2354. SPECIAL is one of the following keywords: `:startgroup',
  2355. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2356. `:newline'. These keywords are used to define a hierarchy of
  2357. tags. See manual for details.
  2358. When this variable is nil, Org mode bases tag input on what is
  2359. already in the buffer. The value can be overridden locally by
  2360. using a TAGS keyword, e.g.,
  2361. #+TAGS: tag1 tag2
  2362. See also `org-tag-persistent-alist' to sidestep this behavior."
  2363. :group 'org-tags
  2364. :type '(repeat
  2365. (choice
  2366. (cons :tag "Tag with key"
  2367. (string :tag "Tag name")
  2368. (character :tag "Access char"))
  2369. (list :tag "Tag" (string :tag "Tag name"))
  2370. (const :tag "Start radio group" (:startgroup))
  2371. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2372. (const :tag "Group tags delimiter" (:grouptags))
  2373. (const :tag "End radio group" (:endgroup))
  2374. (const :tag "End tag group, non distinct" (:endgrouptag))
  2375. (const :tag "New line" (:newline)))))
  2376. (defcustom org-tag-persistent-alist nil
  2377. "Tags always available in Org files.
  2378. The value of this variable is an alist. Associations either:
  2379. (TAG)
  2380. (TAG . SELECT)
  2381. (SPECIAL)
  2382. where TAG is a tag as a string, SELECT is a character, used to
  2383. select that tag through the fast tag selection interface, and
  2384. SPECIAL is one of the following keywords: `:startgroup',
  2385. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2386. `:newline'. These keywords are used to define a hierarchy of
  2387. tags. See manual for details.
  2388. Unlike to `org-tag-alist', tags defined in this variable do not
  2389. depend on a local TAGS keyword. Instead, to disable these tags
  2390. on a per-file basis, insert anywhere in the file:
  2391. #+STARTUP: noptag"
  2392. :group 'org-tags
  2393. :type '(repeat
  2394. (choice
  2395. (cons :tag "Tag with key"
  2396. (string :tag "Tag name")
  2397. (character :tag "Access char"))
  2398. (list :tag "Tag" (string :tag "Tag name"))
  2399. (const :tag "Start radio group" (:startgroup))
  2400. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2401. (const :tag "Group tags delimiter" (:grouptags))
  2402. (const :tag "End radio group" (:endgroup))
  2403. (const :tag "End tag group, non distinct" (:endgrouptag))
  2404. (const :tag "New line" (:newline)))))
  2405. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2406. "If non-nil, always offer completion for all tags of all agenda files.
  2407. Setting this variable locally allows for dynamic generation of tag
  2408. completions in capture buffers.
  2409. (add-hook \\='org-capture-mode-hook
  2410. (lambda ()
  2411. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2412. :group 'org-tags
  2413. :version "24.1"
  2414. :type 'boolean)
  2415. (defvar org-file-tags nil
  2416. "List of tags that can be inherited by all entries in the file.
  2417. The tags will be inherited if the variable `org-use-tag-inheritance'
  2418. says they should be.
  2419. This variable is populated from #+FILETAGS lines.")
  2420. (defcustom org-use-fast-tag-selection 'auto
  2421. "Non-nil means use fast tag selection scheme.
  2422. This is a special interface to select and deselect tags with single keys.
  2423. When nil, fast selection is never used.
  2424. When the symbol `auto', fast selection is used if and only if selection
  2425. characters for tags have been configured, either through the variable
  2426. `org-tag-alist' or through a #+TAGS line in the buffer.
  2427. When t, fast selection is always used and selection keys are assigned
  2428. automatically if necessary."
  2429. :group 'org-tags
  2430. :type '(choice
  2431. (const :tag "Always" t)
  2432. (const :tag "Never" nil)
  2433. (const :tag "When selection characters are configured" auto)))
  2434. (defcustom org-fast-tag-selection-single-key nil
  2435. "Non-nil means fast tag selection exits after first change.
  2436. When nil, you have to press RET to exit it.
  2437. During fast tag selection, you can toggle this flag with `C-c'.
  2438. This variable can also have the value `expert'. In this case, the window
  2439. displaying the tags menu is not even shown, until you press `C-c' again."
  2440. :group 'org-tags
  2441. :type '(choice
  2442. (const :tag "No" nil)
  2443. (const :tag "Yes" t)
  2444. (const :tag "Expert" expert)))
  2445. (defvar org-fast-tag-selection-include-todo nil
  2446. "Non-nil means fast tags selection interface will also offer TODO states.
  2447. This is an undocumented feature, you should not rely on it.")
  2448. (defcustom org-tags-column -77
  2449. "The column to which tags should be indented in a headline.
  2450. If this number is positive, it specifies the column. If it is negative,
  2451. it means that the tags should be flushright to that column. For example,
  2452. -80 works well for a normal 80 character screen.
  2453. When 0, place tags directly after headline text, with only one space in
  2454. between."
  2455. :group 'org-tags
  2456. :type 'integer)
  2457. (defcustom org-auto-align-tags t
  2458. "Non-nil keeps tags aligned when modifying headlines.
  2459. Some operations (i.e. demoting) change the length of a headline and
  2460. therefore shift the tags around. With this option turned on, after
  2461. each such operation the tags are again aligned to `org-tags-column'."
  2462. :group 'org-tags
  2463. :type 'boolean)
  2464. (defcustom org-use-tag-inheritance t
  2465. "Non-nil means tags in levels apply also for sublevels.
  2466. When nil, only the tags directly given in a specific line apply there.
  2467. This may also be a list of tags that should be inherited, or a regexp that
  2468. matches tags that should be inherited. Additional control is possible
  2469. with the variable `org-tags-exclude-from-inheritance' which gives an
  2470. explicit list of tags to be excluded from inheritance, even if the value of
  2471. `org-use-tag-inheritance' would select it for inheritance.
  2472. If this option is t, a match early-on in a tree can lead to a large
  2473. number of matches in the subtree when constructing the agenda or creating
  2474. a sparse tree. If you only want to see the first match in a tree during
  2475. a search, check out the variable `org-tags-match-list-sublevels'."
  2476. :group 'org-tags
  2477. :type '(choice
  2478. (const :tag "Not" nil)
  2479. (const :tag "Always" t)
  2480. (repeat :tag "Specific tags" (string :tag "Tag"))
  2481. (regexp :tag "Tags matched by regexp")))
  2482. (defcustom org-tags-exclude-from-inheritance nil
  2483. "List of tags that should never be inherited.
  2484. This is a way to exclude a few tags from inheritance. For way to do
  2485. the opposite, to actively allow inheritance for selected tags,
  2486. see the variable `org-use-tag-inheritance'."
  2487. :group 'org-tags
  2488. :type '(repeat (string :tag "Tag")))
  2489. (defun org-tag-inherit-p (tag)
  2490. "Check if TAG is one that should be inherited."
  2491. (cond
  2492. ((member tag org-tags-exclude-from-inheritance) nil)
  2493. ((eq org-use-tag-inheritance t) t)
  2494. ((not org-use-tag-inheritance) nil)
  2495. ((stringp org-use-tag-inheritance)
  2496. (string-match org-use-tag-inheritance tag))
  2497. ((listp org-use-tag-inheritance)
  2498. (member tag org-use-tag-inheritance))
  2499. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2500. (defcustom org-tags-match-list-sublevels t
  2501. "Non-nil means list also sublevels of headlines matching a search.
  2502. This variable applies to tags/property searches, and also to stuck
  2503. projects because this search is based on a tags match as well.
  2504. When set to the symbol `indented', sublevels are indented with
  2505. leading dots.
  2506. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2507. the sublevels of a headline matching a tag search often also match
  2508. the same search. Listing all of them can create very long lists.
  2509. Setting this variable to nil causes subtrees of a match to be skipped.
  2510. This variable is semi-obsolete and probably should always be true. It
  2511. is better to limit inheritance to certain tags using the variables
  2512. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2513. :group 'org-tags
  2514. :type '(choice
  2515. (const :tag "No, don't list them" nil)
  2516. (const :tag "Yes, do list them" t)
  2517. (const :tag "List them, indented with leading dots" indented)))
  2518. (defcustom org-tags-sort-function nil
  2519. "When set, tags are sorted using this function as a comparator."
  2520. :group 'org-tags
  2521. :type '(choice
  2522. (const :tag "No sorting" nil)
  2523. (const :tag "Alphabetical" org-string-collate-lessp)
  2524. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2525. (function :tag "Custom function" nil)))
  2526. (defvar org-tags-history nil
  2527. "History of minibuffer reads for tags.")
  2528. (defvar org-last-tags-completion-table nil
  2529. "The last used completion table for tags.")
  2530. (defvar org-after-tags-change-hook nil
  2531. "Hook that is run after the tags in a line have changed.")
  2532. (defgroup org-properties nil
  2533. "Options concerning properties in Org mode."
  2534. :tag "Org Properties"
  2535. :group 'org)
  2536. (defcustom org-property-format "%-10s %s"
  2537. "How property key/value pairs should be formatted by `indent-line'.
  2538. When `indent-line' hits a property definition, it will format the line
  2539. according to this format, mainly to make sure that the values are
  2540. lined-up with respect to each other."
  2541. :group 'org-properties
  2542. :type 'string)
  2543. (defcustom org-properties-postprocess-alist nil
  2544. "Alist of properties and functions to adjust inserted values.
  2545. Elements of this alist must be of the form
  2546. ([string] [function])
  2547. where [string] must be a property name and [function] must be a
  2548. lambda expression: this lambda expression must take one argument,
  2549. the value to adjust, and return the new value as a string.
  2550. For example, this element will allow the property \"Remaining\"
  2551. to be updated wrt the relation between the \"Effort\" property
  2552. and the clock summary:
  2553. ((\"Remaining\" (lambda(value)
  2554. (let ((clocksum (org-clock-sum-current-item))
  2555. (effort (org-duration-to-minutes
  2556. (org-entry-get (point) \"Effort\"))))
  2557. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2558. :group 'org-properties
  2559. :version "24.1"
  2560. :type '(alist :key-type (string :tag "Property")
  2561. :value-type (function :tag "Function")))
  2562. (defcustom org-use-property-inheritance nil
  2563. "Non-nil means properties apply also for sublevels.
  2564. This setting is chiefly used during property searches. Turning it on can
  2565. cause significant overhead when doing a search, which is why it is not
  2566. on by default.
  2567. When nil, only the properties directly given in the current entry count.
  2568. When t, every property is inherited. The value may also be a list of
  2569. properties that should have inheritance, or a regular expression matching
  2570. properties that should be inherited.
  2571. However, note that some special properties use inheritance under special
  2572. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2573. and the properties ending in \"_ALL\" when they are used as descriptor
  2574. for valid values of a property.
  2575. Note for programmers:
  2576. When querying an entry with `org-entry-get', you can control if inheritance
  2577. should be used. By default, `org-entry-get' looks only at the local
  2578. properties. You can request inheritance by setting the inherit argument
  2579. to t (to force inheritance) or to `selective' (to respect the setting
  2580. in this variable)."
  2581. :group 'org-properties
  2582. :type '(choice
  2583. (const :tag "Not" nil)
  2584. (const :tag "Always" t)
  2585. (repeat :tag "Specific properties" (string :tag "Property"))
  2586. (regexp :tag "Properties matched by regexp")))
  2587. (defun org-property-inherit-p (property)
  2588. "Return a non-nil value if PROPERTY should be inherited."
  2589. (cond
  2590. ((eq org-use-property-inheritance t) t)
  2591. ((not org-use-property-inheritance) nil)
  2592. ((stringp org-use-property-inheritance)
  2593. (string-match org-use-property-inheritance property))
  2594. ((listp org-use-property-inheritance)
  2595. (member-ignore-case property org-use-property-inheritance))
  2596. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2597. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2598. "The default column format, if no other format has been defined.
  2599. This variable can be set on the per-file basis by inserting a line
  2600. #+COLUMNS: %25ITEM ....."
  2601. :group 'org-properties
  2602. :type 'string)
  2603. (defcustom org-columns-default-format-for-agenda nil
  2604. "The default column format in an agenda buffer.
  2605. This will be used for column view in the agenda unless a format has
  2606. been set by adding `org-overriding-columns-format' to the local
  2607. settings list of a custom agenda view. When nil, the columns format
  2608. for the first item in the agenda list will be used, or as a fall-back,
  2609. `org-columns-default-format'."
  2610. :group 'org-properties
  2611. :type '(choice
  2612. (const :tag "No default" nil)
  2613. (string :tag "Format string")))
  2614. (defcustom org-columns-ellipses ".."
  2615. "The ellipses to be used when a field in column view is truncated.
  2616. When this is the empty string, as many characters as possible are shown,
  2617. but then there will be no visual indication that the field has been truncated.
  2618. When this is a string of length N, the last N characters of a truncated
  2619. field are replaced by this string. If the column is narrower than the
  2620. ellipses string, only part of the ellipses string will be shown."
  2621. :group 'org-properties
  2622. :type 'string)
  2623. (defconst org-global-properties-fixed
  2624. '(("VISIBILITY_ALL" . "folded children content all")
  2625. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2626. "List of property/value pairs that can be inherited by any entry.
  2627. These are fixed values, for the preset properties. The user variable
  2628. that can be used to add to this list is `org-global-properties'.
  2629. The entries in this list are cons cells where the car is a property
  2630. name and cdr is a string with the value. If the value represents
  2631. multiple items like an \"_ALL\" property, separate the items by
  2632. spaces.")
  2633. (defcustom org-global-properties nil
  2634. "List of property/value pairs that can be inherited by any entry.
  2635. This list will be combined with the constant `org-global-properties-fixed'.
  2636. The entries in this list are cons cells where the car is a property
  2637. name and cdr is a string with the value.
  2638. Buffer local properties are added either by a document property drawer
  2639. :PROPERTIES:
  2640. :NAME: VALUE
  2641. :END:
  2642. or by adding lines like
  2643. #+PROPERTY: NAME VALUE"
  2644. :group 'org-properties
  2645. :type '(repeat
  2646. (cons (string :tag "Property")
  2647. (string :tag "Value"))))
  2648. (defvar-local org-keyword-properties nil
  2649. "List of property/value pairs inherited by any entry.
  2650. Valid for the current buffer. This variable is populated from
  2651. PROPERTY keywords.
  2652. Note that properties are defined also in property drawers.
  2653. Properties defined there take precedence over properties defined
  2654. as keywords.")
  2655. (defgroup org-agenda nil
  2656. "Options concerning agenda views in Org mode."
  2657. :tag "Org Agenda"
  2658. :group 'org)
  2659. (defvar-local org-category nil
  2660. "Variable used by Org files to set a category for agenda display.
  2661. There are multiple ways to set the category. One way is to set
  2662. it in the document property drawer. For example:
  2663. :PROPERTIES:
  2664. :CATEGORY: ELisp
  2665. :END:
  2666. Other ways to define it is as an emacs file variable, for example
  2667. # -*- mode: org; org-category: \"ELisp\"
  2668. or for the file to contain a special line:
  2669. #+CATEGORY: ELisp
  2670. If the file does not specify a category, then file's base name
  2671. is used instead.")
  2672. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2673. (defcustom org-agenda-files nil
  2674. "The files to be used for agenda display.
  2675. If an entry is a directory, all files in that directory that are matched
  2676. by `org-agenda-file-regexp' will be part of the file list.
  2677. If the value of the variable is not a list but a single file name, then
  2678. the list of agenda files is actually stored and maintained in that file,
  2679. one agenda file per line. In this file paths can be given relative to
  2680. `org-directory'. Tilde expansion and environment variable substitution
  2681. are also made.
  2682. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2683. and removed with `\\[org-remove-file]'."
  2684. :group 'org-agenda
  2685. :type '(choice
  2686. (repeat :tag "List of files and directories" file)
  2687. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2688. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2689. "Regular expression to match files for `org-agenda-files'.
  2690. If any element in the list in that variable contains a directory instead
  2691. of a normal file, all files in that directory that are matched by this
  2692. regular expression will be included."
  2693. :group 'org-agenda
  2694. :type 'regexp)
  2695. (defvaralias 'org-agenda-multi-occur-extra-files
  2696. 'org-agenda-text-search-extra-files)
  2697. (defcustom org-agenda-text-search-extra-files nil
  2698. "List of extra files to be searched by text search commands.
  2699. These files will be searched in addition to the agenda files by the
  2700. commands `org-search-view' (`\\[org-agenda] s') \
  2701. and `org-occur-in-agenda-files'.
  2702. Note that these files will only be searched for text search commands,
  2703. not for the other agenda views like todo lists, tag searches or the weekly
  2704. agenda. This variable is intended to list notes and possibly archive files
  2705. that should also be searched by these two commands.
  2706. In fact, if the first element in the list is the symbol `agenda-archives',
  2707. then all archive files of all agenda files will be added to the search
  2708. scope."
  2709. :group 'org-agenda
  2710. :type '(set :greedy t
  2711. (const :tag "Agenda Archives" agenda-archives)
  2712. (repeat :inline t (file))))
  2713. (defcustom org-agenda-skip-unavailable-files nil
  2714. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2715. A nil value means to remove them, after a query, from the list."
  2716. :group 'org-agenda
  2717. :type 'boolean)
  2718. (defgroup org-latex nil
  2719. "Options for embedding LaTeX code into Org mode."
  2720. :tag "Org LaTeX"
  2721. :group 'org)
  2722. (defcustom org-format-latex-options
  2723. '(:foreground default :background default :scale 1.0
  2724. :html-foreground "Black" :html-background "Transparent"
  2725. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2726. "Options for creating images from LaTeX fragments.
  2727. This is a property list with the following properties:
  2728. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2729. `default' means use the foreground of the default face.
  2730. `auto' means use the foreground from the text face.
  2731. :background the background color, or \"Transparent\".
  2732. `default' means use the background of the default face.
  2733. `auto' means use the background from the text face.
  2734. :scale a scaling factor for the size of the images, to get more pixels
  2735. :html-foreground, :html-background, :html-scale
  2736. the same numbers for HTML export.
  2737. :matchers a list indicating which matchers should be used to
  2738. find LaTeX fragments. Valid members of this list are:
  2739. \"begin\" find environments
  2740. \"$1\" find single characters surrounded by $.$
  2741. \"$\" find math expressions surrounded by $...$
  2742. \"$$\" find math expressions surrounded by $$....$$
  2743. \"\\(\" find math expressions surrounded by \\(...\\)
  2744. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2745. :group 'org-latex
  2746. :type 'plist)
  2747. (defcustom org-format-latex-signal-error t
  2748. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2749. When nil, just push out a message."
  2750. :group 'org-latex
  2751. :version "24.1"
  2752. :type 'boolean)
  2753. (defcustom org-latex-to-mathml-jar-file nil
  2754. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2755. Use this to specify additional executable file say a jar file.
  2756. When using MathToWeb as the converter, specify the full-path to
  2757. your mathtoweb.jar file."
  2758. :group 'org-latex
  2759. :version "24.1"
  2760. :type '(choice
  2761. (const :tag "None" nil)
  2762. (file :tag "JAR file" :must-match t)))
  2763. (defcustom org-latex-to-mathml-convert-command nil
  2764. "Command to convert LaTeX fragments to MathML.
  2765. Replace format-specifiers in the command as noted below and use
  2766. `shell-command' to convert LaTeX to MathML.
  2767. %j: Executable file in fully expanded form as specified by
  2768. `org-latex-to-mathml-jar-file'.
  2769. %I: Input LaTeX file in fully expanded form.
  2770. %i: The latex fragment to be converted.
  2771. %o: Output MathML file.
  2772. This command is used by `org-create-math-formula'.
  2773. When using MathToWeb as the converter, set this option to
  2774. \"java -jar %j -unicode -force -df %o %I\".
  2775. When using LaTeXML set this option to
  2776. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2777. :group 'org-latex
  2778. :version "24.1"
  2779. :type '(choice
  2780. (const :tag "None" nil)
  2781. (string :tag "\nShell command")))
  2782. (defcustom org-latex-to-html-convert-command nil
  2783. "Command to convert LaTeX fragments to HTML.
  2784. This command is very open-ended: the output of the command will
  2785. directly replace the LaTeX fragment in the resulting HTML.
  2786. Replace format-specifiers in the command as noted below and use
  2787. `shell-command' to convert LaTeX to HTML.
  2788. %i: The LaTeX fragment to be converted.
  2789. For example, this could be used with LaTeXML as
  2790. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2791. :group 'org-latex
  2792. :package-version '(Org . "9.4")
  2793. :type '(choice
  2794. (const :tag "None" nil)
  2795. (string :tag "Shell command")))
  2796. (defcustom org-preview-latex-default-process 'dvipng
  2797. "The default process to convert LaTeX fragments to image files.
  2798. All available processes and theirs documents can be found in
  2799. `org-preview-latex-process-alist', which see."
  2800. :group 'org-latex
  2801. :version "26.1"
  2802. :package-version '(Org . "9.0")
  2803. :type 'symbol)
  2804. (defcustom org-preview-latex-process-alist
  2805. '((dvipng
  2806. :programs ("latex" "dvipng")
  2807. :description "dvi > png"
  2808. :message "you need to install the programs: latex and dvipng."
  2809. :image-input-type "dvi"
  2810. :image-output-type "png"
  2811. :image-size-adjust (1.0 . 1.0)
  2812. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2813. :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2814. (dvisvgm
  2815. :programs ("latex" "dvisvgm")
  2816. :description "dvi > svg"
  2817. :message "you need to install the programs: latex and dvisvgm."
  2818. :image-input-type "dvi"
  2819. :image-output-type "svg"
  2820. :image-size-adjust (1.7 . 1.5)
  2821. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2822. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2823. (imagemagick
  2824. :programs ("latex" "convert")
  2825. :description "pdf > png"
  2826. :message "you need to install the programs: latex and imagemagick."
  2827. :image-input-type "pdf"
  2828. :image-output-type "png"
  2829. :image-size-adjust (1.0 . 1.0)
  2830. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2831. :image-converter
  2832. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2833. "Definitions of external processes for LaTeX previewing.
  2834. Org mode can use some external commands to generate TeX snippet's images for
  2835. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2836. `org-create-formula-image' how to call them.
  2837. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2838. PROPERTIES accepts the following attributes:
  2839. :programs list of strings, required programs.
  2840. :description string, describe the process.
  2841. :message string, message it when required programs cannot be found.
  2842. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2843. :image-output-type string, output file type of image converter (e.g., \"png\").
  2844. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2845. image size showed in buffer and the cdr element is for
  2846. HTML file. This option is only useful for process
  2847. developers, users should use variable
  2848. `org-format-latex-options' instead.
  2849. :post-clean list of strings, files matched are to be cleaned up once
  2850. the image is generated. When nil, the files with \".dvi\",
  2851. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2852. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2853. be cleaned up.
  2854. :latex-header list of strings, the LaTeX header of the snippet file.
  2855. When nil, the fallback value is used instead, which is
  2856. controlled by `org-format-latex-header',
  2857. `org-latex-default-packages-alist' and
  2858. `org-latex-packages-alist', which see.
  2859. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2860. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2861. replaced with values defined below.
  2862. :image-converter list of image converter commands strings. Each of them is
  2863. given to the shell and supports any of the following
  2864. place-holders defined below.
  2865. Place-holders used by `:image-converter' and `:latex-compiler':
  2866. %f input file name
  2867. %b base name of input file
  2868. %o base directory of input file
  2869. %O absolute output file name
  2870. Place-holders only used by `:image-converter':
  2871. %D dpi, which is used to adjust image size by some processing commands.
  2872. %S the image size scale ratio, which is used to adjust image size by some
  2873. processing commands."
  2874. :group 'org-latex
  2875. :version "26.1"
  2876. :package-version '(Org . "9.0")
  2877. :type '(alist :tag "LaTeX to image backends"
  2878. :value-type (plist)))
  2879. (defcustom org-preview-latex-image-directory "ltximg/"
  2880. "Path to store latex preview images.
  2881. A relative path here creates many directories relative to the
  2882. processed Org files paths. An absolute path puts all preview
  2883. images at the same place."
  2884. :group 'org-latex
  2885. :version "26.1"
  2886. :package-version '(Org . "9.0")
  2887. :type 'string)
  2888. (defun org-format-latex-mathml-available-p ()
  2889. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2890. (save-match-data
  2891. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2892. org-latex-to-mathml-convert-command)
  2893. (let ((executable (car (split-string
  2894. org-latex-to-mathml-convert-command))))
  2895. (when (executable-find executable)
  2896. (if (string-match
  2897. "%j" org-latex-to-mathml-convert-command)
  2898. (file-readable-p org-latex-to-mathml-jar-file)
  2899. t))))))
  2900. (defcustom org-format-latex-header "\\documentclass{article}
  2901. \\usepackage[usenames]{color}
  2902. \[PACKAGES]
  2903. \[DEFAULT-PACKAGES]
  2904. \\pagestyle{empty} % do not remove
  2905. % The settings below are copied from fullpage.sty
  2906. \\setlength{\\textwidth}{\\paperwidth}
  2907. \\addtolength{\\textwidth}{-3cm}
  2908. \\setlength{\\oddsidemargin}{1.5cm}
  2909. \\addtolength{\\oddsidemargin}{-2.54cm}
  2910. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2911. \\setlength{\\textheight}{\\paperheight}
  2912. \\addtolength{\\textheight}{-\\headheight}
  2913. \\addtolength{\\textheight}{-\\headsep}
  2914. \\addtolength{\\textheight}{-\\footskip}
  2915. \\addtolength{\\textheight}{-3cm}
  2916. \\setlength{\\topmargin}{1.5cm}
  2917. \\addtolength{\\topmargin}{-2.54cm}"
  2918. "The document header used for processing LaTeX fragments.
  2919. It is imperative that this header make sure that no page number
  2920. appears on the page. The package defined in the variables
  2921. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2922. will either replace the placeholder \"[PACKAGES]\" in this
  2923. header, or they will be appended."
  2924. :group 'org-latex
  2925. :type 'string)
  2926. (defun org-set-packages-alist (var val)
  2927. "Set the packages alist and make sure it has 3 elements per entry."
  2928. (set var (mapcar (lambda (x)
  2929. (if (and (consp x) (= (length x) 2))
  2930. (list (car x) (nth 1 x) t)
  2931. x))
  2932. val)))
  2933. (defun org-get-packages-alist (var)
  2934. "Get the packages alist and make sure it has 3 elements per entry."
  2935. (mapcar (lambda (x)
  2936. (if (and (consp x) (= (length x) 2))
  2937. (list (car x) (nth 1 x) t)
  2938. x))
  2939. (default-value var)))
  2940. (defcustom org-latex-default-packages-alist
  2941. '(("AUTO" "inputenc" t ("pdflatex"))
  2942. ("T1" "fontenc" t ("pdflatex"))
  2943. ("" "graphicx" t)
  2944. ("" "grffile" t)
  2945. ("" "longtable" nil)
  2946. ("" "wrapfig" nil)
  2947. ("" "rotating" nil)
  2948. ("normalem" "ulem" t)
  2949. ("" "amsmath" t)
  2950. ("" "textcomp" t)
  2951. ("" "amssymb" t)
  2952. ("" "capt-of" nil)
  2953. ("" "hyperref" nil))
  2954. "Alist of default packages to be inserted in the header.
  2955. Change this only if one of the packages here causes an
  2956. incompatibility with another package you are using.
  2957. The packages in this list are needed by one part or another of
  2958. Org mode to function properly:
  2959. - inputenc, fontenc: for basic font and character selection
  2960. - graphicx: for including images
  2961. - grffile: allow periods and spaces in graphics file names
  2962. - longtable: For multipage tables
  2963. - wrapfig: for figure placement
  2964. - rotating: for sideways figures and tables
  2965. - ulem: for underline and strike-through
  2966. - amsmath: for subscript and superscript and math environments
  2967. - textcomp, amssymb: for various symbols used
  2968. for interpreting the entities in `org-entities'. You can skip
  2969. some of these packages if you don't use any of their symbols.
  2970. - capt-of: for captions outside of floats
  2971. - hyperref: for cross references
  2972. Therefore you should not modify this variable unless you know
  2973. what you are doing. The one reason to change it anyway is that
  2974. you might be loading some other package that conflicts with one
  2975. of the default packages. Each element is either a cell or
  2976. a string.
  2977. A cell is of the format
  2978. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2979. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2980. when compiling LaTeX snippets into images for inclusion into
  2981. non-LaTeX output.
  2982. COMPILERS is a list of compilers that should include the package,
  2983. see `org-latex-compiler'. If the document compiler is not in the
  2984. list, and the list is non-nil, the package will not be inserted
  2985. in the final document.
  2986. A string will be inserted as-is in the header of the document."
  2987. :group 'org-latex
  2988. :group 'org-export-latex
  2989. :set 'org-set-packages-alist
  2990. :get 'org-get-packages-alist
  2991. :version "26.1"
  2992. :package-version '(Org . "8.3")
  2993. :type '(repeat
  2994. (choice
  2995. (list :tag "options/package pair"
  2996. (string :tag "options")
  2997. (string :tag "package")
  2998. (boolean :tag "Snippet")
  2999. (choice
  3000. (const :tag "For all compilers" nil)
  3001. (repeat :tag "Allowed compiler" string)))
  3002. (string :tag "A line of LaTeX"))))
  3003. (defcustom org-latex-packages-alist nil
  3004. "Alist of packages to be inserted in every LaTeX header.
  3005. These will be inserted after `org-latex-default-packages-alist'.
  3006. Each element is either a cell or a string.
  3007. A cell is of the format:
  3008. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3009. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3010. needed when turning LaTeX snippets into images for inclusion into
  3011. non-LaTeX output.
  3012. COMPILERS is a list of compilers that should include the package,
  3013. see `org-latex-compiler'. If the document compiler is not in the
  3014. list, and the list is non-nil, the package will not be inserted
  3015. in the final document.
  3016. A string will be inserted as-is in the header of the document.
  3017. Make sure that you only list packages here which:
  3018. - you want in every file;
  3019. - do not conflict with the setup in `org-format-latex-header';
  3020. - do not conflict with the default packages in
  3021. `org-latex-default-packages-alist'."
  3022. :group 'org-latex
  3023. :group 'org-export-latex
  3024. :set 'org-set-packages-alist
  3025. :get 'org-get-packages-alist
  3026. :type '(repeat
  3027. (choice
  3028. (list :tag "options/package pair"
  3029. (string :tag "options")
  3030. (string :tag "package")
  3031. (boolean :tag "Snippet"))
  3032. (string :tag "A line of LaTeX"))))
  3033. (defgroup org-appearance nil
  3034. "Settings for Org mode appearance."
  3035. :tag "Org Appearance"
  3036. :group 'org)
  3037. (defcustom org-level-color-stars-only nil
  3038. "Non-nil means fontify only the stars in each headline.
  3039. When nil, the entire headline is fontified.
  3040. Changing it requires restart of `font-lock-mode' to become effective
  3041. also in regions already fontified."
  3042. :group 'org-appearance
  3043. :type 'boolean)
  3044. (defcustom org-hide-leading-stars nil
  3045. "Non-nil means hide the first N-1 stars in a headline.
  3046. This works by using the face `org-hide' for these stars. This
  3047. face is white for a light background, and black for a dark
  3048. background. You may have to customize the face `org-hide' to
  3049. make this work.
  3050. Changing it requires restart of `font-lock-mode' to become effective
  3051. also in regions already fontified.
  3052. You may also set this on a per-file basis by adding one of the following
  3053. lines to the buffer:
  3054. #+STARTUP: hidestars
  3055. #+STARTUP: showstars"
  3056. :group 'org-appearance
  3057. :type 'boolean)
  3058. (defcustom org-hidden-keywords nil
  3059. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3060. For example, a value \\='(title) for this list makes the document's title
  3061. appear in the buffer without the initial \"#+TITLE:\" part."
  3062. :group 'org-appearance
  3063. :package-version '(Org . "9.5")
  3064. :type '(set (const :tag "#+AUTHOR" author)
  3065. (const :tag "#+DATE" date)
  3066. (const :tag "#+EMAIL" email)
  3067. (const :tag "#+SUBTITLE" subtitle)
  3068. (const :tag "#+TITLE" title)))
  3069. (defcustom org-custom-properties nil
  3070. "List of properties (as strings) with a special meaning.
  3071. The default use of these custom properties is to let the user
  3072. hide them with `org-toggle-custom-properties-visibility'."
  3073. :group 'org-properties
  3074. :group 'org-appearance
  3075. :version "24.3"
  3076. :type '(repeat (string :tag "Property Name")))
  3077. (defcustom org-fontify-todo-headline nil
  3078. "Non-nil means change the face of a headline if it is marked as TODO.
  3079. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3080. When this is non-nil, the headline after the keyword is set to the
  3081. `org-headline-todo' as an additional indication."
  3082. :group 'org-appearance
  3083. :package-version '(Org . "9.4")
  3084. :type 'boolean
  3085. :safe t)
  3086. (defcustom org-fontify-done-headline t
  3087. "Non-nil means change the face of a headline if it is marked DONE.
  3088. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3089. When this is non-nil, the headline after the keyword is set to the
  3090. `org-headline-done' as an additional indication."
  3091. :group 'org-appearance
  3092. :package-version '(Org . "9.4")
  3093. :type 'boolean)
  3094. (defcustom org-fontify-emphasized-text t
  3095. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3096. Changing this variable requires a restart of Emacs to take effect."
  3097. :group 'org-appearance
  3098. :type 'boolean)
  3099. (defcustom org-fontify-whole-heading-line nil
  3100. "Non-nil means fontify the whole line for headings.
  3101. This is useful when setting a background color for the
  3102. org-level-* faces."
  3103. :group 'org-appearance
  3104. :type 'boolean)
  3105. (defcustom org-fontify-whole-block-delimiter-line t
  3106. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3107. This is useful when setting a background color for the
  3108. org-block-begin-line and org-block-end-line faces."
  3109. :group 'org-appearance
  3110. :type 'boolean)
  3111. (defcustom org-highlight-latex-and-related nil
  3112. "Non-nil means highlight LaTeX related syntax in the buffer.
  3113. When non-nil, the value should be a list containing any of the
  3114. following symbols:
  3115. `native' Highlight LaTeX snippets and environments natively.
  3116. `latex' Highlight LaTeX snippets and environments.
  3117. `script' Highlight subscript and superscript.
  3118. `entities' Highlight entities."
  3119. :group 'org-appearance
  3120. :version "24.4"
  3121. :package-version '(Org . "8.0")
  3122. :type '(choice
  3123. (const :tag "No highlighting" nil)
  3124. (set :greedy t :tag "Highlight"
  3125. (const :tag "LaTeX snippets and environments (native)" native)
  3126. (const :tag "LaTeX snippets and environments" latex)
  3127. (const :tag "Subscript and superscript" script)
  3128. (const :tag "Entities" entities))))
  3129. (defcustom org-hide-emphasis-markers nil
  3130. "Non-nil mean font-lock should hide the emphasis marker characters."
  3131. :group 'org-appearance
  3132. :type 'boolean
  3133. :safe #'booleanp)
  3134. (defcustom org-hide-macro-markers nil
  3135. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3136. :group 'org-appearance
  3137. :type 'boolean)
  3138. (defcustom org-pretty-entities nil
  3139. "Non-nil means show entities as UTF8 characters.
  3140. When nil, the \\name form remains in the buffer."
  3141. :group 'org-appearance
  3142. :version "24.1"
  3143. :type 'boolean)
  3144. (defcustom org-pretty-entities-include-sub-superscripts t
  3145. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3146. :group 'org-appearance
  3147. :version "24.1"
  3148. :type 'boolean)
  3149. (defvar org-emph-re nil
  3150. "Regular expression for matching emphasis.
  3151. After a match, the match groups contain these elements:
  3152. 0 The match of the full regular expression, including the characters
  3153. before and after the proper match
  3154. 1 The character before the proper match, or empty at beginning of line
  3155. 2 The proper match, including the leading and trailing markers
  3156. 3 The leading marker like * or /, indicating the type of highlighting
  3157. 4 The text between the emphasis markers, not including the markers
  3158. 5 The character after the match, empty at the end of a line")
  3159. (defvar org-verbatim-re nil
  3160. "Regular expression for matching verbatim text.")
  3161. (defvar org-emphasis-regexp-components) ; defined just below
  3162. (defvar org-emphasis-alist) ; defined just below
  3163. (defun org-set-emph-re (var val)
  3164. "Set variable and compute the emphasis regular expression."
  3165. (set var val)
  3166. (when (and (boundp 'org-emphasis-alist)
  3167. (boundp 'org-emphasis-regexp-components)
  3168. org-emphasis-alist org-emphasis-regexp-components)
  3169. (pcase-let*
  3170. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3171. (body (if (<= nl 0) body
  3172. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3173. (template
  3174. (format (concat "\\([%s]\\|^\\)" ;before markers
  3175. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3176. "\\([%s]\\|$\\)") ;after markers
  3177. pre border border body border post)))
  3178. (setq org-emph-re (format template "*/_+"))
  3179. (setq org-verbatim-re (format template "=~")))))
  3180. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3181. ;; set this option proved cumbersome. See this message/thread:
  3182. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3183. (defvar org-emphasis-regexp-components
  3184. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3185. "Components used to build the regular expression for emphasis.
  3186. This is a list with five entries. Terminology: In an emphasis string
  3187. like \" *strong word* \", we call the initial space PREMATCH, the final
  3188. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3189. and \"trong wor\" is the body. The different components in this variable
  3190. specify what is allowed/forbidden in each part:
  3191. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3192. post Chars allowed as postmatch. End of line will be allowed too.
  3193. border The chars *forbidden* as border characters.
  3194. body-regexp A regexp like \".\" to match a body character. Don't use
  3195. non-shy groups here, and don't allow newline here.
  3196. newline The maximum number of newlines allowed in an emphasis exp.
  3197. You need to reload Org or to restart Emacs after setting this.")
  3198. (defcustom org-emphasis-alist
  3199. '(("*" bold)
  3200. ("/" italic)
  3201. ("_" underline)
  3202. ("=" org-verbatim verbatim)
  3203. ("~" org-code verbatim)
  3204. ("+" (:strike-through t)))
  3205. "Alist of characters and faces to emphasize text.
  3206. Text starting and ending with a special character will be emphasized,
  3207. for example *bold*, _underlined_ and /italic/. This variable sets the
  3208. marker characters and the face to be used by font-lock for highlighting
  3209. in Org buffers.
  3210. You need to reload Org or to restart Emacs after customizing this."
  3211. :group 'org-appearance
  3212. :set 'org-set-emph-re
  3213. :version "24.4"
  3214. :package-version '(Org . "8.0")
  3215. :type '(repeat
  3216. (list
  3217. (string :tag "Marker character")
  3218. (choice
  3219. (face :tag "Font-lock-face")
  3220. (plist :tag "Face property list"))
  3221. (option (const verbatim)))))
  3222. (defvar org-protecting-blocks '("src" "example" "export")
  3223. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3224. This is needed for font-lock setup.")
  3225. ;;; Functions and variables from their packages
  3226. ;; Declared here to avoid compiler warnings
  3227. (defvar mark-active)
  3228. ;; Various packages
  3229. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3230. (declare-function calendar-forward-day "cal-move" (arg))
  3231. (declare-function calendar-goto-date "cal-move" (date))
  3232. (declare-function calendar-goto-today "cal-move" ())
  3233. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3234. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3235. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3236. (declare-function cdlatex-tab "ext:cdlatex" ())
  3237. (declare-function dired-get-filename
  3238. "dired"
  3239. (&optional localp no-error-if-not-filep))
  3240. (declare-function iswitchb-read-buffer
  3241. "iswitchb"
  3242. (prompt &optional
  3243. default require-match _predicate start matches-set))
  3244. (declare-function org-agenda-change-all-lines
  3245. "org-agenda"
  3246. (newhead hdmarker &optional fixface just-this))
  3247. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3248. "org-agenda"
  3249. (&optional end))
  3250. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3251. (declare-function org-agenda-format-item
  3252. "org-agenda"
  3253. (extra txt &optional level category tags dotime
  3254. remove-re habitp))
  3255. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3256. (declare-function org-agenda-save-markers-for-cut-and-paste
  3257. "org-agenda"
  3258. (beg end))
  3259. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3260. (declare-function org-agenda-skip "org-agenda" ())
  3261. (declare-function org-attach-expand "org-attach" (file))
  3262. (declare-function org-attach-reveal "org-attach" ())
  3263. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3264. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3265. (declare-function org-indent-mode "org-indent" (&optional arg))
  3266. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3267. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3268. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3269. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3270. (declare-function parse-time-string "parse-time" (string))
  3271. (defvar align-mode-rules-list)
  3272. (defvar calc-embedded-close-formula)
  3273. (defvar calc-embedded-open-formula)
  3274. (defvar calc-embedded-open-mode)
  3275. (defvar font-lock-unfontify-region-function)
  3276. (defvar iswitchb-temp-buflist)
  3277. (defvar org-agenda-tags-todo-honor-ignore-options)
  3278. (defvar remember-data-file)
  3279. (defvar texmathp-why)
  3280. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3281. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3282. (declare-function org-resolve-clocks "org-clock"
  3283. (&optional also-non-dangling-p prompt last-valid))
  3284. (defvar org-clock-start-time)
  3285. (defvar org-clock-marker (make-marker)
  3286. "Marker recording the last clock-in.")
  3287. (defvar org-clock-hd-marker (make-marker)
  3288. "Marker recording the last clock-in, but the headline position.")
  3289. (defvar org-clock-heading ""
  3290. "The heading of the current clock entry.")
  3291. (defun org-clock-is-active ()
  3292. "Return the buffer where the clock is currently running.
  3293. Return nil if no clock is running."
  3294. (marker-buffer org-clock-marker))
  3295. (defun org-check-running-clock ()
  3296. "Check if the current buffer contains the running clock.
  3297. If yes, offer to stop it and to save the buffer with the changes."
  3298. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3299. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3300. (buffer-name))))
  3301. (org-clock-out)
  3302. (when (y-or-n-p "Save changed buffer?")
  3303. (save-buffer))))
  3304. (defun org-clocktable-try-shift (dir n)
  3305. "Check if this line starts a clock table, if yes, shift the time block."
  3306. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3307. (org-clocktable-shift dir n)))
  3308. ;;;###autoload
  3309. (defun org-clock-persistence-insinuate ()
  3310. "Set up hooks for clock persistence."
  3311. (require 'org-clock)
  3312. (add-hook 'org-mode-hook 'org-clock-load)
  3313. (add-hook 'kill-emacs-hook 'org-clock-save))
  3314. (defun org-clock-auto-clockout-insinuate ()
  3315. "Set up hook for auto clocking out when Emacs is idle.
  3316. See `org-clock-auto-clockout-timer'.
  3317. This function is meant to be added to the user configuration."
  3318. (require 'org-clock)
  3319. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3320. (defgroup org-archive nil
  3321. "Options concerning archiving in Org mode."
  3322. :tag "Org Archive"
  3323. :group 'org-structure)
  3324. (defcustom org-archive-location "%s_archive::"
  3325. "The location where subtrees should be archived.
  3326. The value of this variable is a string, consisting of two parts,
  3327. separated by a double-colon. The first part is a filename and
  3328. the second part is a headline.
  3329. When the filename is omitted, archiving happens in the same file.
  3330. %s in the filename will be replaced by the current file
  3331. name (without the directory part). Archiving to a different file
  3332. is useful to keep archived entries from contributing to the
  3333. Org Agenda.
  3334. The archived entries will be filed as subtrees of the specified
  3335. headline. When the headline is omitted, the subtrees are simply
  3336. filed away at the end of the file, as top-level entries. Also in
  3337. the heading you can use %s to represent the file name, this can be
  3338. useful when using the same archive for a number of different files.
  3339. Here are a few examples:
  3340. \"%s_archive::\"
  3341. If the current file is Projects.org, archive in file
  3342. Projects.org_archive, as top-level trees. This is the default.
  3343. \"::* Archived Tasks\"
  3344. Archive in the current file, under the top-level headline
  3345. \"* Archived Tasks\".
  3346. \"~/org/archive.org::\"
  3347. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3348. \"~/org/archive.org::* From %s\"
  3349. Archive in file ~/org/archive.org (absolute path), under headlines
  3350. \"From FILENAME\" where file name is the current file name.
  3351. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3352. The \"datetree/\" string is special, signifying to archive
  3353. items to the datetree. Items are placed in either the CLOSED
  3354. date of the item, or the current date if there is no CLOSED date.
  3355. The heading will be a subentry to the current date. There doesn't
  3356. need to be a heading, but there always needs to be a slash after
  3357. datetree. For example, to store archived items directly in the
  3358. datetree, use \"~/org/datetree.org::datetree/\".
  3359. \"basement::** Finished Tasks\"
  3360. Archive in file ./basement (relative path), as level 3 trees
  3361. below the level 2 heading \"** Finished Tasks\".
  3362. You may define it locally by setting an ARCHIVE property. If
  3363. such a property is found in the file or in an entry, and anywhere
  3364. up the hierarchy, it will be used.
  3365. You can also set it for the whole file using the keyword-syntax:
  3366. #+ARCHIVE: basement::** Finished Tasks"
  3367. :group 'org-archive
  3368. :type 'string)
  3369. (defcustom org-agenda-skip-archived-trees t
  3370. "Non-nil means the agenda will skip any items located in archived trees.
  3371. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3372. variable is no longer recommended, you should leave it at the value t.
  3373. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3374. :group 'org-archive
  3375. :group 'org-agenda-skip
  3376. :type 'boolean)
  3377. (defcustom org-columns-skip-archived-trees t
  3378. "Non-nil means ignore archived trees when creating column view."
  3379. :group 'org-archive
  3380. :group 'org-properties
  3381. :type 'boolean)
  3382. (defcustom org-cycle-open-archived-trees nil
  3383. "Non-nil means `org-cycle' will open archived trees.
  3384. An archived tree is a tree marked with the tag ARCHIVE.
  3385. When nil, archived trees will stay folded. You can still open them with
  3386. normal outline commands like `show-all', but not with the cycling commands."
  3387. :group 'org-archive
  3388. :group 'org-cycle
  3389. :type 'boolean)
  3390. (defcustom org-sparse-tree-open-archived-trees nil
  3391. "Non-nil means sparse tree construction shows matches in archived trees.
  3392. When nil, matches in these trees are highlighted, but the trees are kept in
  3393. collapsed state."
  3394. :group 'org-archive
  3395. :group 'org-sparse-trees
  3396. :type 'boolean)
  3397. (defcustom org-sparse-tree-default-date-type nil
  3398. "The default date type when building a sparse tree.
  3399. When this is nil, a date is a scheduled or a deadline timestamp.
  3400. Otherwise, these types are allowed:
  3401. all: all timestamps
  3402. active: only active timestamps (<...>)
  3403. inactive: only inactive timestamps ([...])
  3404. scheduled: only scheduled timestamps
  3405. deadline: only deadline timestamps"
  3406. :type '(choice (const :tag "Scheduled or deadline" nil)
  3407. (const :tag "All timestamps" all)
  3408. (const :tag "Only active timestamps" active)
  3409. (const :tag "Only inactive timestamps" inactive)
  3410. (const :tag "Only scheduled timestamps" scheduled)
  3411. (const :tag "Only deadline timestamps" deadline)
  3412. (const :tag "Only closed timestamps" closed))
  3413. :version "26.1"
  3414. :package-version '(Org . "8.3")
  3415. :group 'org-sparse-trees)
  3416. (defun org-cycle-hide-archived-subtrees (state)
  3417. "Re-hide all archived subtrees after a visibility state change.
  3418. STATE should be one of the symbols listed in the docstring of
  3419. `org-cycle-hook'."
  3420. (when (and (not org-cycle-open-archived-trees)
  3421. (not (memq state '(overview folded))))
  3422. (save-excursion
  3423. (let* ((globalp (memq state '(contents all)))
  3424. (beg (if globalp (point-min) (point)))
  3425. (end (if globalp (point-max) (org-end-of-subtree t))))
  3426. (org-hide-archived-subtrees beg end)
  3427. (goto-char beg)
  3428. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3429. (message "%s" (substitute-command-keys
  3430. "Subtree is archived and stays closed. Use \
  3431. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3432. (defun org-force-cycle-archived ()
  3433. "Cycle subtree even if it is archived."
  3434. (interactive)
  3435. (setq this-command 'org-cycle)
  3436. (let ((org-cycle-open-archived-trees t))
  3437. (call-interactively 'org-cycle)))
  3438. (defun org-hide-archived-subtrees (beg end)
  3439. "Re-hide all archived subtrees after a visibility state change."
  3440. (org-with-wide-buffer
  3441. (let ((case-fold-search nil)
  3442. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3443. (goto-char beg)
  3444. ;; Include headline point is currently on.
  3445. (beginning-of-line)
  3446. (while (and (< (point) end) (re-search-forward re end t))
  3447. (when (member org-archive-tag (org-get-tags nil t))
  3448. (org-flag-subtree t)
  3449. (org-end-of-subtree t))))))
  3450. (defun org-flag-subtree (flag)
  3451. (save-excursion
  3452. (org-back-to-heading t)
  3453. (org-flag-region (line-end-position)
  3454. (progn (org-end-of-subtree t) (point))
  3455. flag
  3456. 'outline)))
  3457. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3458. ;; Declare Column View Code
  3459. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3460. (declare-function org-columns-compute "org-colview" (property))
  3461. ;; Declare ID code
  3462. (declare-function org-id-store-link "org-id")
  3463. (declare-function org-id-locations-load "org-id")
  3464. (declare-function org-id-locations-save "org-id")
  3465. (defvar org-id-track-globally)
  3466. ;;; Variables for pre-computed regular expressions, all buffer local
  3467. (defvar-local org-todo-regexp nil
  3468. "Matches any of the TODO state keywords.
  3469. Since TODO keywords are case-sensitive, `case-fold-search' is
  3470. expected to be bound to nil when matching against this regexp.")
  3471. (defvar-local org-not-done-regexp nil
  3472. "Matches any of the TODO state keywords except the last one.
  3473. Since TODO keywords are case-sensitive, `case-fold-search' is
  3474. expected to be bound to nil when matching against this regexp.")
  3475. (defvar-local org-not-done-heading-regexp nil
  3476. "Matches a TODO headline that is not done.
  3477. Since TODO keywords are case-sensitive, `case-fold-search' is
  3478. expected to be bound to nil when matching against this regexp.")
  3479. (defvar-local org-todo-line-regexp nil
  3480. "Matches a headline and puts TODO state into group 2 if present.
  3481. Since TODO keywords are case-sensitive, `case-fold-search' is
  3482. expected to be bound to nil when matching against this regexp.")
  3483. (defvar-local org-complex-heading-regexp nil
  3484. "Matches a headline and puts everything into groups:
  3485. group 1: Stars
  3486. group 2: The TODO keyword, maybe
  3487. group 3: Priority cookie
  3488. group 4: True headline
  3489. group 5: Tags
  3490. Since TODO keywords are case-sensitive, `case-fold-search' is
  3491. expected to be bound to nil when matching against this regexp.")
  3492. (defvar-local org-complex-heading-regexp-format nil
  3493. "Printf format to make regexp to match an exact headline.
  3494. This regexp will match the headline of any node which has the
  3495. exact headline text that is put into the format, but may have any
  3496. TODO state, priority and tags.")
  3497. (defvar-local org-todo-line-tags-regexp nil
  3498. "Matches a headline and puts TODO state into group 2 if present.
  3499. Also put tags into group 4 if tags are present.")
  3500. (defconst org-plain-time-of-day-regexp
  3501. (concat
  3502. "\\(\\<[012]?[0-9]"
  3503. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3504. "\\(--?"
  3505. "\\(\\<[012]?[0-9]"
  3506. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3507. "\\)?")
  3508. "Regular expression to match a plain time or time range.
  3509. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3510. groups carry important information:
  3511. 0 the full match
  3512. 1 the first time, range or not
  3513. 8 the second time, if it is a range.")
  3514. (defconst org-plain-time-extension-regexp
  3515. (concat
  3516. "\\(\\<[012]?[0-9]"
  3517. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3518. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3519. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3520. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3521. groups carry important information:
  3522. 0 the full match
  3523. 7 hours of duration
  3524. 9 minutes of duration")
  3525. (defconst org-stamp-time-of-day-regexp
  3526. (concat
  3527. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3528. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3529. "\\(--?"
  3530. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3531. "Regular expression to match a timestamp time or time range.
  3532. After a match, the following groups carry important information:
  3533. 0 the full match
  3534. 1 date plus weekday, for back referencing to make sure
  3535. both times are on the same day
  3536. 2 the first time, range or not
  3537. 4 the second time, if it is a range.")
  3538. (defconst org-startup-options
  3539. '(("fold" org-startup-folded t)
  3540. ("overview" org-startup-folded t)
  3541. ("nofold" org-startup-folded nil)
  3542. ("showall" org-startup-folded nil)
  3543. ("show2levels" org-startup-folded show2levels)
  3544. ("show3levels" org-startup-folded show3levels)
  3545. ("show4levels" org-startup-folded show4levels)
  3546. ("show5levels" org-startup-folded show5levels)
  3547. ("showeverything" org-startup-folded showeverything)
  3548. ("content" org-startup-folded content)
  3549. ("indent" org-startup-indented t)
  3550. ("noindent" org-startup-indented nil)
  3551. ("num" org-startup-numerated t)
  3552. ("nonum" org-startup-numerated nil)
  3553. ("hidestars" org-hide-leading-stars t)
  3554. ("showstars" org-hide-leading-stars nil)
  3555. ("odd" org-odd-levels-only t)
  3556. ("oddeven" org-odd-levels-only nil)
  3557. ("align" org-startup-align-all-tables t)
  3558. ("noalign" org-startup-align-all-tables nil)
  3559. ("shrink" org-startup-shrink-all-tables t)
  3560. ("inlineimages" org-startup-with-inline-images t)
  3561. ("noinlineimages" org-startup-with-inline-images nil)
  3562. ("latexpreview" org-startup-with-latex-preview t)
  3563. ("nolatexpreview" org-startup-with-latex-preview nil)
  3564. ("customtime" org-display-custom-times t)
  3565. ("logdone" org-log-done time)
  3566. ("lognotedone" org-log-done note)
  3567. ("nologdone" org-log-done nil)
  3568. ("lognoteclock-out" org-log-note-clock-out t)
  3569. ("nolognoteclock-out" org-log-note-clock-out nil)
  3570. ("logrepeat" org-log-repeat state)
  3571. ("lognoterepeat" org-log-repeat note)
  3572. ("logdrawer" org-log-into-drawer t)
  3573. ("nologdrawer" org-log-into-drawer nil)
  3574. ("logstatesreversed" org-log-states-order-reversed t)
  3575. ("nologstatesreversed" org-log-states-order-reversed nil)
  3576. ("nologrepeat" org-log-repeat nil)
  3577. ("logreschedule" org-log-reschedule time)
  3578. ("lognotereschedule" org-log-reschedule note)
  3579. ("nologreschedule" org-log-reschedule nil)
  3580. ("logredeadline" org-log-redeadline time)
  3581. ("lognoteredeadline" org-log-redeadline note)
  3582. ("nologredeadline" org-log-redeadline nil)
  3583. ("logrefile" org-log-refile time)
  3584. ("lognoterefile" org-log-refile note)
  3585. ("nologrefile" org-log-refile nil)
  3586. ("fninline" org-footnote-define-inline t)
  3587. ("nofninline" org-footnote-define-inline nil)
  3588. ("fnlocal" org-footnote-section nil)
  3589. ("fnauto" org-footnote-auto-label t)
  3590. ("fnprompt" org-footnote-auto-label nil)
  3591. ("fnconfirm" org-footnote-auto-label confirm)
  3592. ("fnplain" org-footnote-auto-label plain)
  3593. ("fnadjust" org-footnote-auto-adjust t)
  3594. ("nofnadjust" org-footnote-auto-adjust nil)
  3595. ("constcgs" constants-unit-system cgs)
  3596. ("constSI" constants-unit-system SI)
  3597. ("noptag" org-tag-persistent-alist nil)
  3598. ("hideblocks" org-hide-block-startup t)
  3599. ("nohideblocks" org-hide-block-startup nil)
  3600. ("beamer" org-startup-with-beamer-mode t)
  3601. ("entitiespretty" org-pretty-entities t)
  3602. ("entitiesplain" org-pretty-entities nil))
  3603. "Variable associated with STARTUP options for Org.
  3604. Each element is a list of three items: the startup options (as written
  3605. in the #+STARTUP line), the corresponding variable, and the value to set
  3606. this variable to if the option is found. An optional fourth element PUSH
  3607. means to push this value onto the list in the variable.")
  3608. (defcustom org-group-tags t
  3609. "When non-nil (the default), use group tags.
  3610. This can be turned on/off through `org-toggle-tags-groups'."
  3611. :group 'org-tags
  3612. :group 'org-startup
  3613. :type 'boolean)
  3614. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3615. (defun org-toggle-tags-groups ()
  3616. "Toggle support for group tags.
  3617. Support for group tags is controlled by the option
  3618. `org-group-tags', which is non-nil by default."
  3619. (interactive)
  3620. (setq org-group-tags (not org-group-tags))
  3621. (cond ((and (derived-mode-p 'org-agenda-mode)
  3622. org-group-tags)
  3623. (org-agenda-redo))
  3624. ((derived-mode-p 'org-mode)
  3625. (let ((org-inhibit-startup t)) (org-mode))))
  3626. (message "Groups tags support has been turned %s"
  3627. (if org-group-tags "on" "off")))
  3628. (defun org--tag-add-to-alist (alist1 alist2)
  3629. "Merge tags from ALIST1 into ALIST2.
  3630. Duplicates tags outside a group are removed. Keywords and order
  3631. are preserved.
  3632. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3633. See `org-tag-alist' for their structure."
  3634. (cond
  3635. ((null alist2) alist1)
  3636. ((null alist1) alist2)
  3637. (t
  3638. (let ((to-add nil)
  3639. (group-flag nil))
  3640. (dolist (tag-pair alist1)
  3641. (pcase tag-pair
  3642. (`(,(or :startgrouptag :startgroup))
  3643. (setq group-flag t)
  3644. (push tag-pair to-add))
  3645. (`(,(or :endgrouptag :endgroup))
  3646. (setq group-flag nil)
  3647. (push tag-pair to-add))
  3648. (`(,(or :grouptags :newline))
  3649. (push tag-pair to-add))
  3650. (`(,tag . ,_)
  3651. ;; Remove duplicates from ALIST1, unless they are in
  3652. ;; a group. Indeed, it makes sense to have a tag appear in
  3653. ;; multiple groups.
  3654. (when (or group-flag (not (assoc tag alist2)))
  3655. (push tag-pair to-add)))
  3656. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3657. ;; Preserve order of ALIST1.
  3658. (append (nreverse to-add) alist2)))))
  3659. (defun org-priority-to-value (s)
  3660. "Convert priority string S to its numeric value."
  3661. (or (save-match-data
  3662. (and (string-match "\\([0-9]+\\)" s)
  3663. (string-to-number (match-string 1 s))))
  3664. (string-to-char s)))
  3665. (defun org-set-regexps-and-options (&optional tags-only)
  3666. "Precompute regular expressions used in the current buffer.
  3667. When optional argument TAGS-ONLY is non-nil, only compute tags
  3668. related expressions."
  3669. (when (derived-mode-p 'org-mode)
  3670. (let ((alist (org-collect-keywords
  3671. (append '("FILETAGS" "TAGS")
  3672. (and (not tags-only)
  3673. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3674. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3675. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3676. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3677. ;; Startup options. Get this early since it does change
  3678. ;; behavior for other options (e.g., tags).
  3679. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3680. (cdr (assoc "STARTUP" alist)))))
  3681. (dolist (option startup)
  3682. (pcase (assoc-string option org-startup-options t)
  3683. (`(,_ ,variable ,value t)
  3684. (unless (listp (symbol-value variable))
  3685. (set (make-local-variable variable) nil))
  3686. (add-to-list variable value))
  3687. (`(,_ ,variable ,value . ,_)
  3688. (set (make-local-variable variable) value))
  3689. (_ nil))))
  3690. (setq-local org-file-tags
  3691. (mapcar #'org-add-prop-inherited
  3692. (cl-mapcan (lambda (value)
  3693. (cl-mapcan
  3694. (lambda (k) (org-split-string k ":"))
  3695. (split-string value)))
  3696. (cdr (assoc "FILETAGS" alist)))))
  3697. (setq org-current-tag-alist
  3698. (org--tag-add-to-alist
  3699. org-tag-persistent-alist
  3700. (let ((tags (cdr (assoc "TAGS" alist))))
  3701. (if tags
  3702. (org-tag-string-to-alist
  3703. (mapconcat #'identity tags "\n"))
  3704. org-tag-alist))))
  3705. (setq org-tag-groups-alist
  3706. (org-tag-alist-to-groups org-current-tag-alist))
  3707. (unless tags-only
  3708. ;; Properties.
  3709. (let ((properties nil))
  3710. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3711. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3712. (setq properties (org--update-property-plist
  3713. (match-string-no-properties 1 value)
  3714. (match-string-no-properties 2 value)
  3715. properties))))
  3716. (setq-local org-keyword-properties properties))
  3717. ;; Archive location.
  3718. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3719. (when archive (setq-local org-archive-location archive)))
  3720. ;; Category.
  3721. (let ((category (cdr (assoc "CATEGORY" alist))))
  3722. (when category
  3723. (setq-local org-category (intern category))
  3724. (setq-local org-keyword-properties
  3725. (org--update-property-plist
  3726. "CATEGORY" category org-keyword-properties))))
  3727. ;; Columns.
  3728. (let ((column (cdr (assoc "COLUMNS" alist))))
  3729. (when column (setq-local org-columns-default-format column)))
  3730. ;; Constants.
  3731. (let ((store nil))
  3732. (dolist (pair (cl-mapcan #'split-string
  3733. (cdr (assoc "CONSTANTS" alist))))
  3734. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3735. (let* ((name (match-string 1 pair))
  3736. (value (match-string 2 pair))
  3737. (old (assoc name store)))
  3738. (if old (setcdr old value)
  3739. (push (cons name value) store)))))
  3740. (setq org-table-formula-constants-local store))
  3741. ;; Link abbreviations.
  3742. (let ((links
  3743. (delq nil
  3744. (mapcar
  3745. (lambda (value)
  3746. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3747. (cons (match-string-no-properties 1 value)
  3748. (match-string-no-properties 2 value))))
  3749. (cdr (assoc "LINK" alist))))))
  3750. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3751. ;; Priorities.
  3752. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3753. (pcase (and value (split-string value))
  3754. (`(,high ,low ,default . ,_)
  3755. (setq-local org-priority-highest (org-priority-to-value high))
  3756. (setq-local org-priority-lowest (org-priority-to-value low))
  3757. (setq-local org-priority-default (org-priority-to-value default)))))
  3758. ;; Scripts.
  3759. (let ((value (cdr (assoc "OPTIONS" alist))))
  3760. (dolist (option value)
  3761. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3762. (setq-local org-use-sub-superscripts
  3763. (read (match-string 1 option))))))
  3764. ;; TODO keywords.
  3765. (setq-local org-todo-kwd-alist nil)
  3766. (setq-local org-todo-key-alist nil)
  3767. (setq-local org-todo-key-trigger nil)
  3768. (setq-local org-todo-keywords-1 nil)
  3769. (setq-local org-done-keywords nil)
  3770. (setq-local org-todo-heads nil)
  3771. (setq-local org-todo-sets nil)
  3772. (setq-local org-todo-log-states nil)
  3773. (let ((todo-sequences
  3774. (or (append (mapcar (lambda (value)
  3775. (cons 'type (split-string value)))
  3776. (cdr (assoc "TYP_TODO" alist)))
  3777. (mapcar (lambda (value)
  3778. (cons 'sequence (split-string value)))
  3779. (append (cdr (assoc "TODO" alist))
  3780. (cdr (assoc "SEQ_TODO" alist)))))
  3781. (let ((d (default-value 'org-todo-keywords)))
  3782. (if (not (stringp (car d))) d
  3783. ;; XXX: Backward compatibility code.
  3784. (list (cons org-todo-interpretation d)))))))
  3785. (dolist (sequence todo-sequences)
  3786. (let* ((sequence (or (run-hook-with-args-until-success
  3787. 'org-todo-setup-filter-hook sequence)
  3788. sequence))
  3789. (sequence-type (car sequence))
  3790. (keywords (cdr sequence))
  3791. (sep (member "|" keywords))
  3792. names alist)
  3793. (dolist (k (remove "|" keywords))
  3794. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3795. k)
  3796. (error "Invalid TODO keyword %s" k))
  3797. (let ((name (match-string 1 k))
  3798. (key (match-string 2 k))
  3799. (log (org-extract-log-state-settings k)))
  3800. (push name names)
  3801. (push (cons name (and key (string-to-char key))) alist)
  3802. (when log (push log org-todo-log-states))))
  3803. (let* ((names (nreverse names))
  3804. (done (if sep (org-remove-keyword-keys (cdr sep))
  3805. (last names)))
  3806. (head (car names))
  3807. (tail (list sequence-type head (car done) (org-last done))))
  3808. (add-to-list 'org-todo-heads head 'append)
  3809. (push names org-todo-sets)
  3810. (setq org-done-keywords (append org-done-keywords done nil))
  3811. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3812. (setq org-todo-key-alist
  3813. (append org-todo-key-alist
  3814. (and alist
  3815. (append '((:startgroup))
  3816. (nreverse alist)
  3817. '((:endgroup))))))
  3818. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3819. (setq org-todo-sets (nreverse org-todo-sets)
  3820. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3821. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3822. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3823. ;; Compute the regular expressions and other local variables.
  3824. ;; Using `org-outline-regexp-bol' would complicate them much,
  3825. ;; because of the fixed white space at the end of that string.
  3826. (unless org-done-keywords
  3827. (setq org-done-keywords
  3828. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3829. (setq org-not-done-keywords
  3830. (org-delete-all org-done-keywords
  3831. (copy-sequence org-todo-keywords-1))
  3832. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3833. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3834. org-not-done-heading-regexp
  3835. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3836. org-todo-line-regexp
  3837. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3838. org-complex-heading-regexp
  3839. (concat "^\\(\\*+\\)"
  3840. "\\(?: +" org-todo-regexp "\\)?"
  3841. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3842. "\\(?: +\\(.*?\\)\\)??"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3844. "[ \t]*$")
  3845. org-complex-heading-regexp-format
  3846. (concat "^\\(\\*+\\)"
  3847. "\\(?: +" org-todo-regexp "\\)?"
  3848. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3849. "\\(?: +"
  3850. ;; Stats cookies can be stuck to body.
  3851. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3852. "\\(%s\\)"
  3853. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3854. "\\)"
  3855. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3856. "[ \t]*$")
  3857. org-todo-line-tags-regexp
  3858. (concat "^\\(\\*+\\)"
  3859. "\\(?: +" org-todo-regexp "\\)?"
  3860. "\\(?: +\\(.*?\\)\\)??"
  3861. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3862. "[ \t]*$"))
  3863. (org-compute-latex-and-related-regexp)))))
  3864. (defun org-collect-keywords (keywords &optional unique directory)
  3865. "Return values for KEYWORDS in current buffer, as an alist.
  3866. KEYWORDS is a list of strings. Return value is a list of
  3867. elements with the pattern:
  3868. (NAME . LIST-OF-VALUES)
  3869. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3870. is a list of non-empty values, as strings, in order of appearance
  3871. in the buffer.
  3872. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3873. value, empty or not, appearing in the buffer, as a string.
  3874. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3875. (VALUE . DIRECTORY)
  3876. where VALUE is the regular value, and DIRECTORY is the variable
  3877. `default-directory' for the buffer containing the keyword. This
  3878. is important for values containing relative file names, since the
  3879. function follows SETUPFILE keywords, and may change its working
  3880. directory."
  3881. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3882. (unique (mapcar #'upcase unique))
  3883. (alist (org--collect-keywords-1
  3884. keywords unique directory
  3885. (and buffer-file-name (list buffer-file-name))
  3886. nil)))
  3887. ;; Re-order results.
  3888. (dolist (entry alist)
  3889. (pcase entry
  3890. (`(,_ . ,(and value (pred consp)))
  3891. (setcdr entry (nreverse value)))))
  3892. (nreverse alist)))
  3893. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3894. (org-with-point-at 1
  3895. (let ((case-fold-search t)
  3896. (regexp (org-make-options-regexp keywords)))
  3897. (while (and keywords (re-search-forward regexp nil t))
  3898. (let ((element (org-element-at-point)))
  3899. (when (eq 'keyword (org-element-type element))
  3900. (let ((value (org-element-property :value element)))
  3901. (pcase (org-element-property :key element)
  3902. ("SETUPFILE"
  3903. (when (and (org-string-nw-p value)
  3904. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3905. (let* ((uri (org-strip-quotes value))
  3906. (uri-is-url (org-file-url-p uri))
  3907. (uri (if uri-is-url
  3908. uri
  3909. (expand-file-name uri))))
  3910. (unless (member uri files)
  3911. (with-temp-buffer
  3912. (unless uri-is-url
  3913. (setq default-directory (file-name-directory uri)))
  3914. (let ((contents (org-file-contents uri :noerror)))
  3915. (when contents
  3916. (insert contents)
  3917. ;; Fake Org mode: `org-element-at-point'
  3918. ;; doesn't need full set-up.
  3919. (let ((major-mode 'org-mode))
  3920. (setq alist
  3921. (org--collect-keywords-1
  3922. keywords unique directory
  3923. (cons uri files)
  3924. alist))))))))))
  3925. (keyword
  3926. (let ((entry (assoc keyword alist))
  3927. (final
  3928. (cond ((not (member keyword directory)) value)
  3929. (buffer-file-name
  3930. (cons value
  3931. (file-name-directory buffer-file-name)))
  3932. (t (cons value default-directory)))))
  3933. (cond ((member keyword unique)
  3934. (push (cons keyword final) alist)
  3935. (setq keywords (remove keyword keywords))
  3936. (setq regexp (org-make-options-regexp keywords)))
  3937. ((null entry) (push (list keyword final) alist))
  3938. (t (push final (cdr entry)))))))))))
  3939. alist)))
  3940. (defun org-tag-string-to-alist (s)
  3941. "Return tag alist associated to string S.
  3942. S is a value for TAGS keyword or produced with
  3943. `org-tag-alist-to-string'. Return value is an alist suitable for
  3944. `org-tag-alist' or `org-tag-persistent-alist'."
  3945. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3946. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3947. "\\(?:(\\(.\\))\\)?\\'"))
  3948. alist group-flag)
  3949. (dolist (tokens lines (cdr (nreverse alist)))
  3950. (push '(:newline) alist)
  3951. (while tokens
  3952. (let ((token (pop tokens)))
  3953. (pcase token
  3954. ("{"
  3955. (push '(:startgroup) alist)
  3956. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3957. ("}"
  3958. (push '(:endgroup) alist)
  3959. (setq group-flag nil))
  3960. ("["
  3961. (push '(:startgrouptag) alist)
  3962. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3963. ("]"
  3964. (push '(:endgrouptag) alist)
  3965. (setq group-flag nil))
  3966. (":"
  3967. (push '(:grouptags) alist))
  3968. ((guard (string-match tag-re token))
  3969. (let ((tag (match-string 1 token))
  3970. (key (and (match-beginning 2)
  3971. (string-to-char (match-string 2 token)))))
  3972. ;; Push all tags in groups, no matter if they already
  3973. ;; appear somewhere else in the list.
  3974. (when (or group-flag (not (assoc tag alist)))
  3975. (push (cons tag key) alist))))))))))
  3976. (defun org-tag-alist-to-string (alist &optional skip-key)
  3977. "Return tag string associated to ALIST.
  3978. ALIST is an alist, as defined in `org-tag-alist' or
  3979. `org-tag-persistent-alist', or produced with
  3980. `org-tag-string-to-alist'.
  3981. Return value is a string suitable as a value for \"TAGS\"
  3982. keyword.
  3983. When optional argument SKIP-KEY is non-nil, skip selection keys
  3984. next to tags."
  3985. (mapconcat (lambda (token)
  3986. (pcase token
  3987. (`(:startgroup) "{")
  3988. (`(:endgroup) "}")
  3989. (`(:startgrouptag) "[")
  3990. (`(:endgrouptag) "]")
  3991. (`(:grouptags) ":")
  3992. (`(:newline) "\\n")
  3993. ((and
  3994. (guard (not skip-key))
  3995. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3996. (format "%s(%c)" tag key))
  3997. (`(,(and tag (pred stringp)) . ,_) tag)
  3998. (_ (user-error "Invalid tag token: %S" token))))
  3999. alist
  4000. " "))
  4001. (defun org-tag-alist-to-groups (alist)
  4002. "Return group alist from tag ALIST.
  4003. ALIST is an alist, as defined in `org-tag-alist' or
  4004. `org-tag-persistent-alist', or produced with
  4005. `org-tag-string-to-alist'. Return value is an alist following
  4006. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4007. a string, summarizing TAGS, as a list of strings."
  4008. (let (groups group-status current-group)
  4009. (dolist (token alist (nreverse groups))
  4010. (pcase token
  4011. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4012. (`(,(or :endgroup :endgrouptag))
  4013. (when (eq group-status 'append)
  4014. (push (nreverse current-group) groups))
  4015. (setq group-status nil current-group nil))
  4016. (`(:grouptags) (setq group-status 'append))
  4017. ((and `(,tag . ,_) (guard group-status))
  4018. (if (eq group-status 'append) (push tag current-group)
  4019. (setq current-group (list tag))))
  4020. (_ nil)))))
  4021. (defvar org--file-cache (make-hash-table :test #'equal)
  4022. "Hash table to store contents of files referenced via a URL.
  4023. This is the cache of file URLs read using `org-file-contents'.")
  4024. (defun org-reset-file-cache ()
  4025. "Reset the cache of files downloaded by `org-file-contents'."
  4026. (clrhash org--file-cache))
  4027. (defun org-file-url-p (file)
  4028. "Non-nil if FILE is a URL."
  4029. (require 'ffap)
  4030. (string-match-p ffap-url-regexp file))
  4031. (defun org-file-contents (file &optional noerror nocache)
  4032. "Return the contents of FILE, as a string.
  4033. FILE can be a file name or URL.
  4034. If FILE is a URL, download the contents. If the URL contents are
  4035. already cached in the `org--file-cache' hash table, the download step
  4036. is skipped.
  4037. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4038. from file or URL, and return nil.
  4039. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4040. is available. This option applies only if FILE is a URL."
  4041. (let* ((is-url (org-file-url-p file))
  4042. (cache (and is-url
  4043. (not nocache)
  4044. (gethash file org--file-cache))))
  4045. (cond
  4046. (cache)
  4047. (is-url
  4048. (with-current-buffer (url-retrieve-synchronously file)
  4049. (goto-char (point-min))
  4050. ;; Move point to after the url-retrieve header.
  4051. (search-forward "\n\n" nil :move)
  4052. ;; Search for the success code only in the url-retrieve header.
  4053. (if (save-excursion
  4054. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4055. ;; Update the cache `org--file-cache' and return contents.
  4056. (puthash file
  4057. (buffer-substring-no-properties (point) (point-max))
  4058. org--file-cache)
  4059. (funcall (if noerror #'message #'user-error)
  4060. "Unable to fetch file from %S"
  4061. file)
  4062. nil)))
  4063. (t
  4064. (with-temp-buffer
  4065. (condition-case nil
  4066. (progn
  4067. (insert-file-contents file)
  4068. (buffer-string))
  4069. (file-error
  4070. (funcall (if noerror #'message #'user-error)
  4071. "Unable to read file %S"
  4072. file)
  4073. nil)))))))
  4074. (defun org-extract-log-state-settings (x)
  4075. "Extract the log state setting from a TODO keyword string.
  4076. This will extract info from a string like \"WAIT(w@/!)\"."
  4077. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4078. (let ((kw (match-string 1 x))
  4079. (log1 (and (match-end 3) (match-string 3 x)))
  4080. (log2 (and (match-end 4) (match-string 4 x))))
  4081. (and (or log1 log2)
  4082. (list kw
  4083. (and log1 (if (equal log1 "!") 'time 'note))
  4084. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4085. (defun org-remove-keyword-keys (list)
  4086. "Remove a pair of parenthesis at the end of each string in LIST."
  4087. (mapcar (lambda (x)
  4088. (if (string-match "(.*)$" x)
  4089. (substring x 0 (match-beginning 0))
  4090. x))
  4091. list))
  4092. (defun org-assign-fast-keys (alist)
  4093. "Assign fast keys to a keyword-key alist.
  4094. Respect keys that are already there."
  4095. (let (new e (alt ?0))
  4096. (while (setq e (pop alist))
  4097. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4098. (cdr e)) ;; Key already assigned.
  4099. (push e new)
  4100. (let ((clist (string-to-list (downcase (car e))))
  4101. (used (append new alist)))
  4102. (when (= (car clist) ?@)
  4103. (pop clist))
  4104. (while (and clist (rassoc (car clist) used))
  4105. (pop clist))
  4106. (unless clist
  4107. (while (rassoc alt used)
  4108. (cl-incf alt)))
  4109. (push (cons (car e) (or (car clist) alt)) new))))
  4110. (nreverse new)))
  4111. ;;; Some variables used in various places
  4112. (defvar org-window-configuration nil
  4113. "Used in various places to store a window configuration.")
  4114. (defvar org-selected-window nil
  4115. "Used in various places to store a window configuration.")
  4116. (defvar org-finish-function nil
  4117. "Function to be called when `C-c C-c' is used.
  4118. This is for getting out of special buffers like capture.")
  4119. (defvar org-last-state)
  4120. ;; Defined somewhere in this file, but used before definition.
  4121. (defvar org-entities) ;; defined in org-entities.el
  4122. (defvar org-struct-menu)
  4123. (defvar org-org-menu)
  4124. (defvar org-tbl-menu)
  4125. ;;;; Define the Org mode
  4126. (defun org-before-change-function (_beg _end)
  4127. "Every change indicates that a table might need an update."
  4128. (setq org-table-may-need-update t))
  4129. (defvar org-mode-map)
  4130. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4131. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4132. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4133. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4134. (defvar bidi-paragraph-direction)
  4135. (defvar buffer-face-mode-face)
  4136. (require 'outline)
  4137. ;; Other stuff we need.
  4138. (require 'time-date)
  4139. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4140. (require 'easymenu)
  4141. (require 'overlay)
  4142. (require 'org-entities)
  4143. (require 'org-faces)
  4144. (require 'org-list)
  4145. (require 'org-pcomplete)
  4146. (require 'org-src)
  4147. (require 'org-footnote)
  4148. (require 'org-macro)
  4149. ;; babel
  4150. (require 'ob)
  4151. ;;;###autoload
  4152. (define-derived-mode org-mode outline-mode "Org"
  4153. "Outline-based notes management and organizer, alias
  4154. \"Carsten's outline-mode for keeping track of everything.\"
  4155. Org mode develops organizational tasks around a NOTES file which
  4156. contains information about projects as plain text. Org mode is
  4157. implemented on top of Outline mode, which is ideal to keep the content
  4158. of large files well structured. It supports ToDo items, deadlines and
  4159. time stamps, which magically appear in the diary listing of the Emacs
  4160. calendar. Tables are easily created with a built-in table editor.
  4161. Plain text URL-like links connect to websites, emails (VM), Usenet
  4162. messages (Gnus), BBDB entries, and any files related to the project.
  4163. For printing and sharing of notes, an Org file (or a part of it)
  4164. can be exported as a structured ASCII or HTML file.
  4165. The following commands are available:
  4166. \\{org-mode-map}"
  4167. (org-load-modules-maybe)
  4168. (org-install-agenda-files-menu)
  4169. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4170. (add-to-invisibility-spec '(org-hide-block . t))
  4171. (setq-local outline-regexp org-outline-regexp)
  4172. (setq-local outline-level 'org-outline-level)
  4173. (setq bidi-paragraph-direction 'left-to-right)
  4174. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4175. (unless org-display-table
  4176. (setq org-display-table (make-display-table)))
  4177. (set-display-table-slot
  4178. org-display-table 4
  4179. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4180. org-ellipsis)))
  4181. (setq buffer-display-table org-display-table))
  4182. (org-set-regexps-and-options)
  4183. (org-set-font-lock-defaults)
  4184. (when (and org-tag-faces (not org-tags-special-faces-re))
  4185. ;; tag faces set outside customize.... force initialization.
  4186. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4187. ;; Calc embedded
  4188. (setq-local calc-embedded-open-mode "# ")
  4189. ;; Modify a few syntax entries
  4190. (modify-syntax-entry ?\" "\"")
  4191. (modify-syntax-entry ?\\ "_")
  4192. (modify-syntax-entry ?~ "_")
  4193. (modify-syntax-entry ?< "(>")
  4194. (modify-syntax-entry ?> ")<")
  4195. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4196. ;; Activate before-change-function
  4197. (setq-local org-table-may-need-update t)
  4198. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4199. ;; Check for running clock before killing a buffer
  4200. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4201. ;; Initialize macros templates.
  4202. (org-macro-initialize-templates)
  4203. ;; Initialize radio targets.
  4204. (org-update-radio-target-regexp)
  4205. ;; Indentation.
  4206. (setq-local indent-line-function 'org-indent-line)
  4207. (setq-local indent-region-function 'org-indent-region)
  4208. ;; Filling and auto-filling.
  4209. (org-setup-filling)
  4210. ;; Comments.
  4211. (org-setup-comments-handling)
  4212. ;; Initialize cache.
  4213. (org-element-cache-reset)
  4214. ;; Beginning/end of defun
  4215. (setq-local beginning-of-defun-function 'org-backward-element)
  4216. (setq-local end-of-defun-function
  4217. (lambda ()
  4218. (if (not (org-at-heading-p))
  4219. (org-forward-element)
  4220. (org-forward-element)
  4221. (forward-char -1))))
  4222. ;; Next error for sparse trees
  4223. (setq-local next-error-function 'org-occur-next-match)
  4224. ;; Make commit log messages from Org documents easier.
  4225. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4226. ;; Make sure dependence stuff works reliably, even for users who set it
  4227. ;; too late :-(
  4228. (if org-enforce-todo-dependencies
  4229. (add-hook 'org-blocker-hook
  4230. 'org-block-todo-from-children-or-siblings-or-parent)
  4231. (remove-hook 'org-blocker-hook
  4232. 'org-block-todo-from-children-or-siblings-or-parent))
  4233. (if org-enforce-todo-checkbox-dependencies
  4234. (add-hook 'org-blocker-hook
  4235. 'org-block-todo-from-checkboxes)
  4236. (remove-hook 'org-blocker-hook
  4237. 'org-block-todo-from-checkboxes))
  4238. ;; Align options lines
  4239. (setq-local
  4240. align-mode-rules-list
  4241. '((org-in-buffer-settings
  4242. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4243. (modes . '(org-mode)))))
  4244. ;; Setup the pcomplete hooks
  4245. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4246. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4247. (setq-local pcomplete-default-completion-function #'ignore)
  4248. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4249. (setq-local pcomplete-termination-string "")
  4250. (add-hook 'completion-at-point-functions
  4251. #'pcomplete-completions-at-point nil t)
  4252. (setq-local buffer-face-mode-face 'org-default)
  4253. ;; If empty file that did not turn on Org mode automatically, make
  4254. ;; it to.
  4255. (when (and org-insert-mode-line-in-empty-file
  4256. (called-interactively-p 'any)
  4257. (= (point-min) (point-max)))
  4258. (insert "# -*- mode: org -*-\n\n"))
  4259. (unless org-inhibit-startup
  4260. (org-unmodified
  4261. (when org-startup-with-beamer-mode (org-beamer-mode))
  4262. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4263. (org-table-map-tables
  4264. (cond ((and org-startup-align-all-tables
  4265. org-startup-shrink-all-tables)
  4266. (lambda () (org-table-align) (org-table-shrink)))
  4267. (org-startup-align-all-tables #'org-table-align)
  4268. (t #'org-table-shrink))
  4269. t))
  4270. (when org-startup-with-inline-images (org-display-inline-images))
  4271. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4272. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4273. (when org-startup-truncated (setq truncate-lines t))
  4274. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4275. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4276. ;; Activate `org-table-header-line-mode'
  4277. (when org-table-header-line-p
  4278. (org-table-header-line-mode 1))
  4279. ;; Try to set `org-hide' face correctly.
  4280. (let ((foreground (org-find-invisible-foreground)))
  4281. (when foreground
  4282. (set-face-foreground 'org-hide foreground)))
  4283. ;; Set face extension as requested.
  4284. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4285. org-fontify-whole-block-delimiter-line)
  4286. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4287. ;; Update `customize-package-emacs-version-alist'
  4288. (add-to-list 'customize-package-emacs-version-alist
  4289. '(Org ("8.0" . "24.4")
  4290. ("8.1" . "24.4")
  4291. ("8.2" . "24.4")
  4292. ("8.2.7" . "24.4")
  4293. ("8.3" . "26.1")
  4294. ("9.0" . "26.1")
  4295. ("9.1" . "26.1")
  4296. ("9.2" . "27.1")
  4297. ("9.3" . "27.1")
  4298. ("9.4" . "27.2")
  4299. ("9.5" . "28.1")))
  4300. (defvar org-mode-transpose-word-syntax-table
  4301. (let ((st (make-syntax-table text-mode-syntax-table)))
  4302. (dolist (c org-emphasis-alist st)
  4303. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4304. (when (fboundp 'abbrev-table-put)
  4305. (abbrev-table-put org-mode-abbrev-table
  4306. :parents (list text-mode-abbrev-table)))
  4307. (defun org-find-invisible-foreground ()
  4308. (let ((candidates (remove
  4309. "unspecified-bg"
  4310. (nconc
  4311. (list (face-background 'default)
  4312. (face-background 'org-default))
  4313. (mapcar
  4314. (lambda (alist)
  4315. (when (boundp alist)
  4316. (cdr (assq 'background-color (symbol-value alist)))))
  4317. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4318. (list (face-foreground 'org-hide))))))
  4319. (car (remove nil candidates))))
  4320. (defun org-current-time (&optional rounding-minutes past)
  4321. "Current time, possibly rounded to ROUNDING-MINUTES.
  4322. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4323. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4324. the rounding returns a past time."
  4325. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4326. (car org-time-stamp-rounding-minutes)))
  4327. (now (current-time)))
  4328. (if (< r 1)
  4329. now
  4330. (let* ((time (decode-time now))
  4331. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4332. (nthcdr 2 time))))
  4333. (if (or (not past) (org-time-less-p res now))
  4334. res
  4335. (org-time-subtract res (* r 60)))))))
  4336. (defun org-today ()
  4337. "Return today date, considering `org-extend-today-until'."
  4338. (time-to-days
  4339. (org-time-since (* 3600 org-extend-today-until))))
  4340. ;;;; Font-Lock stuff, including the activators
  4341. (defconst org-match-sexp-depth 3
  4342. "Number of stacked braces for sub/superscript matching.")
  4343. (defun org-create-multibrace-regexp (left right n)
  4344. "Create a regular expression which will match a balanced sexp.
  4345. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4346. as single character strings.
  4347. The regexp returned will match the entire expression including the
  4348. delimiters. It will also define a single group which contains the
  4349. match except for the outermost delimiters. The maximum depth of
  4350. stacked delimiters is N. Escaping delimiters is not possible."
  4351. (let* ((nothing (concat "[^" left right "]*?"))
  4352. (or "\\|")
  4353. (re nothing)
  4354. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4355. (while (> n 1)
  4356. (setq n (1- n)
  4357. re (concat re or next)
  4358. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4359. (concat left "\\(" re "\\)" right)))
  4360. (defconst org-match-substring-regexp
  4361. (concat
  4362. "\\(\\S-\\)\\([_^]\\)\\("
  4363. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4364. "\\|"
  4365. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4366. "\\|"
  4367. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4368. "The regular expression matching a sub- or superscript.")
  4369. (defconst org-match-substring-with-braces-regexp
  4370. (concat
  4371. "\\(\\S-\\)\\([_^]\\)"
  4372. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4373. "The regular expression matching a sub- or superscript, forcing braces.")
  4374. (defvar org-emph-face nil)
  4375. (defun org-do-emphasis-faces (limit)
  4376. "Run through the buffer and emphasize strings."
  4377. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4378. (car org-emphasis-regexp-components))))
  4379. (catch :exit
  4380. (while (re-search-forward quick-re limit t)
  4381. (let* ((marker (match-string 2))
  4382. (verbatim? (member marker '("~" "="))))
  4383. (when (save-excursion
  4384. (goto-char (match-beginning 0))
  4385. (and
  4386. ;; Do not match table hlines.
  4387. (not (and (equal marker "+")
  4388. (org-match-line
  4389. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4390. ;; Do not match headline stars. Do not consider
  4391. ;; stars of a headline as closing marker for bold
  4392. ;; markup either.
  4393. (not (and (equal marker "*")
  4394. (save-excursion
  4395. (forward-char)
  4396. (skip-chars-backward "*")
  4397. (looking-at-p org-outline-regexp-bol))))
  4398. ;; Match full emphasis markup regexp.
  4399. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4400. ;; Do not span over paragraph boundaries.
  4401. (not (string-match-p org-element-paragraph-separate
  4402. (match-string 2)))
  4403. ;; Do not span over cells in table rows.
  4404. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4405. (string-match-p "|" (match-string 4))))))
  4406. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4407. (m (if org-hide-emphasis-markers 4 2)))
  4408. (font-lock-prepend-text-property
  4409. (match-beginning m) (match-end m) 'face face)
  4410. (when verbatim?
  4411. (org-remove-flyspell-overlays-in
  4412. (match-beginning 0) (match-end 0))
  4413. (remove-text-properties (match-beginning 2) (match-end 2)
  4414. '(display t invisible t intangible t)))
  4415. (add-text-properties (match-beginning 2) (match-end 2)
  4416. '(font-lock-multiline t org-emphasis t))
  4417. (when (and org-hide-emphasis-markers
  4418. (not (org-at-comment-p)))
  4419. (add-text-properties (match-end 4) (match-beginning 5)
  4420. '(invisible org-link))
  4421. (add-text-properties (match-beginning 3) (match-end 3)
  4422. '(invisible org-link)))
  4423. (throw :exit t))))))))
  4424. (defun org-emphasize (&optional char)
  4425. "Insert or change an emphasis, i.e. a font like bold or italic.
  4426. If there is an active region, change that region to a new emphasis.
  4427. If there is no region, just insert the marker characters and position
  4428. the cursor between them.
  4429. CHAR should be the marker character. If it is a space, it means to
  4430. remove the emphasis of the selected region.
  4431. If CHAR is not given (for example in an interactive call) it will be
  4432. prompted for."
  4433. (interactive)
  4434. (let ((erc org-emphasis-regexp-components)
  4435. (string "") beg end move s)
  4436. (if (org-region-active-p)
  4437. (setq beg (region-beginning)
  4438. end (region-end)
  4439. string (buffer-substring beg end))
  4440. (setq move t))
  4441. (unless char
  4442. (message "Emphasis marker or tag: [%s]"
  4443. (mapconcat #'car org-emphasis-alist ""))
  4444. (setq char (read-char-exclusive)))
  4445. (if (equal char ?\s)
  4446. (setq s ""
  4447. move nil)
  4448. (unless (assoc (char-to-string char) org-emphasis-alist)
  4449. (user-error "No such emphasis marker: \"%c\"" char))
  4450. (setq s (char-to-string char)))
  4451. (while (and (> (length string) 1)
  4452. (equal (substring string 0 1) (substring string -1))
  4453. (assoc (substring string 0 1) org-emphasis-alist))
  4454. (setq string (substring string 1 -1)))
  4455. (setq string (concat s string s))
  4456. (when beg (delete-region beg end))
  4457. (unless (or (bolp)
  4458. (string-match (concat "[" (nth 0 erc) "\n]")
  4459. (char-to-string (char-before (point)))))
  4460. (insert " "))
  4461. (unless (or (eobp)
  4462. (string-match (concat "[" (nth 1 erc) "\n]")
  4463. (char-to-string (char-after (point)))))
  4464. (insert " ") (backward-char 1))
  4465. (insert string)
  4466. (and move (backward-char 1))))
  4467. (defconst org-nonsticky-props
  4468. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4469. (defsubst org-rear-nonsticky-at (pos)
  4470. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4471. (defun org-activate-links (limit)
  4472. "Add link properties to links.
  4473. This includes angle, plain, and bracket links."
  4474. (catch :exit
  4475. (while (re-search-forward org-link-any-re limit t)
  4476. (let* ((start (match-beginning 0))
  4477. (end (match-end 0))
  4478. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4479. (visible-end (or (match-end 3) (match-end 2)))
  4480. (style (cond ((eq ?< (char-after start)) 'angle)
  4481. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4482. (t 'plain))))
  4483. (when (and (memq style org-highlight-links)
  4484. ;; Do not span over paragraph boundaries.
  4485. (not (string-match-p org-element-paragraph-separate
  4486. (match-string 0)))
  4487. ;; Do not confuse plain links with tags.
  4488. (not (and (eq style 'plain)
  4489. (let ((face (get-text-property
  4490. (max (1- start) (point-min)) 'face)))
  4491. (if (consp face) (memq 'org-tag face)
  4492. (eq 'org-tag face))))))
  4493. (let* ((link-object (save-excursion
  4494. (goto-char start)
  4495. (save-match-data (org-element-link-parser))))
  4496. (link (org-element-property :raw-link link-object))
  4497. (type (org-element-property :type link-object))
  4498. (path (org-element-property :path link-object))
  4499. (face-property (pcase (org-link-get-parameter type :face)
  4500. ((and (pred functionp) face) (funcall face path))
  4501. ((and (pred facep) face) face)
  4502. ((and (pred consp) face) face) ;anonymous
  4503. (_ 'org-link)))
  4504. (properties ;for link's visible part
  4505. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4506. 'highlight)
  4507. 'keymap (or (org-link-get-parameter type :keymap)
  4508. org-mouse-map)
  4509. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4510. ((and (pred stringp) echo) echo)
  4511. ((and (pred functionp) echo) echo)
  4512. (_ (concat "LINK: " link)))
  4513. 'htmlize-link (pcase (org-link-get-parameter type
  4514. :htmlize-link)
  4515. ((and (pred functionp) f) (funcall f))
  4516. (_ `(:uri ,link)))
  4517. 'font-lock-multiline t)))
  4518. (org-remove-flyspell-overlays-in start end)
  4519. (org-rear-nonsticky-at end)
  4520. (if (not (eq 'bracket style))
  4521. (progn
  4522. (add-face-text-property start end face-property)
  4523. (add-text-properties start end properties))
  4524. ;; Handle invisible parts in bracket links.
  4525. (remove-text-properties start end '(invisible nil))
  4526. (let ((hidden
  4527. (append `(invisible
  4528. ,(or (org-link-get-parameter type :display)
  4529. 'org-link))
  4530. properties)))
  4531. (add-text-properties start visible-start hidden)
  4532. (add-face-text-property visible-start visible-end face-property)
  4533. (add-text-properties visible-start visible-end properties)
  4534. (add-text-properties visible-end end hidden)
  4535. (org-rear-nonsticky-at visible-start)
  4536. (org-rear-nonsticky-at visible-end)))
  4537. (let ((f (org-link-get-parameter type :activate-func)))
  4538. (when (functionp f)
  4539. (funcall f start end path (eq style 'bracket))))
  4540. (throw :exit t))))) ;signal success
  4541. nil))
  4542. (defun org-activate-code (limit)
  4543. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4544. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4545. (remove-text-properties (match-beginning 0) (match-end 0)
  4546. '(display t invisible t intangible t))
  4547. t))
  4548. (defcustom org-src-fontify-natively t
  4549. "When non-nil, fontify code in code blocks.
  4550. See also the `org-block' face."
  4551. :type 'boolean
  4552. :version "26.1"
  4553. :package-version '(Org . "8.3")
  4554. :group 'org-appearance
  4555. :group 'org-babel)
  4556. (defcustom org-allow-promoting-top-level-subtree nil
  4557. "When non-nil, allow promoting a top level subtree.
  4558. The leading star of the top level headline will be replaced
  4559. by a #."
  4560. :type 'boolean
  4561. :version "24.1"
  4562. :group 'org-appearance)
  4563. (defun org-fontify-meta-lines-and-blocks (limit)
  4564. (condition-case nil
  4565. (org-fontify-meta-lines-and-blocks-1 limit)
  4566. (error (message "Org mode fontification error in %S at %d"
  4567. (current-buffer)
  4568. (line-number-at-pos)))))
  4569. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4570. "Fontify #+ lines and blocks."
  4571. (let ((case-fold-search t))
  4572. (when (re-search-forward
  4573. (rx bol (group (zero-or-more (any " \t")) "#"
  4574. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4575. (any " \t")
  4576. eol))
  4577. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4578. (zero-or-more (any " \t"))
  4579. (group (group (zero-or-more (not (any " \t\n"))))
  4580. (zero-or-more (any " \t"))
  4581. (group (zero-or-more any)))))
  4582. limit t)
  4583. (let ((beg (match-beginning 0))
  4584. (end-of-beginline (match-end 0))
  4585. ;; Including \n at end of #+begin line will include \n
  4586. ;; after the end of block content.
  4587. (block-start (match-end 0))
  4588. (block-end nil)
  4589. (lang (match-string 7)) ; The language, if it is a source block.
  4590. (bol-after-beginline (line-beginning-position 2))
  4591. (dc1 (downcase (match-string 2)))
  4592. (dc3 (downcase (match-string 3)))
  4593. (whole-blockline org-fontify-whole-block-delimiter-line)
  4594. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4595. (cond
  4596. ((and (match-end 4) (equal dc3 "+begin"))
  4597. ;; Truly a block
  4598. (setq block-type (downcase (match-string 5))
  4599. ;; Src, example, export, maybe more.
  4600. quoting (member block-type org-protecting-blocks))
  4601. (when (re-search-forward
  4602. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4603. (seq (zero-or-more (any " \t"))
  4604. "#+end"
  4605. ,(match-string 4)
  4606. word-end
  4607. (zero-or-more any)))))
  4608. ;; We look further than LIMIT on purpose.
  4609. nil t)
  4610. ;; We do have a matching #+end line.
  4611. (setq beg-of-endline (match-beginning 0)
  4612. end-of-endline (match-end 0)
  4613. nl-before-endline (1- (match-beginning 0)))
  4614. (setq block-end (match-beginning 0)) ; Include the final newline.
  4615. (when quoting
  4616. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4617. (remove-text-properties beg end-of-endline
  4618. '(display t invisible t intangible t)))
  4619. (add-text-properties
  4620. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4621. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4622. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4623. (cond
  4624. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4625. (org-src-font-lock-fontify-block lang block-start block-end)
  4626. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4627. (quoting
  4628. (add-text-properties
  4629. bol-after-beginline beg-of-endline
  4630. (list 'face
  4631. (list :inherit
  4632. (let ((face-name
  4633. (intern (format "org-block-%s" lang))))
  4634. (append (and (facep face-name) (list face-name))
  4635. '(org-block)))))))
  4636. ((not org-fontify-quote-and-verse-blocks))
  4637. ((string= block-type "quote")
  4638. (add-face-text-property
  4639. bol-after-beginline beg-of-endline 'org-quote t))
  4640. ((string= block-type "verse")
  4641. (add-face-text-property
  4642. bol-after-beginline beg-of-endline 'org-verse t)))
  4643. ;; Fontify the #+begin and #+end lines of the blocks
  4644. (add-text-properties
  4645. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4646. '(face org-block-begin-line))
  4647. (unless (eq (char-after beg-of-endline) ?*)
  4648. (add-text-properties
  4649. beg-of-endline
  4650. (if whole-blockline
  4651. (let ((beg-of-next-line (1+ end-of-endline)))
  4652. (min (point-max) beg-of-next-line))
  4653. (min (point-max) end-of-endline))
  4654. '(face org-block-end-line)))
  4655. t))
  4656. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4657. (org-remove-flyspell-overlays-in
  4658. (match-beginning 0)
  4659. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4660. (add-text-properties
  4661. beg (match-end 3)
  4662. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4663. '(font-lock-fontified t invisible t)
  4664. '(font-lock-fontified t face org-document-info-keyword)))
  4665. (add-text-properties
  4666. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4667. (if (string-equal dc1 "+title:")
  4668. '(font-lock-fontified t face org-document-title)
  4669. '(font-lock-fontified t face org-document-info))))
  4670. ((string-prefix-p "+caption" dc1)
  4671. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4672. (remove-text-properties (match-beginning 0) (match-end 0)
  4673. '(display t invisible t intangible t))
  4674. ;; Handle short captions
  4675. (save-excursion
  4676. (beginning-of-line)
  4677. (looking-at (rx (group (zero-or-more (any " \t"))
  4678. "#+caption"
  4679. (optional "[" (zero-or-more any) "]")
  4680. ":")
  4681. (zero-or-more (any " \t")))))
  4682. (add-text-properties (line-beginning-position) (match-end 1)
  4683. '(font-lock-fontified t face org-meta-line))
  4684. (add-text-properties (match-end 0) (line-end-position)
  4685. '(font-lock-fontified t face org-block))
  4686. t)
  4687. ((member dc3 '(" " ""))
  4688. ;; Just a comment, the plus was not there
  4689. (org-remove-flyspell-overlays-in beg (match-end 0))
  4690. (add-text-properties
  4691. beg (match-end 0)
  4692. '(font-lock-fontified t face font-lock-comment-face)))
  4693. (t ;; Just any other in-buffer setting, but not indented
  4694. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4695. (remove-text-properties (match-beginning 0) (match-end 0)
  4696. '(display t invisible t intangible t))
  4697. (add-text-properties beg (match-end 0)
  4698. '(font-lock-fontified t face org-meta-line))
  4699. t))))))
  4700. (defun org-fontify-drawers (limit)
  4701. "Fontify drawers."
  4702. (when (re-search-forward org-drawer-regexp limit t)
  4703. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4704. '(font-lock-fontified t face org-drawer))
  4705. (org-remove-flyspell-overlays-in
  4706. (line-beginning-position) (line-beginning-position 2))
  4707. t))
  4708. (defun org-fontify-macros (limit)
  4709. "Fontify macros."
  4710. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4711. (let ((begin (match-beginning 0))
  4712. (opening-end (match-beginning 1)))
  4713. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4714. (match-string 1))
  4715. (let ((end (match-end 1))
  4716. (closing-start (match-beginning 1)))
  4717. (add-text-properties
  4718. begin end
  4719. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4720. (org-remove-flyspell-overlays-in begin end)
  4721. (when org-hide-macro-markers
  4722. (add-text-properties begin opening-end '(invisible t))
  4723. (add-text-properties closing-start end '(invisible t)))
  4724. t)))))
  4725. (defun org-fontify-extend-region (beg end _old-len)
  4726. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4727. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4728. (extend (lambda (r1 r2 dir)
  4729. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4730. (replace-regexp-in-string "[][]" r2
  4731. (match-string-no-properties 0)))))
  4732. (re-search-forward (regexp-quote re) nil t dir)))))
  4733. (save-match-data
  4734. (save-excursion
  4735. (goto-char beg)
  4736. (back-to-indentation)
  4737. (cond ((looking-at end-re)
  4738. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4739. ((looking-at begin-re)
  4740. (cons beg (or (funcall extend "end" "]" 1) end)))
  4741. (t (cons beg end)))))))
  4742. (defun org-activate-footnote-links (limit)
  4743. "Add text properties for footnotes."
  4744. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4745. (when fn
  4746. (let* ((beg (nth 1 fn))
  4747. (end (nth 2 fn))
  4748. (label (car fn))
  4749. (referencep (/= (line-beginning-position) beg)))
  4750. (when (and referencep (nth 3 fn))
  4751. (save-excursion
  4752. (goto-char beg)
  4753. (search-forward (or label "fn:"))
  4754. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4755. (add-text-properties beg end
  4756. (list 'mouse-face 'highlight
  4757. 'keymap org-mouse-map
  4758. 'help-echo
  4759. (if referencep "Footnote reference"
  4760. "Footnote definition")
  4761. 'font-lock-fontified t
  4762. 'font-lock-multiline t
  4763. 'face 'org-footnote))))))
  4764. (defun org-activate-dates (limit)
  4765. "Add text properties for dates."
  4766. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4767. (not (equal (char-before (match-beginning 0)) 91)))
  4768. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4769. (add-text-properties (match-beginning 0) (match-end 0)
  4770. (list 'mouse-face 'highlight
  4771. 'keymap org-mouse-map))
  4772. (org-rear-nonsticky-at (match-end 0))
  4773. (when org-display-custom-times
  4774. ;; If it's a date range, activate custom time for second date.
  4775. (when (match-end 3)
  4776. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4777. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4778. t))
  4779. (defun org-activate-target-links (limit)
  4780. "Add text properties for target matches."
  4781. (when org-target-link-regexp
  4782. (let ((case-fold-search t))
  4783. ;; `org-target-link-regexp' matches one character before the
  4784. ;; actual target.
  4785. (unless (bolp) (forward-char -1))
  4786. (when (re-search-forward org-target-link-regexp limit t)
  4787. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4788. (add-text-properties (match-beginning 1) (match-end 1)
  4789. (list 'mouse-face 'highlight
  4790. 'keymap org-mouse-map
  4791. 'help-echo "Radio target link"
  4792. 'org-linked-text t))
  4793. (org-rear-nonsticky-at (match-end 1))
  4794. t))))
  4795. (defvar org-latex-and-related-regexp nil
  4796. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4797. (defun org-compute-latex-and-related-regexp ()
  4798. "Compute regular expression for LaTeX, entities and sub/superscript.
  4799. Result depends on variable `org-highlight-latex-and-related'."
  4800. (let ((re-sub
  4801. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4802. ((eq org-use-sub-superscripts '{})
  4803. (list org-match-substring-with-braces-regexp))
  4804. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4805. (re-latex
  4806. (when (or (memq 'latex org-highlight-latex-and-related)
  4807. (memq 'native org-highlight-latex-and-related))
  4808. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4809. (delq nil
  4810. (mapcar (lambda (x)
  4811. (and (member (car x) matchers) (nth 1 x)))
  4812. org-latex-regexps)))))
  4813. (re-entities
  4814. (when (memq 'entities org-highlight-latex-and-related)
  4815. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4816. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4817. (setq-local org-latex-and-related-regexp
  4818. (mapconcat #'identity
  4819. (append re-latex re-entities re-sub)
  4820. "\\|"))))
  4821. (defun org-do-latex-and-related (limit)
  4822. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4823. Stop at first highlighted object, if any. Return t if some
  4824. highlighting was done, nil otherwise."
  4825. (when (org-string-nw-p org-latex-and-related-regexp)
  4826. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4827. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4828. (catch 'found
  4829. (while (and (< (point) limit)
  4830. (re-search-forward org-latex-and-related-regexp nil t))
  4831. (cond
  4832. ((cl-some (lambda (f)
  4833. (memq f '(org-code org-verbatim underline
  4834. org-special-keyword)))
  4835. (save-excursion
  4836. (goto-char (1+ (match-beginning 0)))
  4837. (face-at-point nil t))))
  4838. ;; Try to limit false positives. In this case, ignore
  4839. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4840. ;; contain an empty line.
  4841. ((save-excursion
  4842. (goto-char (match-beginning 0))
  4843. (and (looking-at-p latex-prefix-re)
  4844. (save-match-data
  4845. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4846. (t
  4847. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4848. '(?_ ?^))
  4849. 1
  4850. 0))
  4851. (start (+ offset (match-beginning 0)))
  4852. (end (match-end 0)))
  4853. (if (memq 'native org-highlight-latex-and-related)
  4854. (org-src-font-lock-fontify-block "latex" start end)
  4855. (font-lock-prepend-text-property start end
  4856. 'face 'org-latex-and-related))
  4857. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4858. '(font-lock-multiline t))
  4859. (throw 'found t)))))
  4860. nil))))
  4861. (defun org-restart-font-lock ()
  4862. "Restart `font-lock-mode', to force refontification."
  4863. (when font-lock-mode
  4864. (font-lock-mode -1)
  4865. (font-lock-mode 1)))
  4866. (defun org-activate-tags (limit)
  4867. (when (re-search-forward org-tag-line-re limit t)
  4868. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4869. (add-text-properties (match-beginning 1) (match-end 1)
  4870. (list 'mouse-face 'highlight
  4871. 'keymap org-mouse-map))
  4872. (org-rear-nonsticky-at (match-end 1))
  4873. t))
  4874. (defun org-outline-level ()
  4875. "Compute the outline level of the heading at point.
  4876. If this is called at a normal headline, the level is the number
  4877. of stars. Use `org-reduced-level' to remove the effect of
  4878. `org-odd-levels'. Unlike to `org-current-level', this function
  4879. takes into consideration inlinetasks."
  4880. (org-with-wide-buffer
  4881. (end-of-line)
  4882. (if (re-search-backward org-outline-regexp-bol nil t)
  4883. (1- (- (match-end 0) (match-beginning 0)))
  4884. 0)))
  4885. (defvar org-font-lock-keywords nil)
  4886. (defsubst org-re-property (property &optional literal allow-null value)
  4887. "Return a regexp matching a PROPERTY line.
  4888. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4889. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4890. non-nil, match properties even without a value.
  4891. Match group 3 is set to the value when it exists. If there is no
  4892. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4893. With optional argument VALUE, match only property lines with
  4894. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4895. unless LITERAL is non-nil."
  4896. (concat
  4897. "^\\(?4:[ \t]*\\)"
  4898. (format "\\(?1::\\(?2:%s\\):\\)"
  4899. (if literal property (regexp-quote property)))
  4900. (cond (value
  4901. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4902. (if literal value (regexp-quote value))))
  4903. (allow-null
  4904. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4905. (t
  4906. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4907. (defconst org-property-re
  4908. (org-re-property "\\S-+" 'literal t)
  4909. "Regular expression matching a property line.
  4910. There are four matching groups:
  4911. 1: :PROPKEY: including the leading and trailing colon,
  4912. 2: PROPKEY without the leading and trailing colon,
  4913. 3: PROPVAL without leading or trailing spaces,
  4914. 4: the indentation of the current line,
  4915. 5: trailing whitespace.")
  4916. (defvar org-font-lock-hook nil
  4917. "Functions to be called for special font lock stuff.")
  4918. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4919. (defvar org-font-lock-set-keywords-hook nil
  4920. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4921. This is called after `org-font-lock-extra-keywords' is defined, but before
  4922. it is installed to be used by font lock. This can be useful if something
  4923. needs to be inserted at a specific position in the font-lock sequence.")
  4924. (defun org-font-lock-hook (limit)
  4925. "Run `org-font-lock-hook' within LIMIT."
  4926. (run-hook-with-args 'org-font-lock-hook limit))
  4927. (defun org-set-font-lock-defaults ()
  4928. "Set font lock defaults for the current buffer."
  4929. (let* ((em org-fontify-emphasized-text)
  4930. (lk org-highlight-links)
  4931. (org-font-lock-extra-keywords
  4932. (list
  4933. ;; Call the hook
  4934. '(org-font-lock-hook)
  4935. ;; Headlines
  4936. `(,(if org-fontify-whole-heading-line
  4937. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4938. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4939. (1 (org-get-level-face 1))
  4940. (2 (org-get-level-face 2))
  4941. (3 (org-get-level-face 3)))
  4942. ;; Table lines
  4943. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4944. (1 'org-table t))
  4945. ;; Table internals
  4946. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4947. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4948. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4949. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4950. ;; Properties
  4951. (list org-property-re
  4952. '(1 'org-special-keyword t)
  4953. '(3 'org-property-value t))
  4954. ;; Drawers
  4955. '(org-fontify-drawers)
  4956. ;; Link related fontification.
  4957. '(org-activate-links)
  4958. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4959. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4960. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4961. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4962. ;; Targets.
  4963. (list org-radio-target-regexp '(0 'org-target t))
  4964. (list org-target-regexp '(0 'org-target t))
  4965. ;; Diary sexps.
  4966. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4967. ;; Macro
  4968. '(org-fontify-macros)
  4969. ;; TODO keyword
  4970. (list (format org-heading-keyword-regexp-format
  4971. org-todo-regexp)
  4972. '(2 (org-get-todo-face 2) prepend))
  4973. ;; TODO
  4974. (when org-fontify-todo-headline
  4975. (list (format org-heading-keyword-regexp-format
  4976. (concat
  4977. "\\(?:"
  4978. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4979. "\\)"))
  4980. '(2 'org-headline-todo prepend)))
  4981. ;; DONE
  4982. (when org-fontify-done-headline
  4983. (list (format org-heading-keyword-regexp-format
  4984. (concat
  4985. "\\(?:"
  4986. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4987. "\\)"))
  4988. '(2 'org-headline-done prepend)))
  4989. ;; Priorities
  4990. '(org-font-lock-add-priority-faces)
  4991. ;; Tags
  4992. '(org-font-lock-add-tag-faces)
  4993. ;; Tags groups
  4994. (when (and org-group-tags org-tag-groups-alist)
  4995. (list (concat org-outline-regexp-bol ".+\\(:"
  4996. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4997. ":\\).*$")
  4998. '(1 'org-tag-group prepend)))
  4999. ;; Special keywords
  5000. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5001. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5002. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5003. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5004. ;; Emphasis
  5005. (when em '(org-do-emphasis-faces))
  5006. ;; Checkboxes
  5007. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5008. 1 'org-checkbox prepend)
  5009. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5010. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5011. (0 (org-get-checkbox-statistics-face) prepend)))
  5012. ;; Description list items
  5013. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5014. 1 'org-list-dt prepend)
  5015. ;; ARCHIVEd headings
  5016. (list (concat
  5017. org-outline-regexp-bol
  5018. "\\(.*:" org-archive-tag ":.*\\)")
  5019. '(1 'org-archived prepend))
  5020. ;; Specials
  5021. '(org-do-latex-and-related)
  5022. '(org-fontify-entities)
  5023. '(org-raise-scripts)
  5024. ;; Code
  5025. '(org-activate-code (1 'org-code t))
  5026. ;; COMMENT
  5027. (list (format
  5028. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5029. org-todo-regexp
  5030. org-comment-string)
  5031. '(9 'org-special-keyword t))
  5032. ;; Blocks and meta lines
  5033. '(org-fontify-meta-lines-and-blocks))))
  5034. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5035. (run-hooks 'org-font-lock-set-keywords-hook)
  5036. ;; Now set the full font-lock-keywords
  5037. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5038. (setq-local font-lock-defaults
  5039. '(org-font-lock-keywords t nil nil backward-paragraph))
  5040. (setq-local font-lock-extend-after-change-region-function
  5041. #'org-fontify-extend-region)
  5042. (kill-local-variable 'font-lock-keywords)
  5043. nil))
  5044. (defun org-toggle-pretty-entities ()
  5045. "Toggle the composition display of entities as UTF8 characters."
  5046. (interactive)
  5047. (setq-local org-pretty-entities (not org-pretty-entities))
  5048. (org-restart-font-lock)
  5049. (if org-pretty-entities
  5050. (message "Entities are now displayed as UTF8 characters")
  5051. (save-restriction
  5052. (widen)
  5053. (decompose-region (point-min) (point-max))
  5054. (message "Entities are now displayed as plain text"))))
  5055. (defvar-local org-custom-properties-overlays nil
  5056. "List of overlays used for custom properties.")
  5057. (defun org-toggle-custom-properties-visibility ()
  5058. "Display or hide properties in `org-custom-properties'."
  5059. (interactive)
  5060. (if org-custom-properties-overlays
  5061. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5062. (setq org-custom-properties-overlays nil))
  5063. (when org-custom-properties
  5064. (org-with-wide-buffer
  5065. (goto-char (point-min))
  5066. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5067. (while (re-search-forward regexp nil t)
  5068. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5069. (when (and end (< (point) end))
  5070. ;; Hide first custom property in current drawer.
  5071. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5072. (overlay-put o 'invisible t)
  5073. (overlay-put o 'org-custom-property t)
  5074. (push o org-custom-properties-overlays))
  5075. ;; Hide additional custom properties in the same drawer.
  5076. (while (re-search-forward regexp end t)
  5077. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5078. (overlay-put o 'invisible t)
  5079. (overlay-put o 'org-custom-property t)
  5080. (push o org-custom-properties-overlays)))))
  5081. ;; Each entry is limited to a single property drawer.
  5082. (outline-next-heading)))))))
  5083. (defun org-fontify-entities (limit)
  5084. "Find an entity to fontify."
  5085. (let (ee)
  5086. (when org-pretty-entities
  5087. (catch 'match
  5088. ;; "\_ "-family is left out on purpose. Only the first one,
  5089. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5090. ;; confusing when adding a second white space character.
  5091. (while (re-search-forward
  5092. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5093. limit t)
  5094. (when (and (not (org-at-comment-p))
  5095. (setq ee (org-entity-get (match-string 1)))
  5096. (= (length (nth 6 ee)) 1))
  5097. (let* ((end (if (equal (match-string 2) "{}")
  5098. (match-end 2)
  5099. (match-end 1))))
  5100. (add-text-properties
  5101. (match-beginning 0) end
  5102. (list 'font-lock-fontified t))
  5103. (compose-region (match-beginning 0) end
  5104. (nth 6 ee) nil)
  5105. (backward-char 1)
  5106. (throw 'match t))))
  5107. nil))))
  5108. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5109. "Fontify string S like in Org mode."
  5110. (with-temp-buffer
  5111. (insert s)
  5112. (let ((org-odd-levels-only odd-levels))
  5113. (org-mode)
  5114. (org-font-lock-ensure)
  5115. (buffer-string))))
  5116. (defun org-get-level-face (n)
  5117. "Get the right face for match N in font-lock matching of headlines."
  5118. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5119. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5120. (org-f (if org-cycle-level-faces
  5121. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5122. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5123. (cond
  5124. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5125. ((eq n 2) org-f)
  5126. (t (unless org-level-color-stars-only org-f)))))
  5127. (defun org-face-from-face-or-color (context inherit face-or-color)
  5128. "Create a face list that inherits INHERIT, but sets the foreground color.
  5129. When FACE-OR-COLOR is not a string, just return it."
  5130. (if (stringp face-or-color)
  5131. (list :inherit inherit
  5132. (cdr (assoc context org-faces-easy-properties))
  5133. face-or-color)
  5134. face-or-color))
  5135. (defun org-get-todo-face (kwd)
  5136. "Get the right face for a TODO keyword KWD.
  5137. If KWD is a number, get the corresponding match group."
  5138. (when (numberp kwd) (setq kwd (match-string kwd)))
  5139. (or (org-face-from-face-or-color
  5140. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5141. (and (member kwd org-done-keywords) 'org-done)
  5142. 'org-todo))
  5143. (defun org-get-priority-face (priority)
  5144. "Get the right face for PRIORITY.
  5145. PRIORITY is a character."
  5146. (or (org-face-from-face-or-color
  5147. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5148. 'org-priority))
  5149. (defun org-get-tag-face (tag)
  5150. "Get the right face for TAG.
  5151. If TAG is a number, get the corresponding match group."
  5152. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5153. (or (org-face-from-face-or-color
  5154. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5155. 'org-tag)))
  5156. (defvar org-priority-regexp) ; defined later in the file
  5157. (defun org-font-lock-add-priority-faces (limit)
  5158. "Add the special priority faces."
  5159. (while (re-search-forward org-priority-regexp limit t)
  5160. (let ((beg (match-beginning 1))
  5161. (end (1+ (match-end 2))))
  5162. (add-face-text-property
  5163. beg end
  5164. (org-get-priority-face (string-to-char (match-string 2))))
  5165. (add-text-properties
  5166. beg end
  5167. (list 'font-lock-fontified t)))))
  5168. (defun org-font-lock-add-tag-faces (limit)
  5169. "Add the special tag faces."
  5170. (when (and org-tag-faces org-tags-special-faces-re)
  5171. (while (re-search-forward org-tags-special-faces-re limit t)
  5172. (add-face-text-property
  5173. (match-beginning 1)
  5174. (match-end 1)
  5175. (org-get-tag-face 1))
  5176. (add-text-properties (match-beginning 1) (match-end 1)
  5177. (list 'font-lock-fontified t))
  5178. (backward-char 1))))
  5179. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5180. "Remove fontification and activation overlays from links."
  5181. (font-lock-default-unfontify-region beg end)
  5182. (let* ((buffer-undo-list t)
  5183. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5184. (inhibit-modification-hooks t)
  5185. deactivate-mark buffer-file-name buffer-file-truename)
  5186. (decompose-region beg end)
  5187. (remove-text-properties beg end
  5188. '(mouse-face t keymap t org-linked-text t
  5189. invisible t intangible t
  5190. org-emphasis t))
  5191. (org-remove-font-lock-display-properties beg end)))
  5192. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5193. ((raise 0.3) (height 0.7))
  5194. ((raise -0.5))
  5195. ((raise 0.5)))
  5196. "Display properties for showing superscripts and subscripts.")
  5197. (defun org-remove-font-lock-display-properties (beg end)
  5198. "Remove specific display properties that have been added by font lock.
  5199. The will remove the raise properties that are used to show superscripts
  5200. and subscripts."
  5201. (let (next prop)
  5202. (while (< beg end)
  5203. (setq next (next-single-property-change beg 'display nil end)
  5204. prop (get-text-property beg 'display))
  5205. (when (member prop org-script-display)
  5206. (put-text-property beg next 'display nil))
  5207. (setq beg next))))
  5208. (defun org-raise-scripts (limit)
  5209. "Add raise properties to sub/superscripts."
  5210. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5211. (re-search-forward
  5212. (if (eq org-use-sub-superscripts t)
  5213. org-match-substring-regexp
  5214. org-match-substring-with-braces-regexp)
  5215. limit t))
  5216. (let* ((pos (point)) table-p comment-p
  5217. (mpos (match-beginning 3))
  5218. (emph-p (get-text-property mpos 'org-emphasis))
  5219. (link-p (get-text-property mpos 'mouse-face))
  5220. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5221. (goto-char (point-at-bol))
  5222. (setq table-p (looking-at-p org-table-dataline-regexp)
  5223. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5224. (goto-char pos)
  5225. ;; Handle a_b^c
  5226. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5227. (unless (or comment-p emph-p link-p keyw-p)
  5228. (put-text-property (match-beginning 3) (match-end 0)
  5229. 'display
  5230. (if (equal (char-after (match-beginning 2)) ?^)
  5231. (nth (if table-p 3 1) org-script-display)
  5232. (nth (if table-p 2 0) org-script-display)))
  5233. (add-text-properties (match-beginning 2) (match-end 2)
  5234. (list 'invisible t))
  5235. (when (and (eq (char-after (match-beginning 3)) ?{)
  5236. (eq (char-before (match-end 3)) ?}))
  5237. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5238. (list 'invisible t))
  5239. (add-text-properties (1- (match-end 3)) (match-end 3)
  5240. (list 'invisible t))))
  5241. t)))
  5242. (defun org-remove-empty-overlays-at (pos)
  5243. "Remove outline overlays that do not contain non-white stuff."
  5244. (dolist (o (overlays-at pos))
  5245. (and (eq 'outline (overlay-get o 'invisible))
  5246. (not (string-match-p "\\S-" (buffer-substring (overlay-start o)
  5247. (overlay-end o))))
  5248. (delete-overlay o))))
  5249. (defun org-show-empty-lines-in-parent ()
  5250. "Move to the parent and re-show empty lines before visible headlines."
  5251. (save-excursion
  5252. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5253. (org-cycle-show-empty-lines context))))
  5254. (defun org-files-list ()
  5255. "Return `org-agenda-files' list, plus all open Org files.
  5256. This is useful for operations that need to scan all of a user's
  5257. open and agenda-wise Org files."
  5258. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5259. (dolist (buf (buffer-list))
  5260. (with-current-buffer buf
  5261. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5262. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5263. :test #'equal))))
  5264. files))
  5265. (defsubst org-entry-beginning-position ()
  5266. "Return the beginning position of the current entry."
  5267. (save-excursion (org-back-to-heading t) (point)))
  5268. (defsubst org-entry-end-position ()
  5269. "Return the end position of the current entry."
  5270. (save-excursion (outline-next-heading) (point)))
  5271. (defun org-subtree-end-visible-p ()
  5272. "Is the end of the current subtree visible?"
  5273. (pos-visible-in-window-p
  5274. (save-excursion (org-end-of-subtree t) (point))))
  5275. (defun org-first-headline-recenter ()
  5276. "Move cursor to the first headline and recenter the headline."
  5277. (let ((window (get-buffer-window)))
  5278. (when window
  5279. (goto-char (point-min))
  5280. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5281. (set-window-start window (line-beginning-position))))))
  5282. ;;; Visibility (headlines, blocks, drawers)
  5283. ;;;; Headlines visibility
  5284. (defun org-show-entry ()
  5285. "Show the body directly following its heading.
  5286. Show the heading too, if it is currently invisible."
  5287. (interactive)
  5288. (save-excursion
  5289. (org-back-to-heading-or-point-min t)
  5290. (org-flag-region
  5291. (line-end-position 0)
  5292. (save-excursion
  5293. (if (re-search-forward
  5294. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5295. (match-beginning 1)
  5296. (point-max)))
  5297. nil
  5298. 'outline)
  5299. (org-cycle-hide-drawers 'children)))
  5300. (defun org-hide-entry ()
  5301. "Hide the body directly following its heading."
  5302. (interactive)
  5303. (save-excursion
  5304. (org-back-to-heading-or-point-min t)
  5305. (when (org-at-heading-p) (forward-line))
  5306. (org-flag-region
  5307. (line-end-position 0)
  5308. (save-excursion
  5309. (if (re-search-forward
  5310. (concat "[\r\n]" org-outline-regexp) nil t)
  5311. (line-end-position 0)
  5312. (point-max)))
  5313. t
  5314. 'outline)))
  5315. (defun org-show-children (&optional level)
  5316. "Show all direct subheadings of this heading.
  5317. Prefix arg LEVEL is how many levels below the current level
  5318. should be shown. Default is enough to cause the following
  5319. heading to appear."
  5320. (interactive "p")
  5321. (unless (org-before-first-heading-p)
  5322. (save-excursion
  5323. (org-with-limited-levels (org-back-to-heading t))
  5324. (let* ((current-level (funcall outline-level))
  5325. (max-level (org-get-valid-level
  5326. current-level
  5327. (if level (prefix-numeric-value level) 1)))
  5328. (end (save-excursion (org-end-of-subtree t t)))
  5329. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5330. (past-first-child nil)
  5331. ;; Make sure to skip inlinetasks.
  5332. (re (format regexp-fmt
  5333. current-level
  5334. (cond
  5335. ((not (featurep 'org-inlinetask)) "")
  5336. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5337. 3))
  5338. (t (1- org-inlinetask-min-level))))))
  5339. ;; Display parent heading.
  5340. (org-flag-heading nil)
  5341. (forward-line)
  5342. ;; Display children. First child may be deeper than expected
  5343. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5344. ;; MAX-LEVEL accordingly.
  5345. (while (re-search-forward re end t)
  5346. (unless past-first-child
  5347. (setq re (format regexp-fmt
  5348. current-level
  5349. (max (funcall outline-level) max-level)))
  5350. (setq past-first-child t))
  5351. (org-flag-heading nil))))))
  5352. (defun org-show-subtree ()
  5353. "Show everything after this heading at deeper levels."
  5354. (interactive)
  5355. (org-flag-region
  5356. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5357. ;;;; Blocks and drawers visibility
  5358. (defun org--hide-wrapper-toggle (element category force no-error)
  5359. "Toggle visibility for ELEMENT.
  5360. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5361. either `block' or `drawer'. When FORCE is `off', show the block
  5362. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5363. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5364. Return a non-nil value when toggling is successful."
  5365. (let ((type (org-element-type element)))
  5366. (cond
  5367. ((memq type
  5368. (pcase category
  5369. (`drawer '(drawer property-drawer))
  5370. (`block '(center-block
  5371. comment-block dynamic-block example-block export-block
  5372. quote-block special-block src-block verse-block))
  5373. (_ (error "Unknown category: %S" category))))
  5374. (let* ((post (org-element-property :post-affiliated element))
  5375. (start (save-excursion
  5376. (goto-char post)
  5377. (line-end-position)))
  5378. (end (save-excursion
  5379. (goto-char (org-element-property :end element))
  5380. (skip-chars-backward " \t\n")
  5381. (line-end-position))))
  5382. ;; Do nothing when not before or at the block opening line or
  5383. ;; at the block closing line.
  5384. (unless (let ((eol (line-end-position)))
  5385. (and (> eol start) (/= eol end)))
  5386. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5387. (flag
  5388. (cond ((eq force 'off) nil)
  5389. (force t)
  5390. ((eq spec (get-char-property start 'invisible)) nil)
  5391. (t t))))
  5392. (org-flag-region start end flag spec))
  5393. ;; When the block is hidden away, make sure point is left in
  5394. ;; a visible part of the buffer.
  5395. (when (invisible-p (max (1- (point)) (point-min)))
  5396. (goto-char post))
  5397. ;; Signal success.
  5398. t)))
  5399. (no-error nil)
  5400. (t
  5401. (user-error (if (eq category 'drawer)
  5402. "Not at a drawer"
  5403. "Not at a block"))))))
  5404. (defun org-hide-block-toggle (&optional force no-error element)
  5405. "Toggle the visibility of the current block.
  5406. When optional argument FORCE is `off', make block visible. If it
  5407. is non-nil, hide it unconditionally. Throw an error when not at
  5408. a block, unless NO-ERROR is non-nil. When optional argument
  5409. ELEMENT is provided, consider it instead of the current block.
  5410. Return a non-nil value when toggling is successful."
  5411. (interactive)
  5412. (org--hide-wrapper-toggle
  5413. (or element (org-element-at-point)) 'block force no-error))
  5414. (defun org-hide-drawer-toggle (&optional force no-error element)
  5415. "Toggle the visibility of the current drawer.
  5416. When optional argument FORCE is `off', make drawer visible. If
  5417. it is non-nil, hide it unconditionally. Throw an error when not
  5418. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5419. ELEMENT is provided, consider it instead of the current drawer.
  5420. Return a non-nil value when toggling is successful."
  5421. (interactive)
  5422. (org--hide-wrapper-toggle
  5423. (or element (org-element-at-point)) 'drawer force no-error))
  5424. (defun org-hide-block-all ()
  5425. "Fold all blocks in the current buffer."
  5426. (interactive)
  5427. (org-show-all '(blocks))
  5428. (org-block-map 'org-hide-block-toggle))
  5429. (defun org-hide-drawer-all ()
  5430. "Fold all drawers in the current buffer."
  5431. (let ((begin (point-min))
  5432. (end (point-max)))
  5433. (org--hide-drawers begin end)))
  5434. (defun org-cycle-hide-drawers (state)
  5435. "Re-hide all drawers after a visibility state change.
  5436. STATE should be one of the symbols listed in the docstring of
  5437. `org-cycle-hook'."
  5438. (when (derived-mode-p 'org-mode)
  5439. (cond ((not (memq state '(overview folded contents)))
  5440. (let* ((global? (eq state 'all))
  5441. (beg (if global? (point-min) (line-beginning-position)))
  5442. (end (cond (global? (point-max))
  5443. ((eq state 'children) (org-entry-end-position))
  5444. (t (save-excursion (org-end-of-subtree t t))))))
  5445. (org--hide-drawers beg end)))
  5446. ((memq state '(overview contents))
  5447. ;; Hide drawers before first heading.
  5448. (let ((beg (point-min))
  5449. (end (save-excursion
  5450. (goto-char (point-min))
  5451. (if (org-before-first-heading-p)
  5452. (org-entry-end-position)
  5453. (point-min)))))
  5454. (when (< beg end)
  5455. (org--hide-drawers beg end)))))))
  5456. (defun org--hide-drawers (begin end)
  5457. "Hide all drawers between BEGIN and END."
  5458. (save-excursion
  5459. (goto-char begin)
  5460. (while (re-search-forward org-drawer-regexp end t)
  5461. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5462. 'invisible))
  5463. (o (cdr-safe pair)))
  5464. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5465. (pcase (get-char-property-and-overlay (point) 'invisible)
  5466. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5467. (_
  5468. (let* ((drawer (org-element-at-point))
  5469. (type (org-element-type drawer)))
  5470. (when (memq type '(drawer property-drawer))
  5471. (org-hide-drawer-toggle t nil drawer)
  5472. ;; Make sure to skip drawer entirely or we might flag it
  5473. ;; another time when matching its ending line with
  5474. ;; `org-drawer-regexp'.
  5475. (goto-char (org-element-property :end drawer)))))))))))
  5476. ;;;; Visibility cycling
  5477. (defvar-local org-cycle-global-status nil)
  5478. (put 'org-cycle-global-status 'org-state t)
  5479. (defvar-local org-cycle-subtree-status nil)
  5480. (put 'org-cycle-subtree-status 'org-state t)
  5481. (defun org-show-all (&optional types)
  5482. "Show all contents in the visible part of the buffer.
  5483. By default, the function expands headings, blocks and drawers.
  5484. When optional argument TYPE is a list of symbols among `blocks',
  5485. `drawers' and `headings', to only expand one specific type."
  5486. (interactive)
  5487. (let ((types (or types '(blocks drawers headings))))
  5488. (when (memq 'blocks types)
  5489. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5490. (cond
  5491. ;; Fast path. Since headings and drawers share the same
  5492. ;; invisible spec, clear everything in one go.
  5493. ((and (memq 'headings types)
  5494. (memq 'drawers types))
  5495. (org-flag-region (point-min) (point-max) nil 'outline))
  5496. ((memq 'headings types)
  5497. (org-flag-region (point-min) (point-max) nil 'outline)
  5498. (org-cycle-hide-drawers 'all))
  5499. ((memq 'drawers types)
  5500. (save-excursion
  5501. (goto-char (point-min))
  5502. (while (re-search-forward org-drawer-regexp nil t)
  5503. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5504. 'invisible))
  5505. (o (cdr-safe pair)))
  5506. (if (overlayp o) (goto-char (overlay-end o))
  5507. (pcase (get-char-property-and-overlay (point) 'invisible)
  5508. (`(outline . ,o)
  5509. (goto-char (overlay-end o))
  5510. (delete-overlay o))
  5511. (_ nil))))))))))
  5512. ;;;###autoload
  5513. (defun org-cycle (&optional arg)
  5514. "TAB-action and visibility cycling for Org mode.
  5515. This is the command invoked in Org mode by the `TAB' key. Its main
  5516. purpose is outline visibility cycling, but it also invokes other actions
  5517. in special contexts.
  5518. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5519. the entire
  5520. buffer through 3 states (global cycling)
  5521. 1. OVERVIEW: Show only top-level headlines.
  5522. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5523. 3. SHOW ALL: Show everything.
  5524. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5525. switch to the startup visibility,
  5526. determined by the variable `org-startup-folded', and by any VISIBILITY
  5527. properties in the buffer.
  5528. With a `\\[universal-argument] \\[universal-argument] \
  5529. \\[universal-argument]' prefix argument, show the entire buffer, including
  5530. any drawers.
  5531. When inside a table, re-align the table and move to the next field.
  5532. When point is at the beginning of a headline, rotate the subtree started
  5533. by this line through 3 different states (local cycling)
  5534. 1. FOLDED: Only the main headline is shown.
  5535. 2. CHILDREN: The main headline and the direct children are shown.
  5536. From this state, you can move to one of the children
  5537. and zoom in further.
  5538. 3. SUBTREE: Show the entire subtree, including body text.
  5539. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5540. When point is at the beginning of an empty headline and the variable
  5541. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5542. of the headline by demoting and promoting it to likely levels. This
  5543. speeds up creation document structure by pressing `TAB' once or several
  5544. times right after creating a new headline.
  5545. When there is a numeric prefix, go up to a heading with level ARG, do
  5546. a `show-subtree' and return to the previous cursor position. If ARG
  5547. is negative, go up that many levels.
  5548. When point is not at the beginning of a headline, execute the global
  5549. binding for `TAB', which is re-indenting the line. See the option
  5550. `org-cycle-emulate-tab' for details.
  5551. As a special case, if point is at the very beginning of the buffer, if
  5552. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5553. is non-nil, this function acts as if called with prefix argument \
  5554. \(`\\[universal-argument] TAB',
  5555. same as `S-TAB') also when called without prefix argument."
  5556. (interactive "P")
  5557. (org-load-modules-maybe)
  5558. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5559. (and org-cycle-level-after-item/entry-creation
  5560. (or (org-cycle-level)
  5561. (org-cycle-item-indentation))))
  5562. (let* ((limit-level
  5563. (or org-cycle-max-level
  5564. (and (boundp 'org-inlinetask-min-level)
  5565. org-inlinetask-min-level
  5566. (1- org-inlinetask-min-level))))
  5567. (nstars
  5568. (and limit-level
  5569. (if org-odd-levels-only
  5570. (1- (* 2 limit-level))
  5571. limit-level)))
  5572. (org-outline-regexp
  5573. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5574. (cond
  5575. ((equal arg '(16))
  5576. (setq last-command 'dummy)
  5577. (org-set-startup-visibility)
  5578. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5579. ((equal arg '(64))
  5580. (org-show-all)
  5581. (org-unlogged-message "Entire buffer visible, including drawers"))
  5582. ((equal arg '(4)) (org-cycle-internal-global))
  5583. ;; Show-subtree, ARG levels up from here.
  5584. ((integerp arg)
  5585. (save-excursion
  5586. (org-back-to-heading)
  5587. (outline-up-heading (if (< arg 0) (- arg)
  5588. (- (funcall outline-level) arg)))
  5589. (org-show-subtree)))
  5590. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5591. ((and org-cycle-global-at-bob
  5592. (bobp)
  5593. (not (looking-at org-outline-regexp)))
  5594. (let ((org-cycle-hook
  5595. (remq 'org-optimize-window-after-visibility-change
  5596. org-cycle-hook)))
  5597. (org-cycle-internal-global)))
  5598. ;; Try CDLaTeX TAB completion.
  5599. ((org-try-cdlatex-tab))
  5600. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5601. ((and (featurep 'org-inlinetask)
  5602. (org-inlinetask-at-task-p)
  5603. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5604. (org-inlinetask-toggle-visibility))
  5605. (t
  5606. (let ((pos (point))
  5607. (element (org-element-at-point)))
  5608. (cond
  5609. ;; Try toggling visibility for block at point.
  5610. ((org-hide-block-toggle nil t element))
  5611. ;; Try toggling visibility for drawer at point.
  5612. ((org-hide-drawer-toggle nil t element))
  5613. ;; Table: enter it or move to the next field.
  5614. ((and (org-match-line "[ \t]*[|+]")
  5615. (org-element-lineage element '(table) t))
  5616. (if (and (eq 'table (org-element-type element))
  5617. (eq 'table.el (org-element-property :type element)))
  5618. (message (substitute-command-keys "\\<org-mode-map>\
  5619. Use `\\[org-edit-special]' to edit table.el tables"))
  5620. (org-table-justify-field-maybe)
  5621. (call-interactively #'org-table-next-field)))
  5622. ((run-hook-with-args-until-success
  5623. 'org-tab-after-check-for-table-hook))
  5624. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5625. ((and (or (and org-cycle-include-plain-lists
  5626. (let ((item (org-element-lineage element
  5627. '(item plain-list)
  5628. t)))
  5629. (and item
  5630. (= (line-beginning-position)
  5631. (org-element-property :post-affiliated
  5632. item)))))
  5633. (org-match-line org-outline-regexp))
  5634. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5635. (org-cycle-internal-local))
  5636. ;; From there: TAB emulation and template completion.
  5637. (buffer-read-only (org-back-to-heading))
  5638. ((run-hook-with-args-until-success
  5639. 'org-tab-after-check-for-cycling-hook))
  5640. ((run-hook-with-args-until-success
  5641. 'org-tab-before-tab-emulation-hook))
  5642. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5643. (or (not (bolp))
  5644. (not (looking-at org-outline-regexp))))
  5645. (call-interactively (global-key-binding (kbd "TAB"))))
  5646. ((or (eq org-cycle-emulate-tab t)
  5647. (and (memq org-cycle-emulate-tab '(white whitestart))
  5648. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5649. (or (and (eq org-cycle-emulate-tab 'white)
  5650. (= (match-end 0) (point-at-eol)))
  5651. (and (eq org-cycle-emulate-tab 'whitestart)
  5652. (>= (match-end 0) pos)))))
  5653. (call-interactively (global-key-binding (kbd "TAB"))))
  5654. (t
  5655. (save-excursion
  5656. (org-back-to-heading)
  5657. (org-cycle))))))))))
  5658. (defun org-cycle-internal-global ()
  5659. "Do the global cycling action."
  5660. ;; Hack to avoid display of messages for .org attachments in Gnus
  5661. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5662. (cond
  5663. ((and (eq last-command this-command)
  5664. (eq org-cycle-global-status 'overview))
  5665. ;; We just created the overview - now do table of contents
  5666. ;; This can be slow in very large buffers, so indicate action
  5667. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5668. (unless ga (org-unlogged-message "CONTENTS..."))
  5669. (org-content)
  5670. (unless ga (org-unlogged-message "CONTENTS...done"))
  5671. (setq org-cycle-global-status 'contents)
  5672. (run-hook-with-args 'org-cycle-hook 'contents))
  5673. ((and (eq last-command this-command)
  5674. (eq org-cycle-global-status 'contents))
  5675. ;; We just showed the table of contents - now show everything
  5676. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5677. (org-show-all '(headings blocks))
  5678. (unless ga (org-unlogged-message "SHOW ALL"))
  5679. (setq org-cycle-global-status 'all)
  5680. (run-hook-with-args 'org-cycle-hook 'all))
  5681. (t
  5682. ;; Default action: go to overview
  5683. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5684. (org-overview)
  5685. (unless ga (org-unlogged-message "OVERVIEW"))
  5686. (setq org-cycle-global-status 'overview)
  5687. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5688. (defvar org-called-with-limited-levels nil
  5689. "Non-nil when `org-with-limited-levels' is currently active.")
  5690. (defun org-cycle-internal-local ()
  5691. "Do the local cycling action."
  5692. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5693. ;; First, determine end of headline (EOH), end of subtree or item
  5694. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5695. (save-excursion
  5696. (if (org-at-item-p)
  5697. (progn
  5698. (beginning-of-line)
  5699. (setq struct (org-list-struct))
  5700. (setq eoh (point-at-eol))
  5701. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5702. (setq has-children (org-list-has-child-p (point) struct)))
  5703. (org-back-to-heading)
  5704. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5705. (setq eos (save-excursion
  5706. (org-end-of-subtree t t)
  5707. (unless (eobp) (forward-char -1))
  5708. (point)))
  5709. (setq has-children
  5710. (or
  5711. (save-excursion
  5712. (let ((level (funcall outline-level)))
  5713. (outline-next-heading)
  5714. (and (org-at-heading-p t)
  5715. (> (funcall outline-level) level))))
  5716. (and (eq org-cycle-include-plain-lists 'integrate)
  5717. (save-excursion
  5718. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5719. ;; Determine end invisible part of buffer (EOL)
  5720. (beginning-of-line 2)
  5721. (while (and (not (eobp)) ;this is like `next-line'
  5722. (get-char-property (1- (point)) 'invisible))
  5723. (goto-char (next-single-char-property-change (point) 'invisible))
  5724. (and (eolp) (beginning-of-line 2)))
  5725. (setq eol (point)))
  5726. ;; Find out what to do next and set `this-command'
  5727. (cond
  5728. ((= eos eoh)
  5729. ;; Nothing is hidden behind this heading
  5730. (unless (org-before-first-heading-p)
  5731. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5732. (org-unlogged-message "EMPTY ENTRY")
  5733. (setq org-cycle-subtree-status nil)
  5734. (save-excursion
  5735. (goto-char eos)
  5736. (outline-next-heading)
  5737. (when (org-invisible-p) (org-flag-heading nil))))
  5738. ((and (or (>= eol eos)
  5739. (not (string-match "\\S-" (buffer-substring eol eos))))
  5740. (or has-children
  5741. (not (setq children-skipped
  5742. org-cycle-skip-children-state-if-no-children))))
  5743. ;; Entire subtree is hidden in one line: children view
  5744. (unless (org-before-first-heading-p)
  5745. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5746. (if (org-at-item-p)
  5747. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5748. (org-show-entry)
  5749. (org-with-limited-levels (org-show-children))
  5750. (org-show-set-visibility 'canonical)
  5751. ;; Fold every list in subtree to top-level items.
  5752. (when (eq org-cycle-include-plain-lists 'integrate)
  5753. (save-excursion
  5754. (org-back-to-heading)
  5755. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5756. (beginning-of-line 1)
  5757. (let* ((struct (org-list-struct))
  5758. (prevs (org-list-prevs-alist struct))
  5759. (end (org-list-get-bottom-point struct)))
  5760. (dolist (e (org-list-get-all-items (point) struct prevs))
  5761. (org-list-set-item-visibility e struct 'folded))
  5762. (goto-char (if (< end eos) end eos)))))))
  5763. (org-unlogged-message "CHILDREN")
  5764. (save-excursion
  5765. (goto-char eos)
  5766. (outline-next-heading)
  5767. (when (org-invisible-p) (org-flag-heading nil)))
  5768. (setq org-cycle-subtree-status 'children)
  5769. (unless (org-before-first-heading-p)
  5770. (run-hook-with-args 'org-cycle-hook 'children)))
  5771. ((or children-skipped
  5772. (and (eq last-command this-command)
  5773. (eq org-cycle-subtree-status 'children)))
  5774. ;; We just showed the children, or no children are there,
  5775. ;; now show everything.
  5776. (unless (org-before-first-heading-p)
  5777. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5778. (org-flag-region eoh eos nil 'outline)
  5779. (org-unlogged-message
  5780. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5781. (setq org-cycle-subtree-status 'subtree)
  5782. (unless (org-before-first-heading-p)
  5783. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5784. (t
  5785. ;; Default action: hide the subtree.
  5786. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5787. (org-flag-region eoh eos t 'outline)
  5788. (org-unlogged-message "FOLDED")
  5789. (setq org-cycle-subtree-status 'folded)
  5790. (unless (org-before-first-heading-p)
  5791. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5792. ;;;###autoload
  5793. (defun org-global-cycle (&optional arg)
  5794. "Cycle the global visibility. For details see `org-cycle'.
  5795. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5796. With a numeric prefix, show all headlines up to that level."
  5797. (interactive "P")
  5798. (cond
  5799. ((integerp arg)
  5800. (org-content arg)
  5801. (setq org-cycle-global-status 'contents))
  5802. ((equal arg '(4))
  5803. (org-set-startup-visibility)
  5804. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5805. (t
  5806. (org-cycle '(4)))))
  5807. (defun org-set-startup-visibility ()
  5808. "Set the visibility required by startup options and properties."
  5809. (cond
  5810. ((eq org-startup-folded t)
  5811. (org-overview))
  5812. ((eq org-startup-folded 'content)
  5813. (org-content))
  5814. ((eq org-startup-folded 'show2levels)
  5815. (org-content 2))
  5816. ((eq org-startup-folded 'show3levels)
  5817. (org-content 3))
  5818. ((eq org-startup-folded 'show4levels)
  5819. (org-content 4))
  5820. ((eq org-startup-folded 'show5levels)
  5821. (org-content 5))
  5822. ((or (eq org-startup-folded 'showeverything)
  5823. (eq org-startup-folded nil))
  5824. (org-show-all)))
  5825. (unless (eq org-startup-folded 'showeverything)
  5826. (when org-hide-block-startup (org-hide-block-all))
  5827. (org-set-visibility-according-to-property)
  5828. (org-cycle-hide-archived-subtrees 'all)
  5829. (org-cycle-hide-drawers 'all)
  5830. (org-cycle-show-empty-lines t)))
  5831. (defun org-set-visibility-according-to-property ()
  5832. "Switch subtree visibility according to VISIBILITY property."
  5833. (interactive)
  5834. (let ((regexp (org-re-property "VISIBILITY")))
  5835. (org-with-point-at 1
  5836. (while (re-search-forward regexp nil t)
  5837. (let ((state (match-string 3)))
  5838. (if (not (org-at-property-p)) (outline-next-heading)
  5839. (save-excursion
  5840. (org-back-to-heading t)
  5841. (org-flag-subtree t)
  5842. (org-reveal)
  5843. (pcase state
  5844. ("folded"
  5845. (org-flag-subtree t))
  5846. ("children"
  5847. (org-show-hidden-entry)
  5848. (org-show-children))
  5849. ("content"
  5850. (save-excursion
  5851. (save-restriction
  5852. (org-narrow-to-subtree)
  5853. (org-content))))
  5854. ((or "all" "showall")
  5855. (outline-show-subtree))
  5856. (_ nil)))
  5857. (org-end-of-subtree)))))))
  5858. (defun org-overview ()
  5859. "Switch to overview mode, showing only top-level headlines."
  5860. (interactive)
  5861. (org-show-all '(headings drawers))
  5862. (save-excursion
  5863. (goto-char (point-min))
  5864. (when (re-search-forward org-outline-regexp-bol nil t)
  5865. (let* ((last (line-end-position))
  5866. (level (- (match-end 0) (match-beginning 0) 1))
  5867. (regexp (format "^\\*\\{1,%d\\} " level)))
  5868. (while (re-search-forward regexp nil :move)
  5869. (org-flag-region last (line-end-position 0) t 'outline)
  5870. (setq last (line-end-position))
  5871. (setq level (- (match-end 0) (match-beginning 0) 1))
  5872. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5873. (org-flag-region last (point) t 'outline)))))
  5874. (defun org-content (&optional arg)
  5875. "Show all headlines in the buffer, like a table of contents.
  5876. With numerical argument N, show content up to level N."
  5877. (interactive "p")
  5878. (org-show-all '(headings drawers))
  5879. (save-excursion
  5880. (goto-char (point-max))
  5881. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5882. (format "^\\*\\{1,%d\\} " arg)
  5883. "^\\*+ "))
  5884. (last (point)))
  5885. (while (re-search-backward regexp nil t)
  5886. (org-flag-region (line-end-position) last t 'outline)
  5887. (setq last (line-end-position 0))))))
  5888. (defvar org-scroll-position-to-restore nil
  5889. "Temporarily store scroll position to restore.")
  5890. (defun org-optimize-window-after-visibility-change (state)
  5891. "Adjust the window after a change in outline visibility.
  5892. This function is the default value of the hook `org-cycle-hook'."
  5893. (when (get-buffer-window (current-buffer))
  5894. (let ((repeat (eq last-command this-command)))
  5895. (unless repeat
  5896. (setq org-scroll-position-to-restore nil))
  5897. (cond
  5898. ((eq state 'content) nil)
  5899. ((eq state 'all) nil)
  5900. ((and org-scroll-position-to-restore repeat
  5901. (eq state 'folded))
  5902. (set-window-start nil org-scroll-position-to-restore))
  5903. ((eq state 'folded) nil)
  5904. ((eq state 'children)
  5905. (setq org-scroll-position-to-restore (window-start))
  5906. (or (org-subtree-end-visible-p) (recenter 1)))
  5907. ((eq state 'subtree)
  5908. (unless repeat
  5909. (setq org-scroll-position-to-restore (window-start)))
  5910. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5911. (defun org-clean-visibility-after-subtree-move ()
  5912. "Fix visibility issues after moving a subtree."
  5913. ;; First, find a reasonable region to look at:
  5914. ;; Start two siblings above, end three below
  5915. (let* ((beg (save-excursion
  5916. (and (org-get-last-sibling)
  5917. (org-get-last-sibling))
  5918. (point)))
  5919. (end (save-excursion
  5920. (and (org-get-next-sibling)
  5921. (org-get-next-sibling)
  5922. (org-get-next-sibling))
  5923. (if (org-at-heading-p)
  5924. (point-at-eol)
  5925. (point))))
  5926. (level (looking-at "\\*+"))
  5927. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5928. (save-excursion
  5929. (save-restriction
  5930. (narrow-to-region beg end)
  5931. (when re
  5932. ;; Properly fold already folded siblings
  5933. (goto-char (point-min))
  5934. (while (re-search-forward re nil t)
  5935. (when (and (not (org-invisible-p))
  5936. (org-invisible-p (line-end-position)))
  5937. (outline-hide-entry))))
  5938. (org-cycle-hide-drawers 'all)
  5939. (org-cycle-show-empty-lines 'overview)))))
  5940. (defun org-cycle-show-empty-lines (state)
  5941. "Show empty lines above all visible headlines.
  5942. The region to be covered depends on STATE when called through
  5943. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5944. entire buffer covered. Note that an empty line is only shown if there
  5945. are at least `org-cycle-separator-lines' empty lines before the headline."
  5946. (when (/= org-cycle-separator-lines 0)
  5947. (save-excursion
  5948. (let* ((n (abs org-cycle-separator-lines))
  5949. (re (cond
  5950. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5951. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5952. (t (let ((ns (number-to-string (- n 2))))
  5953. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5954. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5955. beg end)
  5956. (cond
  5957. ((memq state '(overview contents t))
  5958. (setq beg (point-min) end (point-max)))
  5959. ((memq state '(children folded))
  5960. (setq beg (point)
  5961. end (progn (org-end-of-subtree t t)
  5962. (line-beginning-position 2)))))
  5963. (when beg
  5964. (goto-char beg)
  5965. (while (re-search-forward re end t)
  5966. (unless (get-char-property (match-end 1) 'invisible)
  5967. (let ((e (match-end 1))
  5968. (b (if (>= org-cycle-separator-lines 0)
  5969. (match-beginning 1)
  5970. (save-excursion
  5971. (goto-char (match-beginning 0))
  5972. (skip-chars-backward " \t\n")
  5973. (line-end-position)))))
  5974. (org-flag-region b e nil 'outline))))))))
  5975. ;; Never hide empty lines at the end of the file.
  5976. (save-excursion
  5977. (goto-char (point-max))
  5978. (outline-previous-heading)
  5979. (outline-end-of-heading)
  5980. (when (and (looking-at "[ \t\n]+")
  5981. (= (match-end 0) (point-max)))
  5982. (org-flag-region (point) (match-end 0) nil 'outline))))
  5983. ;;;; Reveal point location
  5984. (defun org-show-context (&optional key)
  5985. "Make sure point and context are visible.
  5986. Optional argument KEY, when non-nil, is a symbol. See
  5987. `org-show-context-detail' for allowed values and how much is to
  5988. be shown."
  5989. (org-show-set-visibility
  5990. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5991. ((cdr (assq key org-show-context-detail)))
  5992. (t (cdr (assq 'default org-show-context-detail))))))
  5993. (defun org-show-set-visibility (detail)
  5994. "Set visibility around point according to DETAIL.
  5995. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5996. `tree', `canonical' or t. See `org-show-context-detail' for more
  5997. information."
  5998. ;; Show current heading and possibly its entry, following headline
  5999. ;; or all children.
  6000. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6001. (org-flag-heading nil)
  6002. (org-show-entry)
  6003. ;; If point is hidden within a drawer or a block, make sure to
  6004. ;; expose it.
  6005. (dolist (o (overlays-at (point)))
  6006. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6007. (delete-overlay o)))
  6008. (unless (org-before-first-heading-p)
  6009. (org-with-limited-levels
  6010. (cl-case detail
  6011. ((tree canonical t) (org-show-children))
  6012. ((nil minimal ancestors))
  6013. (t (save-excursion
  6014. (outline-next-heading)
  6015. (org-flag-heading nil)))))))
  6016. ;; Show all siblings.
  6017. (when (eq detail 'lineage) (org-show-siblings))
  6018. ;; Show ancestors, possibly with their children.
  6019. (when (memq detail '(ancestors lineage tree canonical t))
  6020. (save-excursion
  6021. (while (org-up-heading-safe)
  6022. (org-flag-heading nil)
  6023. (when (memq detail '(canonical t)) (org-show-entry))
  6024. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6025. (defvar org-reveal-start-hook nil
  6026. "Hook run before revealing a location.")
  6027. (defun org-reveal (&optional siblings)
  6028. "Show current entry, hierarchy above it, and the following headline.
  6029. This can be used to show a consistent set of context around
  6030. locations exposed with `org-show-context'.
  6031. With optional argument SIBLINGS, on each level of the hierarchy all
  6032. siblings are shown. This repairs the tree structure to what it would
  6033. look like when opened with hierarchical calls to `org-cycle'.
  6034. With a \\[universal-argument] \\[universal-argument] prefix, \
  6035. go to the parent and show the entire tree."
  6036. (interactive "P")
  6037. (run-hooks 'org-reveal-start-hook)
  6038. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6039. ((equal siblings '(16))
  6040. (save-excursion
  6041. (when (org-up-heading-safe)
  6042. (org-show-subtree)
  6043. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6044. (t (org-show-set-visibility 'lineage))))
  6045. ;;; Indirect buffer display of subtrees
  6046. (defvar org-indirect-dedicated-frame nil
  6047. "This is the frame being used for indirect tree display.")
  6048. (defvar org-last-indirect-buffer nil)
  6049. (defun org-tree-to-indirect-buffer (&optional arg)
  6050. "Create indirect buffer and narrow it to current subtree.
  6051. With a numerical prefix ARG, go up to this level and then take that tree.
  6052. If ARG is negative, go up that many levels.
  6053. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6054. indirect buffer previously made with this command, to avoid proliferation of
  6055. indirect buffers. However, when you call the command with a \
  6056. `\\[universal-argument]' prefix, or
  6057. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6058. so that you can work with several indirect buffers at the same time. If
  6059. `org-indirect-buffer-display' is `dedicated-frame', the \
  6060. `\\[universal-argument]' prefix also
  6061. requests that a new frame be made for the new buffer, so that the dedicated
  6062. frame is not changed."
  6063. (interactive "P")
  6064. (let ((cbuf (current-buffer))
  6065. (cwin (selected-window))
  6066. (pos (point))
  6067. beg end level heading ibuf)
  6068. (save-excursion
  6069. (org-back-to-heading t)
  6070. (when (numberp arg)
  6071. (setq level (org-outline-level))
  6072. (when (< arg 0) (setq arg (+ level arg)))
  6073. (while (> (setq level (org-outline-level)) arg)
  6074. (org-up-heading-safe)))
  6075. (setq beg (point)
  6076. heading (org-get-heading 'no-tags))
  6077. (org-end-of-subtree t t)
  6078. (when (org-at-heading-p) (backward-char 1))
  6079. (setq end (point)))
  6080. (when (and (buffer-live-p org-last-indirect-buffer)
  6081. (not (eq org-indirect-buffer-display 'new-frame))
  6082. (not arg))
  6083. (kill-buffer org-last-indirect-buffer))
  6084. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6085. org-last-indirect-buffer ibuf)
  6086. (cond
  6087. ((or (eq org-indirect-buffer-display 'new-frame)
  6088. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6089. (select-frame (make-frame))
  6090. (delete-other-windows)
  6091. (pop-to-buffer-same-window ibuf)
  6092. (org-set-frame-title heading))
  6093. ((eq org-indirect-buffer-display 'dedicated-frame)
  6094. (raise-frame
  6095. (select-frame (or (and org-indirect-dedicated-frame
  6096. (frame-live-p org-indirect-dedicated-frame)
  6097. org-indirect-dedicated-frame)
  6098. (setq org-indirect-dedicated-frame (make-frame)))))
  6099. (delete-other-windows)
  6100. (pop-to-buffer-same-window ibuf)
  6101. (org-set-frame-title (concat "Indirect: " heading)))
  6102. ((eq org-indirect-buffer-display 'current-window)
  6103. (pop-to-buffer-same-window ibuf))
  6104. ((eq org-indirect-buffer-display 'other-window)
  6105. (pop-to-buffer ibuf))
  6106. (t (error "Invalid value")))
  6107. (narrow-to-region beg end)
  6108. (org-show-all '(headings drawers blocks))
  6109. (goto-char pos)
  6110. (run-hook-with-args 'org-cycle-hook 'all)
  6111. (and (window-live-p cwin) (select-window cwin))))
  6112. (defun org-get-indirect-buffer (&optional buffer heading)
  6113. (setq buffer (or buffer (current-buffer)))
  6114. (let ((n 1) (base (buffer-name buffer)) bname)
  6115. (while (buffer-live-p
  6116. (get-buffer
  6117. (setq bname
  6118. (concat base "-"
  6119. (if heading (concat heading "-" (number-to-string n))
  6120. (number-to-string n))))))
  6121. (setq n (1+ n)))
  6122. (condition-case nil
  6123. (make-indirect-buffer buffer bname 'clone)
  6124. (error (make-indirect-buffer buffer bname)))))
  6125. (defun org-set-frame-title (title)
  6126. "Set the title of the current frame to the string TITLE."
  6127. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6128. ;;;; Structure editing
  6129. ;;; Inserting headlines
  6130. (defun org--blank-before-heading-p (&optional parent)
  6131. "Non-nil when an empty line should precede a new heading here.
  6132. When optional argument PARENT is non-nil, consider parent
  6133. headline instead of current one."
  6134. (pcase (assq 'heading org-blank-before-new-entry)
  6135. (`(heading . auto)
  6136. (save-excursion
  6137. (org-with-limited-levels
  6138. (unless (and (org-before-first-heading-p)
  6139. (not (outline-next-heading)))
  6140. (org-back-to-heading t)
  6141. (when parent (org-up-heading-safe))
  6142. (cond ((not (bobp))
  6143. (org-previous-line-empty-p))
  6144. ((outline-next-heading)
  6145. (org-previous-line-empty-p))
  6146. ;; Ignore trailing spaces on last buffer line.
  6147. ((progn (skip-chars-backward " \t") (bolp))
  6148. (org-previous-line-empty-p))
  6149. (t nil))))))
  6150. (`(heading . ,value) value)
  6151. (_ nil)))
  6152. (defun org-insert-heading (&optional arg invisible-ok top)
  6153. "Insert a new heading or an item with the same depth at point.
  6154. If point is at the beginning of a heading, insert a new heading
  6155. or a new headline above the current one. When at the beginning
  6156. of a regular line of text, turn it into a heading.
  6157. If point is in the middle of a line, split it and create a new
  6158. headline with the text in the current line after point (see
  6159. `org-M-RET-may-split-line' on how to modify this behavior). As
  6160. a special case, on a headline, splitting can only happen on the
  6161. title itself. E.g., this excludes breaking stars or tags.
  6162. With a `\\[universal-argument]' prefix, set \
  6163. `org-insert-heading-respect-content' to
  6164. a non-nil value for the duration of the command. This forces the
  6165. insertion of a heading after the current subtree, independently
  6166. on the location of point.
  6167. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6168. insert the heading at the end of the tree
  6169. above the current heading. For example, if point is within a
  6170. 2nd-level heading, then it will insert a 2nd-level heading at
  6171. the end of the 1st-level parent subtree.
  6172. When INVISIBLE-OK is set, stop at invisible headlines when going
  6173. back. This is important for non-interactive uses of the
  6174. command.
  6175. When optional argument TOP is non-nil, insert a level 1 heading,
  6176. unconditionally."
  6177. (interactive "P")
  6178. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6179. (level (org-current-level))
  6180. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6181. (cond
  6182. ((or org-insert-heading-respect-content
  6183. (member arg '((4) (16)))
  6184. (and (not invisible-ok)
  6185. (invisible-p (max (1- (point)) (point-min)))))
  6186. ;; Position point at the location of insertion. Make sure we
  6187. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6188. (org-with-limited-levels
  6189. (if (not level) (outline-next-heading) ;before first headline
  6190. (org-back-to-heading invisible-ok)
  6191. (when (equal arg '(16)) (org-up-heading-safe))
  6192. (org-end-of-subtree)))
  6193. (unless (bolp) (insert "\n"))
  6194. (unless (and blank? (org-previous-line-empty-p))
  6195. (org-N-empty-lines-before-current (if blank? 1 0)))
  6196. (insert stars " ")
  6197. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6198. ;; is visible.
  6199. (unless invisible-ok
  6200. (pcase (get-char-property-and-overlay (point) 'invisible)
  6201. (`(outline . ,o)
  6202. (move-overlay o (overlay-start o) (line-end-position 0)))
  6203. (_ nil))))
  6204. ;; At a headline...
  6205. ((org-at-heading-p)
  6206. (cond ((bolp)
  6207. (when blank? (save-excursion (insert "\n")))
  6208. (save-excursion (insert stars " \n"))
  6209. (unless (and blank? (org-previous-line-empty-p))
  6210. (org-N-empty-lines-before-current (if blank? 1 0)))
  6211. (end-of-line))
  6212. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6213. (org-match-line org-complex-heading-regexp)
  6214. (org-pos-in-match-range (point) 4))
  6215. ;; Grab the text that should moved to the new headline.
  6216. ;; Preserve tags.
  6217. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6218. (if (looking-at "[ \t]*$") (replace-match "")
  6219. (org-align-tags))
  6220. (end-of-line)
  6221. (when blank? (insert "\n"))
  6222. (insert "\n" stars " ")
  6223. (when (org-string-nw-p split) (insert split))))
  6224. (t
  6225. (end-of-line)
  6226. (when blank? (insert "\n"))
  6227. (insert "\n" stars " "))))
  6228. ;; On regular text, turn line into a headline or split, if
  6229. ;; appropriate.
  6230. ((bolp)
  6231. (insert stars " ")
  6232. (unless (and blank? (org-previous-line-empty-p))
  6233. (org-N-empty-lines-before-current (if blank? 1 0))))
  6234. (t
  6235. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6236. (end-of-line))
  6237. (insert "\n" stars " ")
  6238. (unless (and blank? (org-previous-line-empty-p))
  6239. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6240. (run-hooks 'org-insert-heading-hook))
  6241. (defun org-N-empty-lines-before-current (n)
  6242. "Make the number of empty lines before current exactly N.
  6243. So this will delete or add empty lines."
  6244. (let ((column (current-column)))
  6245. (beginning-of-line)
  6246. (unless (bobp)
  6247. (let ((start (save-excursion
  6248. (skip-chars-backward " \r\t\n")
  6249. (line-end-position))))
  6250. (delete-region start (line-end-position 0))))
  6251. (insert (make-string n ?\n))
  6252. (move-to-column column)))
  6253. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6254. "Return the heading of the current entry, without the stars.
  6255. When NO-TAGS is non-nil, don't include tags.
  6256. When NO-TODO is non-nil, don't include TODO keywords.
  6257. When NO-PRIORITY is non-nil, don't include priority cookie.
  6258. When NO-COMMENT is non-nil, don't include COMMENT string.
  6259. Return nil before first heading."
  6260. (unless (org-before-first-heading-p)
  6261. (save-excursion
  6262. (org-back-to-heading t)
  6263. (let ((case-fold-search nil))
  6264. (looking-at org-complex-heading-regexp)
  6265. (let ((todo (and (not no-todo) (match-string 2)))
  6266. (priority (and (not no-priority) (match-string 3)))
  6267. (headline (pcase (match-string 4)
  6268. (`nil "")
  6269. ((and (guard no-comment) h)
  6270. (replace-regexp-in-string
  6271. (eval-when-compile
  6272. (format "\\`%s[ \t]+" org-comment-string))
  6273. "" h))
  6274. (h h)))
  6275. (tags (and (not no-tags) (match-string 5))))
  6276. (mapconcat #'identity
  6277. (delq nil (list todo priority headline tags))
  6278. " "))))))
  6279. (defun org-heading-components ()
  6280. "Return the components of the current heading.
  6281. This is a list with the following elements:
  6282. - the level as an integer
  6283. - the reduced level, different if `org-odd-levels-only' is set.
  6284. - the TODO keyword, or nil
  6285. - the priority character, like ?A, or nil if no priority is given
  6286. - the headline text itself, or the tags string if no headline text
  6287. - the tags string, or nil."
  6288. (save-excursion
  6289. (org-back-to-heading t)
  6290. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6291. (list (length (match-string 1))
  6292. (org-reduced-level (length (match-string 1)))
  6293. (match-string-no-properties 2)
  6294. (and (match-end 3) (aref (match-string 3) 2))
  6295. (match-string-no-properties 4)
  6296. (match-string-no-properties 5)))))
  6297. (defun org-get-entry ()
  6298. "Get the entry text, after heading, entire subtree."
  6299. (save-excursion
  6300. (org-back-to-heading t)
  6301. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6302. (defun org-edit-headline (&optional heading)
  6303. "Edit the current headline.
  6304. Set it to HEADING when provided."
  6305. (interactive)
  6306. (org-with-wide-buffer
  6307. (org-back-to-heading t)
  6308. (let ((case-fold-search nil))
  6309. (when (looking-at org-complex-heading-regexp)
  6310. (let* ((old (match-string-no-properties 4))
  6311. (new (save-match-data
  6312. (org-trim (or heading (read-string "Edit: " old))))))
  6313. (unless (equal old new)
  6314. (if old (replace-match new t t nil 4)
  6315. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6316. (insert " " new))
  6317. (org-align-tags)
  6318. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6319. (defun org-insert-heading-after-current ()
  6320. "Insert a new heading with same level as current, after current subtree."
  6321. (interactive)
  6322. (org-back-to-heading)
  6323. (org-insert-heading)
  6324. (org-move-subtree-down)
  6325. (end-of-line 1))
  6326. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6327. "Insert heading with `org-insert-heading-respect-content' set to t."
  6328. (interactive)
  6329. (org-insert-heading '(4) invisible-ok))
  6330. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6331. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6332. (interactive)
  6333. (org-insert-todo-heading force-state '(4)))
  6334. (defun org-insert-todo-heading (arg &optional force-heading)
  6335. "Insert a new heading with the same level and TODO state as current heading.
  6336. If the heading has no TODO state, or if the state is DONE, use
  6337. the first state (TODO by default). Also with one prefix arg,
  6338. force first state. With two prefix args, force inserting at the
  6339. end of the parent subtree.
  6340. When called at a plain list item, insert a new item with an
  6341. unchecked check box."
  6342. (interactive "P")
  6343. (when (or force-heading (not (org-insert-item 'checkbox)))
  6344. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6345. force-heading))
  6346. (save-excursion
  6347. (org-forward-heading-same-level -1)
  6348. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6349. (let* ((new-mark-x
  6350. (if (or (equal arg '(4))
  6351. (not (match-beginning 2))
  6352. (member (match-string 2) org-done-keywords))
  6353. (car org-todo-keywords-1)
  6354. (match-string 2)))
  6355. (new-mark
  6356. (or
  6357. (run-hook-with-args-until-success
  6358. 'org-todo-get-default-hook new-mark-x nil)
  6359. new-mark-x)))
  6360. (beginning-of-line 1)
  6361. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6362. (if org-treat-insert-todo-heading-as-state-change
  6363. (org-todo new-mark)
  6364. (insert new-mark " "))))
  6365. (when org-provide-todo-statistics
  6366. (org-update-parent-todo-statistics))))
  6367. (defun org-insert-subheading (arg)
  6368. "Insert a new subheading and demote it.
  6369. Works for outline headings and for plain lists alike."
  6370. (interactive "P")
  6371. (org-insert-heading arg)
  6372. (cond
  6373. ((org-at-heading-p) (org-do-demote))
  6374. ((org-at-item-p) (org-indent-item))))
  6375. (defun org-insert-todo-subheading (arg)
  6376. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6377. Works for outline headings and for plain lists alike."
  6378. (interactive "P")
  6379. (org-insert-todo-heading arg)
  6380. (cond
  6381. ((org-at-heading-p) (org-do-demote))
  6382. ((org-at-item-p) (org-indent-item))))
  6383. ;;; Promotion and Demotion
  6384. (defvar org-after-demote-entry-hook nil
  6385. "Hook run after an entry has been demoted.
  6386. The cursor will be at the beginning of the entry.
  6387. When a subtree is being demoted, the hook will be called for each node.")
  6388. (defvar org-after-promote-entry-hook nil
  6389. "Hook run after an entry has been promoted.
  6390. The cursor will be at the beginning of the entry.
  6391. When a subtree is being promoted, the hook will be called for each node.")
  6392. (defun org-promote-subtree ()
  6393. "Promote the entire subtree.
  6394. See also `org-promote'."
  6395. (interactive)
  6396. (save-excursion
  6397. (org-with-limited-levels (org-map-tree 'org-promote)))
  6398. (org-fix-position-after-promote))
  6399. (defun org-demote-subtree ()
  6400. "Demote the entire subtree.
  6401. See `org-demote' and `org-promote'."
  6402. (interactive)
  6403. (save-excursion
  6404. (org-with-limited-levels (org-map-tree 'org-demote)))
  6405. (org-fix-position-after-promote))
  6406. (defun org-do-promote ()
  6407. "Promote the current heading higher up the tree.
  6408. If the region is active in `transient-mark-mode', promote all
  6409. headings in the region."
  6410. (interactive)
  6411. (save-excursion
  6412. (if (org-region-active-p)
  6413. (org-map-region 'org-promote (region-beginning) (region-end))
  6414. (org-promote)))
  6415. (org-fix-position-after-promote))
  6416. (defun org-do-demote ()
  6417. "Demote the current heading lower down the tree.
  6418. If the region is active in `transient-mark-mode', demote all
  6419. headings in the region."
  6420. (interactive)
  6421. (save-excursion
  6422. (if (org-region-active-p)
  6423. (org-map-region 'org-demote (region-beginning) (region-end))
  6424. (org-demote)))
  6425. (org-fix-position-after-promote))
  6426. (defun org-fix-position-after-promote ()
  6427. "Fix cursor position and indentation after demoting/promoting."
  6428. (let ((pos (point)))
  6429. (when (save-excursion
  6430. (beginning-of-line)
  6431. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6432. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6433. (cond ((eobp) (insert " "))
  6434. ((eolp) (insert " "))
  6435. ((equal (char-after) ?\s) (forward-char 1))))))
  6436. (defun org-current-level ()
  6437. "Return the level of the current entry, or nil if before the first headline.
  6438. The level is the number of stars at the beginning of the
  6439. headline. Use `org-reduced-level' to remove the effect of
  6440. `org-odd-levels'. Unlike to `org-outline-level', this function
  6441. ignores inlinetasks."
  6442. (let ((level (org-with-limited-levels (org-outline-level))))
  6443. (and (> level 0) level)))
  6444. (defun org-get-previous-line-level ()
  6445. "Return the outline depth of the last headline before the current line.
  6446. Returns 0 for the first headline in the buffer, and nil if before the
  6447. first headline."
  6448. (and (org-current-level)
  6449. (or (and (/= (line-beginning-position) (point-min))
  6450. (save-excursion (beginning-of-line 0) (org-current-level)))
  6451. 0)))
  6452. (defun org-reduced-level (l)
  6453. "Compute the effective level of a heading.
  6454. This takes into account the setting of `org-odd-levels-only'."
  6455. (cond
  6456. ((zerop l) 0)
  6457. (org-odd-levels-only (1+ (floor (/ l 2))))
  6458. (t l)))
  6459. (defun org-level-increment ()
  6460. "Return the number of stars that will be added or removed at a
  6461. time to headlines when structure editing, based on the value of
  6462. `org-odd-levels-only'."
  6463. (if org-odd-levels-only 2 1))
  6464. (defun org-get-valid-level (level &optional change)
  6465. "Rectify a level change under the influence of `org-odd-levels-only'.
  6466. LEVEL is a current level, CHANGE is by how much the level should
  6467. be modified. Even if CHANGE is nil, LEVEL may be returned
  6468. modified because even level numbers will become the next higher
  6469. odd number. Returns values greater than 0."
  6470. (if org-odd-levels-only
  6471. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6472. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6473. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6474. (max 1 (+ level (or change 0)))))
  6475. (defun org-promote ()
  6476. "Promote the current heading higher up the tree."
  6477. (org-with-wide-buffer
  6478. (org-back-to-heading t)
  6479. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6480. after-change-functions))
  6481. (level (save-match-data (funcall outline-level)))
  6482. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6483. (diff (abs (- level (length up-head) -1))))
  6484. (cond
  6485. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6486. (replace-match "# " nil t))
  6487. ((= level 1)
  6488. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6489. (t (replace-match up-head nil t)))
  6490. (unless (= level 1)
  6491. (when org-auto-align-tags (org-align-tags))
  6492. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6493. (run-hooks 'org-after-promote-entry-hook))))
  6494. (defun org-demote ()
  6495. "Demote the current heading lower down the tree."
  6496. (org-with-wide-buffer
  6497. (org-back-to-heading t)
  6498. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6499. after-change-functions))
  6500. (level (save-match-data (funcall outline-level)))
  6501. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6502. (diff (abs (- level (length down-head) -1))))
  6503. (replace-match down-head nil t)
  6504. (when org-auto-align-tags (org-align-tags))
  6505. (when org-adapt-indentation (org-fixup-indentation diff))
  6506. (run-hooks 'org-after-demote-entry-hook))))
  6507. (defun org-cycle-level ()
  6508. "Cycle the level of an empty headline through possible states.
  6509. This goes first to child, then to parent, level, then up the hierarchy.
  6510. After top level, it switches back to sibling level."
  6511. (interactive)
  6512. (let ((org-adapt-indentation nil))
  6513. (when (org-point-at-end-of-empty-headline)
  6514. (setq this-command 'org-cycle-level) ; Only needed for caching
  6515. (let ((cur-level (org-current-level))
  6516. (prev-level (org-get-previous-line-level)))
  6517. (cond
  6518. ;; If first headline in file, promote to top-level.
  6519. ((= prev-level 0)
  6520. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6521. do (org-do-promote)))
  6522. ;; If same level as prev, demote one.
  6523. ((= prev-level cur-level)
  6524. (org-do-demote))
  6525. ;; If parent is top-level, promote to top level if not already.
  6526. ((= prev-level 1)
  6527. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6528. do (org-do-promote)))
  6529. ;; If top-level, return to prev-level.
  6530. ((= cur-level 1)
  6531. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6532. do (org-do-demote)))
  6533. ;; If less than prev-level, promote one.
  6534. ((< cur-level prev-level)
  6535. (org-do-promote))
  6536. ;; If deeper than prev-level, promote until higher than
  6537. ;; prev-level.
  6538. ((> cur-level prev-level)
  6539. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6540. do (org-do-promote))))
  6541. t))))
  6542. (defun org-map-tree (fun)
  6543. "Call FUN for every heading underneath the current one."
  6544. (org-back-to-heading t)
  6545. (let ((level (funcall outline-level)))
  6546. (save-excursion
  6547. (funcall fun)
  6548. (while (and (progn
  6549. (outline-next-heading)
  6550. (> (funcall outline-level) level))
  6551. (not (eobp)))
  6552. (funcall fun)))))
  6553. (defun org-map-region (fun beg end)
  6554. "Call FUN for every heading between BEG and END."
  6555. (let ((org-ignore-region t))
  6556. (save-excursion
  6557. (setq end (copy-marker end))
  6558. (goto-char beg)
  6559. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6560. (< (point) end))
  6561. (funcall fun))
  6562. (while (and (progn
  6563. (outline-next-heading)
  6564. (< (point) end))
  6565. (not (eobp)))
  6566. (funcall fun)))))
  6567. (defun org-fixup-indentation (diff)
  6568. "Change the indentation in the current entry by DIFF.
  6569. DIFF is an integer. Indentation is done according to the
  6570. following rules:
  6571. - Planning information and property drawers are always indented
  6572. according to the new level of the headline;
  6573. - Footnote definitions and their contents are ignored;
  6574. - Inlinetasks' boundaries are not shifted;
  6575. - Empty lines are ignored;
  6576. - Other lines' indentation are shifted by DIFF columns, unless
  6577. it would introduce a structural change in the document, in
  6578. which case no shifting is done at all.
  6579. Assume point is at a heading or an inlinetask beginning."
  6580. (org-with-wide-buffer
  6581. (narrow-to-region (line-beginning-position)
  6582. (save-excursion
  6583. (if (org-with-limited-levels (org-at-heading-p))
  6584. (org-with-limited-levels (outline-next-heading))
  6585. (org-inlinetask-goto-end))
  6586. (point)))
  6587. (forward-line)
  6588. ;; Indent properly planning info and property drawer.
  6589. (when (looking-at-p org-planning-line-re)
  6590. (org-indent-line)
  6591. (forward-line))
  6592. (when (looking-at org-property-drawer-re)
  6593. (goto-char (match-end 0))
  6594. (forward-line)
  6595. (org-indent-region (match-beginning 0) (match-end 0)))
  6596. (when (looking-at org-logbook-drawer-re)
  6597. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6598. (col (+ (current-indentation) diff)))
  6599. (when (wholenump col)
  6600. (while (< (point) end-marker)
  6601. (indent-line-to col)
  6602. (forward-line)))))
  6603. (catch 'no-shift
  6604. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6605. (throw 'no-shift nil))
  6606. ;; If DIFF is negative, first check if a shift is possible at all
  6607. ;; (e.g., it doesn't break structure). This can only happen if
  6608. ;; some contents are not properly indented.
  6609. (let ((case-fold-search t))
  6610. (when (< diff 0)
  6611. (let ((diff (- diff))
  6612. (forbidden-re (concat org-outline-regexp
  6613. "\\|"
  6614. (substring org-footnote-definition-re 1))))
  6615. (save-excursion
  6616. (while (not (eobp))
  6617. (cond
  6618. ((looking-at-p "[ \t]*$") (forward-line))
  6619. ((and (looking-at-p org-footnote-definition-re)
  6620. (let ((e (org-element-at-point)))
  6621. (and (eq (org-element-type e) 'footnote-definition)
  6622. (goto-char (org-element-property :end e))))))
  6623. ((looking-at-p org-outline-regexp) (forward-line))
  6624. ;; Give up if shifting would move before column 0 or
  6625. ;; if it would introduce a headline or a footnote
  6626. ;; definition.
  6627. (t
  6628. (skip-chars-forward " \t")
  6629. (let ((ind (current-column)))
  6630. (when (or (< ind diff)
  6631. (and (= ind diff) (looking-at-p forbidden-re)))
  6632. (throw 'no-shift nil)))
  6633. ;; Ignore contents of example blocks and source
  6634. ;; blocks if their indentation is meant to be
  6635. ;; preserved. Jump to block's closing line.
  6636. (beginning-of-line)
  6637. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6638. (let ((e (org-element-at-point)))
  6639. (and (memq (org-element-type e)
  6640. '(example-block src-block))
  6641. (or org-src-preserve-indentation
  6642. (org-element-property :preserve-indent e))
  6643. (goto-char (org-element-property :end e))
  6644. (progn (skip-chars-backward " \r\t\n")
  6645. (beginning-of-line)
  6646. t))))
  6647. (forward-line))))))))
  6648. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6649. ;; by DIFF. Also skip contents of source or example blocks
  6650. ;; when indentation is meant to be preserved.
  6651. (while (not (eobp))
  6652. (cond
  6653. ((and (looking-at-p org-footnote-definition-re)
  6654. (let ((e (org-element-at-point)))
  6655. (and (eq (org-element-type e) 'footnote-definition)
  6656. (goto-char (org-element-property :end e))))))
  6657. ((looking-at-p org-outline-regexp) (forward-line))
  6658. ((looking-at-p "[ \t]*$") (forward-line))
  6659. (t
  6660. (indent-line-to (+ (current-indentation) diff))
  6661. (beginning-of-line)
  6662. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6663. (let ((e (org-element-at-point)))
  6664. (and (memq (org-element-type e)
  6665. '(example-block src-block))
  6666. (or org-src-preserve-indentation
  6667. (org-element-property :preserve-indent e))
  6668. (goto-char (org-element-property :end e))
  6669. (progn (skip-chars-backward " \r\t\n")
  6670. (beginning-of-line)
  6671. t))))
  6672. (forward-line)))))))))
  6673. (defun org-convert-to-odd-levels ()
  6674. "Convert an Org file with all levels allowed to one with odd levels.
  6675. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6676. level 5 etc."
  6677. (interactive)
  6678. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6679. (let ((outline-level 'org-outline-level)
  6680. (org-odd-levels-only nil) n)
  6681. (save-excursion
  6682. (goto-char (point-min))
  6683. (while (re-search-forward "^\\*\\*+ " nil t)
  6684. (setq n (- (length (match-string 0)) 2))
  6685. (while (>= (setq n (1- n)) 0)
  6686. (org-demote))
  6687. (end-of-line 1))))))
  6688. (defun org-convert-to-oddeven-levels ()
  6689. "Convert an Org file with only odd levels to one with odd/even levels.
  6690. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6691. file contains a section with an even level, conversion would
  6692. destroy the structure of the file. An error is signaled in this
  6693. case."
  6694. (interactive)
  6695. (goto-char (point-min))
  6696. ;; First check if there are no even levels
  6697. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6698. (org-show-set-visibility 'canonical)
  6699. (error "Not all levels are odd in this file. Conversion not possible"))
  6700. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6701. (let ((outline-regexp org-outline-regexp)
  6702. (outline-level 'org-outline-level)
  6703. (org-odd-levels-only nil) n)
  6704. (save-excursion
  6705. (goto-char (point-min))
  6706. (while (re-search-forward "^\\*\\*+ " nil t)
  6707. (setq n (/ (1- (length (match-string 0))) 2))
  6708. (while (>= (setq n (1- n)) 0)
  6709. (org-promote))
  6710. (end-of-line 1))))))
  6711. (defun org-tr-level (n)
  6712. "Make N odd if required."
  6713. (if org-odd-levels-only (1+ (/ n 2)) n))
  6714. ;;; Vertical tree motion, cutting and pasting of subtrees
  6715. (defun org-move-subtree-up (&optional arg)
  6716. "Move the current subtree up past ARG headlines of the same level."
  6717. (interactive "p")
  6718. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6719. (defun org-move-subtree-down (&optional arg)
  6720. "Move the current subtree down past ARG headlines of the same level."
  6721. (interactive "p")
  6722. (setq arg (prefix-numeric-value arg))
  6723. (org-preserve-local-variables
  6724. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6725. 'org-get-last-sibling))
  6726. (ins-point (make-marker))
  6727. (cnt (abs arg))
  6728. (col (current-column))
  6729. beg end txt folded)
  6730. ;; Select the tree
  6731. (org-back-to-heading)
  6732. (setq beg (point))
  6733. (save-match-data
  6734. (save-excursion (outline-end-of-heading)
  6735. (setq folded (org-invisible-p)))
  6736. (progn (org-end-of-subtree nil t)
  6737. (unless (eobp) (backward-char))))
  6738. (outline-next-heading)
  6739. (setq end (point))
  6740. (goto-char beg)
  6741. ;; Find insertion point, with error handling
  6742. (while (> cnt 0)
  6743. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6744. (goto-char beg)
  6745. (user-error "Cannot move past superior level or buffer limit"))
  6746. (setq cnt (1- cnt)))
  6747. (when (> arg 0)
  6748. ;; Moving forward - still need to move over subtree
  6749. (org-end-of-subtree t t)
  6750. (save-excursion
  6751. (org-back-over-empty-lines)
  6752. (or (bolp) (newline))))
  6753. (move-marker ins-point (point))
  6754. (setq txt (buffer-substring beg end))
  6755. (org-save-markers-in-region beg end)
  6756. (delete-region beg end)
  6757. (org-remove-empty-overlays-at beg)
  6758. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6759. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6760. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6761. (let ((bbb (point)))
  6762. (insert-before-markers txt)
  6763. (org-reinstall-markers-in-region bbb)
  6764. (move-marker ins-point bbb))
  6765. (or (bolp) (insert "\n"))
  6766. (goto-char ins-point)
  6767. (org-skip-whitespace)
  6768. (move-marker ins-point nil)
  6769. (if folded
  6770. (org-flag-subtree t)
  6771. (org-show-entry)
  6772. (org-show-children))
  6773. (org-clean-visibility-after-subtree-move)
  6774. ;; move back to the initial column we were at
  6775. (move-to-column col))))
  6776. (defvar org-subtree-clip ""
  6777. "Clipboard for cut and paste of subtrees.
  6778. This is actually only a copy of the kill, because we use the normal kill
  6779. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6780. (defvar org-subtree-clip-folded nil
  6781. "Was the last copied subtree folded?
  6782. This is used to fold the tree back after pasting.")
  6783. (defun org-cut-subtree (&optional n)
  6784. "Cut the current subtree into the clipboard.
  6785. With prefix arg N, cut this many sequential subtrees.
  6786. This is a short-hand for marking the subtree and then cutting it."
  6787. (interactive "p")
  6788. (org-copy-subtree n 'cut))
  6789. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6790. "Copy the current subtree into the clipboard.
  6791. With prefix arg N, copy this many sequential subtrees.
  6792. This is a short-hand for marking the subtree and then copying it.
  6793. If CUT is non-nil, actually cut the subtree.
  6794. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6795. of some markers in the region, even if CUT is non-nil. This is
  6796. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6797. (interactive "p")
  6798. (org-preserve-local-variables
  6799. (let (beg end folded (beg0 (point)))
  6800. (if (called-interactively-p 'any)
  6801. (org-back-to-heading nil) ; take what looks like a subtree
  6802. (org-back-to-heading t)) ; take what is really there
  6803. (setq beg (point))
  6804. (skip-chars-forward " \t\r\n")
  6805. (save-match-data
  6806. (if nosubtrees
  6807. (outline-next-heading)
  6808. (save-excursion (outline-end-of-heading)
  6809. (setq folded (org-invisible-p)))
  6810. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6811. (org-end-of-subtree t t)))
  6812. ;; Include the end of an inlinetask
  6813. (when (and (featurep 'org-inlinetask)
  6814. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6815. "END[ \t]*$")))
  6816. (end-of-line))
  6817. (setq end (point))
  6818. (goto-char beg0)
  6819. (when (> end beg)
  6820. (setq org-subtree-clip-folded folded)
  6821. (when (or cut force-store-markers)
  6822. (org-save-markers-in-region beg end))
  6823. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6824. (setq org-subtree-clip (current-kill 0))
  6825. (message "%s: Subtree(s) with %d characters"
  6826. (if cut "Cut" "Copied")
  6827. (length org-subtree-clip))))))
  6828. (defun org-paste-subtree (&optional level tree for-yank remove)
  6829. "Paste the clipboard as a subtree, with modification of headline level.
  6830. The entire subtree is promoted or demoted in order to match a new headline
  6831. level.
  6832. If the cursor is at the beginning of a headline, the same level as
  6833. that headline is used to paste the tree.
  6834. If not, the new level is derived from the *visible* headings
  6835. before and after the insertion point, and taken to be the inferior headline
  6836. level of the two. So if the previous visible heading is level 3 and the
  6837. next is level 4 (or vice versa), level 4 will be used for insertion.
  6838. This makes sure that the subtree remains an independent subtree and does
  6839. not swallow low level entries.
  6840. You can also force a different level, either by using a numeric prefix
  6841. argument, or by inserting the heading marker by hand. For example, if the
  6842. cursor is after \"*****\", then the tree will be shifted to level 5.
  6843. If optional TREE is given, use this text instead of the kill ring.
  6844. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6845. move back over whitespace before inserting, and move point to the end of
  6846. the inserted text when done.
  6847. When REMOVE is non-nil, remove the subtree from the clipboard."
  6848. (interactive "P")
  6849. (setq tree (or tree (and kill-ring (current-kill 0))))
  6850. (unless (org-kill-is-subtree-p tree)
  6851. (user-error
  6852. (substitute-command-keys
  6853. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6854. (org-with-limited-levels
  6855. (let* ((visp (not (org-invisible-p)))
  6856. (txt tree)
  6857. (old-level (if (string-match org-outline-regexp-bol txt)
  6858. (- (match-end 0) (match-beginning 0) 1)
  6859. -1))
  6860. (force-level
  6861. (cond
  6862. (level (prefix-numeric-value level))
  6863. ;; When point is after the stars in an otherwise empty
  6864. ;; headline, use the number of stars as the forced level.
  6865. ((and (org-match-line "^\\*+[ \t]*$")
  6866. (not (eq ?* (char-after))))
  6867. (org-outline-level))
  6868. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6869. (previous-level
  6870. (save-excursion
  6871. (org-previous-visible-heading 1)
  6872. (if (org-at-heading-p) (org-outline-level) 1)))
  6873. (next-level
  6874. (save-excursion
  6875. (if (org-at-heading-p) (org-outline-level)
  6876. (org-next-visible-heading 1)
  6877. (if (org-at-heading-p) (org-outline-level) 1))))
  6878. (new-level (or force-level (max previous-level next-level)))
  6879. (shift (if (or (= old-level -1)
  6880. (= new-level -1)
  6881. (= old-level new-level))
  6882. 0
  6883. (- new-level old-level)))
  6884. (delta (if (> shift 0) -1 1))
  6885. (func (if (> shift 0) #'org-demote #'org-promote))
  6886. (org-odd-levels-only nil)
  6887. beg end newend)
  6888. ;; Remove the forced level indicator.
  6889. (when (and force-level (not level))
  6890. (delete-region (line-beginning-position) (point)))
  6891. ;; Paste before the next visible heading or at end of buffer,
  6892. ;; unless point is at the beginning of a headline.
  6893. (unless (and (bolp) (org-at-heading-p))
  6894. (org-next-visible-heading 1)
  6895. (unless (bolp) (insert "\n")))
  6896. (setq beg (point))
  6897. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6898. (insert-before-markers txt)
  6899. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6900. (setq newend (point))
  6901. (org-reinstall-markers-in-region beg)
  6902. (setq end (point))
  6903. (goto-char beg)
  6904. (skip-chars-forward " \t\n\r")
  6905. (setq beg (point))
  6906. (when (and (org-invisible-p) visp)
  6907. (save-excursion (outline-show-heading)))
  6908. ;; Shift if necessary.
  6909. (unless (= shift 0)
  6910. (save-restriction
  6911. (narrow-to-region beg end)
  6912. (while (not (= shift 0))
  6913. (org-map-region func (point-min) (point-max))
  6914. (setq shift (+ delta shift)))
  6915. (goto-char (point-min))
  6916. (setq newend (point-max))))
  6917. (when (or for-yank (called-interactively-p 'interactive))
  6918. (message "Clipboard pasted as level %d subtree" new-level))
  6919. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6920. kill-ring
  6921. (equal org-subtree-clip (current-kill 0))
  6922. org-subtree-clip-folded)
  6923. ;; The tree was folded before it was killed/copied
  6924. (org-flag-subtree t))
  6925. (when for-yank (goto-char newend))
  6926. (when remove (pop kill-ring)))))
  6927. (defun org-kill-is-subtree-p (&optional txt)
  6928. "Check if the current kill is an outline subtree, or a set of trees.
  6929. Returns nil if kill does not start with a headline, or if the first
  6930. headline level is not the largest headline level in the tree.
  6931. So this will actually accept several entries of equal levels as well,
  6932. which is OK for `org-paste-subtree'.
  6933. If optional TXT is given, check this string instead of the current kill."
  6934. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6935. (re (org-get-limited-outline-regexp))
  6936. (^re (concat "^" re))
  6937. (start-level (and kill
  6938. (string-match
  6939. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6940. kill)
  6941. (- (match-end 2) (match-beginning 2) 1)))
  6942. (start (1+ (or (match-beginning 2) -1))))
  6943. (if (not start-level)
  6944. (progn
  6945. nil) ;; does not even start with a heading
  6946. (catch 'exit
  6947. (while (setq start (string-match ^re kill (1+ start)))
  6948. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6949. (throw 'exit nil)))
  6950. t))))
  6951. (defvar org-markers-to-move nil
  6952. "Markers that should be moved with a cut-and-paste operation.
  6953. Those markers are stored together with their positions relative to
  6954. the start of the region.")
  6955. (defun org-save-markers-in-region (beg end)
  6956. "Check markers in region.
  6957. If these markers are between BEG and END, record their position relative
  6958. to BEG, so that after moving the block of text, we can put the markers back
  6959. into place.
  6960. This function gets called just before an entry or tree gets cut from the
  6961. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6962. called immediately, to move the markers with the entries."
  6963. (setq org-markers-to-move nil)
  6964. (when (featurep 'org-clock)
  6965. (org-clock-save-markers-for-cut-and-paste beg end))
  6966. (when (featurep 'org-agenda)
  6967. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6968. (defun org-check-and-save-marker (marker beg end)
  6969. "Check if MARKER is between BEG and END.
  6970. If yes, remember the marker and the distance to BEG."
  6971. (when (and (marker-buffer marker)
  6972. (equal (marker-buffer marker) (current-buffer))
  6973. (>= marker beg) (< marker end))
  6974. (push (cons marker (- marker beg)) org-markers-to-move)))
  6975. (defun org-reinstall-markers-in-region (beg)
  6976. "Move all remembered markers to their position relative to BEG."
  6977. (dolist (x org-markers-to-move)
  6978. (move-marker (car x) (+ beg (cdr x))))
  6979. (setq org-markers-to-move nil))
  6980. (defun org-narrow-to-subtree ()
  6981. "Narrow buffer to the current subtree."
  6982. (interactive)
  6983. (save-excursion
  6984. (save-match-data
  6985. (org-with-limited-levels
  6986. (narrow-to-region
  6987. (progn (org-back-to-heading t) (point))
  6988. (progn (org-end-of-subtree t t)
  6989. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6990. (point)))))))
  6991. (defun org-toggle-narrow-to-subtree ()
  6992. "Narrow to the subtree at point or widen a narrowed buffer."
  6993. (interactive)
  6994. (if (buffer-narrowed-p)
  6995. (progn (widen) (message "Buffer widen"))
  6996. (org-narrow-to-subtree)
  6997. (message "Buffer narrowed to current subtree")))
  6998. (defun org-narrow-to-block ()
  6999. "Narrow buffer to the current block."
  7000. (interactive)
  7001. (let* ((case-fold-search t)
  7002. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7003. "^[ \t]*#\\+end_.*")))
  7004. (if blockp
  7005. (narrow-to-region (car blockp) (cdr blockp))
  7006. (user-error "Not in a block"))))
  7007. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7008. "Clone the task (subtree) at point N times.
  7009. The clones will be inserted as siblings.
  7010. In interactive use, the user will be prompted for the number of
  7011. clones to be produced. If the entry has a timestamp, the user
  7012. will also be prompted for a time shift, which may be a repeater
  7013. as used in time stamps, for example `+3d'. To disable this,
  7014. you can call the function with a universal prefix argument.
  7015. When a valid repeater is given and the entry contains any time
  7016. stamps, the clones will become a sequence in time, with time
  7017. stamps in the subtree shifted for each clone produced. If SHIFT
  7018. is nil or the empty string, time stamps will be left alone. The
  7019. ID property of the original subtree is removed.
  7020. In each clone, all the CLOCK entries will be removed. This
  7021. prevents Org from considering that the clocked times overlap.
  7022. If the original subtree did contain time stamps with a repeater,
  7023. the following will happen:
  7024. - the repeater will be removed in each clone
  7025. - an additional clone will be produced, with the current, unshifted
  7026. date(s) in the entry.
  7027. - the original entry will be placed *after* all the clones, with
  7028. repeater intact.
  7029. - the start days in the repeater in the original entry will be shifted
  7030. to past the last clone.
  7031. In this way you can spell out a number of instances of a repeating task,
  7032. and still retain the repeater to cover future instances of the task.
  7033. As described above, N+1 clones are produced when the original
  7034. subtree has a repeater. Setting N to 0, then, can be used to
  7035. remove the repeater from a subtree and create a shifted clone
  7036. with the original repeater."
  7037. (interactive "nNumber of clones to produce: ")
  7038. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7039. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7040. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7041. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7042. (shift
  7043. (or shift
  7044. (if (and (not (equal current-prefix-arg '(4)))
  7045. (save-excursion
  7046. (goto-char beg)
  7047. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7048. (read-from-minibuffer
  7049. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7050. ""))) ;No time shift
  7051. (doshift
  7052. (and (org-string-nw-p shift)
  7053. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7054. shift)
  7055. (user-error "Invalid shift specification %s" shift)))))
  7056. (goto-char end-of-tree)
  7057. (unless (bolp) (insert "\n"))
  7058. (let* ((end (point))
  7059. (template (buffer-substring beg end))
  7060. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7061. (shift-what (pcase (and doshift (match-string 2 shift))
  7062. (`nil nil)
  7063. ("d" 'day)
  7064. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7065. ("m" 'month)
  7066. ("y" 'year)
  7067. (_ (error "Unsupported time unit"))))
  7068. (nmin 1)
  7069. (nmax n)
  7070. (n-no-remove -1)
  7071. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7072. (idprop (org-entry-get beg "ID")))
  7073. (when (and doshift
  7074. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7075. template))
  7076. (delete-region beg end)
  7077. (setq end beg)
  7078. (setq nmin 0)
  7079. (setq nmax (1+ nmax))
  7080. (setq n-no-remove nmax))
  7081. (goto-char end)
  7082. (cl-loop for n from nmin to nmax do
  7083. (insert
  7084. ;; Prepare clone.
  7085. (with-temp-buffer
  7086. (insert template)
  7087. (org-mode)
  7088. (goto-char (point-min))
  7089. (org-show-subtree)
  7090. (and idprop (if org-clone-delete-id
  7091. (org-entry-delete nil "ID")
  7092. (org-id-get-create t)))
  7093. (unless (= n 0)
  7094. (while (re-search-forward org-clock-line-re nil t)
  7095. (delete-region (line-beginning-position)
  7096. (line-beginning-position 2)))
  7097. (goto-char (point-min))
  7098. (while (re-search-forward org-drawer-regexp nil t)
  7099. (org-remove-empty-drawer-at (point))))
  7100. (goto-char (point-min))
  7101. (when doshift
  7102. (while (re-search-forward org-ts-regexp-both nil t)
  7103. (org-timestamp-change (* n shift-n) shift-what))
  7104. (unless (= n n-no-remove)
  7105. (goto-char (point-min))
  7106. (while (re-search-forward org-ts-regexp nil t)
  7107. (save-excursion
  7108. (goto-char (match-beginning 0))
  7109. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7110. (delete-region (match-beginning 1) (match-end 1)))))))
  7111. (buffer-string)))))
  7112. (goto-char beg)))
  7113. ;;; Outline path
  7114. (defvar org-outline-path-cache nil
  7115. "Alist between buffer positions and outline paths.
  7116. It value is an alist (POSITION . PATH) where POSITION is the
  7117. buffer position at the beginning of an entry and PATH is a list
  7118. of strings describing the outline path for that entry, in reverse
  7119. order.")
  7120. (defun org--get-outline-path-1 (&optional use-cache)
  7121. "Return outline path to current headline.
  7122. Outline path is a list of strings, in reverse order. When
  7123. optional argument USE-CACHE is non-nil, make use of a cache. See
  7124. `org-get-outline-path' for details.
  7125. Assume buffer is widened and point is on a headline."
  7126. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7127. (let ((p (point))
  7128. (heading (let ((case-fold-search nil))
  7129. (looking-at org-complex-heading-regexp)
  7130. (if (not (match-end 4)) ""
  7131. ;; Remove statistics cookies.
  7132. (org-trim
  7133. (org-link-display-format
  7134. (replace-regexp-in-string
  7135. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7136. (match-string-no-properties 4))))))))
  7137. (if (org-up-heading-safe)
  7138. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7139. (when use-cache
  7140. (push (cons p path) org-outline-path-cache))
  7141. path)
  7142. ;; This is a new root node. Since we assume we are moving
  7143. ;; forward, we can drop previous cache so as to limit number
  7144. ;; of associations there.
  7145. (let ((path (list heading)))
  7146. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7147. path)))))
  7148. (defun org-get-outline-path (&optional with-self use-cache)
  7149. "Return the outline path to the current entry.
  7150. An outline path is a list of ancestors for current headline, as
  7151. a list of strings. Statistics cookies are removed and links are
  7152. replaced with their description, if any, or their path otherwise.
  7153. When optional argument WITH-SELF is non-nil, the path also
  7154. includes the current headline.
  7155. When optional argument USE-CACHE is non-nil, cache outline paths
  7156. between calls to this function so as to avoid backtracking. This
  7157. argument is useful when planning to find more than one outline
  7158. path in the same document. In that case, there are two
  7159. conditions to satisfy:
  7160. - `org-outline-path-cache' is set to nil before starting the
  7161. process;
  7162. - outline paths are computed by increasing buffer positions."
  7163. (org-with-wide-buffer
  7164. (and (or (and with-self (org-back-to-heading t))
  7165. (org-up-heading-safe))
  7166. (reverse (org--get-outline-path-1 use-cache)))))
  7167. (defun org-format-outline-path (path &optional width prefix separator)
  7168. "Format the outline path PATH for display.
  7169. WIDTH is the maximum number of characters that is available.
  7170. PREFIX is a prefix to be included in the returned string,
  7171. such as the file name.
  7172. SEPARATOR is inserted between the different parts of the path,
  7173. the default is \"/\"."
  7174. (setq width (or width 79))
  7175. (setq path (delq nil path))
  7176. (unless (> width 0)
  7177. (user-error "Argument `width' must be positive"))
  7178. (setq separator (or separator "/"))
  7179. (let* ((org-odd-levels-only nil)
  7180. (fpath (concat
  7181. prefix (and prefix path separator)
  7182. (mapconcat
  7183. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7184. (cl-loop for head in path
  7185. for n from 0
  7186. collect (org-add-props
  7187. head nil 'face
  7188. (nth (% n org-n-level-faces) org-level-faces)))
  7189. separator))))
  7190. (when (> (length fpath) width)
  7191. (if (< width 7)
  7192. ;; It's unlikely that `width' will be this small, but don't
  7193. ;; waste characters by adding ".." if it is.
  7194. (setq fpath (substring fpath 0 width))
  7195. (setf (substring fpath (- width 2)) "..")))
  7196. fpath))
  7197. (defun org-display-outline-path (&optional file current separator just-return-string)
  7198. "Display the current outline path in the echo area.
  7199. If FILE is non-nil, prepend the output with the file name.
  7200. If CURRENT is non-nil, append the current heading to the output.
  7201. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7202. the different parts of the path and defaults to \"/\".
  7203. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7204. (interactive "P")
  7205. (let* (case-fold-search
  7206. (bfn (buffer-file-name (buffer-base-buffer)))
  7207. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7208. res)
  7209. (when current (setq path (append path
  7210. (save-excursion
  7211. (org-back-to-heading t)
  7212. (when (looking-at org-complex-heading-regexp)
  7213. (list (match-string 4)))))))
  7214. (setq res
  7215. (org-format-outline-path
  7216. path
  7217. (1- (frame-width))
  7218. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7219. separator))
  7220. (add-face-text-property 0 (length res)
  7221. `(:height ,(face-attribute 'default :height))
  7222. nil res)
  7223. (if just-return-string
  7224. res
  7225. (org-unlogged-message "%s" res))))
  7226. ;;; Outline Sorting
  7227. (defun org-sort (&optional with-case)
  7228. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7229. Optional argument WITH-CASE means sort case-sensitively."
  7230. (interactive "P")
  7231. (org-call-with-arg
  7232. (cond ((org-at-table-p) #'org-table-sort-lines)
  7233. ((org-at-item-p) #'org-sort-list)
  7234. (t #'org-sort-entries))
  7235. with-case))
  7236. (defun org-sort-remove-invisible (s)
  7237. "Remove invisible part of links and emphasis markers from string S."
  7238. (remove-text-properties 0 (length s) org-rm-props s)
  7239. (replace-regexp-in-string
  7240. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7241. (replace-regexp-in-string
  7242. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7243. (org-link-display-format s)
  7244. t t) t t))
  7245. (defvar org-after-sorting-entries-or-items-hook nil
  7246. "Hook that is run after a bunch of entries or items have been sorted.
  7247. When children are sorted, the cursor is in the parent line when this
  7248. hook gets called. When a region or a plain list is sorted, the cursor
  7249. will be in the first entry of the sorted region/list.")
  7250. (defun org-sort-entries
  7251. (&optional with-case sorting-type getkey-func compare-func property
  7252. interactive?)
  7253. "Sort entries on a certain level of an outline tree.
  7254. If there is an active region, the entries in the region are sorted.
  7255. Else, if the cursor is before the first entry, sort the top-level items.
  7256. Else, the children of the entry at point are sorted.
  7257. Sorting can be alphabetically, numerically, by date/time as given by
  7258. a time stamp, by a property, by priority order, or by a custom function.
  7259. The command prompts for the sorting type unless it has been given to the
  7260. function through the SORTING-TYPE argument, which needs to be a character,
  7261. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7262. the precise meaning of each character:
  7263. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7264. c By creation time, which is assumed to be the first inactive time stamp
  7265. at the beginning of a line.
  7266. d By deadline date/time.
  7267. k By clocking time.
  7268. n Numerically, by converting the beginning of the entry/item to a number.
  7269. o By order of TODO keywords.
  7270. p By priority according to the cookie.
  7271. r By the value of a property.
  7272. s By scheduled date/time.
  7273. t By date/time, either the first active time stamp in the entry, or, if
  7274. none exist, by the first inactive one.
  7275. Capital letters will reverse the sort order.
  7276. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7277. called with point at the beginning of the record. It must return a
  7278. value that is compatible with COMPARE-FUNC, the function used to
  7279. compare entries.
  7280. Comparing entries ignores case by default. However, with an optional argument
  7281. WITH-CASE, the sorting considers case as well.
  7282. Sorting is done against the visible part of the headlines, it ignores hidden
  7283. links.
  7284. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7285. A non-nil value for INTERACTIVE? is used to signal that this
  7286. function is being called interactively."
  7287. (interactive (list current-prefix-arg nil nil nil nil t))
  7288. (let ((case-func (if with-case 'identity 'downcase))
  7289. start beg end stars re re2
  7290. txt what tmp)
  7291. ;; Find beginning and end of region to sort
  7292. (cond
  7293. ((org-region-active-p)
  7294. ;; we will sort the region
  7295. (setq end (region-end)
  7296. what "region")
  7297. (goto-char (region-beginning))
  7298. (unless (org-at-heading-p) (outline-next-heading))
  7299. (setq start (point)))
  7300. ((or (org-at-heading-p)
  7301. (ignore-errors (progn (org-back-to-heading) t)))
  7302. ;; we will sort the children of the current headline
  7303. (org-back-to-heading)
  7304. (setq start (point)
  7305. end (progn (org-end-of-subtree t t)
  7306. (or (bolp) (insert "\n"))
  7307. (when (>= (org-back-over-empty-lines) 1)
  7308. (forward-line 1))
  7309. (point))
  7310. what "children")
  7311. (goto-char start)
  7312. (outline-show-subtree)
  7313. (outline-next-heading))
  7314. (t
  7315. ;; we will sort the top-level entries in this file
  7316. (goto-char (point-min))
  7317. (or (org-at-heading-p) (outline-next-heading))
  7318. (setq start (point))
  7319. (goto-char (point-max))
  7320. (beginning-of-line 1)
  7321. (when (looking-at ".*?\\S-")
  7322. ;; File ends in a non-white line
  7323. (end-of-line 1)
  7324. (insert "\n"))
  7325. (setq end (point-max))
  7326. (setq what "top-level")
  7327. (goto-char start)
  7328. (org-show-all '(headings drawers blocks))))
  7329. (setq beg (point))
  7330. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7331. (looking-at "\\(\\*+\\)")
  7332. (setq stars (match-string 1)
  7333. re (concat "^" (regexp-quote stars) " +")
  7334. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7335. txt (buffer-substring beg end))
  7336. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7337. (when (and (not (equal stars "*")) (string-match re2 txt))
  7338. (user-error "Region to sort contains a level above the first entry"))
  7339. (unless sorting-type
  7340. (message
  7341. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7342. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7343. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7344. what)
  7345. (setq sorting-type (read-char-exclusive)))
  7346. (unless getkey-func
  7347. (and (= (downcase sorting-type) ?f)
  7348. (setq getkey-func
  7349. (or (and interactive?
  7350. (org-read-function
  7351. "Function for extracting keys: "))
  7352. (error "Missing key extractor")))))
  7353. (and (= (downcase sorting-type) ?r)
  7354. (not property)
  7355. (setq property
  7356. (completing-read "Property: "
  7357. (mapcar #'list (org-buffer-property-keys t))
  7358. nil t)))
  7359. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7360. (message "Sorting entries...")
  7361. (save-restriction
  7362. (narrow-to-region start end)
  7363. (let ((restore-clock?
  7364. ;; The clock marker is lost when using `sort-subr'; mark
  7365. ;; the clock with temporary `:org-clock-marker-backup'
  7366. ;; text property.
  7367. (when (and (eq (org-clock-is-active) (current-buffer))
  7368. (<= start (marker-position org-clock-marker))
  7369. (>= end (marker-position org-clock-marker)))
  7370. (with-silent-modifications
  7371. (put-text-property (1- org-clock-marker) org-clock-marker
  7372. :org-clock-marker-backup t))
  7373. t))
  7374. (dcst (downcase sorting-type))
  7375. (case-fold-search nil)
  7376. (now (current-time)))
  7377. (org-preserve-local-variables
  7378. (sort-subr
  7379. (/= dcst sorting-type)
  7380. ;; This function moves to the beginning character of the
  7381. ;; "record" to be sorted.
  7382. (lambda nil
  7383. (if (re-search-forward re nil t)
  7384. (goto-char (match-beginning 0))
  7385. (goto-char (point-max))))
  7386. ;; This function moves to the last character of the "record" being
  7387. ;; sorted.
  7388. (lambda nil
  7389. (save-match-data
  7390. (condition-case nil
  7391. (outline-forward-same-level 1)
  7392. (error
  7393. (goto-char (point-max))))))
  7394. ;; This function returns the value that gets sorted against.
  7395. (lambda ()
  7396. (cond
  7397. ((= dcst ?n)
  7398. (string-to-number
  7399. (org-sort-remove-invisible (org-get-heading t t t t))))
  7400. ((= dcst ?a)
  7401. (funcall case-func
  7402. (org-sort-remove-invisible (org-get-heading t t t t))))
  7403. ((= dcst ?k)
  7404. (or (get-text-property (point) :org-clock-minutes) 0))
  7405. ((= dcst ?t)
  7406. (let ((end (save-excursion (outline-next-heading) (point))))
  7407. (if (or (re-search-forward org-ts-regexp end t)
  7408. (re-search-forward org-ts-regexp-both end t))
  7409. (org-time-string-to-seconds (match-string 0))
  7410. (float-time now))))
  7411. ((= dcst ?c)
  7412. (let ((end (save-excursion (outline-next-heading) (point))))
  7413. (if (re-search-forward
  7414. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7415. end t)
  7416. (org-time-string-to-seconds (match-string 0))
  7417. (float-time now))))
  7418. ((= dcst ?s)
  7419. (let ((end (save-excursion (outline-next-heading) (point))))
  7420. (if (re-search-forward org-scheduled-time-regexp end t)
  7421. (org-time-string-to-seconds (match-string 1))
  7422. (float-time now))))
  7423. ((= dcst ?d)
  7424. (let ((end (save-excursion (outline-next-heading) (point))))
  7425. (if (re-search-forward org-deadline-time-regexp end t)
  7426. (org-time-string-to-seconds (match-string 1))
  7427. (float-time now))))
  7428. ((= dcst ?p)
  7429. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7430. (string-to-char (match-string 2))
  7431. org-priority-default))
  7432. ((= dcst ?r)
  7433. (or (org-entry-get nil property) ""))
  7434. ((= dcst ?o)
  7435. (when (looking-at org-complex-heading-regexp)
  7436. (let* ((m (match-string 2))
  7437. (s (if (member m org-done-keywords) '- '+)))
  7438. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7439. ((= dcst ?f)
  7440. (if getkey-func
  7441. (progn
  7442. (setq tmp (funcall getkey-func))
  7443. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7444. tmp)
  7445. (error "Invalid key function `%s'" getkey-func)))
  7446. (t (error "Invalid sorting type `%c'" sorting-type))))
  7447. nil
  7448. (cond
  7449. ((= dcst ?a) 'org-string-collate-lessp)
  7450. ((= dcst ?f)
  7451. (or compare-func
  7452. (and interactive?
  7453. (org-read-function
  7454. (concat "Function for comparing keys "
  7455. "(empty for default `sort-subr' predicate): ")
  7456. 'allow-empty))))
  7457. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7458. (org-cycle-hide-drawers 'all)
  7459. (when restore-clock?
  7460. (move-marker org-clock-marker
  7461. (1+ (next-single-property-change
  7462. start :org-clock-marker-backup)))
  7463. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7464. '(:org-clock-marker-backup t)))))
  7465. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7466. (message "Sorting entries...done")))
  7467. (defun org-contextualize-keys (alist contexts)
  7468. "Return valid elements in ALIST depending on CONTEXTS.
  7469. `org-agenda-custom-commands' or `org-capture-templates' are the
  7470. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7471. or `org-capture-templates-contexts' are the associated contexts
  7472. definitions."
  7473. (let ((contexts
  7474. ;; normalize contexts
  7475. (mapcar
  7476. (lambda(c) (cond ((listp (cadr c))
  7477. (list (car c) (car c) (nth 1 c)))
  7478. ((string= "" (cadr c))
  7479. (list (car c) (car c) (nth 2 c)))
  7480. (t c)))
  7481. contexts))
  7482. (a alist) r s)
  7483. ;; loop over all commands or templates
  7484. (dolist (c a)
  7485. (let (vrules repl)
  7486. (cond
  7487. ((not (assoc (car c) contexts))
  7488. (push c r))
  7489. ((and (assoc (car c) contexts)
  7490. (setq vrules (org-contextualize-validate-key
  7491. (car c) contexts)))
  7492. (mapc (lambda (vr)
  7493. (unless (equal (car vr) (cadr vr))
  7494. (setq repl vr)))
  7495. vrules)
  7496. (if (not repl) (push c r)
  7497. (push (cadr repl) s)
  7498. (push
  7499. (cons (car c)
  7500. (cdr (or (assoc (cadr repl) alist)
  7501. (error "Undefined key `%s' as contextual replacement for `%s'"
  7502. (cadr repl) (car c)))))
  7503. r))))))
  7504. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7505. (delq
  7506. nil
  7507. (delete-dups
  7508. (mapcar (lambda (x)
  7509. (let ((tpl (car x)))
  7510. (unless (delq
  7511. nil
  7512. (mapcar (lambda (y)
  7513. (equal y tpl))
  7514. s))
  7515. x)))
  7516. (reverse r))))))
  7517. (defun org-contextualize-validate-key (key contexts)
  7518. "Check CONTEXTS for agenda or capture KEY."
  7519. (let (res)
  7520. (dolist (r contexts)
  7521. (dolist (rr (car (last r)))
  7522. (when
  7523. (and (equal key (car r))
  7524. (if (functionp rr) (funcall rr)
  7525. (or (and (eq (car rr) 'in-file)
  7526. (buffer-file-name)
  7527. (string-match (cdr rr) (buffer-file-name)))
  7528. (and (eq (car rr) 'in-mode)
  7529. (string-match (cdr rr) (symbol-name major-mode)))
  7530. (and (eq (car rr) 'in-buffer)
  7531. (string-match (cdr rr) (buffer-name)))
  7532. (when (and (eq (car rr) 'not-in-file)
  7533. (buffer-file-name))
  7534. (not (string-match (cdr rr) (buffer-file-name))))
  7535. (when (eq (car rr) 'not-in-mode)
  7536. (not (string-match (cdr rr) (symbol-name major-mode))))
  7537. (when (eq (car rr) 'not-in-buffer)
  7538. (not (string-match (cdr rr) (buffer-name)))))))
  7539. (push r res))))
  7540. (delete-dups (delq nil res))))
  7541. ;; Defined to provide a value for defcustom, since there is no
  7542. ;; string-collate-greaterp in Emacs.
  7543. (defun org-string-collate-greaterp (s1 s2)
  7544. "Return non-nil if S1 is greater than S2 in collation order."
  7545. (not (org-string-collate-lessp s1 s2)))
  7546. ;;;###autoload
  7547. (defun org-run-like-in-org-mode (cmd)
  7548. "Run a command, pretending that the current buffer is in Org mode.
  7549. This will temporarily bind local variables that are typically bound in
  7550. Org mode to the values they have in Org mode, and then interactively
  7551. call CMD."
  7552. (org-load-modules-maybe)
  7553. (let (binds)
  7554. (dolist (var (org-get-local-variables))
  7555. (when (or (not (boundp (car var)))
  7556. (eq (symbol-value (car var))
  7557. (default-value (car var))))
  7558. (push (list (car var) `(quote ,(cadr var))) binds)))
  7559. (eval `(let ,binds
  7560. (call-interactively (quote ,cmd))))))
  7561. (defun org-get-category (&optional pos force-refresh)
  7562. "Get the category applying to position POS."
  7563. (save-match-data
  7564. (when force-refresh (org-refresh-category-properties))
  7565. (let ((pos (or pos (point))))
  7566. (or (get-text-property pos 'org-category)
  7567. (progn (org-refresh-category-properties)
  7568. (get-text-property pos 'org-category))))))
  7569. ;;; Refresh properties
  7570. (defun org-refresh-properties (dprop tprop)
  7571. "Refresh buffer text properties.
  7572. DPROP is the drawer property and TPROP is either the
  7573. corresponding text property to set, or an alist with each element
  7574. being a text property (as a symbol) and a function to apply to
  7575. the value of the drawer property."
  7576. (let* ((case-fold-search t)
  7577. (inhibit-read-only t)
  7578. (inherit? (org-property-inherit-p dprop))
  7579. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7580. (global-or-keyword (and inherit?
  7581. (org--property-global-or-keyword-value dprop nil))))
  7582. (with-silent-modifications
  7583. (org-with-point-at 1
  7584. ;; Set global and keyword based values to the whole buffer.
  7585. (when global-or-keyword
  7586. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7587. ;; Set values based on property-drawers throughout the document.
  7588. (while (re-search-forward property-re nil t)
  7589. (when (org-at-property-p)
  7590. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7591. (outline-next-heading))))))
  7592. (defun org-refresh-property (tprop p &optional inherit)
  7593. "Refresh the buffer text property TPROP from the drawer property P.
  7594. The refresh happens only for the current entry, or the whole
  7595. sub-tree if optional argument INHERIT is non-nil.
  7596. If point is before first headline, the function applies to the
  7597. part before the first headline. In that particular case, when
  7598. optional argument INHERIT is non-nil, it refreshes properties for
  7599. the whole buffer."
  7600. (save-excursion
  7601. (org-back-to-heading-or-point-min t)
  7602. (let ((start (point))
  7603. (end (save-excursion
  7604. (cond ((and inherit (org-before-first-heading-p))
  7605. (point-max))
  7606. (inherit
  7607. (org-end-of-subtree t t))
  7608. ((outline-next-heading))
  7609. ((point-max))))))
  7610. (if (symbolp tprop)
  7611. ;; TPROP is a text property symbol.
  7612. (put-text-property start end tprop p)
  7613. ;; TPROP is an alist with (property . function) elements.
  7614. (pcase-dolist (`(,prop . ,f) tprop)
  7615. (put-text-property start end prop (funcall f p)))))))
  7616. (defun org-refresh-category-properties ()
  7617. "Refresh category text properties in the buffer."
  7618. (let ((case-fold-search t)
  7619. (inhibit-read-only t)
  7620. (default-category
  7621. (cond ((null org-category)
  7622. (if buffer-file-name
  7623. (file-name-sans-extension
  7624. (file-name-nondirectory buffer-file-name))
  7625. "???"))
  7626. ((symbolp org-category) (symbol-name org-category))
  7627. (t org-category))))
  7628. (with-silent-modifications
  7629. (org-with-wide-buffer
  7630. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7631. ;; keyword. If none is found, fall-back to `org-category' or
  7632. ;; buffer file name, or set it by the document property drawer.
  7633. (put-text-property
  7634. (point-min) (point-max)
  7635. 'org-category
  7636. (catch 'buffer-category
  7637. (goto-char (point-max))
  7638. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7639. (let ((element (org-element-at-point)))
  7640. (when (eq (org-element-type element) 'keyword)
  7641. (throw 'buffer-category
  7642. (org-element-property :value element)))))
  7643. default-category))
  7644. ;; Set categories from the document property drawer or
  7645. ;; property drawers in the outline. If category is found in
  7646. ;; the property drawer for the whole buffer that value
  7647. ;; overrides the keyword-based value set above.
  7648. (goto-char (point-min))
  7649. (let ((regexp (org-re-property "CATEGORY")))
  7650. (while (re-search-forward regexp nil t)
  7651. (let ((value (match-string-no-properties 3)))
  7652. (when (org-at-property-p)
  7653. (put-text-property
  7654. (save-excursion (org-back-to-heading-or-point-min t))
  7655. (save-excursion (if (org-before-first-heading-p)
  7656. (point-max)
  7657. (org-end-of-subtree t t)))
  7658. 'org-category
  7659. value)))))))))
  7660. (defun org-refresh-stats-properties ()
  7661. "Refresh stats text properties in the buffer."
  7662. (with-silent-modifications
  7663. (org-with-point-at 1
  7664. (let ((regexp (concat org-outline-regexp-bol
  7665. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7666. (while (re-search-forward regexp nil t)
  7667. (let* ((numerator (string-to-number (match-string 1)))
  7668. (denominator (and (match-end 2)
  7669. (string-to-number (match-string 2))))
  7670. (stats (cond ((not denominator) numerator) ;percent
  7671. ((= denominator 0) 0)
  7672. (t (/ (* numerator 100) denominator)))))
  7673. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7674. 'org-stats stats)))))))
  7675. (defun org-refresh-effort-properties ()
  7676. "Refresh effort properties."
  7677. (org-refresh-properties
  7678. org-effort-property
  7679. '((effort . identity)
  7680. (effort-minutes . org-duration-to-minutes))))
  7681. (defun org-find-file-at-mouse (ev)
  7682. "Open file link or URL at mouse."
  7683. (interactive "e")
  7684. (mouse-set-point ev)
  7685. (org-open-at-point 'in-emacs))
  7686. (defun org-open-at-mouse (ev)
  7687. "Open file link or URL at mouse.
  7688. See the docstring of `org-open-file' for details."
  7689. (interactive "e")
  7690. (mouse-set-point ev)
  7691. (when (eq major-mode 'org-agenda-mode)
  7692. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7693. (org-open-at-point))
  7694. (defvar org-window-config-before-follow-link nil
  7695. "The window configuration before following a link.
  7696. This is saved in case the need arises to restore it.")
  7697. (defun org--file-default-apps ()
  7698. "Return the default applications for this operating system."
  7699. (pcase system-type
  7700. (`darwin org-file-apps-macos)
  7701. (`windows-nt org-file-apps-windowsnt)
  7702. (_ org-file-apps-gnu)))
  7703. (defun org--file-apps-entry-dlink-p (entry)
  7704. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7705. It assumes that is the case when the entry uses a regular
  7706. expression which has at least one grouping construct and the
  7707. action is either a Lisp form or a command string containing
  7708. \"%1\", i.e., using at least one subexpression match as
  7709. a parameter."
  7710. (pcase entry
  7711. (`(,selector . ,action)
  7712. (and (stringp selector)
  7713. (> (regexp-opt-depth selector) 0)
  7714. (or (and (stringp action)
  7715. (string-match "%[0-9]" action))
  7716. (consp action))))
  7717. (_ nil)))
  7718. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7719. "Convert extensions to regular expressions in the cars of LIST.
  7720. Also, weed out any non-string entries, because the return value
  7721. is used only for regexp matching.
  7722. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7723. point to the symbol `emacs', indicating that the file should be
  7724. opened in Emacs."
  7725. (append
  7726. (delq nil
  7727. (mapcar (lambda (x)
  7728. (unless (not (stringp (car x)))
  7729. (if (string-match "\\W" (car x))
  7730. x
  7731. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7732. list))
  7733. (when add-auto-mode
  7734. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7735. ;;;###autoload
  7736. (defun org-open-file (path &optional in-emacs line search)
  7737. "Open the file at PATH.
  7738. First, this expands any special file name abbreviations. Then the
  7739. configuration variable `org-file-apps' is checked if it contains an
  7740. entry for this file type, and if yes, the corresponding command is launched.
  7741. If no application is found, Emacs simply visits the file.
  7742. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7743. With a double \\[universal-argument] \\[universal-argument] \
  7744. prefix arg, Org tries to avoid opening in Emacs
  7745. and to use an external application to visit the file.
  7746. Optional LINE specifies a line to go to, optional SEARCH a string
  7747. to search for. If LINE or SEARCH is given, the file will be
  7748. opened in Emacs, unless an entry from `org-file-apps' that makes
  7749. use of groups in a regexp matches.
  7750. If you want to change the way frames are used when following a
  7751. link, please customize `org-link-frame-setup'.
  7752. If the file does not exist, throw an error."
  7753. (let* ((file (if (equal path "") buffer-file-name
  7754. (substitute-in-file-name (expand-file-name path))))
  7755. (file-apps (append org-file-apps (org--file-default-apps)))
  7756. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7757. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7758. file-apps))
  7759. (remp (and (assq 'remote apps) (file-remote-p file)))
  7760. (dirp (unless remp (file-directory-p file)))
  7761. (file (if (and dirp org-open-directory-means-index-dot-org)
  7762. (concat (file-name-as-directory file) "index.org")
  7763. file))
  7764. (a-m-a-p (assq 'auto-mode apps))
  7765. (dfile (downcase file))
  7766. ;; Reconstruct the original link from the PATH, LINE and
  7767. ;; SEARCH args.
  7768. (link (cond (line (concat file "::" (number-to-string line)))
  7769. (search (concat file "::" search))
  7770. (t file)))
  7771. (dlink (downcase link))
  7772. (ext
  7773. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7774. (match-string 1 dfile)))
  7775. (save-position-maybe
  7776. (let ((old-buffer (current-buffer))
  7777. (old-pos (point))
  7778. (old-mode major-mode))
  7779. (lambda ()
  7780. (and (derived-mode-p 'org-mode)
  7781. (eq old-mode 'org-mode)
  7782. (or (not (eq old-buffer (current-buffer)))
  7783. (not (eq old-pos (point))))
  7784. (org-mark-ring-push old-pos old-buffer)))))
  7785. cmd link-match-data)
  7786. (cond
  7787. ((member in-emacs '((16) system))
  7788. (setq cmd (cdr (assq 'system apps))))
  7789. (in-emacs (setq cmd 'emacs))
  7790. (t
  7791. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7792. (and dirp (cdr (assq 'directory apps)))
  7793. ;; First, try matching against apps-dlink if we
  7794. ;; get a match here, store the match data for
  7795. ;; later.
  7796. (let ((match (assoc-default dlink apps-dlink
  7797. 'string-match)))
  7798. (if match
  7799. (progn (setq link-match-data (match-data))
  7800. match)
  7801. (progn (setq in-emacs (or in-emacs line search))
  7802. nil))) ; if we have no match in apps-dlink,
  7803. ; always open the file in emacs if line or search
  7804. ; is given (for backwards compatibility)
  7805. (assoc-default dfile
  7806. (org--file-apps-regexp-alist apps a-m-a-p)
  7807. 'string-match)
  7808. (cdr (assoc ext apps))
  7809. (cdr (assq t apps))))))
  7810. (when (eq cmd 'system)
  7811. (setq cmd (cdr (assq 'system apps))))
  7812. (when (eq cmd 'default)
  7813. (setq cmd (cdr (assoc t apps))))
  7814. (when (eq cmd 'mailcap)
  7815. (require 'mailcap)
  7816. (mailcap-parse-mailcaps)
  7817. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7818. (command (mailcap-mime-info mime-type)))
  7819. (if (stringp command)
  7820. (setq cmd command)
  7821. (setq cmd 'emacs))))
  7822. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7823. (not (file-exists-p file))
  7824. (not org-open-non-existing-files))
  7825. (user-error "No such file: %s" file))
  7826. (cond
  7827. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7828. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7829. (while (string-match "['\"]%s['\"]" cmd)
  7830. (setq cmd (replace-match "%s" t t cmd)))
  7831. (setq cmd (replace-regexp-in-string
  7832. "%s"
  7833. (shell-quote-argument (convert-standard-filename file))
  7834. cmd
  7835. nil t))
  7836. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7837. (save-match-data
  7838. (let ((match-index 1)
  7839. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7840. (set-match-data link-match-data)
  7841. (while (<= match-index number-of-groups)
  7842. (let ((regex (concat "%" (number-to-string match-index)))
  7843. (replace-with (match-string match-index dlink)))
  7844. (while (string-match regex cmd)
  7845. (setq cmd (replace-match replace-with t t cmd))))
  7846. (setq match-index (+ match-index 1)))))
  7847. (save-window-excursion
  7848. (message "Running %s...done" cmd)
  7849. (start-process-shell-command cmd nil cmd)
  7850. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7851. ((or (stringp cmd)
  7852. (eq cmd 'emacs))
  7853. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7854. (widen)
  7855. (cond (line (org-goto-line line)
  7856. (when (derived-mode-p 'org-mode) (org-reveal)))
  7857. (search (condition-case err
  7858. (org-link-search search)
  7859. ;; Save position before error-ing out so user
  7860. ;; can easily move back to the original buffer.
  7861. (error (funcall save-position-maybe)
  7862. (error (nth 1 err)))))))
  7863. ((functionp cmd)
  7864. (save-match-data
  7865. (set-match-data link-match-data)
  7866. (condition-case nil
  7867. (funcall cmd file link)
  7868. ;; FIXME: Remove this check when most default installations
  7869. ;; of Emacs have at least Org 9.0.
  7870. ((debug wrong-number-of-arguments wrong-type-argument
  7871. invalid-function)
  7872. (user-error "Please see Org News for version 9.0 about \
  7873. `org-file-apps'--Lisp error: %S" cmd)))))
  7874. ((consp cmd)
  7875. ;; FIXME: Remove this check when most default installations of
  7876. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7877. ;; fall back to `org-link-frame-setup' for an old usage of
  7878. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7879. (user-error "Please see Org News for version 9.0 about \
  7880. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7881. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7882. (funcall save-position-maybe)))
  7883. ;;;###autoload
  7884. (defun org-open-at-point-global ()
  7885. "Follow a link or a time-stamp like Org mode does.
  7886. Also follow links and emails as seen by `thing-at-point'.
  7887. This command can be called in any mode to follow an external
  7888. link or a time-stamp that has Org mode syntax. Its behavior
  7889. is undefined when called on internal links like fuzzy links.
  7890. Raise a user error when there is nothing to follow."
  7891. (interactive)
  7892. (let ((tap-url (thing-at-point 'url))
  7893. (tap-email (thing-at-point 'email)))
  7894. (cond ((org-in-regexp org-link-any-re)
  7895. (org-link-open-from-string (match-string-no-properties 0)))
  7896. ((or (org-in-regexp org-ts-regexp-both nil t)
  7897. (org-in-regexp org-tsr-regexp-both nil t))
  7898. (org-follow-timestamp-link))
  7899. (tap-url (org-link-open-from-string tap-url))
  7900. (tap-email (org-link-open-from-string
  7901. (concat "mailto:" tap-email)))
  7902. (t (user-error "No link found")))))
  7903. (defvar org-open-at-point-functions nil
  7904. "Hook that is run when following a link at point.
  7905. Functions in this hook must return t if they identify and follow
  7906. a link at point. If they don't find anything interesting at point,
  7907. they must return nil.")
  7908. (defun org-open-at-point (&optional arg)
  7909. "Open link, timestamp, footnote or tags at point.
  7910. When point is on a link, follow it. Normally, files will be
  7911. opened by an appropriate application. If the optional prefix
  7912. argument ARG is non-nil, Emacs will visit the file. With
  7913. a double prefix argument, try to open outside of Emacs, in the
  7914. application the system uses for this file type.
  7915. When point is on a timestamp, open the agenda at the day
  7916. specified.
  7917. When point is a footnote definition, move to the first reference
  7918. found. If it is on a reference, move to the associated
  7919. definition.
  7920. When point is on a headline, display a list of every link in the
  7921. entry, so it is possible to pick one, or all, of them. If point
  7922. is on a tag, call `org-tags-view' instead.
  7923. On top of syntactically correct links, this function also tries
  7924. to open links and time-stamps in comments, node properties, and
  7925. keywords if point is on something looking like a timestamp or
  7926. a link."
  7927. (interactive "P")
  7928. (org-load-modules-maybe)
  7929. (setq org-window-config-before-follow-link (current-window-configuration))
  7930. (org-remove-occur-highlights nil nil t)
  7931. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7932. (let* ((context
  7933. ;; Only consider supported types, even if they are not the
  7934. ;; closest one.
  7935. (org-element-lineage
  7936. (org-element-context)
  7937. '(clock comment comment-block footnote-definition
  7938. footnote-reference headline inline-src-block inlinetask
  7939. keyword link node-property planning src-block timestamp)
  7940. t))
  7941. (type (org-element-type context))
  7942. (value (org-element-property :value context)))
  7943. (cond
  7944. ((not type) (user-error "No link found"))
  7945. ;; No valid link at point. For convenience, look if something
  7946. ;; looks like a link under point in some specific places.
  7947. ((memq type '(comment comment-block node-property keyword))
  7948. (call-interactively #'org-open-at-point-global))
  7949. ;; On a headline or an inlinetask, but not on a timestamp,
  7950. ;; a link, a footnote reference.
  7951. ((memq type '(headline inlinetask))
  7952. (org-match-line org-complex-heading-regexp)
  7953. (let ((tags-beg (match-beginning 5))
  7954. (tags-end (match-end 5)))
  7955. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7956. ;; On tags.
  7957. (org-tags-view
  7958. arg
  7959. (save-excursion
  7960. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7961. (end-tag (search-forward ":" tags-end nil 2)))
  7962. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7963. ;; Not on tags.
  7964. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7965. (`(nil . ,_)
  7966. (require 'org-attach)
  7967. (when (org-attach-dir)
  7968. (message "Opening attachment")
  7969. (if (equal arg '(4))
  7970. (org-attach-reveal-in-emacs)
  7971. (org-attach-reveal))))
  7972. (`(,links . ,links-end)
  7973. (dolist (link (if (stringp links) (list links) links))
  7974. (search-forward link nil links-end)
  7975. (goto-char (match-beginning 0))
  7976. (org-open-at-point arg)))))))
  7977. ;; On a footnote reference or at definition's label.
  7978. ((or (eq type 'footnote-reference)
  7979. (and (eq type 'footnote-definition)
  7980. (save-excursion
  7981. ;; Do not validate action when point is on the
  7982. ;; spaces right after the footnote label, in order
  7983. ;; to be on par with behavior on links.
  7984. (skip-chars-forward " \t")
  7985. (let ((begin
  7986. (org-element-property :contents-begin context)))
  7987. (if begin (< (point) begin)
  7988. (= (org-element-property :post-affiliated context)
  7989. (line-beginning-position)))))))
  7990. (org-footnote-action))
  7991. ;; On a planning line. Check if we are really on a timestamp.
  7992. ((and (eq type 'planning)
  7993. (org-in-regexp org-ts-regexp-both nil t))
  7994. (org-follow-timestamp-link))
  7995. ;; On a clock line, make sure point is on the timestamp
  7996. ;; before opening it.
  7997. ((and (eq type 'clock)
  7998. value
  7999. (>= (point) (org-element-property :begin value))
  8000. (<= (point) (org-element-property :end value)))
  8001. (org-follow-timestamp-link))
  8002. ((eq type 'src-block) (org-babel-open-src-block-result))
  8003. ;; Do nothing on white spaces after an object.
  8004. ((>= (point)
  8005. (save-excursion
  8006. (goto-char (org-element-property :end context))
  8007. (skip-chars-backward " \t")
  8008. (point)))
  8009. (user-error "No link found"))
  8010. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8011. ((eq type 'timestamp) (org-follow-timestamp-link))
  8012. ((eq type 'link) (org-link-open context arg))
  8013. (t (user-error "No link found")))))
  8014. (run-hook-with-args 'org-follow-link-hook))
  8015. ;;;###autoload
  8016. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8017. "Offer links in the current entry and return the selected link.
  8018. If there is only one link, return it.
  8019. If NTH is an integer, return the NTH link found.
  8020. If ZERO is a string, check also this string for a link, and if
  8021. there is one, return it."
  8022. (with-current-buffer buffer
  8023. (org-with-wide-buffer
  8024. (goto-char marker)
  8025. (let ((cnt ?0)
  8026. have-zero end links link c)
  8027. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8028. (push (match-string 0 zero) links)
  8029. (setq cnt (1- cnt) have-zero t))
  8030. (save-excursion
  8031. (org-back-to-heading t)
  8032. (setq end (save-excursion (outline-next-heading) (point)))
  8033. (while (re-search-forward org-link-any-re end t)
  8034. (push (match-string 0) links))
  8035. (setq links (org-uniquify (reverse links))))
  8036. (cond
  8037. ((null links)
  8038. (message "No links"))
  8039. ((equal (length links) 1)
  8040. (setq link (car links)))
  8041. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8042. (setq link (nth (if have-zero nth (1- nth)) links)))
  8043. (t ; we have to select a link
  8044. (save-excursion
  8045. (save-window-excursion
  8046. (delete-other-windows)
  8047. (with-output-to-temp-buffer "*Select Link*"
  8048. (dolist (l links)
  8049. (cond
  8050. ((not (string-match org-link-bracket-re l))
  8051. (princ (format "[%c] %s\n" (cl-incf cnt)
  8052. (org-unbracket-string "<" ">" l))))
  8053. ((match-end 2)
  8054. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8055. (match-string 2 l) (match-string 1 l))))
  8056. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8057. (match-string 1 l)))))))
  8058. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8059. (message "Select link to open, RET to open all:")
  8060. (setq c (read-char-exclusive))
  8061. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8062. (when (equal c ?q) (user-error "Abort"))
  8063. (if (equal c ?\C-m)
  8064. (setq link links)
  8065. (setq nth (- c ?0))
  8066. (when have-zero (setq nth (1+ nth)))
  8067. (unless (and (integerp nth) (>= (length links) nth))
  8068. (user-error "Invalid link selection"))
  8069. (setq link (nth (1- nth) links)))))
  8070. (cons link end)))))
  8071. ;;; File search
  8072. (defun org-do-occur (regexp &optional cleanup)
  8073. "Call the Emacs command `occur'.
  8074. If CLEANUP is non-nil, remove the printout of the regular expression
  8075. in the *Occur* buffer. This is useful if the regex is long and not useful
  8076. to read."
  8077. (occur regexp)
  8078. (when cleanup
  8079. (let ((cwin (selected-window)) win beg end)
  8080. (when (setq win (get-buffer-window "*Occur*"))
  8081. (select-window win))
  8082. (goto-char (point-min))
  8083. (when (re-search-forward "match[a-z]+" nil t)
  8084. (setq beg (match-end 0))
  8085. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8086. (setq end (1- (match-beginning 0)))))
  8087. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8088. (goto-char (point-min))
  8089. (select-window cwin))))
  8090. ;;; The Mark Ring
  8091. (defvar org-mark-ring nil
  8092. "Mark ring for positions before jumps in Org mode.")
  8093. (defvar org-mark-ring-last-goto nil
  8094. "Last position in the mark ring used to go back.")
  8095. ;; Fill and close the ring
  8096. (setq org-mark-ring nil)
  8097. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8098. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8099. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8100. org-mark-ring)
  8101. (defun org-mark-ring-push (&optional pos buffer)
  8102. "Put the current position into the mark ring and rotate it.
  8103. Also push position into the Emacs mark ring. If optional
  8104. argument POS and BUFFER are not nil, mark this location instead."
  8105. (interactive)
  8106. (let ((pos (or pos (point)))
  8107. (buffer (or buffer (current-buffer))))
  8108. (with-current-buffer buffer
  8109. (org-with-point-at pos (push-mark nil t)))
  8110. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8111. (move-marker (car org-mark-ring) pos buffer))
  8112. (message
  8113. (substitute-command-keys
  8114. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8115. (defun org-mark-ring-goto (&optional n)
  8116. "Jump to the previous position in the mark ring.
  8117. With prefix arg N, jump back that many stored positions. When
  8118. called several times in succession, walk through the entire ring.
  8119. Org mode commands jumping to a different position in the current file,
  8120. or to another Org file, automatically push the old position onto the ring."
  8121. (interactive "p")
  8122. (let (p m)
  8123. (if (eq last-command this-command)
  8124. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8125. (setq p org-mark-ring))
  8126. (setq org-mark-ring-last-goto p)
  8127. (setq m (car p))
  8128. (pop-to-buffer-same-window (marker-buffer m))
  8129. (goto-char m)
  8130. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8131. ;;; Following specific links
  8132. (defvar org-agenda-buffer-tmp-name)
  8133. (defvar org-agenda-start-on-weekday)
  8134. (defun org-follow-timestamp-link ()
  8135. "Open an agenda view for the time-stamp date/range at point."
  8136. (cond
  8137. ((org-at-date-range-p t)
  8138. (let ((org-agenda-start-on-weekday)
  8139. (t1 (match-string 1))
  8140. (t2 (match-string 2)) tt1 tt2)
  8141. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8142. tt2 (time-to-days (org-time-string-to-time t2)))
  8143. (let ((org-agenda-buffer-tmp-name
  8144. (format "*Org Agenda(a:%s)"
  8145. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8146. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8147. ((org-at-timestamp-p 'lax)
  8148. (let ((org-agenda-buffer-tmp-name
  8149. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8150. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8151. (substring (match-string 1) 0 10)))
  8152. 1)))
  8153. (t (error "This should not happen"))))
  8154. ;;; Following file links
  8155. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8156. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8157. (declare-function mailcap-mime-info
  8158. "mailcap" (string &optional request no-decode))
  8159. (defvar org-wait nil)
  8160. ;;;; Refiling
  8161. (defun org-get-org-file ()
  8162. "Read a filename, with default directory `org-directory'."
  8163. (let ((default (or org-default-notes-file remember-data-file)))
  8164. (read-file-name (format "File name [%s]: " default)
  8165. (file-name-as-directory org-directory)
  8166. default)))
  8167. (defun org-notes-order-reversed-p ()
  8168. "Check if the current file should receive notes in reversed order."
  8169. (cond
  8170. ((not org-reverse-note-order) nil)
  8171. ((eq t org-reverse-note-order) t)
  8172. ((not (listp org-reverse-note-order)) nil)
  8173. (t (catch 'exit
  8174. (dolist (entry org-reverse-note-order)
  8175. (when (string-match (car entry) buffer-file-name)
  8176. (throw 'exit (cdr entry))))))))
  8177. (defvar org-agenda-new-buffers nil
  8178. "Buffers created to visit agenda files.")
  8179. (declare-function org-string-nw-p "org-macs" (s))
  8180. ;;;; Dynamic blocks
  8181. (defun org-find-dblock (name)
  8182. "Find the first dynamic block with name NAME in the buffer.
  8183. If not found, stay at current position and return nil."
  8184. (let ((case-fold-search t) pos)
  8185. (save-excursion
  8186. (goto-char (point-min))
  8187. (setq pos (and (re-search-forward
  8188. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8189. (match-beginning 0))))
  8190. (when pos (goto-char pos))
  8191. pos))
  8192. (defun org-create-dblock (plist)
  8193. "Create a dynamic block section, with parameters taken from PLIST.
  8194. PLIST must contain a :name entry which is used as the name of the block."
  8195. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8196. (end-of-line 1)
  8197. (newline))
  8198. (let ((col (current-column))
  8199. (name (plist-get plist :name)))
  8200. (insert "#+BEGIN: " name)
  8201. (while plist
  8202. (if (eq (car plist) :name)
  8203. (setq plist (cddr plist))
  8204. (insert " " (prin1-to-string (pop plist)))))
  8205. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8206. (beginning-of-line -2)))
  8207. (defun org-prepare-dblock ()
  8208. "Prepare dynamic block for refresh.
  8209. This empties the block, puts the cursor at the insert position and returns
  8210. the property list including an extra property :name with the block name."
  8211. (unless (looking-at org-dblock-start-re)
  8212. (user-error "Not at a dynamic block"))
  8213. (let* ((begdel (1+ (match-end 0)))
  8214. (name (org-no-properties (match-string 1)))
  8215. (params (append (list :name name)
  8216. (read (concat "(" (match-string 3) ")")))))
  8217. (save-excursion
  8218. (beginning-of-line 1)
  8219. (skip-chars-forward " \t")
  8220. (setq params (plist-put params :indentation-column (current-column))))
  8221. (unless (re-search-forward org-dblock-end-re nil t)
  8222. (error "Dynamic block not terminated"))
  8223. (setq params
  8224. (append params
  8225. (list :content (buffer-substring
  8226. begdel (match-beginning 0)))))
  8227. (delete-region begdel (match-beginning 0))
  8228. (goto-char begdel)
  8229. (open-line 1)
  8230. params))
  8231. (defun org-map-dblocks (&optional command)
  8232. "Apply COMMAND to all dynamic blocks in the current buffer.
  8233. If COMMAND is not given, use `org-update-dblock'."
  8234. (let ((cmd (or command 'org-update-dblock)))
  8235. (save-excursion
  8236. (goto-char (point-min))
  8237. (while (re-search-forward org-dblock-start-re nil t)
  8238. (goto-char (match-beginning 0))
  8239. (save-excursion
  8240. (condition-case nil
  8241. (funcall cmd)
  8242. (error (message "Error during update of dynamic block"))))
  8243. (unless (re-search-forward org-dblock-end-re nil t)
  8244. (error "Dynamic block not terminated"))))))
  8245. (defvar org-dynamic-block-alist nil
  8246. "Alist defining all the Org dynamic blocks.
  8247. The key is the dynamic block type name, as a string. The value
  8248. is the function used to insert the dynamic block.
  8249. Use `org-dynamic-block-define' to populate it.")
  8250. (defun org-dynamic-block-function (type)
  8251. "Return function associated to a given dynamic block type.
  8252. TYPE is the dynamic block type, as a string."
  8253. (cdr (assoc type org-dynamic-block-alist)))
  8254. (defun org-dynamic-block-types ()
  8255. "List all defined dynamic block types."
  8256. (mapcar #'car org-dynamic-block-alist))
  8257. (defun org-dynamic-block-define (type func)
  8258. "Define dynamic block TYPE with FUNC.
  8259. TYPE is a string. FUNC is the function creating the dynamic
  8260. block of such type."
  8261. (pcase (assoc type org-dynamic-block-alist)
  8262. (`nil (push (cons type func) org-dynamic-block-alist))
  8263. (def (setcdr def func))))
  8264. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8265. "Insert a dynamic block of type TYPE.
  8266. When used interactively, select the dynamic block types among
  8267. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8268. is non-nil, call the dynamic block function interactively."
  8269. (interactive (list (completing-read "Dynamic block: "
  8270. (org-dynamic-block-types))
  8271. t))
  8272. (pcase (org-dynamic-block-function type)
  8273. (`nil (error "No such dynamic block: %S" type))
  8274. ((and f (pred functionp))
  8275. (if interactive-p (call-interactively f) (funcall f)))
  8276. (_ (error "Invalid function for dynamic block %S" type))))
  8277. (defun org-dblock-update (&optional arg)
  8278. "User command for updating dynamic blocks.
  8279. Update the dynamic block at point. With prefix ARG, update all dynamic
  8280. blocks in the buffer."
  8281. (interactive "P")
  8282. (if arg
  8283. (org-update-all-dblocks)
  8284. (or (looking-at org-dblock-start-re)
  8285. (org-beginning-of-dblock))
  8286. (org-update-dblock)))
  8287. (defun org-update-dblock ()
  8288. "Update the dynamic block at point.
  8289. This means to empty the block, parse for parameters and then call
  8290. the correct writing function."
  8291. (interactive)
  8292. (save-excursion
  8293. (let* ((win (selected-window))
  8294. (pos (point))
  8295. (line (org-current-line))
  8296. (params (org-prepare-dblock))
  8297. (name (plist-get params :name))
  8298. (indent (plist-get params :indentation-column))
  8299. (cmd (intern (concat "org-dblock-write:" name))))
  8300. (message "Updating dynamic block `%s' at line %d..." name line)
  8301. (funcall cmd params)
  8302. (message "Updating dynamic block `%s' at line %d...done" name line)
  8303. (goto-char pos)
  8304. (when (and indent (> indent 0))
  8305. (setq indent (make-string indent ?\ ))
  8306. (save-excursion
  8307. (select-window win)
  8308. (org-beginning-of-dblock)
  8309. (forward-line 1)
  8310. (while (not (looking-at org-dblock-end-re))
  8311. (insert indent)
  8312. (beginning-of-line 2))
  8313. (when (looking-at org-dblock-end-re)
  8314. (and (looking-at "[ \t]+")
  8315. (replace-match ""))
  8316. (insert indent)))))))
  8317. (defun org-beginning-of-dblock ()
  8318. "Find the beginning of the dynamic block at point.
  8319. Error if there is no such block at point."
  8320. (let ((pos (point))
  8321. beg)
  8322. (end-of-line 1)
  8323. (if (and (re-search-backward org-dblock-start-re nil t)
  8324. (setq beg (match-beginning 0))
  8325. (re-search-forward org-dblock-end-re nil t)
  8326. (> (match-end 0) pos))
  8327. (goto-char beg)
  8328. (goto-char pos)
  8329. (error "Not in a dynamic block"))))
  8330. (defun org-update-all-dblocks ()
  8331. "Update all dynamic blocks in the buffer.
  8332. This function can be used in a hook."
  8333. (interactive)
  8334. (when (derived-mode-p 'org-mode)
  8335. (org-map-dblocks 'org-update-dblock)))
  8336. ;;;; Completion
  8337. (declare-function org-export-backend-options "ox" (cl-x) t)
  8338. (defun org-get-export-keywords ()
  8339. "Return a list of all currently understood export keywords.
  8340. Export keywords include options, block names, attributes and
  8341. keywords relative to each registered export back-end."
  8342. (let (keywords)
  8343. (dolist (backend
  8344. (bound-and-true-p org-export-registered-backends)
  8345. (delq nil keywords))
  8346. ;; Back-end name (for keywords, like #+LATEX:)
  8347. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8348. (dolist (option-entry (org-export-backend-options backend))
  8349. ;; Back-end options.
  8350. (push (nth 1 option-entry) keywords)))))
  8351. (defconst org-options-keywords
  8352. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8353. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8354. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8355. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8356. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8357. (defcustom org-structure-template-alist
  8358. '(("a" . "export ascii")
  8359. ("c" . "center")
  8360. ("C" . "comment")
  8361. ("e" . "example")
  8362. ("E" . "export")
  8363. ("h" . "export html")
  8364. ("l" . "export latex")
  8365. ("q" . "quote")
  8366. ("s" . "src")
  8367. ("v" . "verse"))
  8368. "An alist of keys and block types.
  8369. `org-insert-structure-template' will display a menu with this
  8370. list of templates to choose from. The block type is inserted,
  8371. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8372. The menu keys are defined by the car of each entry in this alist.
  8373. If two entries have the keys \"a\" and \"aa\" respectively, the
  8374. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8375. latter will be inserted by typing \"aa\". If an entry with the
  8376. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8377. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8378. block can be inserted by pressing TAB after the string \"<KEY\"."
  8379. :group 'org-edit-structure
  8380. :type '(repeat
  8381. (cons (string :tag "Key")
  8382. (string :tag "Template")))
  8383. :package-version '(Org . "9.2"))
  8384. (defun org--check-org-structure-template-alist (&optional checklist)
  8385. "Check whether `org-structure-template-alist' is set up correctly.
  8386. In particular, check if the Org 9.2 format is used as opposed to
  8387. previous format."
  8388. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8389. (or (eval checklist)
  8390. org-structure-template-alist))))
  8391. (when elm
  8392. (org-display-warning
  8393. (format "
  8394. Please update the entries of `%s'.
  8395. In Org 9.2 the format was changed from something like
  8396. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8397. to something like
  8398. (\"s\" . \"src\")
  8399. Please refer to the documentation of `org-structure-template-alist'.
  8400. The following entries must be updated:
  8401. %s"
  8402. (or checklist 'org-structure-template-alist)
  8403. (pp-to-string elm))))))
  8404. (defun org--insert-structure-template-mks ()
  8405. "Present `org-structure-template-alist' with `org-mks'.
  8406. Menus are added if keys require more than one keystroke. Tabs
  8407. are added to single key entries when more than one stroke is
  8408. needed. Keys longer than two characters are reduced to two
  8409. characters."
  8410. (org--check-org-structure-template-alist)
  8411. (let* (case-fold-search
  8412. (templates (append org-structure-template-alist
  8413. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8414. (keys (mapcar #'car templates))
  8415. (start-letters
  8416. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8417. ;; Sort each element of `org-structure-template-alist' into
  8418. ;; sublists according to the first letter.
  8419. (superlist
  8420. (mapcar (lambda (letter)
  8421. (list letter
  8422. (cl-remove-if-not
  8423. (apply-partially #'string-match-p (concat "^" letter))
  8424. templates :key #'car)))
  8425. start-letters)))
  8426. (org-mks
  8427. (apply #'append
  8428. ;; Make an `org-mks' table. If only one element is
  8429. ;; present in a sublist, make it part of the top-menu,
  8430. ;; otherwise make a submenu according to the starting
  8431. ;; letter and populate it.
  8432. (mapcar (lambda (sublist)
  8433. (if (eq 1 (length (cadr sublist)))
  8434. (mapcar (lambda (elm)
  8435. (list (substring (car elm) 0 1)
  8436. (cdr elm) ""))
  8437. (cadr sublist))
  8438. ;; Create submenu.
  8439. (let* ((topkey (car sublist))
  8440. (elms (cadr sublist))
  8441. (keys (mapcar #'car elms))
  8442. (long (> (length elms) 3)))
  8443. (append
  8444. (list
  8445. ;; Make a description of the submenu.
  8446. (list topkey
  8447. (concat
  8448. (mapconcat #'cdr
  8449. (cl-subseq elms 0 (if long 3 (length elms)))
  8450. ", ")
  8451. (when long ", ..."))))
  8452. ;; List of entries in submenu.
  8453. (cl-mapcar #'list
  8454. (org--insert-structure-template-unique-keys keys)
  8455. (mapcar #'cdr elms)
  8456. (make-list (length elms) ""))))))
  8457. superlist))
  8458. "Select a key\n============"
  8459. "Key: ")))
  8460. (defun org--insert-structure-template-unique-keys (keys)
  8461. "Make a list of unique, two characters long elements from KEYS.
  8462. Elements of length one have a tab appended. Elements of length
  8463. two are kept as is. Longer elements are truncated to length two.
  8464. If an element cannot be made unique, an error is raised."
  8465. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8466. menu-keys)
  8467. (dolist (key ordered-keys)
  8468. (let ((potential-key
  8469. (cl-case (length key)
  8470. (1 (concat key "\t"))
  8471. (2 key)
  8472. (otherwise
  8473. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8474. (mapcar (apply-partially #'concat (substring key 0 1))
  8475. (split-string (substring key 1) "" t)))))))
  8476. (if (or (not potential-key) (assoc potential-key menu-keys))
  8477. (user-error "Could not make unique key for %s." key)
  8478. (push (cons potential-key key) menu-keys))))
  8479. (mapcar #'car
  8480. (cl-sort menu-keys #'<
  8481. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8482. (defun org-insert-structure-template (type)
  8483. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8484. Select a block from `org-structure-template-alist' then type
  8485. either RET, TAB or SPC to write the block type. With an active
  8486. region, wrap the region in the block. Otherwise, insert an empty
  8487. block."
  8488. (interactive
  8489. (list (pcase (org--insert-structure-template-mks)
  8490. (`("\t" . ,_) (read-string "Structure type: "))
  8491. (`(,_ ,choice . ,_) choice))))
  8492. (let* ((region? (use-region-p))
  8493. (region-start (and region? (region-beginning)))
  8494. (region-end (and region? (copy-marker (region-end))))
  8495. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8496. (verbatim? (string-match-p
  8497. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8498. type)))
  8499. (when region? (goto-char region-start))
  8500. (let ((column (current-indentation)))
  8501. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8502. (beginning-of-line)
  8503. (insert "\n"))
  8504. (save-excursion
  8505. (indent-to column)
  8506. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8507. (when region?
  8508. (when verbatim? (org-escape-code-in-region (point) region-end))
  8509. (goto-char region-end)
  8510. ;; Ignore empty lines at the end of the region.
  8511. (skip-chars-backward " \r\t\n")
  8512. (end-of-line))
  8513. (unless (bolp) (insert "\n"))
  8514. (indent-to column)
  8515. (insert (format "#+end_%s" (car (split-string type))))
  8516. (if (looking-at "[ \t]*$") (replace-match "")
  8517. (insert "\n"))
  8518. (when (and (eobp) (not (bolp))) (insert "\n")))
  8519. (if extended? (end-of-line)
  8520. (forward-line)
  8521. (skip-chars-forward " \t")))))
  8522. ;;;; TODO, DEADLINE, Comments
  8523. (defun org-toggle-comment ()
  8524. "Change the COMMENT state of an entry."
  8525. (interactive)
  8526. (save-excursion
  8527. (org-back-to-heading)
  8528. (let ((case-fold-search nil))
  8529. (looking-at org-complex-heading-regexp))
  8530. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8531. (skip-chars-forward " \t")
  8532. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8533. (if (org-in-commented-heading-p t)
  8534. (delete-region (point)
  8535. (progn (search-forward " " (line-end-position) 'move)
  8536. (skip-chars-forward " \t")
  8537. (point)))
  8538. (insert org-comment-string)
  8539. (unless (eolp) (insert " ")))))
  8540. (defvar org-last-todo-state-is-todo nil
  8541. "This is non-nil when the last TODO state change led to a TODO state.
  8542. If the last change removed the TODO tag or switched to DONE, then
  8543. this is nil.")
  8544. (defvar org-todo-setup-filter-hook nil
  8545. "Hook for functions that pre-filter todo specs.
  8546. Each function takes a todo spec and returns either nil or the spec
  8547. transformed into canonical form." )
  8548. (defvar org-todo-get-default-hook nil
  8549. "Hook for functions that get a default item for todo.
  8550. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8551. nil or a string to be used for the todo mark." )
  8552. (defvar org-agenda-headline-snapshot-before-repeat)
  8553. (defun org-current-effective-time ()
  8554. "Return current time adjusted for `org-extend-today-until' variable."
  8555. (let* ((ct (org-current-time))
  8556. (dct (decode-time ct))
  8557. (ct1
  8558. (cond
  8559. (org-use-last-clock-out-time-as-effective-time
  8560. (or (org-clock-get-last-clock-out-time) ct))
  8561. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8562. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8563. (t ct))))
  8564. ct1))
  8565. (defun org-todo-yesterday (&optional arg)
  8566. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8567. (interactive "P")
  8568. (if (eq major-mode 'org-agenda-mode)
  8569. (apply 'org-agenda-todo-yesterday arg)
  8570. (let* ((org-use-effective-time t)
  8571. (hour (nth 2 (decode-time (org-current-time))))
  8572. (org-extend-today-until (1+ hour)))
  8573. (org-todo arg))))
  8574. (defvar org-block-entry-blocking ""
  8575. "First entry preventing the TODO state change.")
  8576. (defun org-cancel-repeater ()
  8577. "Cancel a repeater by setting its numeric value to zero."
  8578. (interactive)
  8579. (save-excursion
  8580. (org-back-to-heading t)
  8581. (let ((bound1 (point))
  8582. (bound0 (save-excursion (outline-next-heading) (point))))
  8583. (when (and (re-search-forward
  8584. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8585. org-deadline-time-regexp "\\)\\|\\("
  8586. org-ts-regexp "\\)")
  8587. bound0 t)
  8588. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8589. bound1 t))
  8590. (replace-match "0" t nil nil 1)))))
  8591. (defvar org-state)
  8592. (defvar org-blocked-by-checkboxes)
  8593. (defun org-todo (&optional arg)
  8594. "Change the TODO state of an item.
  8595. The state of an item is given by a keyword at the start of the heading,
  8596. like
  8597. *** TODO Write paper
  8598. *** DONE Call mom
  8599. The different keywords are specified in the variable `org-todo-keywords'.
  8600. By default the available states are \"TODO\" and \"DONE\". So, for this
  8601. example: when the item starts with TODO, it is changed to DONE.
  8602. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8603. DONE are present, add TODO at the beginning of the heading.
  8604. You can set up single-character keys to fast-select the new state. See the
  8605. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8606. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8607. and take a
  8608. logging note.
  8609. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8610. next set of TODO \
  8611. keywords (nextset).
  8612. Another way to achieve this is `S-C-<right>'.
  8613. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8614. prefix, circumvent any state blocking.
  8615. With numeric prefix arg, switch to the Nth state.
  8616. With a numeric prefix arg of 0, inhibit note taking for the change.
  8617. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8618. When called through ELisp, arg is also interpreted in the following way:
  8619. `none' -> empty state
  8620. \"\" -> switch to empty state
  8621. `done' -> switch to DONE
  8622. `nextset' -> switch to the next set of keywords
  8623. `previousset' -> switch to the previous set of keywords
  8624. \"WAITING\" -> switch to the specified keyword, but only if it
  8625. really is a member of `org-todo-keywords'."
  8626. (interactive "P")
  8627. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8628. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8629. 'region-start-level 'region))
  8630. org-loop-over-headlines-in-active-region)
  8631. (org-map-entries
  8632. (lambda () (org-todo arg))
  8633. nil cl
  8634. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8635. (when (equal arg '(16)) (setq arg 'nextset))
  8636. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8637. (let ((org-blocker-hook org-blocker-hook)
  8638. commentp
  8639. case-fold-search)
  8640. (when (equal arg '(64))
  8641. (setq arg nil org-blocker-hook nil))
  8642. (when (and org-blocker-hook
  8643. (or org-inhibit-blocking
  8644. (org-entry-get nil "NOBLOCKING")))
  8645. (setq org-blocker-hook nil))
  8646. (save-excursion
  8647. (catch 'exit
  8648. (org-back-to-heading t)
  8649. (when (org-in-commented-heading-p t)
  8650. (org-toggle-comment)
  8651. (setq commentp t))
  8652. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8653. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8654. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8655. (let* ((match-data (match-data))
  8656. (startpos (copy-marker (line-beginning-position)))
  8657. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8658. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8659. (org-log-done org-log-done)
  8660. (org-log-repeat org-log-repeat)
  8661. (org-todo-log-states org-todo-log-states)
  8662. (org-inhibit-logging
  8663. (if (equal arg 0)
  8664. (progn (setq arg nil) 'note) org-inhibit-logging))
  8665. (this (match-string 1))
  8666. (hl-pos (match-beginning 0))
  8667. (head (org-get-todo-sequence-head this))
  8668. (ass (assoc head org-todo-kwd-alist))
  8669. (interpret (nth 1 ass))
  8670. (done-word (nth 3 ass))
  8671. (final-done-word (nth 4 ass))
  8672. (org-last-state (or this ""))
  8673. (completion-ignore-case t)
  8674. (member (member this org-todo-keywords-1))
  8675. (tail (cdr member))
  8676. (org-state (cond
  8677. ((eq arg 'right)
  8678. ;; Next state
  8679. (if this
  8680. (if tail (car tail) nil)
  8681. (car org-todo-keywords-1)))
  8682. ((eq arg 'left)
  8683. ;; Previous state
  8684. (unless (equal member org-todo-keywords-1)
  8685. (if this
  8686. (nth (- (length org-todo-keywords-1)
  8687. (length tail) 2)
  8688. org-todo-keywords-1)
  8689. (org-last org-todo-keywords-1))))
  8690. (arg
  8691. ;; User or caller requests a specific state.
  8692. (cond
  8693. ((equal arg "") nil)
  8694. ((eq arg 'none) nil)
  8695. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8696. ((eq arg 'nextset)
  8697. (or (car (cdr (member head org-todo-heads)))
  8698. (car org-todo-heads)))
  8699. ((eq arg 'previousset)
  8700. (let ((org-todo-heads (reverse org-todo-heads)))
  8701. (or (car (cdr (member head org-todo-heads)))
  8702. (car org-todo-heads))))
  8703. ((car (member arg org-todo-keywords-1)))
  8704. ((stringp arg)
  8705. (user-error "State `%s' not valid in this file" arg))
  8706. ((nth (1- (prefix-numeric-value arg))
  8707. org-todo-keywords-1))))
  8708. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8709. ;; Use fast selection.
  8710. (org-fast-todo-selection this))
  8711. ((null member) (or head (car org-todo-keywords-1)))
  8712. ((equal this final-done-word) nil) ;-> make empty
  8713. ((null tail) nil) ;-> first entry
  8714. ((memq interpret '(type priority))
  8715. (if (eq this-command last-command)
  8716. (car tail)
  8717. (if (> (length tail) 0)
  8718. (or done-word (car org-done-keywords))
  8719. nil)))
  8720. (t
  8721. (car tail))))
  8722. (org-state (or
  8723. (run-hook-with-args-until-success
  8724. 'org-todo-get-default-hook org-state org-last-state)
  8725. org-state))
  8726. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8727. (change-plist (list :type 'todo-state-change :from this :to org-state
  8728. :position startpos))
  8729. dolog now-done-p)
  8730. (when org-blocker-hook
  8731. (let (org-blocked-by-checkboxes block-reason)
  8732. (setq org-last-todo-state-is-todo
  8733. (not (member this org-done-keywords)))
  8734. (unless (save-excursion
  8735. (save-match-data
  8736. (org-with-wide-buffer
  8737. (run-hook-with-args-until-failure
  8738. 'org-blocker-hook change-plist))))
  8739. (setq block-reason (if org-blocked-by-checkboxes
  8740. "contained checkboxes"
  8741. (format "\"%s\"" org-block-entry-blocking)))
  8742. (if (called-interactively-p 'interactive)
  8743. (user-error "TODO state change from %s to %s blocked (by %s)"
  8744. this org-state block-reason)
  8745. ;; Fail silently.
  8746. (message "TODO state change from %s to %s blocked (by %s)"
  8747. this org-state block-reason)
  8748. (throw 'exit nil)))))
  8749. (store-match-data match-data)
  8750. (replace-match next t t)
  8751. (cond ((and org-state (equal this org-state))
  8752. (message "TODO state was already %s" (org-trim next)))
  8753. ((not (pos-visible-in-window-p hl-pos))
  8754. (message "TODO state changed to %s" (org-trim next))))
  8755. (unless head
  8756. (setq head (org-get-todo-sequence-head org-state)
  8757. ass (assoc head org-todo-kwd-alist)
  8758. interpret (nth 1 ass)
  8759. done-word (nth 3 ass)
  8760. final-done-word (nth 4 ass)))
  8761. (when (memq arg '(nextset previousset))
  8762. (message "Keyword-Set %d/%d: %s"
  8763. (- (length org-todo-sets) -1
  8764. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8765. (length org-todo-sets)
  8766. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8767. (setq org-last-todo-state-is-todo
  8768. (not (member org-state org-done-keywords)))
  8769. (setq now-done-p (and (member org-state org-done-keywords)
  8770. (not (member this org-done-keywords))))
  8771. (and logging (org-local-logging logging))
  8772. (when (or (and (or org-todo-log-states org-log-done)
  8773. (not (eq org-inhibit-logging t))
  8774. (not (memq arg '(nextset previousset))))
  8775. force-log)
  8776. ;; We need to look at recording a time and note.
  8777. (setq dolog (or (if force-log 'note)
  8778. (nth 1 (assoc org-state org-todo-log-states))
  8779. (nth 2 (assoc this org-todo-log-states))))
  8780. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8781. (setq dolog 'time))
  8782. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8783. (and org-state
  8784. (member org-state org-not-done-keywords)
  8785. (not (member this org-not-done-keywords))))
  8786. ;; This is now a todo state and was not one before
  8787. ;; If there was a CLOSED time stamp, get rid of it.
  8788. (org-add-planning-info nil nil 'closed))
  8789. (when (and now-done-p org-log-done)
  8790. ;; It is now done, and it was not done before.
  8791. (org-add-planning-info 'closed (org-current-effective-time))
  8792. (when (and (not dolog) (eq 'note org-log-done))
  8793. (org-add-log-setup 'done org-state this 'note)))
  8794. (when (and org-state dolog)
  8795. ;; This is a non-nil state, and we need to log it.
  8796. (org-add-log-setup 'state org-state this dolog)))
  8797. ;; Fixup tag positioning.
  8798. (org-todo-trigger-tag-changes org-state)
  8799. (when org-auto-align-tags (org-align-tags))
  8800. (when org-provide-todo-statistics
  8801. (org-update-parent-todo-statistics))
  8802. (when (bound-and-true-p org-clock-out-when-done)
  8803. (org-clock-out-if-current))
  8804. (run-hooks 'org-after-todo-state-change-hook)
  8805. (when (and arg (not (member org-state org-done-keywords)))
  8806. (setq head (org-get-todo-sequence-head org-state)))
  8807. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8808. ;; Do we need to trigger a repeat?
  8809. (when now-done-p
  8810. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8811. ;; This is for the agenda, take a snapshot of the headline.
  8812. (save-match-data
  8813. (setq org-agenda-headline-snapshot-before-repeat
  8814. (org-get-heading))))
  8815. (org-auto-repeat-maybe org-state))
  8816. ;; Fixup cursor location if close to the keyword.
  8817. (when (and (outline-on-heading-p)
  8818. (not (bolp))
  8819. (save-excursion (beginning-of-line 1)
  8820. (looking-at org-todo-line-regexp))
  8821. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8822. (goto-char (or (match-end 2) (match-end 1)))
  8823. (and (looking-at " ")
  8824. (not (looking-at " *:"))
  8825. (just-one-space)))
  8826. (when org-trigger-hook
  8827. (save-excursion
  8828. (run-hook-with-args 'org-trigger-hook change-plist)))
  8829. (when commentp (org-toggle-comment))))))))
  8830. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8831. "Block turning an entry into a TODO, using the hierarchy.
  8832. This checks whether the current task should be blocked from state
  8833. changes. Such blocking occurs when:
  8834. 1. The task has children which are not all in a completed state.
  8835. 2. A task has a parent with the property :ORDERED:, and there
  8836. are siblings prior to the current task with incomplete
  8837. status.
  8838. 3. The parent of the task is blocked because it has siblings that should
  8839. be done first, or is child of a block grandparent TODO entry."
  8840. (if (not org-enforce-todo-dependencies)
  8841. t ; if locally turned off don't block
  8842. (catch 'dont-block
  8843. ;; If this is not a todo state change, or if this entry is already DONE,
  8844. ;; do not block
  8845. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8846. (member (plist-get change-plist :from)
  8847. (cons 'done org-done-keywords))
  8848. (member (plist-get change-plist :to)
  8849. (cons 'todo org-not-done-keywords))
  8850. (not (plist-get change-plist :to)))
  8851. (throw 'dont-block t))
  8852. ;; If this task has children, and any are undone, it's blocked
  8853. (save-excursion
  8854. (org-back-to-heading t)
  8855. (let ((this-level (funcall outline-level)))
  8856. (outline-next-heading)
  8857. (let ((child-level (funcall outline-level)))
  8858. (while (and (not (eobp))
  8859. (> child-level this-level))
  8860. ;; this todo has children, check whether they are all
  8861. ;; completed
  8862. (when (and (not (org-entry-is-done-p))
  8863. (org-entry-is-todo-p))
  8864. (setq org-block-entry-blocking (org-get-heading))
  8865. (throw 'dont-block nil))
  8866. (outline-next-heading)
  8867. (setq child-level (funcall outline-level))))))
  8868. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8869. ;; any previous siblings are undone, it's blocked
  8870. (save-excursion
  8871. (org-back-to-heading t)
  8872. (let* ((pos (point))
  8873. (parent-pos (and (org-up-heading-safe) (point)))
  8874. (case-fold-search nil))
  8875. (unless parent-pos (throw 'dont-block t)) ; no parent
  8876. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8877. (forward-line 1)
  8878. (re-search-forward org-not-done-heading-regexp pos t))
  8879. (setq org-block-entry-blocking (match-string 0))
  8880. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8881. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8882. (while t
  8883. (goto-char parent-pos)
  8884. (unless (looking-at org-not-done-heading-regexp)
  8885. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8886. (setq pos (point))
  8887. (setq parent-pos (and (org-up-heading-safe) (point)))
  8888. (unless parent-pos (throw 'dont-block t)) ; no parent
  8889. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8890. (forward-line 1)
  8891. (re-search-forward org-not-done-heading-regexp pos t)
  8892. (setq org-block-entry-blocking (org-get-heading)))
  8893. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8894. (defcustom org-track-ordered-property-with-tag nil
  8895. "Should the ORDERED property also be shown as a tag?
  8896. The ORDERED property decides if an entry should require subtasks to be
  8897. completed in sequence. Since a property is not very visible, setting
  8898. this option means that toggling the ORDERED property with the command
  8899. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8900. not relevant for the behavior, but it makes things more visible.
  8901. Note that toggling the tag with tags commands will not change the property
  8902. and therefore not influence behavior!
  8903. This can be t, meaning the tag ORDERED should be used. It can also be a
  8904. string to select a different tag for this task."
  8905. :group 'org-todo
  8906. :type '(choice
  8907. (const :tag "No tracking" nil)
  8908. (const :tag "Track with ORDERED tag" t)
  8909. (string :tag "Use other tag")))
  8910. (defun org-toggle-ordered-property ()
  8911. "Toggle the ORDERED property of the current entry.
  8912. For better visibility, you can track the value of this property with a tag.
  8913. See variable `org-track-ordered-property-with-tag'."
  8914. (interactive)
  8915. (let* ((t1 org-track-ordered-property-with-tag)
  8916. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8917. (save-excursion
  8918. (org-back-to-heading)
  8919. (if (org-entry-get nil "ORDERED")
  8920. (progn
  8921. (org-delete-property "ORDERED")
  8922. (and tag (org-toggle-tag tag 'off))
  8923. (message "Subtasks can be completed in arbitrary order"))
  8924. (org-entry-put nil "ORDERED" "t")
  8925. (and tag (org-toggle-tag tag 'on))
  8926. (message "Subtasks must be completed in sequence")))))
  8927. (defun org-block-todo-from-checkboxes (change-plist)
  8928. "Block turning an entry into a TODO, using checkboxes.
  8929. This checks whether the current task should be blocked from state
  8930. changes because there are unchecked boxes in this entry."
  8931. (if (not org-enforce-todo-checkbox-dependencies)
  8932. t ; if locally turned off don't block
  8933. (catch 'dont-block
  8934. ;; If this is not a todo state change, or if this entry is already DONE,
  8935. ;; do not block
  8936. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8937. (member (plist-get change-plist :from)
  8938. (cons 'done org-done-keywords))
  8939. (member (plist-get change-plist :to)
  8940. (cons 'todo org-not-done-keywords))
  8941. (not (plist-get change-plist :to)))
  8942. (throw 'dont-block t))
  8943. ;; If this task has checkboxes that are not checked, it's blocked
  8944. (save-excursion
  8945. (org-back-to-heading t)
  8946. (let ((beg (point)) end)
  8947. (outline-next-heading)
  8948. (setq end (point))
  8949. (goto-char beg)
  8950. (when (org-list-search-forward
  8951. (concat (org-item-beginning-re)
  8952. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8953. "\\[[- ]\\]")
  8954. end t)
  8955. (when (boundp 'org-blocked-by-checkboxes)
  8956. (setq org-blocked-by-checkboxes t))
  8957. (throw 'dont-block nil))))
  8958. t))) ; do not block
  8959. (defun org-entry-blocked-p ()
  8960. "Non-nil if entry at point is blocked."
  8961. (and (not (org-entry-get nil "NOBLOCKING"))
  8962. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8963. (not (run-hook-with-args-until-failure
  8964. 'org-blocker-hook
  8965. (list :type 'todo-state-change
  8966. :position (point)
  8967. :from 'todo
  8968. :to 'done)))))
  8969. (defun org-update-statistics-cookies (all)
  8970. "Update the statistics cookie, either from TODO or from checkboxes.
  8971. This should be called with the cursor in a line with a statistics
  8972. cookie. When called with a \\[universal-argument] prefix, update
  8973. all statistics cookies in the buffer."
  8974. (interactive "P")
  8975. (if all
  8976. (progn
  8977. (org-update-checkbox-count 'all)
  8978. (org-map-entries 'org-update-parent-todo-statistics))
  8979. (if (not (org-at-heading-p))
  8980. (org-update-checkbox-count)
  8981. (let ((pos (point-marker))
  8982. end l1 l2)
  8983. (ignore-errors (org-back-to-heading t))
  8984. (if (not (org-at-heading-p))
  8985. (org-update-checkbox-count)
  8986. (setq l1 (org-outline-level))
  8987. (setq end (save-excursion
  8988. (outline-next-heading)
  8989. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8990. (point)))
  8991. (if (and (save-excursion
  8992. (re-search-forward
  8993. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8994. (not (save-excursion (re-search-forward
  8995. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8996. (org-update-checkbox-count)
  8997. (if (and l2 (> l2 l1))
  8998. (progn
  8999. (goto-char end)
  9000. (org-update-parent-todo-statistics))
  9001. (goto-char pos)
  9002. (beginning-of-line 1)
  9003. (while (re-search-forward
  9004. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9005. (point-at-eol) t)
  9006. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9007. (goto-char pos)
  9008. (move-marker pos nil)))))
  9009. (defvar org-entry-property-inherited-from) ;; defined below
  9010. (defun org-update-parent-todo-statistics ()
  9011. "Update any statistics cookie in the parent of the current headline.
  9012. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9013. the entire subtree and this will travel up the hierarchy and update
  9014. statistics everywhere."
  9015. (let* ((prop (save-excursion (org-up-heading-safe)
  9016. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9017. (recursive (or (not org-hierarchical-todo-statistics)
  9018. (and prop (string-match "\\<recursive\\>" prop))))
  9019. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9020. 0))
  9021. (first t)
  9022. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9023. level ltoggle l1 new ndel
  9024. (cnt-all 0) (cnt-done 0) is-percent kwd
  9025. checkbox-beg cookie-present)
  9026. (catch 'exit
  9027. (save-excursion
  9028. (beginning-of-line 1)
  9029. (setq ltoggle (funcall outline-level))
  9030. ;; Three situations are to consider:
  9031. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9032. ;; to the top-level ancestor on the headline;
  9033. ;; 2. If parent has "recursive" property, repeat up to the
  9034. ;; headline setting that property, taking inheritance into
  9035. ;; account;
  9036. ;; 3. Else, move up to direct parent and proceed only once.
  9037. (while (and (setq level (org-up-heading-safe))
  9038. (or recursive first)
  9039. (>= (point) lim))
  9040. (setq first nil cookie-present nil)
  9041. (unless (and level
  9042. (not (string-match
  9043. "\\<checkbox\\>"
  9044. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9045. "")))))
  9046. (throw 'exit nil))
  9047. (while (re-search-forward box-re (point-at-eol) t)
  9048. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9049. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9050. (save-match-data
  9051. (unless (outline-next-heading) (throw 'exit nil))
  9052. (while (and (looking-at org-complex-heading-regexp)
  9053. (> (setq l1 (length (match-string 1))) level))
  9054. (setq kwd (and (or recursive (= l1 ltoggle))
  9055. (match-string 2)))
  9056. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9057. (and (eq org-provide-todo-statistics t)
  9058. (or (member kwd org-done-keywords)))
  9059. (and (listp org-provide-todo-statistics)
  9060. (stringp (car org-provide-todo-statistics))
  9061. (or (member kwd org-provide-todo-statistics)
  9062. (member kwd org-done-keywords)))
  9063. (and (listp org-provide-todo-statistics)
  9064. (listp (car org-provide-todo-statistics))
  9065. (or (member kwd (car org-provide-todo-statistics))
  9066. (and (member kwd org-done-keywords)
  9067. (member kwd (cadr org-provide-todo-statistics))))))
  9068. (setq cnt-all (1+ cnt-all))
  9069. (and (eq org-provide-todo-statistics t)
  9070. kwd
  9071. (setq cnt-all (1+ cnt-all))))
  9072. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9073. (member kwd org-done-keywords))
  9074. (and (listp org-provide-todo-statistics)
  9075. (listp (car org-provide-todo-statistics))
  9076. (member kwd org-done-keywords)
  9077. (member kwd (cadr org-provide-todo-statistics)))
  9078. (and (listp org-provide-todo-statistics)
  9079. (stringp (car org-provide-todo-statistics))
  9080. (member kwd org-done-keywords)))
  9081. (setq cnt-done (1+ cnt-done)))
  9082. (outline-next-heading)))
  9083. (setq new
  9084. (if is-percent
  9085. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9086. (max 1 cnt-all)))
  9087. (format "[%d/%d]" cnt-done cnt-all))
  9088. ndel (- (match-end 0) checkbox-beg))
  9089. (goto-char checkbox-beg)
  9090. (insert new)
  9091. (delete-region (point) (+ (point) ndel))
  9092. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9093. (when cookie-present
  9094. (run-hook-with-args 'org-after-todo-statistics-hook
  9095. cnt-done (- cnt-all cnt-done))))))
  9096. (run-hooks 'org-todo-statistics-hook)))
  9097. (defvar org-after-todo-statistics-hook nil
  9098. "Hook that is called after a TODO statistics cookie has been updated.
  9099. Each function is called with two arguments: the number of not-done entries
  9100. and the number of done entries.
  9101. For example, the following function, when added to this hook, will switch
  9102. an entry to DONE when all children are done, and back to TODO when new
  9103. entries are set to a TODO status. Note that this hook is only called
  9104. when there is a statistics cookie in the headline!
  9105. (defun org-summary-todo (n-done n-not-done)
  9106. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9107. (let (org-log-done org-log-states) ; turn off logging
  9108. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9109. (defvar org-todo-statistics-hook nil
  9110. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9111. This hook runs even if there is no statistics cookie present, in which case
  9112. `org-after-todo-statistics-hook' would not run.")
  9113. (defun org-todo-trigger-tag-changes (state)
  9114. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9115. (let ((l org-todo-state-tags-triggers)
  9116. changes)
  9117. (when (or (not state) (equal state ""))
  9118. (setq changes (append changes (cdr (assoc "" l)))))
  9119. (when (and (stringp state) (> (length state) 0))
  9120. (setq changes (append changes (cdr (assoc state l)))))
  9121. (when (member state org-not-done-keywords)
  9122. (setq changes (append changes (cdr (assq 'todo l)))))
  9123. (when (member state org-done-keywords)
  9124. (setq changes (append changes (cdr (assq 'done l)))))
  9125. (dolist (c changes)
  9126. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9127. (defun org-local-logging (value)
  9128. "Get logging settings from a property VALUE."
  9129. ;; Directly set the variables, they are already local.
  9130. (setq org-log-done nil
  9131. org-log-repeat nil
  9132. org-todo-log-states nil)
  9133. (dolist (w (split-string value))
  9134. (let (a)
  9135. (cond
  9136. ((setq a (assoc w org-startup-options))
  9137. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9138. (set (nth 1 a) (nth 2 a))))
  9139. ((setq a (org-extract-log-state-settings w))
  9140. (and (member (car a) org-todo-keywords-1)
  9141. (push a org-todo-log-states)))))))
  9142. (defun org-get-todo-sequence-head (kwd)
  9143. "Return the head of the TODO sequence to which KWD belongs.
  9144. If KWD is not set, check if there is a text property remembering the
  9145. right sequence."
  9146. (let (p)
  9147. (cond
  9148. ((not kwd)
  9149. (or (get-text-property (point-at-bol) 'org-todo-head)
  9150. (progn
  9151. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9152. nil (point-at-eol)))
  9153. (get-text-property p 'org-todo-head))))
  9154. ((not (member kwd org-todo-keywords-1))
  9155. (car org-todo-keywords-1))
  9156. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9157. (defun org-fast-todo-selection (&optional current-state)
  9158. "Fast TODO keyword selection with single keys.
  9159. Returns the new TODO keyword, or nil if no state change should occur.
  9160. When CURRENT-STATE is given and selection letters are not unique globally,
  9161. prefer a state in the current sequence over on in another sequence."
  9162. (let* ((fulltable org-todo-key-alist)
  9163. (head (org-get-todo-sequence-head current-state))
  9164. (done-keywords org-done-keywords) ;; needed for the faces.
  9165. (maxlen (apply 'max (mapcar
  9166. (lambda (x)
  9167. (if (stringp (car x)) (string-width (car x)) 0))
  9168. fulltable)))
  9169. (expert (equal org-use-fast-todo-selection 'expert))
  9170. (prompt "")
  9171. (fwidth (+ maxlen 3 1 3))
  9172. (ncol (/ (- (window-width) 4) fwidth))
  9173. tg cnt e c tbl subtable
  9174. groups ingroup in-current-sequence)
  9175. (save-excursion
  9176. (save-window-excursion
  9177. (if expert
  9178. (set-buffer (get-buffer-create " *Org todo*"))
  9179. (delete-other-windows)
  9180. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9181. (org-switch-to-buffer-other-window " *Org todo*"))
  9182. (erase-buffer)
  9183. (setq-local org-done-keywords done-keywords)
  9184. (setq tbl fulltable cnt 0)
  9185. (while (setq e (pop tbl))
  9186. (cond
  9187. ((equal e '(:startgroup))
  9188. (push '() groups) (setq ingroup t)
  9189. (unless (= cnt 0)
  9190. (setq cnt 0)
  9191. (insert "\n"))
  9192. (setq prompt (concat prompt "{"))
  9193. (insert "{ "))
  9194. ((equal e '(:endgroup))
  9195. (setq ingroup nil cnt 0 in-current-sequence nil)
  9196. (setq prompt (concat prompt "}"))
  9197. (insert "}\n"))
  9198. ((equal e '(:newline))
  9199. (unless (= cnt 0)
  9200. (setq cnt 0)
  9201. (insert "\n")
  9202. (setq e (car tbl))
  9203. (while (equal (car tbl) '(:newline))
  9204. (insert "\n")
  9205. (setq tbl (cdr tbl)))))
  9206. (t
  9207. (setq tg (car e) c (cdr e))
  9208. (if (equal tg head) (setq in-current-sequence t))
  9209. (when ingroup (push tg (car groups)))
  9210. (when in-current-sequence (push e subtable))
  9211. (setq tg (org-add-props tg nil 'face
  9212. (org-get-todo-face tg)))
  9213. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9214. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9215. (insert "[" c "] " tg (make-string
  9216. (- fwidth 4 (length tg)) ?\ ))
  9217. (when (and (= (setq cnt (1+ cnt)) ncol)
  9218. ;; Avoid lines with just a closing delimiter.
  9219. (not (equal (car tbl) '(:endgroup))))
  9220. (insert "\n")
  9221. (when ingroup (insert " "))
  9222. (setq cnt 0)))))
  9223. (insert "\n")
  9224. (goto-char (point-min))
  9225. (unless expert (org-fit-window-to-buffer))
  9226. (message (concat "[a-z..]:Set [SPC]:clear"
  9227. (if expert (concat "\n" prompt) "")))
  9228. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9229. (setq subtable (nreverse subtable))
  9230. (cond
  9231. ((or (= c ?\C-g)
  9232. (and (= c ?q) (not (rassoc c fulltable))))
  9233. (setq quit-flag t))
  9234. ((= c ?\ ) nil)
  9235. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9236. tg (car e))
  9237. tg)
  9238. (t (setq quit-flag t)))))))
  9239. (defun org-entry-is-todo-p ()
  9240. (member (org-get-todo-state) org-not-done-keywords))
  9241. (defun org-entry-is-done-p ()
  9242. (member (org-get-todo-state) org-done-keywords))
  9243. (defun org-get-todo-state ()
  9244. "Return the TODO keyword of the current subtree."
  9245. (save-excursion
  9246. (org-back-to-heading t)
  9247. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9248. (match-end 2)
  9249. (match-string 2))))
  9250. (defun org-at-date-range-p (&optional inactive-ok)
  9251. "Non-nil if point is inside a date range.
  9252. When optional argument INACTIVE-OK is non-nil, also consider
  9253. inactive time ranges.
  9254. When this function returns a non-nil value, match data is set
  9255. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9256. on INACTIVE-OK."
  9257. (interactive)
  9258. (save-excursion
  9259. (catch 'exit
  9260. (let ((pos (point)))
  9261. (skip-chars-backward "^[<\r\n")
  9262. (skip-chars-backward "<[")
  9263. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9264. (>= (match-end 0) pos)
  9265. (throw 'exit t))
  9266. (skip-chars-backward "^<[\r\n")
  9267. (skip-chars-backward "<[")
  9268. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9269. (>= (match-end 0) pos)
  9270. (throw 'exit t)))
  9271. nil)))
  9272. (defun org-get-repeat (&optional timestamp)
  9273. "Check if there is a time-stamp with repeater in this entry.
  9274. Return the repeater, as a string, or nil. Also return nil when
  9275. this function is called before first heading.
  9276. When optional argument TIMESTAMP is a string, extract the
  9277. repeater from there instead."
  9278. (save-match-data
  9279. (cond (timestamp
  9280. (and (string-match org-repeat-re timestamp)
  9281. (match-string-no-properties 1 timestamp)))
  9282. ((org-before-first-heading-p) nil)
  9283. (t
  9284. (save-excursion
  9285. (org-back-to-heading t)
  9286. (let ((end (org-entry-end-position)))
  9287. (catch :repeat
  9288. (while (re-search-forward org-repeat-re end t)
  9289. (when (save-match-data (org-at-timestamp-p 'agenda))
  9290. (throw :repeat (match-string-no-properties 1)))))))))))
  9291. (defvar org-last-changed-timestamp)
  9292. (defvar org-last-inserted-timestamp)
  9293. (defvar org-log-post-message)
  9294. (defvar org-log-note-purpose)
  9295. (defvar org-log-note-how nil)
  9296. (defvar org-log-note-extra)
  9297. (defun org-auto-repeat-maybe (done-word)
  9298. "Check if the current headline contains a repeated time-stamp.
  9299. If yes, set TODO state back to what it was and change the base date
  9300. of repeating deadline/scheduled time stamps to new date.
  9301. This function is run automatically after each state change to a DONE state."
  9302. (let* ((repeat (org-get-repeat))
  9303. (aa (assoc org-last-state org-todo-kwd-alist))
  9304. (interpret (nth 1 aa))
  9305. (head (nth 2 aa))
  9306. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9307. (msg "Entry repeats: ")
  9308. (org-log-done nil)
  9309. (org-todo-log-states nil)
  9310. (end (copy-marker (org-entry-end-position))))
  9311. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9312. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9313. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9314. (and (stringp org-todo-repeat-to-state)
  9315. org-todo-repeat-to-state)
  9316. (and org-todo-repeat-to-state org-last-state))))
  9317. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9318. to-state)
  9319. ((eq interpret 'type) org-last-state)
  9320. (head)
  9321. (t 'none))))
  9322. (org-back-to-heading t)
  9323. (org-add-planning-info nil nil 'closed)
  9324. ;; When `org-log-repeat' is non-nil or entry contains
  9325. ;; a clock, set LAST_REPEAT property.
  9326. (when (or org-log-repeat
  9327. (catch :clock
  9328. (save-excursion
  9329. (while (re-search-forward org-clock-line-re end t)
  9330. (when (org-at-clock-log-p) (throw :clock t))))))
  9331. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9332. (org-time-stamp-format t t))))
  9333. (when org-log-repeat
  9334. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9335. (memq 'org-add-log-note post-command-hook))
  9336. ;; We are already setup for some record.
  9337. (when (eq org-log-repeat 'note)
  9338. ;; Make sure we take a note, not only a time stamp.
  9339. (setq org-log-note-how 'note))
  9340. ;; Set up for taking a record.
  9341. (org-add-log-setup 'state
  9342. (or done-word (car org-done-keywords))
  9343. org-last-state
  9344. org-log-repeat)))
  9345. ;; Time-stamps without a repeater are usually skipped. However,
  9346. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9347. ;; longer relevant.
  9348. (save-excursion
  9349. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9350. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9351. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9352. ;; Update every time-stamp with a repeater in the entry.
  9353. (let ((planning-re (regexp-opt
  9354. (list org-scheduled-string org-deadline-string))))
  9355. (while (re-search-forward org-repeat-re end t)
  9356. (let* ((ts (match-string 0))
  9357. (type (if (not (org-at-planning-p)) "Plain:"
  9358. (save-excursion
  9359. (re-search-backward
  9360. planning-re (line-beginning-position) t)
  9361. (match-string 0)))))
  9362. (when (and (org-at-timestamp-p 'agenda)
  9363. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9364. (let ((n (string-to-number (match-string 2 ts)))
  9365. (what (match-string 3 ts)))
  9366. (when (equal what "w") (setq n (* n 7) what "d"))
  9367. (when (and (equal what "h")
  9368. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9369. ts)))
  9370. (user-error
  9371. "Cannot repeat in %d hour(s) because no hour has been set"
  9372. n))
  9373. ;; Preparation, see if we need to modify the start
  9374. ;; date for the change.
  9375. (when (match-end 1)
  9376. (let ((time (save-match-data (org-time-string-to-time ts)))
  9377. (repeater-type (match-string 1 ts)))
  9378. (cond
  9379. ((equal "." repeater-type)
  9380. ;; Shift starting date to today, or now if
  9381. ;; repeater is by hours.
  9382. (if (equal what "h")
  9383. (org-timestamp-change
  9384. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9385. (org-timestamp-change
  9386. (- (org-today) (time-to-days time)) 'day)))
  9387. ((equal "+" repeater-type)
  9388. (let ((nshiftmax 10)
  9389. (nshift 0))
  9390. (while (or (= nshift 0)
  9391. (not (org-time-less-p nil time)))
  9392. (when (= nshiftmax (cl-incf nshift))
  9393. (or (y-or-n-p
  9394. (format "%d repeater intervals were not \
  9395. enough to shift date past today. Continue? "
  9396. nshift))
  9397. (user-error "Abort")))
  9398. (org-timestamp-change n (cdr (assoc what whata)))
  9399. (org-in-regexp org-ts-regexp3)
  9400. (setq ts (match-string 1))
  9401. (setq time
  9402. (save-match-data
  9403. (org-time-string-to-time ts)))))
  9404. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9405. ;; Rematch, so that we have everything in place
  9406. ;; for the real shift.
  9407. (org-in-regexp org-ts-regexp3)
  9408. (setq ts (match-string 1))
  9409. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9410. ts)))))
  9411. (save-excursion
  9412. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9413. (setq msg
  9414. (concat msg type " " org-last-changed-timestamp " ")))))))
  9415. (run-hooks 'org-todo-repeat-hook)
  9416. (setq org-log-post-message msg)
  9417. (message msg))))
  9418. (defun org-show-todo-tree (arg)
  9419. "Make a compact tree which shows all headlines marked with TODO.
  9420. The tree will show the lines where the regexp matches, and all higher
  9421. headlines above the match.
  9422. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9423. With a numeric prefix N, construct a sparse tree for the Nth element
  9424. of `org-todo-keywords-1'."
  9425. (interactive "P")
  9426. (let ((case-fold-search nil)
  9427. (kwd-re
  9428. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9429. ((equal arg '(4))
  9430. (let ((kwd
  9431. (completing-read "Keyword (or KWD1|KWD2|...): "
  9432. (mapcar #'list org-todo-keywords-1))))
  9433. (concat "\\("
  9434. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9435. "\\)\\>")))
  9436. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9437. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9438. org-todo-keywords-1)))
  9439. (t (user-error "Invalid prefix argument: %s" arg)))))
  9440. (message "%d TODO entries found"
  9441. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9442. (defun org--deadline-or-schedule (arg type time)
  9443. "Insert DEADLINE or SCHEDULE information in current entry.
  9444. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9445. `org-schedule' for information about ARG and TIME arguments."
  9446. (let* ((deadline? (eq type 'deadline))
  9447. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9448. (log (if deadline? org-log-redeadline org-log-reschedule))
  9449. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9450. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9451. ;; Save repeater cookie from either TIME or current scheduled
  9452. ;; time stamp. We are going to insert it back at the end of
  9453. ;; the process.
  9454. (repeater (or (and (org-string-nw-p time)
  9455. ;; We use `org-repeat-re' because we need
  9456. ;; to tell the difference between a real
  9457. ;; repeater and a time delta, e.g. "+2d".
  9458. (string-match org-repeat-re time)
  9459. (match-string 1 time))
  9460. (and (org-string-nw-p old-date)
  9461. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9462. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9463. old-date)
  9464. (match-string 1 old-date)))))
  9465. (pcase arg
  9466. (`(4)
  9467. (if (not old-date)
  9468. (message (if deadline? "Entry had no deadline to remove"
  9469. "Entry was not scheduled"))
  9470. (when (and old-date log)
  9471. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9472. nil old-date log))
  9473. (org-remove-timestamp-with-keyword keyword)
  9474. (message (if deadline? "Entry no longer has a deadline."
  9475. "Entry is no longer scheduled."))))
  9476. (`(16)
  9477. (save-excursion
  9478. (org-back-to-heading t)
  9479. (let ((regexp (if deadline? org-deadline-time-regexp
  9480. org-scheduled-time-regexp)))
  9481. (if (not (re-search-forward regexp (line-end-position 2) t))
  9482. (user-error (if deadline? "No deadline information to update"
  9483. "No scheduled information to update"))
  9484. (let* ((rpl0 (match-string 1))
  9485. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9486. (msg (if deadline? "Warn starting from" "Delay until")))
  9487. (replace-match
  9488. (concat keyword
  9489. " <" rpl
  9490. (format " -%dd"
  9491. (abs (- (time-to-days
  9492. (save-match-data
  9493. (org-read-date
  9494. nil t nil msg old-date-time)))
  9495. (time-to-days old-date-time))))
  9496. ">") t t))))))
  9497. (_
  9498. (org-add-planning-info type time 'closed)
  9499. (when (and old-date
  9500. log
  9501. (not (equal old-date org-last-inserted-timestamp)))
  9502. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9503. org-last-inserted-timestamp
  9504. old-date
  9505. log))
  9506. (when repeater
  9507. (save-excursion
  9508. (org-back-to-heading t)
  9509. (when (re-search-forward
  9510. (concat keyword " " org-last-inserted-timestamp)
  9511. (line-end-position 2)
  9512. t)
  9513. (goto-char (1- (match-end 0)))
  9514. (insert " " repeater)
  9515. (setq org-last-inserted-timestamp
  9516. (concat (substring org-last-inserted-timestamp 0 -1)
  9517. " " repeater
  9518. (substring org-last-inserted-timestamp -1))))))
  9519. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9520. org-last-inserted-timestamp)))))
  9521. (defun org-deadline (arg &optional time)
  9522. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9523. When called interactively, this command pops up the Emacs calendar to let
  9524. the user select a date.
  9525. With one universal prefix argument, remove any deadline from the item.
  9526. With two universal prefix arguments, prompt for a warning delay.
  9527. With argument TIME, set the deadline at the corresponding date. TIME
  9528. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9529. (interactive "P")
  9530. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9531. (org-map-entries
  9532. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9533. nil
  9534. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9535. 'region-start-level
  9536. 'region)
  9537. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9538. (org--deadline-or-schedule arg 'deadline time)))
  9539. (defun org-schedule (arg &optional time)
  9540. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9541. When called interactively, this command pops up the Emacs calendar to let
  9542. the user select a date.
  9543. With one universal prefix argument, remove any scheduling date from the item.
  9544. With two universal prefix arguments, prompt for a delay cookie.
  9545. With argument TIME, scheduled at the corresponding date. TIME can
  9546. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9547. (interactive "P")
  9548. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9549. (org-map-entries
  9550. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9551. nil
  9552. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9553. 'region-start-level
  9554. 'region)
  9555. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9556. (org--deadline-or-schedule arg 'scheduled time)))
  9557. (defun org-get-scheduled-time (pom &optional inherit)
  9558. "Get the scheduled time as a time tuple, of a format suitable
  9559. for calling org-schedule with, or if there is no scheduling,
  9560. returns nil."
  9561. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9562. (when time
  9563. (org-time-string-to-time time))))
  9564. (defun org-get-deadline-time (pom &optional inherit)
  9565. "Get the deadline as a time tuple, of a format suitable for
  9566. calling org-deadline with, or if there is no scheduling, returns
  9567. nil."
  9568. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9569. (when time
  9570. (org-time-string-to-time time))))
  9571. (defun org-remove-timestamp-with-keyword (keyword)
  9572. "Remove all time stamps with KEYWORD in the current entry."
  9573. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9574. beg)
  9575. (save-excursion
  9576. (org-back-to-heading t)
  9577. (setq beg (point))
  9578. (outline-next-heading)
  9579. (while (re-search-backward re beg t)
  9580. (replace-match "")
  9581. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9582. (equal (char-before) ?\ ))
  9583. (backward-delete-char 1)
  9584. (when (string-match "^[ \t]*$" (buffer-substring
  9585. (point-at-bol) (point-at-eol)))
  9586. (delete-region (point-at-bol)
  9587. (min (point-max) (1+ (point-at-eol))))))))))
  9588. (defvar org-time-was-given) ; dynamically scoped parameter
  9589. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9590. (defun org-at-planning-p ()
  9591. "Non-nil when point is on a planning info line."
  9592. ;; This is as accurate and faster than `org-element-at-point' since
  9593. ;; planning info location is fixed in the section.
  9594. (org-with-wide-buffer
  9595. (beginning-of-line)
  9596. (and (looking-at-p org-planning-line-re)
  9597. (eq (point)
  9598. (ignore-errors
  9599. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9600. (org-back-to-heading t)
  9601. (org-with-limited-levels (org-back-to-heading t)))
  9602. (line-beginning-position 2))))))
  9603. (defun org-add-planning-info (what &optional time &rest remove)
  9604. "Insert new timestamp with keyword in the planning line.
  9605. WHAT indicates what kind of time stamp to add. It is a symbol
  9606. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9607. the time to use. If none is given, the user is prompted for
  9608. a date. REMOVE indicates what kind of entries to remove. An old
  9609. WHAT entry will also be removed."
  9610. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9611. (when (and (memq what '(scheduled deadline))
  9612. (or (not time)
  9613. (and (stringp time)
  9614. (string-match "^[-+]+[0-9]" time))))
  9615. ;; Try to get a default date/time from existing timestamp
  9616. (save-excursion
  9617. (org-back-to-heading t)
  9618. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9619. (when (re-search-forward (if (eq what 'scheduled)
  9620. org-scheduled-time-regexp
  9621. org-deadline-time-regexp)
  9622. end t)
  9623. (setq ts (match-string 1)
  9624. default-time (org-time-string-to-time ts)
  9625. default-input (and ts (org-get-compact-tod ts)))))))
  9626. (when what
  9627. (setq time
  9628. (if (stringp time)
  9629. ;; This is a string (relative or absolute), set
  9630. ;; proper date.
  9631. (apply #'encode-time
  9632. (org-read-date-analyze
  9633. time default-time (decode-time default-time)))
  9634. ;; If necessary, get the time from the user
  9635. (or time (org-read-date nil 'to-time nil
  9636. (cl-case what
  9637. (deadline "DEADLINE")
  9638. (scheduled "SCHEDULED")
  9639. (otherwise nil))
  9640. default-time default-input)))))
  9641. (org-with-wide-buffer
  9642. (org-back-to-heading t)
  9643. (let ((planning? (save-excursion
  9644. (forward-line)
  9645. (looking-at-p org-planning-line-re))))
  9646. (cond
  9647. (planning?
  9648. (forward-line)
  9649. ;; Move to current indentation.
  9650. (skip-chars-forward " \t")
  9651. ;; Check if we have to remove something.
  9652. (dolist (type (if what (cons what remove) remove))
  9653. (save-excursion
  9654. (when (re-search-forward
  9655. (cl-case type
  9656. (closed org-closed-time-regexp)
  9657. (deadline org-deadline-time-regexp)
  9658. (scheduled org-scheduled-time-regexp)
  9659. (otherwise (error "Invalid planning type: %s" type)))
  9660. (line-end-position)
  9661. t)
  9662. ;; Delete until next keyword or end of line.
  9663. (delete-region
  9664. (match-beginning 0)
  9665. (if (re-search-forward org-keyword-time-not-clock-regexp
  9666. (line-end-position)
  9667. t)
  9668. (match-beginning 0)
  9669. (line-end-position))))))
  9670. ;; If there is nothing more to add and no more keyword is
  9671. ;; left, remove the line completely.
  9672. (if (and (looking-at-p "[ \t]*$") (not what))
  9673. (delete-region (line-end-position 0)
  9674. (line-end-position))
  9675. ;; If we removed last keyword, do not leave trailing white
  9676. ;; space at the end of line.
  9677. (let ((p (point)))
  9678. (save-excursion
  9679. (end-of-line)
  9680. (unless (= (skip-chars-backward " \t" p) 0)
  9681. (delete-region (point) (line-end-position)))))))
  9682. (what
  9683. (end-of-line)
  9684. (insert "\n")
  9685. (when org-adapt-indentation
  9686. (indent-to-column (1+ (org-outline-level)))))
  9687. (t nil)))
  9688. (when what
  9689. ;; Insert planning keyword.
  9690. (insert (cl-case what
  9691. (closed org-closed-string)
  9692. (deadline org-deadline-string)
  9693. (scheduled org-scheduled-string)
  9694. (otherwise (error "Invalid planning type: %s" what)))
  9695. " ")
  9696. ;; Insert associated timestamp.
  9697. (let ((ts (org-insert-time-stamp
  9698. time
  9699. (or org-time-was-given
  9700. (and (eq what 'closed) org-log-done-with-time))
  9701. (eq what 'closed)
  9702. nil nil (list org-end-time-was-given))))
  9703. (unless (eolp) (insert " "))
  9704. ts)))))
  9705. (defvar org-log-note-marker (make-marker)
  9706. "Marker pointing at the entry where the note is to be inserted.")
  9707. (defvar org-log-note-purpose nil)
  9708. (defvar org-log-note-state nil)
  9709. (defvar org-log-note-previous-state nil)
  9710. (defvar org-log-note-extra nil)
  9711. (defvar org-log-note-window-configuration nil)
  9712. (defvar org-log-note-return-to (make-marker))
  9713. (defvar org-log-note-effective-time nil
  9714. "Remembered current time.
  9715. So that dynamically scoped `org-extend-today-until' affects
  9716. timestamps in state change log.")
  9717. (defvar org-log-post-message nil
  9718. "Message to be displayed after a log note has been stored.
  9719. The auto-repeater uses this.")
  9720. (defun org-add-note ()
  9721. "Add a note to the current entry.
  9722. This is done in the same way as adding a state change note."
  9723. (interactive)
  9724. (org-add-log-setup 'note))
  9725. (defun org-log-beginning (&optional create)
  9726. "Return expected start of log notes in current entry.
  9727. When optional argument CREATE is non-nil, the function creates
  9728. a drawer to store notes, if necessary. Returned position ignores
  9729. narrowing."
  9730. (org-with-wide-buffer
  9731. (let ((drawer (org-log-into-drawer)))
  9732. (cond
  9733. (drawer
  9734. (org-end-of-meta-data)
  9735. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9736. (end (if (org-at-heading-p) (point)
  9737. (save-excursion (outline-next-heading) (point))))
  9738. (case-fold-search t))
  9739. (catch 'exit
  9740. ;; Try to find existing drawer.
  9741. (while (re-search-forward regexp end t)
  9742. (let ((element (org-element-at-point)))
  9743. (when (eq (org-element-type element) 'drawer)
  9744. (let ((cend (org-element-property :contents-end element)))
  9745. (when (and (not org-log-states-order-reversed) cend)
  9746. (goto-char cend)))
  9747. (throw 'exit nil))))
  9748. ;; No drawer found. Create one, if permitted.
  9749. (when create
  9750. (unless (bolp) (insert "\n"))
  9751. (let ((beg (point)))
  9752. (insert ":" drawer ":\n:END:\n")
  9753. (org-indent-region beg (point))
  9754. (org-flag-region (line-end-position -1) (1- (point)) t 'outline))
  9755. (end-of-line -1)))))
  9756. (t
  9757. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9758. (skip-chars-forward " \t\n")
  9759. (beginning-of-line)
  9760. (unless org-log-states-order-reversed
  9761. (org-skip-over-state-notes)
  9762. (skip-chars-backward " \t\n")
  9763. (forward-line)))))
  9764. (if (bolp) (point) (line-beginning-position 2))))
  9765. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9766. "Set up the post command hook to take a note.
  9767. If this is about to TODO state change, the new state is expected in STATE.
  9768. HOW is an indicator what kind of note should be created.
  9769. EXTRA is additional text that will be inserted into the notes buffer."
  9770. (move-marker org-log-note-marker (point))
  9771. (setq org-log-note-purpose purpose
  9772. org-log-note-state state
  9773. org-log-note-previous-state prev-state
  9774. org-log-note-how how
  9775. org-log-note-extra extra
  9776. org-log-note-effective-time (org-current-effective-time))
  9777. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9778. (defun org-skip-over-state-notes ()
  9779. "Skip past the list of State notes in an entry."
  9780. (when (ignore-errors (goto-char (org-in-item-p)))
  9781. (let* ((struct (org-list-struct))
  9782. (prevs (org-list-prevs-alist struct))
  9783. (regexp
  9784. (concat "[ \t]*- +"
  9785. (replace-regexp-in-string
  9786. " +" " +"
  9787. (org-replace-escapes
  9788. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9789. `(("%d" . ,org-ts-regexp-inactive)
  9790. ("%D" . ,org-ts-regexp)
  9791. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9792. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9793. ("%t" . ,org-ts-regexp-inactive)
  9794. ("%T" . ,org-ts-regexp)
  9795. ("%u" . ".*?")
  9796. ("%U" . ".*?")))))))
  9797. (while (looking-at-p regexp)
  9798. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9799. (org-list-get-item-end (point) struct)))))))
  9800. (defun org-add-log-note (&optional _purpose)
  9801. "Pop up a window for taking a note, and add this note later."
  9802. (remove-hook 'post-command-hook 'org-add-log-note)
  9803. (setq org-log-note-window-configuration (current-window-configuration))
  9804. (delete-other-windows)
  9805. (move-marker org-log-note-return-to (point))
  9806. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9807. (goto-char org-log-note-marker)
  9808. (org-switch-to-buffer-other-window "*Org Note*")
  9809. (erase-buffer)
  9810. (if (memq org-log-note-how '(time state))
  9811. (org-store-log-note)
  9812. (let ((org-inhibit-startup t)) (org-mode))
  9813. (insert (format "# Insert note for %s.
  9814. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9815. (cl-case org-log-note-purpose
  9816. (clock-out "stopped clock")
  9817. (done "closed todo item")
  9818. (reschedule "rescheduling")
  9819. (delschedule "no longer scheduled")
  9820. (redeadline "changing deadline")
  9821. (deldeadline "removing deadline")
  9822. (refile "refiling")
  9823. (note "this entry")
  9824. (state
  9825. (format "state change from \"%s\" to \"%s\""
  9826. (or org-log-note-previous-state "")
  9827. (or org-log-note-state "")))
  9828. (t (error "This should not happen")))))
  9829. (when org-log-note-extra (insert org-log-note-extra))
  9830. (setq-local org-finish-function 'org-store-log-note)
  9831. (run-hooks 'org-log-buffer-setup-hook)))
  9832. (defvar org-note-abort nil) ; dynamically scoped
  9833. (defun org-store-log-note ()
  9834. "Finish taking a log note, and insert it to where it belongs."
  9835. (let ((txt (prog1 (buffer-string)
  9836. (kill-buffer)))
  9837. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9838. lines)
  9839. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9840. (setq txt (replace-match "" t t txt)))
  9841. (when (string-match "\\s-+\\'" txt)
  9842. (setq txt (replace-match "" t t txt)))
  9843. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9844. (when (org-string-nw-p note)
  9845. (setq note
  9846. (org-replace-escapes
  9847. note
  9848. (list (cons "%u" (user-login-name))
  9849. (cons "%U" user-full-name)
  9850. (cons "%t" (format-time-string
  9851. (org-time-stamp-format 'long 'inactive)
  9852. org-log-note-effective-time))
  9853. (cons "%T" (format-time-string
  9854. (org-time-stamp-format 'long nil)
  9855. org-log-note-effective-time))
  9856. (cons "%d" (format-time-string
  9857. (org-time-stamp-format nil 'inactive)
  9858. org-log-note-effective-time))
  9859. (cons "%D" (format-time-string
  9860. (org-time-stamp-format nil nil)
  9861. org-log-note-effective-time))
  9862. (cons "%s" (cond
  9863. ((not org-log-note-state) "")
  9864. ((string-match-p org-ts-regexp
  9865. org-log-note-state)
  9866. (format "\"[%s]\""
  9867. (substring org-log-note-state 1 -1)))
  9868. (t (format "\"%s\"" org-log-note-state))))
  9869. (cons "%S"
  9870. (cond
  9871. ((not org-log-note-previous-state) "")
  9872. ((string-match-p org-ts-regexp
  9873. org-log-note-previous-state)
  9874. (format "\"[%s]\""
  9875. (substring
  9876. org-log-note-previous-state 1 -1)))
  9877. (t (format "\"%s\""
  9878. org-log-note-previous-state)))))))
  9879. (when lines (setq note (concat note " \\\\")))
  9880. (push note lines))
  9881. (when (and lines (not org-note-abort))
  9882. (with-current-buffer (marker-buffer org-log-note-marker)
  9883. (org-with-wide-buffer
  9884. ;; Find location for the new note.
  9885. (goto-char org-log-note-marker)
  9886. (set-marker org-log-note-marker nil)
  9887. ;; Note associated to a clock is to be located right after
  9888. ;; the clock. Do not move point.
  9889. (unless (eq org-log-note-purpose 'clock-out)
  9890. (goto-char (org-log-beginning t)))
  9891. ;; Make sure point is at the beginning of an empty line.
  9892. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9893. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9894. ;; In an existing list, add a new item at the top level.
  9895. ;; Otherwise, indent line like a regular one.
  9896. (let ((itemp (org-in-item-p)))
  9897. (if itemp
  9898. (indent-line-to
  9899. (let ((struct (save-excursion
  9900. (goto-char itemp) (org-list-struct))))
  9901. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9902. (org-indent-line)))
  9903. (insert (org-list-bullet-string "-") (pop lines))
  9904. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9905. (dolist (line lines)
  9906. (insert "\n")
  9907. (indent-line-to ind)
  9908. (insert line)))
  9909. (message "Note stored")
  9910. (org-back-to-heading t))
  9911. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9912. ;; from within `org-add-log-note' because `buffer-undo-list'
  9913. ;; is then modified outside of `org-with-remote-undo'.
  9914. (when (eq this-command 'org-agenda-todo)
  9915. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9916. ;; Don't add undo information when called from `org-agenda-todo'.
  9917. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9918. (set-window-configuration org-log-note-window-configuration)
  9919. (with-current-buffer (marker-buffer org-log-note-return-to)
  9920. (goto-char org-log-note-return-to))
  9921. (move-marker org-log-note-return-to nil)
  9922. (when org-log-post-message (message "%s" org-log-post-message))))
  9923. (defun org-remove-empty-drawer-at (pos)
  9924. "Remove an empty drawer at position POS.
  9925. POS may also be a marker."
  9926. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9927. (org-with-wide-buffer
  9928. (goto-char pos)
  9929. (let ((drawer (org-element-at-point)))
  9930. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9931. (not (org-element-property :contents-begin drawer)))
  9932. (delete-region (org-element-property :begin drawer)
  9933. (progn (goto-char (org-element-property :end drawer))
  9934. (skip-chars-backward " \r\t\n")
  9935. (forward-line)
  9936. (point))))))))
  9937. (defvar org-ts-type nil)
  9938. (defun org-sparse-tree (&optional arg type)
  9939. "Create a sparse tree, prompt for the details.
  9940. This command can create sparse trees. You first need to select the type
  9941. of match used to create the tree:
  9942. t Show all TODO entries.
  9943. T Show entries with a specific TODO keyword.
  9944. m Show entries selected by a tags/property match.
  9945. p Enter a property name and its value (both with completion on existing
  9946. names/values) and show entries with that property.
  9947. r Show entries matching a regular expression (`/' can be used as well).
  9948. b Show deadlines and scheduled items before a date.
  9949. a Show deadlines and scheduled items after a date.
  9950. d Show deadlines due within `org-deadline-warning-days'.
  9951. D Show deadlines and scheduled items between a date range."
  9952. (interactive "P")
  9953. (setq type (or type org-sparse-tree-default-date-type))
  9954. (setq org-ts-type type)
  9955. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9956. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9957. [c]ycle through date types: %s"
  9958. (cl-case type
  9959. (all "all timestamps")
  9960. (scheduled "only scheduled")
  9961. (deadline "only deadline")
  9962. (active "only active timestamps")
  9963. (inactive "only inactive timestamps")
  9964. (closed "with a closed time-stamp")
  9965. (otherwise "scheduled/deadline")))
  9966. (let ((answer (read-char-exclusive)))
  9967. (cl-case answer
  9968. (?c
  9969. (org-sparse-tree
  9970. arg
  9971. (cadr
  9972. (memq type '(nil all scheduled deadline active inactive closed)))))
  9973. (?d (call-interactively 'org-check-deadlines))
  9974. (?b (call-interactively 'org-check-before-date))
  9975. (?a (call-interactively 'org-check-after-date))
  9976. (?D (call-interactively 'org-check-dates-range))
  9977. (?t (call-interactively 'org-show-todo-tree))
  9978. (?T (org-show-todo-tree '(4)))
  9979. (?m (call-interactively 'org-match-sparse-tree))
  9980. ((?p ?P)
  9981. (let* ((kwd (completing-read
  9982. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9983. (value (completing-read
  9984. "Value: " (mapcar #'list (org-property-values kwd)))))
  9985. (unless (string-match "\\`{.*}\\'" value)
  9986. (setq value (concat "\"" value "\"")))
  9987. (org-match-sparse-tree arg (concat kwd "=" value))))
  9988. ((?r ?R ?/) (call-interactively 'org-occur))
  9989. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9990. (defvar-local org-occur-highlights nil
  9991. "List of overlays used for occur matches.")
  9992. (defvar-local org-occur-parameters nil
  9993. "Parameters of the active org-occur calls.
  9994. This is a list, each call to org-occur pushes as cons cell,
  9995. containing the regular expression and the callback, onto the list.
  9996. The list can contain several entries if `org-occur' has been called
  9997. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9998. will only contain one set of parameters. When the highlights are
  9999. removed (for example with `C-c C-c', or with the next edit (depending
  10000. on `org-remove-highlights-with-change'), this variable is emptied
  10001. as well.")
  10002. (defun org-occur (regexp &optional keep-previous callback)
  10003. "Make a compact tree showing all matches of REGEXP.
  10004. The tree will show the lines where the regexp matches, and any other context
  10005. defined in `org-show-context-detail', which see.
  10006. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10007. done by a previous call to `org-occur' will be kept, to allow stacking of
  10008. calls to this command.
  10009. Optional argument CALLBACK can be a function of no argument. In this case,
  10010. it is called with point at the end of the match, match data being set
  10011. accordingly. Current match is shown only if the return value is non-nil.
  10012. The function must neither move point nor alter narrowing."
  10013. (interactive "sRegexp: \nP")
  10014. (when (equal regexp "")
  10015. (user-error "Regexp cannot be empty"))
  10016. (unless keep-previous
  10017. (org-remove-occur-highlights nil nil t))
  10018. (push (cons regexp callback) org-occur-parameters)
  10019. (let ((cnt 0))
  10020. (save-excursion
  10021. (goto-char (point-min))
  10022. (when (or (not keep-previous) ; do not want to keep
  10023. (not org-occur-highlights)) ; no previous matches
  10024. ;; hide everything
  10025. (org-overview))
  10026. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10027. (isearch-no-upper-case-p regexp t)
  10028. org-occur-case-fold-search)))
  10029. (while (re-search-forward regexp nil t)
  10030. (when (or (not callback)
  10031. (save-match-data (funcall callback)))
  10032. (setq cnt (1+ cnt))
  10033. (when org-highlight-sparse-tree-matches
  10034. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10035. (org-show-context 'occur-tree)))))
  10036. (when org-remove-highlights-with-change
  10037. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10038. nil 'local))
  10039. (unless org-sparse-tree-open-archived-trees
  10040. (org-hide-archived-subtrees (point-min) (point-max)))
  10041. (run-hooks 'org-occur-hook)
  10042. (when (called-interactively-p 'interactive)
  10043. (message "%d match(es) for regexp %s" cnt regexp))
  10044. cnt))
  10045. (defun org-occur-next-match (&optional n _reset)
  10046. "Function for `next-error-function' to find sparse tree matches.
  10047. N is the number of matches to move, when negative move backwards.
  10048. This function always goes back to the starting point when no
  10049. match is found."
  10050. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10051. (search-func (if (< n 0)
  10052. 'previous-single-char-property-change
  10053. 'next-single-char-property-change))
  10054. (n (abs n))
  10055. (pos (point))
  10056. p1)
  10057. (catch 'exit
  10058. (while (setq p1 (funcall search-func (point) 'org-type))
  10059. (when (equal p1 limit)
  10060. (goto-char pos)
  10061. (user-error "No more matches"))
  10062. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10063. (setq n (1- n))
  10064. (when (= n 0)
  10065. (goto-char p1)
  10066. (throw 'exit (point))))
  10067. (goto-char p1))
  10068. (goto-char p1)
  10069. (user-error "No more matches"))))
  10070. (defun org-highlight-new-match (beg end)
  10071. "Highlight from BEG to END and mark the highlight is an occur headline."
  10072. (let ((ov (make-overlay beg end)))
  10073. (overlay-put ov 'face 'secondary-selection)
  10074. (overlay-put ov 'org-type 'org-occur)
  10075. (push ov org-occur-highlights)))
  10076. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10077. "Remove the occur highlights from the buffer.
  10078. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10079. from the `before-change-functions' in the current buffer."
  10080. (interactive)
  10081. (unless org-inhibit-highlight-removal
  10082. (mapc #'delete-overlay org-occur-highlights)
  10083. (setq org-occur-highlights nil)
  10084. (setq org-occur-parameters nil)
  10085. (unless noremove
  10086. (remove-hook 'before-change-functions
  10087. 'org-remove-occur-highlights 'local))))
  10088. ;;;; Priorities
  10089. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10090. "Regular expression matching the priority indicator.
  10091. A priority indicator can be e.g. [#A] or [#1].
  10092. This regular expression matches these groups:
  10093. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10094. 1 : the priority cookie, e.g. \"[#A]\"
  10095. 2 : the value of the priority cookie, e.g. \"A\".")
  10096. (defun org-priority-up ()
  10097. "Increase the priority of the current item."
  10098. (interactive)
  10099. (org-priority 'up))
  10100. (defun org-priority-down ()
  10101. "Decrease the priority of the current item."
  10102. (interactive)
  10103. (org-priority 'down))
  10104. (defun org-priority (&optional action show)
  10105. "Change the priority of an item.
  10106. When called interactively with a `\\[universal-argument]' prefix,
  10107. show the priority in the minibuffer instead of changing it.
  10108. When called programmatically, ACTION can be `set', `up', `down',
  10109. or a character."
  10110. (interactive "P")
  10111. (when show
  10112. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10113. ;; passed the SHOW argument should be removed.
  10114. (warn "`org-priority' called with deprecated SHOW argument"))
  10115. (if (equal action '(4))
  10116. (org-priority-show)
  10117. (unless org-priority-enable-commands
  10118. (user-error "Priority commands are disabled"))
  10119. (setq action (or action 'set))
  10120. (let ((nump (< org-priority-lowest 65))
  10121. current new news have remove)
  10122. (save-excursion
  10123. (org-back-to-heading t)
  10124. (when (looking-at org-priority-regexp)
  10125. (let ((ms (match-string 2)))
  10126. (setq current (org-priority-to-value ms)
  10127. have t)))
  10128. (cond
  10129. ((eq action 'remove)
  10130. (setq remove t new ?\ ))
  10131. ((or (eq action 'set)
  10132. (integerp action))
  10133. (if (not (eq action 'set))
  10134. (setq new action)
  10135. (setq
  10136. new
  10137. (if nump
  10138. (string-to-number
  10139. (read-string (format "Priority %s-%s, SPC to remove: "
  10140. (number-to-string org-priority-highest)
  10141. (number-to-string org-priority-lowest))))
  10142. (progn (message "Priority %c-%c, SPC to remove: "
  10143. org-priority-highest org-priority-lowest)
  10144. (save-match-data
  10145. (setq new (read-char-exclusive)))))))
  10146. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10147. (= (upcase org-priority-lowest) org-priority-lowest))
  10148. (setq new (upcase new)))
  10149. (cond ((equal new ?\s) (setq remove t))
  10150. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10151. (user-error
  10152. (if nump
  10153. "Priority must be between `%s' and `%s'"
  10154. "Priority must be between `%c' and `%c'")
  10155. org-priority-highest org-priority-lowest))))
  10156. ((eq action 'up)
  10157. (setq new (if have
  10158. (1- current) ; normal cycling
  10159. ;; last priority was empty
  10160. (if (eq last-command this-command)
  10161. org-priority-lowest ; wrap around empty to lowest
  10162. ;; default
  10163. (if org-priority-start-cycle-with-default
  10164. org-priority-default
  10165. (1- org-priority-default))))))
  10166. ((eq action 'down)
  10167. (setq new (if have
  10168. (1+ current) ; normal cycling
  10169. ;; last priority was empty
  10170. (if (eq last-command this-command)
  10171. org-priority-highest ; wrap around empty to highest
  10172. ;; default
  10173. (if org-priority-start-cycle-with-default
  10174. org-priority-default
  10175. (1+ org-priority-default))))))
  10176. (t (user-error "Invalid action")))
  10177. (when (or (< (upcase new) org-priority-highest)
  10178. (> (upcase new) org-priority-lowest))
  10179. (if (and (memq action '(up down))
  10180. (not have) (not (eq last-command this-command)))
  10181. ;; `new' is from default priority
  10182. (error
  10183. "The default can not be set, see `org-priority-default' why")
  10184. ;; normal cycling: `new' is beyond highest/lowest priority
  10185. ;; and is wrapped around to the empty priority
  10186. (setq remove t)))
  10187. ;; Numerical priorities are limited to 64, beyond that number,
  10188. ;; assume the priority cookie is a character.
  10189. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10190. (if have
  10191. (if remove
  10192. (replace-match "" t t nil 1)
  10193. (replace-match news t t nil 2))
  10194. (if remove
  10195. (user-error "No priority cookie found in line")
  10196. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10197. (if (match-end 2)
  10198. (progn
  10199. (goto-char (match-end 2))
  10200. (insert " [#" news "]"))
  10201. (goto-char (match-beginning 3))
  10202. (insert "[#" news "] "))))
  10203. (org-align-tags))
  10204. (if remove
  10205. (message "Priority removed")
  10206. (message "Priority of current item set to %s" news)))))
  10207. (defalias 'org-show-priority 'org-priority-show)
  10208. (defun org-priority-show ()
  10209. "Show the priority of the current item.
  10210. This priority is composed of the main priority given with the [#A] cookies,
  10211. and by additional input from the age of a schedules or deadline entry."
  10212. (interactive)
  10213. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10214. (org-get-at-bol 'priority)
  10215. (save-excursion
  10216. (save-match-data
  10217. (beginning-of-line)
  10218. (and (looking-at org-heading-regexp)
  10219. (org-get-priority (match-string 0))))))))
  10220. (message "Priority is %d" (if pri pri -1000))))
  10221. (defun org-get-priority (s)
  10222. "Find priority cookie and return priority.
  10223. S is a string against which you can match `org-priority-regexp'.
  10224. If `org-priority-get-priority-function' is set to a custom
  10225. function, use it. Otherwise process S and output the priority
  10226. value, an integer."
  10227. (save-match-data
  10228. (if (functionp org-priority-get-priority-function)
  10229. (funcall org-priority-get-priority-function s)
  10230. (if (not (string-match org-priority-regexp s))
  10231. (* 1000 (- org-priority-lowest org-priority-default))
  10232. (* 1000 (- org-priority-lowest
  10233. (org-priority-to-value (match-string 2 s))))))))
  10234. ;;;; Tags
  10235. (defvar org-agenda-archives-mode)
  10236. (defvar org-map-continue-from nil
  10237. "Position from where mapping should continue.
  10238. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10239. (defvar org-scanner-tags nil
  10240. "The current tag list while the tags scanner is running.")
  10241. (defvar org-trust-scanner-tags nil
  10242. "Should `org-get-tags' use the tags for the scanner.
  10243. This is for internal dynamical scoping only.
  10244. When this is non-nil, the function `org-get-tags' will return the value
  10245. of `org-scanner-tags' instead of building the list by itself. This
  10246. can lead to large speed-ups when the tags scanner is used in a file with
  10247. many entries, and when the list of tags is retrieved, for example to
  10248. obtain a list of properties. Building the tags list for each entry in such
  10249. a file becomes an N^2 operation - but with this variable set, it scales
  10250. as N.")
  10251. (defvar org--matcher-tags-todo-only nil)
  10252. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10253. "Scan headline tags with inheritance and produce output ACTION.
  10254. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10255. or `agenda' to produce an entry list for an agenda view. It can also be
  10256. a Lisp form or a function that should be called at each matched headline, in
  10257. this case the return value is a list of all return values from these calls.
  10258. MATCHER is a function accepting three arguments, returning
  10259. a non-nil value whenever a given set of tags qualifies a headline
  10260. for inclusion. See `org-make-tags-matcher' for more information.
  10261. As a special case, it can also be set to t (respectively nil) in
  10262. order to match all (respectively none) headline.
  10263. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10264. included in the output.
  10265. START-LEVEL can be a string with asterisks, reducing the scope to
  10266. headlines matching this string."
  10267. (require 'org-agenda)
  10268. (let* ((re (concat "^"
  10269. (if start-level
  10270. ;; Get the correct level to match
  10271. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10272. org-outline-regexp)
  10273. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10274. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10275. (props (list 'face 'default
  10276. 'done-face 'org-agenda-done
  10277. 'undone-face 'default
  10278. 'mouse-face 'highlight
  10279. 'org-not-done-regexp org-not-done-regexp
  10280. 'org-todo-regexp org-todo-regexp
  10281. 'org-complex-heading-regexp org-complex-heading-regexp
  10282. 'help-echo
  10283. (format "mouse-2 or RET jump to Org file %S"
  10284. (abbreviate-file-name
  10285. (or (buffer-file-name (buffer-base-buffer))
  10286. (buffer-name (buffer-base-buffer)))))))
  10287. (org-map-continue-from nil)
  10288. lspos tags tags-list
  10289. (tags-alist (list (cons 0 org-file-tags)))
  10290. (llast 0) rtn rtn1 level category i txt
  10291. todo marker entry priority
  10292. ts-date ts-date-type ts-date-pair)
  10293. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10294. (setq action (list 'lambda nil action)))
  10295. (save-excursion
  10296. (goto-char (point-min))
  10297. (when (eq action 'sparse-tree)
  10298. (org-overview)
  10299. (org-remove-occur-highlights))
  10300. (while (let (case-fold-search)
  10301. (re-search-forward re nil t))
  10302. (setq org-map-continue-from nil)
  10303. (catch :skip
  10304. ;; Ignore closing parts of inline tasks.
  10305. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10306. (throw :skip t))
  10307. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10308. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10309. (goto-char (setq lspos (match-beginning 0)))
  10310. (setq level (org-reduced-level (org-outline-level))
  10311. category (org-get-category))
  10312. (when (eq action 'agenda)
  10313. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10314. ts-date (car ts-date-pair)
  10315. ts-date-type (cdr ts-date-pair)))
  10316. (setq i llast llast level)
  10317. ;; remove tag lists from same and sublevels
  10318. (while (>= i level)
  10319. (when (setq entry (assoc i tags-alist))
  10320. (setq tags-alist (delete entry tags-alist)))
  10321. (setq i (1- i)))
  10322. ;; add the next tags
  10323. (when tags
  10324. (setq tags (org-split-string tags ":")
  10325. tags-alist
  10326. (cons (cons level tags) tags-alist)))
  10327. ;; compile tags for current headline
  10328. (setq tags-list
  10329. (if org-use-tag-inheritance
  10330. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10331. tags)
  10332. org-scanner-tags tags-list)
  10333. (when org-use-tag-inheritance
  10334. (setcdr (car tags-alist)
  10335. (mapcar (lambda (x)
  10336. (setq x (copy-sequence x))
  10337. (org-add-prop-inherited x))
  10338. (cdar tags-alist))))
  10339. (when (and tags org-use-tag-inheritance
  10340. (or (not (eq t org-use-tag-inheritance))
  10341. org-tags-exclude-from-inheritance))
  10342. ;; Selective inheritance, remove uninherited ones.
  10343. (setcdr (car tags-alist)
  10344. (org-remove-uninherited-tags (cdar tags-alist))))
  10345. (when (and
  10346. ;; eval matcher only when the todo condition is OK
  10347. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10348. (if (functionp matcher)
  10349. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10350. (funcall matcher todo tags-list level))
  10351. matcher))
  10352. ;; Call the skipper, but return t if it does not
  10353. ;; skip, so that the `and' form continues evaluating.
  10354. (progn
  10355. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10356. t)
  10357. ;; Check if timestamps are deselecting this entry
  10358. (or (not todo-only)
  10359. (and (member todo org-todo-keywords-1)
  10360. (or (not org-agenda-tags-todo-honor-ignore-options)
  10361. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10362. ;; select this headline
  10363. (cond
  10364. ((eq action 'sparse-tree)
  10365. (and org-highlight-sparse-tree-matches
  10366. (org-get-heading) (match-end 0)
  10367. (org-highlight-new-match
  10368. (match-beginning 1) (match-end 1)))
  10369. (org-show-context 'tags-tree))
  10370. ((eq action 'agenda)
  10371. (setq txt (org-agenda-format-item
  10372. ""
  10373. (concat
  10374. (if (eq org-tags-match-list-sublevels 'indented)
  10375. (make-string (1- level) ?.) "")
  10376. (org-get-heading))
  10377. (make-string level ?\s)
  10378. category
  10379. tags-list)
  10380. priority (org-get-priority txt))
  10381. (goto-char lspos)
  10382. (setq marker (org-agenda-new-marker))
  10383. (org-add-props txt props
  10384. 'org-marker marker 'org-hd-marker marker 'org-category category
  10385. 'todo-state todo
  10386. 'ts-date ts-date
  10387. 'priority priority
  10388. 'type (concat "tagsmatch" ts-date-type))
  10389. (push txt rtn))
  10390. ((functionp action)
  10391. (setq org-map-continue-from nil)
  10392. (save-excursion
  10393. (setq rtn1 (funcall action))
  10394. (push rtn1 rtn)))
  10395. (t (user-error "Invalid action")))
  10396. ;; if we are to skip sublevels, jump to end of subtree
  10397. (unless org-tags-match-list-sublevels
  10398. (org-end-of-subtree t)
  10399. (backward-char 1))))
  10400. ;; Get the correct position from where to continue
  10401. (if org-map-continue-from
  10402. (goto-char org-map-continue-from)
  10403. (and (= (point) lspos) (end-of-line 1)))))
  10404. (when (and (eq action 'sparse-tree)
  10405. (not org-sparse-tree-open-archived-trees))
  10406. (org-hide-archived-subtrees (point-min) (point-max)))
  10407. (nreverse rtn)))
  10408. (defun org-remove-uninherited-tags (tags)
  10409. "Remove all tags that are not inherited from the list TAGS."
  10410. (cond
  10411. ((eq org-use-tag-inheritance t)
  10412. (if org-tags-exclude-from-inheritance
  10413. (org-delete-all org-tags-exclude-from-inheritance tags)
  10414. tags))
  10415. ((not org-use-tag-inheritance) nil)
  10416. ((stringp org-use-tag-inheritance)
  10417. (delq nil (mapcar
  10418. (lambda (x)
  10419. (if (and (string-match org-use-tag-inheritance x)
  10420. (not (member x org-tags-exclude-from-inheritance)))
  10421. x nil))
  10422. tags)))
  10423. ((listp org-use-tag-inheritance)
  10424. (delq nil (mapcar
  10425. (lambda (x)
  10426. (if (member x org-use-tag-inheritance) x nil))
  10427. tags)))))
  10428. (defun org-match-sparse-tree (&optional todo-only match)
  10429. "Create a sparse tree according to tags string MATCH.
  10430. MATCH is a string with match syntax. It can contain a selection
  10431. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10432. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10433. those. See the manual for details.
  10434. If optional argument TODO-ONLY is non-nil, only select lines that
  10435. are also TODO tasks."
  10436. (interactive "P")
  10437. (org-agenda-prepare-buffers (list (current-buffer)))
  10438. (let ((org--matcher-tags-todo-only todo-only))
  10439. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10440. org--matcher-tags-todo-only)))
  10441. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10442. (defvar org-cached-props nil)
  10443. (defun org-cached-entry-get (pom property)
  10444. (if (or (eq t org-use-property-inheritance)
  10445. (and (stringp org-use-property-inheritance)
  10446. (let ((case-fold-search t))
  10447. (string-match-p org-use-property-inheritance property)))
  10448. (and (listp org-use-property-inheritance)
  10449. (member-ignore-case property org-use-property-inheritance)))
  10450. ;; Caching is not possible, check it directly.
  10451. (org-entry-get pom property 'inherit)
  10452. ;; Get all properties, so we can do complicated checks easily.
  10453. (cdr (assoc-string property
  10454. (or org-cached-props
  10455. (setq org-cached-props (org-entry-properties pom)))
  10456. t))))
  10457. (defun org-global-tags-completion-table (&optional files)
  10458. "Return the list of all tags in all agenda buffer/files.
  10459. Optional FILES argument is a list of files which can be used
  10460. instead of the agenda files."
  10461. (save-excursion
  10462. (org-uniquify
  10463. (delq nil
  10464. (apply #'append
  10465. (mapcar
  10466. (lambda (file)
  10467. (set-buffer (find-file-noselect file))
  10468. (org--tag-add-to-alist
  10469. (org-get-buffer-tags)
  10470. (mapcar (lambda (x)
  10471. (and (stringp (car-safe x))
  10472. (list (car-safe x))))
  10473. org-current-tag-alist)))
  10474. (if (car-safe files) files
  10475. (org-agenda-files))))))))
  10476. (defun org-make-tags-matcher (match &optional only-local-tags)
  10477. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10478. Returns a cons of the selection string MATCH and a function
  10479. implementing the matcher.
  10480. The matcher is to be called at an Org entry, with point on the
  10481. headline, and returns non-nil if the entry matches the selection
  10482. string MATCH. It must be called with three arguments: the TODO
  10483. keyword at the entry (or nil if none), the list of all tags at
  10484. the entry including inherited ones and the reduced level of the
  10485. headline. Additionally, the category of the entry, if any, must
  10486. be specified as the text property `org-category' on the headline.
  10487. This function sets the variable `org--matcher-tags-todo-only' to
  10488. a non-nil value if the matcher restricts matching to TODO
  10489. entries, otherwise it is not touched.
  10490. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10491. table, only get buffer tags.
  10492. See also `org-scan-tags'."
  10493. (unless match
  10494. ;; Get a new match request, with completion against the global
  10495. ;; tags table and the local tags in current buffer.
  10496. (let ((org-last-tags-completion-table
  10497. (org--tag-add-to-alist
  10498. (org-get-buffer-tags)
  10499. (unless only-local-tags
  10500. (org-global-tags-completion-table)))))
  10501. (setq match
  10502. (completing-read
  10503. "Match: "
  10504. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10505. (let ((match0 match)
  10506. (re (concat
  10507. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10508. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10509. "\\([<>=]\\{1,2\\}\\)"
  10510. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10511. "\\|" org-tag-re "\\)"))
  10512. (start 0)
  10513. tagsmatch todomatch tagsmatcher todomatcher)
  10514. ;; Expand group tags.
  10515. (setq match (org-tags-expand match))
  10516. ;; Check if there is a TODO part of this match, which would be the
  10517. ;; part after a "/". To make sure that this slash is not part of
  10518. ;; a property value to be matched against, we also check that
  10519. ;; there is no / after that slash. First, find the last slash.
  10520. (let ((s 0))
  10521. (while (string-match "/+" match s)
  10522. (setq start (match-beginning 0))
  10523. (setq s (match-end 0))))
  10524. (if (and (string-match "/+" match start)
  10525. (not (string-match-p "\"" match start)))
  10526. ;; Match contains also a TODO-matching request.
  10527. (progn
  10528. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10529. (setq todomatch (substring match (match-end 0)))
  10530. (when (string-prefix-p "!" todomatch)
  10531. (setq org--matcher-tags-todo-only t)
  10532. (setq todomatch (substring todomatch 1)))
  10533. (when (string-match "\\`\\s-*\\'" todomatch)
  10534. (setq todomatch nil)))
  10535. ;; Only matching tags.
  10536. (setq tagsmatch match)
  10537. (setq todomatch nil))
  10538. ;; Make the tags matcher.
  10539. (when (org-string-nw-p tagsmatch)
  10540. (let ((orlist nil)
  10541. (orterms (org-split-string tagsmatch "|"))
  10542. term)
  10543. (while (setq term (pop orterms))
  10544. (while (and (equal (substring term -1) "\\") orterms)
  10545. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10546. (while (string-match re term)
  10547. (let* ((rest (substring term (match-end 0)))
  10548. (minus (and (match-end 1)
  10549. (equal (match-string 1 term) "-")))
  10550. (tag (save-match-data
  10551. (replace-regexp-in-string
  10552. "\\\\-" "-" (match-string 2 term))))
  10553. (regexp (eq (string-to-char tag) ?{))
  10554. (levelp (match-end 4))
  10555. (propp (match-end 5))
  10556. (mm
  10557. (cond
  10558. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10559. (levelp
  10560. `(,(org-op-to-function (match-string 3 term))
  10561. level
  10562. ,(string-to-number (match-string 4 term))))
  10563. (propp
  10564. (let* ((gv (pcase (upcase (match-string 5 term))
  10565. ("CATEGORY"
  10566. '(get-text-property (point) 'org-category))
  10567. ("TODO" 'todo)
  10568. (p `(org-cached-entry-get nil ,p))))
  10569. (pv (match-string 7 term))
  10570. (regexp (eq (string-to-char pv) ?{))
  10571. (strp (eq (string-to-char pv) ?\"))
  10572. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10573. (po (org-op-to-function (match-string 6 term)
  10574. (if timep 'time strp))))
  10575. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10576. (when timep (setq pv (org-matcher-time pv)))
  10577. (cond ((and regexp (eq po '/=))
  10578. `(not (string-match ,pv (or ,gv ""))))
  10579. (regexp `(string-match ,pv (or ,gv "")))
  10580. (strp `(,po (or ,gv "") ,pv))
  10581. (t
  10582. `(,po
  10583. (string-to-number (or ,gv ""))
  10584. ,(string-to-number pv))))))
  10585. (t `(member ,tag tags-list)))))
  10586. (push (if minus `(not ,mm) mm) tagsmatcher)
  10587. (setq term rest)))
  10588. (push `(and ,@tagsmatcher) orlist)
  10589. (setq tagsmatcher nil))
  10590. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10591. ;; Make the TODO matcher.
  10592. (when (org-string-nw-p todomatch)
  10593. (let ((orlist nil))
  10594. (dolist (term (org-split-string todomatch "|"))
  10595. (while (string-match re term)
  10596. (let* ((minus (and (match-end 1)
  10597. (equal (match-string 1 term) "-")))
  10598. (kwd (match-string 2 term))
  10599. (regexp (eq (string-to-char kwd) ?{))
  10600. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10601. `(equal todo ,kwd))))
  10602. (push (if minus `(not ,mm) mm) todomatcher))
  10603. (setq term (substring term (match-end 0))))
  10604. (push (if (> (length todomatcher) 1)
  10605. (cons 'and todomatcher)
  10606. (car todomatcher))
  10607. orlist)
  10608. (setq todomatcher nil))
  10609. (setq todomatcher (cons 'or orlist))))
  10610. ;; Return the string and function of the matcher. If no
  10611. ;; tags-specific or todo-specific matcher exists, match
  10612. ;; everything.
  10613. (let ((matcher (if (and tagsmatcher todomatcher)
  10614. `(and ,tagsmatcher ,todomatcher)
  10615. (or tagsmatcher todomatcher t))))
  10616. (when org--matcher-tags-todo-only
  10617. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10618. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10619. (defun org--tags-expand-group (group tag-groups expanded)
  10620. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10621. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10622. an accumulator used in recursive calls."
  10623. (dolist (tag group)
  10624. (unless (member tag expanded)
  10625. (let ((group (assoc tag tag-groups)))
  10626. (push tag expanded)
  10627. (when group
  10628. (setq expanded
  10629. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10630. expanded)
  10631. (defun org-tags-expand (match &optional single-as-list downcased)
  10632. "Expand group tags in MATCH.
  10633. This replaces every group tag in MATCH with a regexp tag search.
  10634. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10635. will be replaced like this:
  10636. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10637. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10638. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10639. Replacing by a regexp preserves the structure of the match.
  10640. E.g., this expansion
  10641. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10642. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10643. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10644. A group tag in MATCH can contain regular expressions of its own.
  10645. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10646. will be replaced like this:
  10647. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10648. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10649. assumed to be a single group tag, and the function will return
  10650. the list of tags in this group.
  10651. When DOWNCASED is non-nil, expand downcased TAGS."
  10652. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10653. (let ((tag-groups
  10654. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10655. (if (not downcased) g
  10656. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10657. (cond
  10658. (single-as-list (org--tags-expand-group
  10659. (list (if downcased (downcase match) match))
  10660. tag-groups nil))
  10661. (org-group-tags
  10662. (let* ((case-fold-search t)
  10663. (tag-syntax org-mode-syntax-table)
  10664. (group-keys (mapcar #'car tag-groups))
  10665. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10666. (return-match (if downcased (downcase match) match)))
  10667. ;; Mark regexp-expressions in the match-expression so that we
  10668. ;; do not replace them later on.
  10669. (let ((s 0))
  10670. (while (string-match "{.+?}" return-match s)
  10671. (setq s (match-end 0))
  10672. (add-text-properties
  10673. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10674. ;; @ and _ are allowed as word-components in tags.
  10675. (modify-syntax-entry ?@ "w" tag-syntax)
  10676. (modify-syntax-entry ?_ "w" tag-syntax)
  10677. ;; For each tag token found in MATCH, compute a regexp and it
  10678. (with-syntax-table tag-syntax
  10679. (replace-regexp-in-string
  10680. key-regexp
  10681. (lambda (m)
  10682. (if (get-text-property (match-beginning 2) 'regexp m)
  10683. m ;regexp tag: ignore
  10684. (let* ((operator (match-string 1 m))
  10685. (tag-token (let ((tag (match-string 2 m)))
  10686. (list (if downcased (downcase tag) tag))))
  10687. regexp-tags regular-tags)
  10688. ;; Partition tags between regexp and regular tags.
  10689. ;; Remove curly bracket syntax from regexp tags.
  10690. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10691. (save-match-data
  10692. (if (string-match "{\\(.+?\\)}" tag)
  10693. (push (match-string 1 tag) regexp-tags)
  10694. (push tag regular-tags))))
  10695. ;; Replace tag token by the appropriate regexp.
  10696. ;; Regular tags need to be regexp-quoted, whereas
  10697. ;; regexp-tags are inserted as-is.
  10698. (let ((regular (regexp-opt regular-tags))
  10699. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10700. (concat operator
  10701. (cond
  10702. ((null regular-tags) (format "{%s}" regexp))
  10703. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10704. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10705. return-match
  10706. t t))))
  10707. (t match))))
  10708. (defun org-op-to-function (op &optional stringp)
  10709. "Turn an operator into the appropriate function."
  10710. (setq op
  10711. (cond
  10712. ((equal op "<" ) '(< org-string< org-time<))
  10713. ((equal op ">" ) '(> org-string> org-time>))
  10714. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10715. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10716. ((member op '("=" "==")) '(= string= org-time=))
  10717. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10718. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10719. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10720. (defvar org-tags-overlay (make-overlay 1 1))
  10721. (delete-overlay org-tags-overlay)
  10722. (defun org-add-prop-inherited (s)
  10723. (add-text-properties 0 (length s) '(inherited t) s)
  10724. s)
  10725. (defun org-toggle-tag (tag &optional onoff)
  10726. "Toggle the tag TAG for the current line.
  10727. If ONOFF is `on' or `off', don't toggle but set to this state."
  10728. (save-excursion
  10729. (org-back-to-heading t)
  10730. (let ((current
  10731. ;; Reverse the tags list so any new tag is appended to the
  10732. ;; current list of tags.
  10733. (nreverse (org-get-tags nil t)))
  10734. res)
  10735. (pcase onoff
  10736. (`off (setq current (delete tag current)))
  10737. ((or `on (guard (not (member tag current))))
  10738. (setq res t)
  10739. (cl-pushnew tag current :test #'equal))
  10740. (_ (setq current (delete tag current))))
  10741. (org-set-tags (nreverse current))
  10742. res)))
  10743. (defun org--align-tags-here (to-col)
  10744. "Align tags on the current headline to TO-COL.
  10745. Assume point is on a headline. Preserve point when aligning
  10746. tags."
  10747. (when (org-match-line org-tag-line-re)
  10748. (let* ((tags-start (match-beginning 1))
  10749. (blank-start (save-excursion
  10750. (goto-char tags-start)
  10751. (skip-chars-backward " \t")
  10752. (point)))
  10753. (new (max (if (>= to-col 0) to-col
  10754. (- (abs to-col) (string-width (match-string 1))))
  10755. ;; Introduce at least one space after the heading
  10756. ;; or the stars.
  10757. (save-excursion
  10758. (goto-char blank-start)
  10759. (1+ (current-column)))))
  10760. (current
  10761. (save-excursion (goto-char tags-start) (current-column)))
  10762. (origin (point-marker))
  10763. (column (current-column))
  10764. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10765. (when (/= new current)
  10766. (delete-region blank-start tags-start)
  10767. (goto-char blank-start)
  10768. (let ((indent-tabs-mode nil)) (indent-to new))
  10769. ;; Try to move back to original position. If point was in the
  10770. ;; blanks before the tags, ORIGIN marker is of no use because
  10771. ;; it now points to BLANK-START. Use COLUMN instead.
  10772. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10773. (defun org-set-tags-command (&optional arg)
  10774. "Set the tags for the current visible entry.
  10775. When called with `\\[universal-argument]' prefix argument ARG, \
  10776. realign all tags
  10777. in the current buffer.
  10778. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10779. unconditionally do not
  10780. offer the fast tag selection interface.
  10781. If a region is active, set tags in the region according to the
  10782. setting of `org-loop-over-headlines-in-active-region'.
  10783. This function is for interactive use only;
  10784. in Lisp code use `org-set-tags' instead."
  10785. (interactive "P")
  10786. (let ((org-use-fast-tag-selection
  10787. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10788. (cond
  10789. ((equal '(4) arg) (org-align-tags t))
  10790. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10791. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10792. (org-map-entries
  10793. #'org-set-tags-command
  10794. nil
  10795. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10796. 'region-start-level
  10797. 'region)
  10798. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10799. (t
  10800. (save-excursion
  10801. (org-back-to-heading)
  10802. (let* ((all-tags (org-get-tags))
  10803. (table (setq org-last-tags-completion-table
  10804. (org--tag-add-to-alist
  10805. (and org-complete-tags-always-offer-all-agenda-tags
  10806. (org-global-tags-completion-table
  10807. (org-agenda-files)))
  10808. (or org-current-tag-alist (org-get-buffer-tags)))))
  10809. (current-tags
  10810. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10811. all-tags))
  10812. (inherited-tags
  10813. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10814. all-tags))
  10815. (tags
  10816. (replace-regexp-in-string
  10817. ;; Ignore all forbidden characters in tags.
  10818. "[^[:alnum:]_@#%]+" ":"
  10819. (if (or (eq t org-use-fast-tag-selection)
  10820. (and org-use-fast-tag-selection
  10821. (delq nil (mapcar #'cdr table))))
  10822. (org-fast-tag-selection
  10823. current-tags
  10824. inherited-tags
  10825. table
  10826. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10827. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10828. (org-trim (completing-read
  10829. "Tags: "
  10830. #'org-tags-completion-function
  10831. nil nil (org-make-tag-string current-tags)
  10832. 'org-tags-history)))))))
  10833. (org-set-tags tags)))))
  10834. ;; `save-excursion' may not replace the point at the right
  10835. ;; position.
  10836. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10837. (looking-at-p " "))
  10838. (forward-char))))
  10839. (defun org-align-tags (&optional all)
  10840. "Align tags in current entry.
  10841. When optional argument ALL is non-nil, align all tags in the
  10842. visible part of the buffer."
  10843. (let ((get-indent-column
  10844. (lambda ()
  10845. (let ((offset (if (bound-and-true-p org-indent-mode)
  10846. (* (1- org-indent-indentation-per-level)
  10847. (1- (org-current-level)))
  10848. 0)))
  10849. (+ org-tags-column
  10850. (if (> org-tags-column 0) (- offset) offset))))))
  10851. (if (and (not all) (org-at-heading-p))
  10852. (org--align-tags-here (funcall get-indent-column))
  10853. (save-excursion
  10854. (if all
  10855. (progn
  10856. (goto-char (point-min))
  10857. (while (re-search-forward org-tag-line-re nil t)
  10858. (org--align-tags-here (funcall get-indent-column))))
  10859. (org-back-to-heading t)
  10860. (org--align-tags-here (funcall get-indent-column)))))))
  10861. (defun org-set-tags (tags)
  10862. "Set the tags of the current entry to TAGS, replacing current tags.
  10863. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10864. If TAGS is nil or the empty string, all tags are removed.
  10865. This function assumes point is on a headline."
  10866. (org-with-wide-buffer
  10867. (let ((tags (pcase tags
  10868. ((pred listp) tags)
  10869. ((pred stringp) (split-string (org-trim tags) ":" t))
  10870. (_ (error "Invalid tag specification: %S" tags))))
  10871. (old-tags (org-get-tags nil t))
  10872. (tags-change? nil))
  10873. (when (functionp org-tags-sort-function)
  10874. (setq tags (sort tags org-tags-sort-function)))
  10875. (setq tags-change? (not (equal tags old-tags)))
  10876. (when tags-change?
  10877. ;; Delete previous tags and any trailing white space.
  10878. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10879. (line-end-position)))
  10880. (skip-chars-backward " \t")
  10881. (delete-region (point) (line-end-position))
  10882. ;; Deleting white spaces may break an otherwise empty headline.
  10883. ;; Re-introduce one space in this case.
  10884. (unless (org-at-heading-p) (insert " "))
  10885. (when tags
  10886. (save-excursion (insert " " (org-make-tag-string tags)))
  10887. ;; When text is being inserted on an invisible region
  10888. ;; boundary, it can be inadvertently sucked into
  10889. ;; invisibility.
  10890. (unless (org-invisible-p (line-beginning-position))
  10891. (org-flag-region (point) (line-end-position) nil 'outline))))
  10892. ;; Align tags, if any.
  10893. (when tags (org-align-tags))
  10894. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10895. (defun org-change-tag-in-region (beg end tag off)
  10896. "Add or remove TAG for each entry in the region.
  10897. This works in the agenda, and also in an Org buffer."
  10898. (interactive
  10899. (list (region-beginning) (region-end)
  10900. (let ((org-last-tags-completion-table
  10901. (if (derived-mode-p 'org-mode)
  10902. (org--tag-add-to-alist
  10903. (org-get-buffer-tags)
  10904. (org-global-tags-completion-table))
  10905. (org-global-tags-completion-table))))
  10906. (completing-read
  10907. "Tag: " 'org-tags-completion-function nil nil nil
  10908. 'org-tags-history))
  10909. (progn
  10910. (message "[s]et or [r]emove? ")
  10911. (equal (read-char-exclusive) ?r))))
  10912. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10913. (let ((agendap (equal major-mode 'org-agenda-mode))
  10914. l1 l2 m buf pos newhead (cnt 0))
  10915. (goto-char end)
  10916. (setq l2 (1- (org-current-line)))
  10917. (goto-char beg)
  10918. (setq l1 (org-current-line))
  10919. (cl-loop for l from l1 to l2 do
  10920. (org-goto-line l)
  10921. (setq m (get-text-property (point) 'org-hd-marker))
  10922. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10923. (and agendap m))
  10924. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10925. pos (if agendap m (point)))
  10926. (with-current-buffer buf
  10927. (save-excursion
  10928. (save-restriction
  10929. (goto-char pos)
  10930. (setq cnt (1+ cnt))
  10931. (org-toggle-tag tag (if off 'off 'on))
  10932. (setq newhead (org-get-heading)))))
  10933. (and agendap (org-agenda-change-all-lines newhead m))))
  10934. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10935. (defun org-tags-completion-function (string _predicate &optional flag)
  10936. "Complete tag STRING.
  10937. FLAG specifies the type of completion operation to perform. This
  10938. function is passed as a collection function to `completing-read',
  10939. which see."
  10940. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10941. (confirm (lambda (x) (stringp (car x))))
  10942. (prefix ""))
  10943. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10944. (setq prefix (match-string 1 string))
  10945. (setq string (match-string 2 string)))
  10946. (pcase flag
  10947. (`t (all-completions string org-last-tags-completion-table confirm))
  10948. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10949. (`nil
  10950. (pcase (try-completion string org-last-tags-completion-table confirm)
  10951. ((and completion (pred stringp))
  10952. (concat prefix
  10953. completion
  10954. (if (and org-add-colon-after-tag-completion
  10955. (assoc completion org-last-tags-completion-table))
  10956. ":"
  10957. "")))
  10958. (completion completion)))
  10959. (_ nil))))
  10960. (defun org-fast-tag-insert (kwd tags face &optional end)
  10961. "Insert KWD, and the TAGS, the latter with face FACE.
  10962. Also insert END."
  10963. (insert (format "%-12s" (concat kwd ":"))
  10964. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10965. (or end "")))
  10966. (defun org-fast-tag-show-exit (flag)
  10967. (save-excursion
  10968. (org-goto-line 3)
  10969. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10970. (replace-match ""))
  10971. (when flag
  10972. (end-of-line 1)
  10973. (org-move-to-column (- (window-width) 19) t)
  10974. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10975. (defun org-set-current-tags-overlay (current prefix)
  10976. "Add an overlay to CURRENT tag with PREFIX."
  10977. (let ((s (org-make-tag-string current)))
  10978. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10979. (org-overlay-display org-tags-overlay (concat prefix s))))
  10980. (defvar org-last-tag-selection-key nil)
  10981. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10982. "Fast tag selection with single keys.
  10983. CURRENT is the current list of tags in the headline, INHERITED is the
  10984. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10985. possibly with grouping information. TODO-TABLE is a similar table with
  10986. TODO keywords, should these have keys assigned to them.
  10987. If the keys are nil, a-z are automatically assigned.
  10988. Returns the new tags string, or nil to not change the current settings."
  10989. (let* ((fulltable (append table todo-table))
  10990. (maxlen (if (null fulltable) 0
  10991. (apply #'max
  10992. (mapcar (lambda (x)
  10993. (if (stringp (car x)) (string-width (car x))
  10994. 0))
  10995. fulltable))))
  10996. (buf (current-buffer))
  10997. (expert (eq org-fast-tag-selection-single-key 'expert))
  10998. (tab-tags nil)
  10999. (fwidth (+ maxlen 3 1 3))
  11000. (ncol (/ (- (window-width) 4) fwidth))
  11001. (i-face 'org-done)
  11002. (c-face 'org-todo)
  11003. tg cnt e c char c1 c2 ntable tbl rtn
  11004. ov-start ov-end ov-prefix
  11005. (exit-after-next org-fast-tag-selection-single-key)
  11006. (done-keywords org-done-keywords)
  11007. groups ingroup intaggroup)
  11008. (save-excursion
  11009. (beginning-of-line)
  11010. (if (looking-at org-tag-line-re)
  11011. (setq ov-start (match-beginning 1)
  11012. ov-end (match-end 1)
  11013. ov-prefix "")
  11014. (setq ov-start (1- (point-at-eol))
  11015. ov-end (1+ ov-start))
  11016. (skip-chars-forward "^\n\r")
  11017. (setq ov-prefix
  11018. (concat
  11019. (buffer-substring (1- (point)) (point))
  11020. (if (> (current-column) org-tags-column)
  11021. " "
  11022. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11023. (move-overlay org-tags-overlay ov-start ov-end)
  11024. (save-excursion
  11025. (save-window-excursion
  11026. (if expert
  11027. (set-buffer (get-buffer-create " *Org tags*"))
  11028. (delete-other-windows)
  11029. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11030. (org-switch-to-buffer-other-window " *Org tags*"))
  11031. (erase-buffer)
  11032. (setq-local org-done-keywords done-keywords)
  11033. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11034. (org-fast-tag-insert "Current" current c-face "\n\n")
  11035. (org-fast-tag-show-exit exit-after-next)
  11036. (org-set-current-tags-overlay current ov-prefix)
  11037. (setq tbl fulltable char ?a cnt 0)
  11038. (while (setq e (pop tbl))
  11039. (cond
  11040. ((eq (car e) :startgroup)
  11041. (push '() groups) (setq ingroup t)
  11042. (unless (zerop cnt)
  11043. (setq cnt 0)
  11044. (insert "\n"))
  11045. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11046. ((eq (car e) :endgroup)
  11047. (setq ingroup nil cnt 0)
  11048. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11049. ((eq (car e) :startgrouptag)
  11050. (setq intaggroup t)
  11051. (unless (zerop cnt)
  11052. (setq cnt 0)
  11053. (insert "\n"))
  11054. (insert "[ "))
  11055. ((eq (car e) :endgrouptag)
  11056. (setq intaggroup nil cnt 0)
  11057. (insert "]\n"))
  11058. ((equal e '(:newline))
  11059. (unless (zerop cnt)
  11060. (setq cnt 0)
  11061. (insert "\n")
  11062. (setq e (car tbl))
  11063. (while (equal (car tbl) '(:newline))
  11064. (insert "\n")
  11065. (setq tbl (cdr tbl)))))
  11066. ((equal e '(:grouptags)) (insert " : "))
  11067. (t
  11068. (setq tg (copy-sequence (car e)) c2 nil)
  11069. (if (cdr e)
  11070. (setq c (cdr e))
  11071. ;; automatically assign a character.
  11072. (setq c1 (string-to-char
  11073. (downcase (substring
  11074. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11075. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11076. (while (or (rassoc char ntable) (rassoc char table))
  11077. (setq char (1+ char)))
  11078. (setq c2 c1))
  11079. (setq c (or c2 char)))
  11080. (when ingroup (push tg (car groups)))
  11081. (setq tg (org-add-props tg nil 'face
  11082. (cond
  11083. ((not (assoc tg table))
  11084. (org-get-todo-face tg))
  11085. ((member tg current) c-face)
  11086. ((member tg inherited) i-face))))
  11087. (when (equal (caar tbl) :grouptags)
  11088. (org-add-props tg nil 'face 'org-tag-group))
  11089. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11090. (insert "[" c "] " tg (make-string
  11091. (- fwidth 4 (length tg)) ?\ ))
  11092. (push (cons tg c) ntable)
  11093. (when (= (cl-incf cnt) ncol)
  11094. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11095. (insert "\n")
  11096. (when (or ingroup intaggroup) (insert " ")))
  11097. (setq cnt 0)))))
  11098. (setq ntable (nreverse ntable))
  11099. (insert "\n")
  11100. (goto-char (point-min))
  11101. (unless expert (org-fit-window-to-buffer))
  11102. (setq rtn
  11103. (catch 'exit
  11104. (while t
  11105. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11106. (if (not groups) "no " "")
  11107. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11108. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11109. (setq org-last-tag-selection-key c)
  11110. (cond
  11111. ((= c ?\r) (throw 'exit t))
  11112. ((= c ?!)
  11113. (setq groups (not groups))
  11114. (goto-char (point-min))
  11115. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11116. ((= c ?\C-c)
  11117. (if (not expert)
  11118. (org-fast-tag-show-exit
  11119. (setq exit-after-next (not exit-after-next)))
  11120. (setq expert nil)
  11121. (delete-other-windows)
  11122. (set-window-buffer (split-window-vertically) " *Org tags*")
  11123. (org-switch-to-buffer-other-window " *Org tags*")
  11124. (org-fit-window-to-buffer)))
  11125. ((or (= c ?\C-g)
  11126. (and (= c ?q) (not (rassoc c ntable))))
  11127. (delete-overlay org-tags-overlay)
  11128. (setq quit-flag t))
  11129. ((= c ?\ )
  11130. (setq current nil)
  11131. (when exit-after-next (setq exit-after-next 'now)))
  11132. ((= c ?\t)
  11133. (condition-case nil
  11134. (unless tab-tags
  11135. (setq tab-tags
  11136. (delq nil
  11137. (mapcar (lambda (x)
  11138. (let ((item (car-safe x)))
  11139. (and (stringp item)
  11140. (list item))))
  11141. (org--tag-add-to-alist
  11142. (with-current-buffer buf
  11143. (org-get-buffer-tags))
  11144. table))))))
  11145. (setq tg (completing-read "Tag: " tab-tags))
  11146. (when (string-match "\\S-" tg)
  11147. (cl-pushnew (list tg) tab-tags :test #'equal)
  11148. (if (member tg current)
  11149. (setq current (delete tg current))
  11150. (push tg current)))
  11151. (when exit-after-next (setq exit-after-next 'now)))
  11152. ((setq e (rassoc c todo-table) tg (car e))
  11153. (with-current-buffer buf
  11154. (save-excursion (org-todo tg)))
  11155. (when exit-after-next (setq exit-after-next 'now)))
  11156. ((setq e (rassoc c ntable) tg (car e))
  11157. (if (member tg current)
  11158. (setq current (delete tg current))
  11159. (cl-loop for g in groups do
  11160. (when (member tg g)
  11161. (dolist (x g) (setq current (delete x current)))))
  11162. (push tg current))
  11163. (when exit-after-next (setq exit-after-next 'now))))
  11164. ;; Create a sorted list
  11165. (setq current
  11166. (sort current
  11167. (lambda (a b)
  11168. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11169. (when (eq exit-after-next 'now) (throw 'exit t))
  11170. (goto-char (point-min))
  11171. (beginning-of-line 2)
  11172. (delete-region (point) (point-at-eol))
  11173. (org-fast-tag-insert "Current" current c-face)
  11174. (org-set-current-tags-overlay current ov-prefix)
  11175. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11176. (while (re-search-forward tag-re nil t)
  11177. (let ((tag (match-string 1)))
  11178. (add-text-properties
  11179. (match-beginning 1) (match-end 1)
  11180. (list 'face
  11181. (cond
  11182. ((member tag current) c-face)
  11183. ((member tag inherited) i-face)
  11184. (t (get-text-property (match-beginning 1) '
  11185. face))))))))
  11186. (goto-char (point-min)))))
  11187. (delete-overlay org-tags-overlay)
  11188. (if rtn
  11189. (mapconcat 'identity current ":")
  11190. nil)))))
  11191. (defun org-make-tag-string (tags)
  11192. "Return string associated to TAGS.
  11193. TAGS is a list of strings."
  11194. (if (null tags) ""
  11195. (format ":%s:" (mapconcat #'identity tags ":"))))
  11196. (defun org--get-local-tags ()
  11197. "Return list of tags for the current headline.
  11198. Assume point is at the beginning of the headline."
  11199. (and (looking-at org-tag-line-re)
  11200. (split-string (match-string-no-properties 2) ":" t)))
  11201. (defun org-get-tags (&optional pos local)
  11202. "Get the list of tags specified in the current headline.
  11203. When argument POS is non-nil, retrieve tags for headline at POS.
  11204. According to `org-use-tag-inheritance', tags may be inherited
  11205. from parent headlines, and from the whole document, through
  11206. `org-file-tags'. In this case, the returned list of tags
  11207. contains tags in this order: file tags, tags inherited from
  11208. parent headlines, local tags. If a tag appears multiple times,
  11209. only the most local tag is returned.
  11210. However, when optional argument LOCAL is non-nil, only return
  11211. tags specified at the headline.
  11212. Inherited tags have the `inherited' text property."
  11213. (if (and org-trust-scanner-tags
  11214. (or (not pos) (eq pos (point)))
  11215. (not local))
  11216. org-scanner-tags
  11217. (org-with-point-at (or pos (point))
  11218. (unless (org-before-first-heading-p)
  11219. (org-back-to-heading t)
  11220. (let ((ltags (org--get-local-tags)) itags)
  11221. (if (or local (not org-use-tag-inheritance)) ltags
  11222. (while (org-up-heading-safe)
  11223. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11224. (org--get-local-tags))
  11225. itags)))
  11226. (setq itags (append org-file-tags itags))
  11227. (nreverse
  11228. (delete-dups
  11229. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11230. (defun org-get-buffer-tags ()
  11231. "Get a table of all tags used in the buffer, for completion."
  11232. (org-with-point-at 1
  11233. (let (tags)
  11234. (while (re-search-forward org-tag-line-re nil t)
  11235. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11236. tags)))
  11237. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11238. ;;;; The mapping API
  11239. (defvar org-agenda-skip-comment-trees)
  11240. (defvar org-agenda-skip-function)
  11241. (defun org-map-entries (func &optional match scope &rest skip)
  11242. "Call FUNC at each headline selected by MATCH in SCOPE.
  11243. FUNC is a function or a lisp form. The function will be called without
  11244. arguments, with the cursor positioned at the beginning of the headline.
  11245. The return values of all calls to the function will be collected and
  11246. returned as a list.
  11247. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11248. does not need to preserve point. After evaluation, the cursor will be
  11249. moved to the end of the line (presumably of the headline of the
  11250. processed entry) and search continues from there. Under some
  11251. circumstances, this may not produce the wanted results. For example,
  11252. if you have removed (e.g. archived) the current (sub)tree it could
  11253. mean that the next entry will be skipped entirely. In such cases, you
  11254. can specify the position from where search should continue by making
  11255. FUNC set the variable `org-map-continue-from' to the desired buffer
  11256. position.
  11257. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11258. Only headlines that are matched by this query will be considered during
  11259. the iteration. When MATCH is nil or t, all headlines will be
  11260. visited by the iteration.
  11261. SCOPE determines the scope of this command. It can be any of:
  11262. nil The current buffer, respecting the restriction if any
  11263. tree The subtree started with the entry at point
  11264. region The entries within the active region, if any
  11265. region-start-level
  11266. The entries within the active region, but only those at
  11267. the same level than the first one.
  11268. file The current buffer, without restriction
  11269. file-with-archives
  11270. The current buffer, and any archives associated with it
  11271. agenda All agenda files
  11272. agenda-with-archives
  11273. All agenda files with any archive files associated with them
  11274. \(file1 file2 ...)
  11275. If this is a list, all files in the list will be scanned
  11276. The remaining args are treated as settings for the skipping facilities of
  11277. the scanner. The following items can be given here:
  11278. archive skip trees with the archive tag
  11279. comment skip trees with the COMMENT keyword
  11280. function or Emacs Lisp form:
  11281. will be used as value for `org-agenda-skip-function', so
  11282. whenever the function returns a position, FUNC will not be
  11283. called for that entry and search will continue from the
  11284. position returned
  11285. If your function needs to retrieve the tags including inherited tags
  11286. at the *current* entry, you can use the value of the variable
  11287. `org-scanner-tags' which will be much faster than getting the value
  11288. with `org-get-tags'. If your function gets properties with
  11289. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11290. to t around the call to `org-entry-properties' to get the same speedup.
  11291. Note that if your function moves around to retrieve tags and properties at
  11292. a *different* entry, you cannot use these techniques."
  11293. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11294. (not (org-region-active-p)))
  11295. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11296. (org-agenda-skip-archived-trees (memq 'archive skip))
  11297. (org-agenda-skip-comment-trees (memq 'comment skip))
  11298. (org-agenda-skip-function
  11299. (car (org-delete-all '(comment archive) skip)))
  11300. (org-tags-match-list-sublevels t)
  11301. (start-level (eq scope 'region-start-level))
  11302. matcher res
  11303. org-todo-keywords-for-agenda
  11304. org-done-keywords-for-agenda
  11305. org-todo-keyword-alist-for-agenda
  11306. org-tag-alist-for-agenda
  11307. org--matcher-tags-todo-only)
  11308. (cond
  11309. ((eq match t) (setq matcher t))
  11310. ((eq match nil) (setq matcher t))
  11311. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11312. (save-excursion
  11313. (save-restriction
  11314. (cond ((eq scope 'tree)
  11315. (org-back-to-heading t)
  11316. (org-narrow-to-subtree)
  11317. (setq scope nil))
  11318. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11319. (org-region-active-p))
  11320. ;; If needed, set start-level to a string like "2"
  11321. (when start-level
  11322. (save-excursion
  11323. (goto-char (region-beginning))
  11324. (unless (org-at-heading-p) (outline-next-heading))
  11325. (setq start-level (org-current-level))))
  11326. (narrow-to-region (region-beginning)
  11327. (save-excursion
  11328. (goto-char (region-end))
  11329. (unless (and (bolp) (org-at-heading-p))
  11330. (outline-next-heading))
  11331. (point)))
  11332. (setq scope nil)))
  11333. (if (not scope)
  11334. (progn
  11335. (org-agenda-prepare-buffers
  11336. (and buffer-file-name (list buffer-file-name)))
  11337. (setq res
  11338. (org-scan-tags
  11339. func matcher org--matcher-tags-todo-only start-level)))
  11340. ;; Get the right scope
  11341. (cond
  11342. ((and scope (listp scope) (symbolp (car scope)))
  11343. (setq scope (eval scope)))
  11344. ((eq scope 'agenda)
  11345. (setq scope (org-agenda-files t)))
  11346. ((eq scope 'agenda-with-archives)
  11347. (setq scope (org-agenda-files t))
  11348. (setq scope (org-add-archive-files scope)))
  11349. ((eq scope 'file)
  11350. (setq scope (and buffer-file-name (list buffer-file-name))))
  11351. ((eq scope 'file-with-archives)
  11352. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11353. (org-agenda-prepare-buffers scope)
  11354. (dolist (file scope)
  11355. (with-current-buffer (org-find-base-buffer-visiting file)
  11356. (org-with-wide-buffer
  11357. (goto-char (point-min))
  11358. (setq res
  11359. (append
  11360. res
  11361. (org-scan-tags
  11362. func matcher org--matcher-tags-todo-only)))))))))
  11363. res)))
  11364. ;;; Properties API
  11365. (defconst org-special-properties
  11366. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11367. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11368. "The special properties valid in Org mode.
  11369. These are properties that are not defined in the property drawer,
  11370. but in some other way.")
  11371. (defconst org-default-properties
  11372. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11373. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11374. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11375. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11376. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11377. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11378. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11379. "Some properties that are used by Org mode for various purposes.
  11380. Being in this list makes sure that they are offered for completion.")
  11381. (defun org--valid-property-p (property)
  11382. "Non-nil when string PROPERTY is a valid property name."
  11383. (not
  11384. (or (equal property "")
  11385. (string-match-p "\\s-" property))))
  11386. (defun org--update-property-plist (key val props)
  11387. "Associate KEY to VAL in alist PROPS.
  11388. Modifications are made by side-effect. Return new alist."
  11389. (let* ((appending (string= (substring key -1) "+"))
  11390. (key (if appending (substring key 0 -1) key))
  11391. (old (assoc-string key props t)))
  11392. (if (not old) (cons (cons key val) props)
  11393. (setcdr old (if appending (concat (cdr old) " " val) val))
  11394. props)))
  11395. (defun org-get-property-block (&optional beg force)
  11396. "Return the (beg . end) range of the body of the property drawer.
  11397. BEG is the beginning of the current subtree or the beginning of
  11398. the document if before the first headline. If it is not given,
  11399. it will be found. If the drawer does not exist, create it if
  11400. FORCE is non-nil, or return nil."
  11401. (org-with-wide-buffer
  11402. (let ((beg (cond (beg (goto-char beg))
  11403. ((or (not (featurep 'org-inlinetask))
  11404. (org-inlinetask-in-task-p))
  11405. (org-back-to-heading-or-point-min t) (point))
  11406. (t (org-with-limited-levels
  11407. (org-back-to-heading-or-point-min t))
  11408. (point)))))
  11409. ;; Move point to its position according to its positional rules.
  11410. (cond ((org-before-first-heading-p)
  11411. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11412. (t (forward-line)
  11413. (when (looking-at-p org-planning-line-re) (forward-line))))
  11414. (cond ((looking-at org-property-drawer-re)
  11415. (forward-line)
  11416. (cons (point) (progn (goto-char (match-end 0))
  11417. (line-beginning-position))))
  11418. (force
  11419. (goto-char beg)
  11420. (org-insert-property-drawer)
  11421. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11422. (line-beginning-position))))
  11423. (cons pos pos)))))))
  11424. (defun org-at-property-drawer-p ()
  11425. "Non-nil when point is at the first line of a property drawer."
  11426. (org-with-wide-buffer
  11427. (beginning-of-line)
  11428. (and (looking-at org-property-drawer-re)
  11429. (or (bobp)
  11430. (progn
  11431. (forward-line -1)
  11432. (cond ((org-at-heading-p))
  11433. ((looking-at org-planning-line-re)
  11434. (forward-line -1)
  11435. (org-at-heading-p))
  11436. ((looking-at org-comment-regexp)
  11437. (forward-line -1)
  11438. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11439. (forward-line -1))
  11440. (looking-at org-comment-regexp))
  11441. (t nil)))))))
  11442. (defun org-at-property-p ()
  11443. "Non-nil when point is inside a property drawer.
  11444. See `org-property-re' for match data, if applicable."
  11445. (save-excursion
  11446. (beginning-of-line)
  11447. (and (looking-at org-property-re)
  11448. (let ((property-drawer (save-match-data (org-get-property-block))))
  11449. (and property-drawer
  11450. (>= (point) (car property-drawer))
  11451. (< (point) (cdr property-drawer)))))))
  11452. (defun org-property-action ()
  11453. "Do an action on properties."
  11454. (interactive)
  11455. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11456. (let ((c (read-char-exclusive)))
  11457. (cl-case c
  11458. (?s (call-interactively #'org-set-property))
  11459. (?d (call-interactively #'org-delete-property))
  11460. (?D (call-interactively #'org-delete-property-globally))
  11461. (?c (call-interactively #'org-compute-property-at-point))
  11462. (otherwise (user-error "No such property action %c" c)))))
  11463. (defun org-inc-effort ()
  11464. "Increment the value of the effort property in the current entry."
  11465. (interactive)
  11466. (org-set-effort t))
  11467. (defvar org-clock-effort) ; Defined in org-clock.el.
  11468. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11469. (defun org-set-effort (&optional increment value)
  11470. "Set the effort property of the current entry.
  11471. If INCREMENT is non-nil, set the property to the next allowed
  11472. value. Otherwise, if optional argument VALUE is provided, use
  11473. it. Eventually, prompt for the new value if none of the previous
  11474. variables is set."
  11475. (interactive "P")
  11476. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11477. (current (org-entry-get nil org-effort-property))
  11478. (value
  11479. (cond
  11480. (increment
  11481. (unless allowed (user-error "Allowed effort values are not set"))
  11482. (or (cl-caadr (member (list current) allowed))
  11483. (user-error "Unknown value %S among allowed values" current)))
  11484. (value
  11485. (if (stringp value) value
  11486. (error "Invalid effort value: %S" value)))
  11487. (t
  11488. (let ((must-match
  11489. (and allowed
  11490. (not (get-text-property 0 'org-unrestricted
  11491. (caar allowed))))))
  11492. (completing-read "Effort: " allowed nil must-match))))))
  11493. ;; Test whether the value can be interpreted as a duration before
  11494. ;; inserting it in the buffer:
  11495. (org-duration-to-minutes value)
  11496. ;; Maybe update the effort value:
  11497. (unless (equal current value)
  11498. (org-entry-put nil org-effort-property value))
  11499. (org-refresh-property '((effort . identity)
  11500. (effort-minutes . org-duration-to-minutes))
  11501. value)
  11502. (when (equal (org-get-heading t t t t)
  11503. (bound-and-true-p org-clock-current-task))
  11504. (setq org-clock-effort value)
  11505. (org-clock-update-mode-line))
  11506. (message "%s is now %s" org-effort-property value)))
  11507. (defun org-entry-properties (&optional pom which)
  11508. "Get all properties of the current entry.
  11509. When POM is a buffer position, get all properties from the entry
  11510. there instead.
  11511. This includes the TODO keyword, the tags, time strings for
  11512. deadline, scheduled, and clocking, and any additional properties
  11513. defined in the entry.
  11514. If WHICH is nil or `all', get all properties. If WHICH is
  11515. `special' or `standard', only get that subclass. If WHICH is
  11516. a string, only get that property.
  11517. Return value is an alist. Keys are properties, as upcased
  11518. strings."
  11519. (org-with-point-at pom
  11520. (when (and (derived-mode-p 'org-mode)
  11521. (org-back-to-heading-or-point-min t))
  11522. (catch 'exit
  11523. (let* ((beg (point))
  11524. (specific (and (stringp which) (upcase which)))
  11525. (which (cond ((not specific) which)
  11526. ((member specific org-special-properties) 'special)
  11527. (t 'standard)))
  11528. props)
  11529. ;; Get the special properties, like TODO and TAGS.
  11530. (when (memq which '(nil all special))
  11531. (when (or (not specific) (string= specific "CLOCKSUM"))
  11532. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11533. (when clocksum
  11534. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11535. props)))
  11536. (when specific (throw 'exit props)))
  11537. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11538. (let ((clocksumt (get-text-property (point)
  11539. :org-clock-minutes-today)))
  11540. (when clocksumt
  11541. (push (cons "CLOCKSUM_T"
  11542. (org-duration-from-minutes clocksumt))
  11543. props)))
  11544. (when specific (throw 'exit props)))
  11545. (when (or (not specific) (string= specific "ITEM"))
  11546. (let ((case-fold-search nil))
  11547. (when (looking-at org-complex-heading-regexp)
  11548. (push (cons "ITEM"
  11549. (let ((title (match-string-no-properties 4)))
  11550. (if (org-string-nw-p title)
  11551. (org-remove-tabs title)
  11552. "")))
  11553. props)))
  11554. (when specific (throw 'exit props)))
  11555. (when (or (not specific) (string= specific "TODO"))
  11556. (let ((case-fold-search nil))
  11557. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11558. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11559. (when specific (throw 'exit props)))
  11560. (when (or (not specific) (string= specific "PRIORITY"))
  11561. (push (cons "PRIORITY"
  11562. (if (looking-at org-priority-regexp)
  11563. (match-string-no-properties 2)
  11564. (char-to-string org-priority-default)))
  11565. props)
  11566. (when specific (throw 'exit props)))
  11567. (when (or (not specific) (string= specific "FILE"))
  11568. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11569. props)
  11570. (when specific (throw 'exit props)))
  11571. (when (or (not specific) (string= specific "TAGS"))
  11572. (let ((tags (org-get-tags nil t)))
  11573. (when tags
  11574. (push (cons "TAGS" (org-make-tag-string tags))
  11575. props)))
  11576. (when specific (throw 'exit props)))
  11577. (when (or (not specific) (string= specific "ALLTAGS"))
  11578. (let ((tags (org-get-tags)))
  11579. (when tags
  11580. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11581. props)))
  11582. (when specific (throw 'exit props)))
  11583. (when (or (not specific) (string= specific "BLOCKED"))
  11584. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11585. (when specific (throw 'exit props)))
  11586. (when (or (not specific)
  11587. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11588. (forward-line)
  11589. (when (looking-at-p org-planning-line-re)
  11590. (end-of-line)
  11591. (let ((bol (line-beginning-position))
  11592. ;; Backward compatibility: time keywords used to
  11593. ;; be configurable (before 8.3). Make sure we
  11594. ;; get the correct keyword.
  11595. (key-assoc `(("CLOSED" . ,org-closed-string)
  11596. ("DEADLINE" . ,org-deadline-string)
  11597. ("SCHEDULED" . ,org-scheduled-string))))
  11598. (dolist (pair (if specific (list (assoc specific key-assoc))
  11599. key-assoc))
  11600. (save-excursion
  11601. (when (search-backward (cdr pair) bol t)
  11602. (goto-char (match-end 0))
  11603. (skip-chars-forward " \t")
  11604. (and (looking-at org-ts-regexp-both)
  11605. (push (cons (car pair)
  11606. (match-string-no-properties 0))
  11607. props)))))))
  11608. (when specific (throw 'exit props)))
  11609. (when (or (not specific)
  11610. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11611. (let ((find-ts
  11612. (lambda (end ts)
  11613. ;; Fix next time-stamp before END. TS is the
  11614. ;; list of time-stamps found so far.
  11615. (let ((ts ts)
  11616. (regexp (cond
  11617. ((string= specific "TIMESTAMP")
  11618. org-ts-regexp)
  11619. ((string= specific "TIMESTAMP_IA")
  11620. org-ts-regexp-inactive)
  11621. ((assoc "TIMESTAMP_IA" ts)
  11622. org-ts-regexp)
  11623. ((assoc "TIMESTAMP" ts)
  11624. org-ts-regexp-inactive)
  11625. (t org-ts-regexp-both))))
  11626. (catch 'next
  11627. (while (re-search-forward regexp end t)
  11628. (backward-char)
  11629. (let ((object (org-element-context)))
  11630. ;; Accept to match timestamps in node
  11631. ;; properties, too.
  11632. (when (memq (org-element-type object)
  11633. '(node-property timestamp))
  11634. (let ((type
  11635. (org-element-property :type object)))
  11636. (cond
  11637. ((and (memq type '(active active-range))
  11638. (not (equal specific "TIMESTAMP_IA")))
  11639. (unless (assoc "TIMESTAMP" ts)
  11640. (push (cons "TIMESTAMP"
  11641. (org-element-property
  11642. :raw-value object))
  11643. ts)
  11644. (when specific (throw 'exit ts))))
  11645. ((and (memq type '(inactive inactive-range))
  11646. (not (string= specific "TIMESTAMP")))
  11647. (unless (assoc "TIMESTAMP_IA" ts)
  11648. (push (cons "TIMESTAMP_IA"
  11649. (org-element-property
  11650. :raw-value object))
  11651. ts)
  11652. (when specific (throw 'exit ts))))))
  11653. ;; Both timestamp types are found,
  11654. ;; move to next part.
  11655. (when (= (length ts) 2) (throw 'next ts)))))
  11656. ts)))))
  11657. (goto-char beg)
  11658. ;; First look for timestamps within headline.
  11659. (let ((ts (funcall find-ts (line-end-position) nil)))
  11660. (if (= (length ts) 2) (setq props (nconc ts props))
  11661. ;; Then find timestamps in the section, skipping
  11662. ;; planning line.
  11663. (let ((end (save-excursion (outline-next-heading))))
  11664. (forward-line)
  11665. (when (looking-at-p org-planning-line-re) (forward-line))
  11666. (setq props (nconc (funcall find-ts end ts) props))))))))
  11667. ;; Get the standard properties, like :PROP:.
  11668. (when (memq which '(nil all standard))
  11669. ;; If we are looking after a specific property, delegate
  11670. ;; to `org-entry-get', which is faster. However, make an
  11671. ;; exception for "CATEGORY", since it can be also set
  11672. ;; through keywords (i.e. #+CATEGORY).
  11673. (if (and specific (not (equal specific "CATEGORY")))
  11674. (let ((value (org-entry-get beg specific nil t)))
  11675. (throw 'exit (and value (list (cons specific value)))))
  11676. (let ((range (org-get-property-block beg)))
  11677. (when range
  11678. (let ((end (cdr range)) seen-base)
  11679. (goto-char (car range))
  11680. ;; Unlike to `org--update-property-plist', we
  11681. ;; handle the case where base values is found
  11682. ;; after its extension. We also forbid standard
  11683. ;; properties to be named as special properties.
  11684. (while (re-search-forward org-property-re end t)
  11685. (let* ((key (upcase (match-string-no-properties 2)))
  11686. (extendp (string-match-p "\\+\\'" key))
  11687. (key-base (if extendp (substring key 0 -1) key))
  11688. (value (match-string-no-properties 3)))
  11689. (cond
  11690. ((member-ignore-case key-base org-special-properties))
  11691. (extendp
  11692. (setq props
  11693. (org--update-property-plist key value props)))
  11694. ((member key seen-base))
  11695. (t (push key seen-base)
  11696. (let ((p (assoc-string key props t)))
  11697. (if p (setcdr p (concat value " " (cdr p)))
  11698. (push (cons key value) props))))))))))))
  11699. (unless (assoc "CATEGORY" props)
  11700. (push (cons "CATEGORY" (org-get-category beg)) props)
  11701. (when (string= specific "CATEGORY") (throw 'exit props)))
  11702. ;; Return value.
  11703. props)))))
  11704. (defun org--property-local-values (property literal-nil)
  11705. "Return value for PROPERTY in current entry.
  11706. Value is a list whose car is the base value for PROPERTY and cdr
  11707. a list of accumulated values. Return nil if neither is found in
  11708. the entry. Also return nil when PROPERTY is set to \"nil\",
  11709. unless LITERAL-NIL is non-nil."
  11710. (let ((range (org-get-property-block)))
  11711. (when range
  11712. (goto-char (car range))
  11713. (let* ((case-fold-search t)
  11714. (end (cdr range))
  11715. (value
  11716. ;; Base value.
  11717. (save-excursion
  11718. (let ((v (and (re-search-forward
  11719. (org-re-property property nil t) end t)
  11720. (match-string-no-properties 3))))
  11721. (list (if literal-nil v (org-not-nil v)))))))
  11722. ;; Find additional values.
  11723. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11724. (while (re-search-forward property+ end t)
  11725. (push (match-string-no-properties 3) value)))
  11726. ;; Return final values.
  11727. (and (not (equal value '(nil))) (nreverse value))))))
  11728. (defun org--property-global-or-keyword-value (property literal-nil)
  11729. "Return value for PROPERTY as defined by global properties or by keyword.
  11730. Return value is a string. Return nil if property is not set
  11731. globally or by keyword. Also return nil when PROPERTY is set to
  11732. \"nil\", unless LITERAL-NIL is non-nil."
  11733. (let ((global
  11734. (cdr (or (assoc-string property org-keyword-properties t)
  11735. (assoc-string property org-global-properties t)
  11736. (assoc-string property org-global-properties-fixed t)))))
  11737. (if literal-nil global (org-not-nil global))))
  11738. (defun org-entry-get (pom property &optional inherit literal-nil)
  11739. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11740. If INHERIT is non-nil and the entry does not have the property,
  11741. then also check higher levels of the hierarchy. If INHERIT is
  11742. the symbol `selective', use inheritance only if the setting in
  11743. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11744. If the property is present but empty, the return value is the
  11745. empty string. If the property is not present at all, nil is
  11746. returned. In any other case, return the value as a string.
  11747. Search is case-insensitive.
  11748. If LITERAL-NIL is set, return the string value \"nil\" as
  11749. a string, do not interpret it as the list atom nil. This is used
  11750. for inheritance when a \"nil\" value can supersede a non-nil
  11751. value higher up the hierarchy."
  11752. (org-with-point-at pom
  11753. (cond
  11754. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11755. ;; We need a special property. Use `org-entry-properties' to
  11756. ;; retrieve it, but specify the wanted property.
  11757. (cdr (assoc-string property (org-entry-properties nil property))))
  11758. ((and inherit
  11759. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11760. (org-entry-get-with-inheritance property literal-nil))
  11761. (t
  11762. (let* ((local (org--property-local-values property literal-nil))
  11763. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11764. (if literal-nil value (org-not-nil value)))))))
  11765. (defun org-property-or-variable-value (var &optional inherit)
  11766. "Check if there is a property fixing the value of VAR.
  11767. If yes, return this value. If not, return the current value of the variable."
  11768. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11769. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11770. (read prop)
  11771. (symbol-value var))))
  11772. (defun org-entry-delete (pom property)
  11773. "Delete PROPERTY from entry at point-or-marker POM.
  11774. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11775. non-nil when a property was removed."
  11776. (org-with-point-at pom
  11777. (pcase (org-get-property-block)
  11778. (`(,begin . ,origin)
  11779. (let* ((end (copy-marker origin))
  11780. (re (org-re-property
  11781. (concat (regexp-quote property) "\\+?") t t)))
  11782. (goto-char begin)
  11783. (while (re-search-forward re end t)
  11784. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11785. ;; If drawer is empty, remove it altogether.
  11786. (when (= begin end)
  11787. (delete-region (line-beginning-position 0)
  11788. (line-beginning-position 2)))
  11789. ;; Return non-nil if some property was removed.
  11790. (prog1 (/= end origin) (set-marker end nil))))
  11791. (_ nil))))
  11792. ;; Multi-values properties are properties that contain multiple values
  11793. ;; These values are assumed to be single words, separated by whitespace.
  11794. (defun org-entry-add-to-multivalued-property (pom property value)
  11795. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11796. (let* ((old (org-entry-get pom property))
  11797. (values (and old (split-string old))))
  11798. (setq value (org-entry-protect-space value))
  11799. (unless (member value values)
  11800. (setq values (append values (list value)))
  11801. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11802. (defun org-entry-remove-from-multivalued-property (pom property value)
  11803. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11804. (let* ((old (org-entry-get pom property))
  11805. (values (and old (split-string old))))
  11806. (setq value (org-entry-protect-space value))
  11807. (when (member value values)
  11808. (setq values (delete value values))
  11809. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11810. (defun org-entry-member-in-multivalued-property (pom property value)
  11811. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11812. (let* ((old (org-entry-get pom property))
  11813. (values (and old (split-string old))))
  11814. (setq value (org-entry-protect-space value))
  11815. (member value values)))
  11816. (defun org-entry-get-multivalued-property (pom property)
  11817. "Return a list of values in a multivalued property."
  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-put-multivalued-property (pom property &rest values)
  11822. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11823. VALUES should be a list of strings. Spaces will be protected."
  11824. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11825. (let* ((value (org-entry-get pom property))
  11826. (values (and value (split-string value))))
  11827. (mapcar #'org-entry-restore-space values)))
  11828. (defun org-entry-protect-space (s)
  11829. "Protect spaces and newline in string S."
  11830. (while (string-match " " s)
  11831. (setq s (replace-match "%20" t t s)))
  11832. (while (string-match "\n" s)
  11833. (setq s (replace-match "%0A" t t s)))
  11834. s)
  11835. (defun org-entry-restore-space (s)
  11836. "Restore spaces and newline in string S."
  11837. (while (string-match "%20" s)
  11838. (setq s (replace-match " " t t s)))
  11839. (while (string-match "%0A" s)
  11840. (setq s (replace-match "\n" t t s)))
  11841. s)
  11842. (defvar org-entry-property-inherited-from (make-marker)
  11843. "Marker pointing to the entry from where a property was inherited.
  11844. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11845. location of the entry where the inheritance search matched. If there was
  11846. no match, the marker will point nowhere.
  11847. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11848. is set.")
  11849. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11850. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11851. The search will stop at the first ancestor which has the property defined.
  11852. If the value found is \"nil\", return nil to show that the property
  11853. should be considered as undefined (this is the meaning of nil here).
  11854. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11855. (move-marker org-entry-property-inherited-from nil)
  11856. (org-with-wide-buffer
  11857. (let (value)
  11858. (catch 'exit
  11859. (while t
  11860. (let ((v (org--property-local-values property literal-nil)))
  11861. (when v
  11862. (setq value
  11863. (concat (mapconcat #'identity (delq nil v) " ")
  11864. (and value " ")
  11865. value)))
  11866. (cond
  11867. ((car v)
  11868. (org-back-to-heading-or-point-min t)
  11869. (move-marker org-entry-property-inherited-from (point))
  11870. (throw 'exit nil))
  11871. ((org-up-heading-or-point-min))
  11872. (t
  11873. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11874. (cond ((not global))
  11875. (value (setq value (concat global " " value)))
  11876. (t (setq value global))))
  11877. (throw 'exit nil))))))
  11878. (if literal-nil value (org-not-nil value)))))
  11879. (defvar org-property-changed-functions nil
  11880. "Hook called when the value of a property has changed.
  11881. Each hook function should accept two arguments, the name of the property
  11882. and the new value.")
  11883. (defun org-entry-put (pom property value)
  11884. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11885. If the value is nil, it is converted to the empty string. If it
  11886. is not a string, an error is raised. Also raise an error on
  11887. invalid property names.
  11888. PROPERTY can be any regular property (see
  11889. `org-special-properties'). It can also be \"TODO\",
  11890. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11891. For the last two properties, VALUE may have any of the special
  11892. values \"earlier\" and \"later\". The function then increases or
  11893. decreases scheduled or deadline date by one day."
  11894. (cond ((null value) (setq value ""))
  11895. ((not (stringp value)) (error "Properties values should be strings"))
  11896. ((not (org--valid-property-p property))
  11897. (user-error "Invalid property name: \"%s\"" property)))
  11898. (org-with-point-at pom
  11899. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11900. (org-back-to-heading-or-point-min t)
  11901. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11902. (let ((beg (point)))
  11903. (cond
  11904. ((equal property "TODO")
  11905. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11906. ((not (member value org-todo-keywords-1))
  11907. (user-error "\"%s\" is not a valid TODO state" value)))
  11908. (org-todo value)
  11909. (org-align-tags))
  11910. ((equal property "PRIORITY")
  11911. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11912. (org-align-tags))
  11913. ((equal property "SCHEDULED")
  11914. (forward-line)
  11915. (if (and (looking-at-p org-planning-line-re)
  11916. (re-search-forward
  11917. org-scheduled-time-regexp (line-end-position) t))
  11918. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11919. ((string= value "later") (org-timestamp-change 1 'day))
  11920. ((string= value "") (org-schedule '(4)))
  11921. (t (org-schedule nil value)))
  11922. (if (member value '("earlier" "later" ""))
  11923. (call-interactively #'org-schedule)
  11924. (org-schedule nil value))))
  11925. ((equal property "DEADLINE")
  11926. (forward-line)
  11927. (if (and (looking-at-p org-planning-line-re)
  11928. (re-search-forward
  11929. org-deadline-time-regexp (line-end-position) t))
  11930. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11931. ((string= value "later") (org-timestamp-change 1 'day))
  11932. ((string= value "") (org-deadline '(4)))
  11933. (t (org-deadline nil value)))
  11934. (if (member value '("earlier" "later" ""))
  11935. (call-interactively #'org-deadline)
  11936. (org-deadline nil value))))
  11937. ((member property org-special-properties)
  11938. (error "The %s property cannot be set with `org-entry-put'" property))
  11939. (t
  11940. (let* ((range (org-get-property-block beg 'force))
  11941. (end (cdr range))
  11942. (case-fold-search t))
  11943. (goto-char (car range))
  11944. (if (re-search-forward (org-re-property property nil t) end t)
  11945. (progn (delete-region (match-beginning 0) (match-end 0))
  11946. (goto-char (match-beginning 0)))
  11947. (goto-char end)
  11948. (insert "\n")
  11949. (backward-char))
  11950. (insert ":" property ":")
  11951. (when value (insert " " value))
  11952. (org-indent-line)))))
  11953. (run-hook-with-args 'org-property-changed-functions property value)))
  11954. (defun org-buffer-property-keys (&optional specials defaults columns)
  11955. "Get all property keys in the current buffer.
  11956. When SPECIALS is non-nil, also list the special properties that
  11957. reflect things like tags and TODO state.
  11958. When DEFAULTS is non-nil, also include properties that has
  11959. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11960. DESCRIPTION, LOCATION, and LOGGING and others.
  11961. When COLUMNS in non-nil, also include property names given in
  11962. COLUMN formats in the current buffer."
  11963. (let ((case-fold-search t)
  11964. (props (append
  11965. (and specials org-special-properties)
  11966. (and defaults (cons org-effort-property org-default-properties))
  11967. ;; Get property names from #+PROPERTY keywords as well
  11968. (mapcar (lambda (s)
  11969. (nth 0 (split-string s)))
  11970. (cdar (org-collect-keywords '("PROPERTY")))))))
  11971. (org-with-wide-buffer
  11972. (goto-char (point-min))
  11973. (while (re-search-forward org-property-start-re nil t)
  11974. (catch :skip
  11975. (let ((range (org-get-property-block)))
  11976. (unless range (throw :skip nil))
  11977. (goto-char (car range))
  11978. (let ((begin (car range))
  11979. (end (cdr range)))
  11980. ;; Make sure that found property block is not located
  11981. ;; before current point, as it would generate an infloop.
  11982. ;; It can happen, for example, in the following
  11983. ;; situation:
  11984. ;;
  11985. ;; * Headline
  11986. ;; :PROPERTIES:
  11987. ;; ...
  11988. ;; :END:
  11989. ;; *************** Inlinetask
  11990. ;; #+BEGIN_EXAMPLE
  11991. ;; :PROPERTIES:
  11992. ;; #+END_EXAMPLE
  11993. ;;
  11994. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11995. (while (< (point) end)
  11996. (let ((p (progn (looking-at org-property-re)
  11997. (match-string-no-properties 2))))
  11998. ;; Only add true property name, not extension symbol.
  11999. (push (if (not (string-match-p "\\+\\'" p)) p
  12000. (substring p 0 -1))
  12001. props))
  12002. (forward-line))))
  12003. (outline-next-heading)))
  12004. (when columns
  12005. (goto-char (point-min))
  12006. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12007. (let ((element (org-element-at-point)))
  12008. (when (memq (org-element-type element) '(keyword node-property))
  12009. (let ((value (org-element-property :value element))
  12010. (start 0))
  12011. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12012. \\(?:{[^}]+}\\)?"
  12013. value start)
  12014. (setq start (match-end 0))
  12015. (let ((p (match-string-no-properties 1 value)))
  12016. (unless (member-ignore-case p org-special-properties)
  12017. (push p props))))))))))
  12018. (sort (delete-dups
  12019. (append props
  12020. ;; for each xxx_ALL property, make sure the bare
  12021. ;; xxx property is also included
  12022. (delq nil (mapcar (lambda (p)
  12023. (and (string-match-p "._ALL\\'" p)
  12024. (substring p 0 -4)))
  12025. props))))
  12026. (lambda (a b) (string< (upcase a) (upcase b))))))
  12027. (defun org-property-values (key)
  12028. "List all non-nil values of property KEY in current buffer."
  12029. (org-with-wide-buffer
  12030. (goto-char (point-min))
  12031. (let ((case-fold-search t)
  12032. (re (org-re-property key))
  12033. values)
  12034. (while (re-search-forward re nil t)
  12035. (push (org-entry-get (point) key) values))
  12036. (delete-dups values))))
  12037. (defun org-insert-property-drawer ()
  12038. "Insert a property drawer into the current entry.
  12039. Do nothing if the drawer already exists. The newly created
  12040. drawer is immediately hidden."
  12041. (org-with-wide-buffer
  12042. ;; Set point to the position where the drawer should be inserted.
  12043. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12044. (org-back-to-heading-or-point-min t)
  12045. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12046. (if (org-before-first-heading-p)
  12047. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12048. (progn
  12049. (forward-line)
  12050. (when (looking-at-p org-planning-line-re) (forward-line))))
  12051. (unless (looking-at-p org-property-drawer-re)
  12052. ;; Make sure we start editing a line from current entry, not from
  12053. ;; next one. It prevents extending text properties or overlays
  12054. ;; belonging to the latter.
  12055. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12056. (let ((begin (if (bobp) (point) (1+ (point))))
  12057. (inhibit-read-only t))
  12058. (unless (bobp) (insert "\n"))
  12059. (insert ":PROPERTIES:\n:END:")
  12060. (org-flag-region (line-end-position 0) (point) t 'outline)
  12061. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12062. (org-indent-region begin (point))))))
  12063. (defun org-insert-drawer (&optional arg drawer)
  12064. "Insert a drawer at point.
  12065. When optional argument ARG is non-nil, insert a property drawer.
  12066. Optional argument DRAWER, when non-nil, is a string representing
  12067. drawer's name. Otherwise, the user is prompted for a name.
  12068. If a region is active, insert the drawer around that region
  12069. instead.
  12070. Point is left between drawer's boundaries."
  12071. (interactive "P")
  12072. (let* ((drawer (if arg "PROPERTIES"
  12073. (or drawer (read-from-minibuffer "Drawer: ")))))
  12074. (cond
  12075. ;; With C-u, fall back on `org-insert-property-drawer'
  12076. (arg (org-insert-property-drawer))
  12077. ;; Check validity of suggested drawer's name.
  12078. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12079. (user-error "Invalid drawer name"))
  12080. ;; With an active region, insert a drawer at point.
  12081. ((not (org-region-active-p))
  12082. (progn
  12083. (unless (bolp) (insert "\n"))
  12084. (insert (format ":%s:\n\n:END:\n" drawer))
  12085. (forward-line -2)))
  12086. ;; Otherwise, insert the drawer at point
  12087. (t
  12088. (let ((rbeg (region-beginning))
  12089. (rend (copy-marker (region-end))))
  12090. (unwind-protect
  12091. (progn
  12092. (goto-char rbeg)
  12093. (beginning-of-line)
  12094. (when (save-excursion
  12095. (re-search-forward org-outline-regexp-bol rend t))
  12096. (user-error "Drawers cannot contain headlines"))
  12097. ;; Position point at the beginning of the first
  12098. ;; non-blank line in region. Insert drawer's opening
  12099. ;; there, then indent it.
  12100. (org-skip-whitespace)
  12101. (beginning-of-line)
  12102. (insert ":" drawer ":\n")
  12103. (forward-line -1)
  12104. (indent-for-tab-command)
  12105. ;; Move point to the beginning of the first blank line
  12106. ;; after the last non-blank line in region. Insert
  12107. ;; drawer's closing, then indent it.
  12108. (goto-char rend)
  12109. (skip-chars-backward " \r\t\n")
  12110. (insert "\n:END:")
  12111. (deactivate-mark t)
  12112. (indent-for-tab-command)
  12113. (unless (eolp) (insert "\n")))
  12114. ;; Clear marker, whatever the outcome of insertion is.
  12115. (set-marker rend nil)))))))
  12116. (defvar org-property-set-functions-alist nil
  12117. "Property set function alist.
  12118. Each entry should have the following format:
  12119. (PROPERTY . READ-FUNCTION)
  12120. The read function will be called with the same argument as
  12121. `org-completing-read'.")
  12122. (defun org-set-property-function (property)
  12123. "Get the function that should be used to set PROPERTY.
  12124. This is computed according to `org-property-set-functions-alist'."
  12125. (or (cdr (assoc property org-property-set-functions-alist))
  12126. 'org-completing-read))
  12127. (defun org-read-property-value (property &optional pom default)
  12128. "Read value for PROPERTY, as a string.
  12129. When optional argument POM is non-nil, completion uses additional
  12130. information, i.e., allowed or existing values at point or marker
  12131. POM.
  12132. Optional argument DEFAULT provides a default value for PROPERTY."
  12133. (let* ((completion-ignore-case t)
  12134. (allowed
  12135. (or (org-property-get-allowed-values nil property 'table)
  12136. (and pom (org-property-get-allowed-values pom property 'table))))
  12137. (current (org-entry-get nil property))
  12138. (prompt (format "%s value%s: "
  12139. property
  12140. (if (org-string-nw-p current)
  12141. (format " [%s]" current)
  12142. "")))
  12143. (set-function (org-set-property-function property)))
  12144. (org-trim
  12145. (if allowed
  12146. (funcall set-function
  12147. prompt allowed nil
  12148. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12149. default nil default)
  12150. (let ((all (mapcar #'list
  12151. (append (org-property-values property)
  12152. (and pom
  12153. (org-with-point-at pom
  12154. (org-property-values property)))))))
  12155. (funcall set-function prompt all nil nil "" nil current))))))
  12156. (defvar org-last-set-property nil)
  12157. (defvar org-last-set-property-value nil)
  12158. (defun org-read-property-name ()
  12159. "Read a property name."
  12160. (let ((completion-ignore-case t)
  12161. (default-prop (or (and (org-at-property-p)
  12162. (match-string-no-properties 2))
  12163. org-last-set-property)))
  12164. (org-completing-read
  12165. (concat "Property"
  12166. (if default-prop (concat " [" default-prop "]") "")
  12167. ": ")
  12168. (mapcar #'list (org-buffer-property-keys nil t t))
  12169. nil nil nil nil default-prop)))
  12170. (defun org-set-property-and-value (use-last)
  12171. "Allow to set [PROPERTY]: [value] direction from prompt.
  12172. When use-default, don't even ask, just use the last
  12173. \"[PROPERTY]: [value]\" string from the history."
  12174. (interactive "P")
  12175. (let* ((completion-ignore-case t)
  12176. (pv (or (and use-last org-last-set-property-value)
  12177. (org-completing-read
  12178. "Enter a \"[Property]: [value]\" pair: "
  12179. nil nil nil nil nil
  12180. org-last-set-property-value)))
  12181. prop val)
  12182. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12183. (setq prop (match-string 1 pv)
  12184. val (match-string 2 pv))
  12185. (org-set-property prop val))))
  12186. (defun org-set-property (property value)
  12187. "In the current entry, set PROPERTY to VALUE.
  12188. When called interactively, this will prompt for a property name, offering
  12189. completion on existing and default properties. And then it will prompt
  12190. for a value, offering completion either on allowed values (via an inherited
  12191. xxx_ALL property) or on existing values in other instances of this property
  12192. in the current file.
  12193. Throw an error when trying to set a property with an invalid name."
  12194. (interactive (list nil nil))
  12195. (let ((property (or property (org-read-property-name))))
  12196. ;; `org-entry-put' also makes the following check, but this one
  12197. ;; avoids polluting `org-last-set-property' and
  12198. ;; `org-last-set-property-value' needlessly.
  12199. (unless (org--valid-property-p property)
  12200. (user-error "Invalid property name: \"%s\"" property))
  12201. (let ((value (or value (org-read-property-value property)))
  12202. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12203. (setq org-last-set-property property)
  12204. (setq org-last-set-property-value (concat property ": " value))
  12205. ;; Possibly postprocess the inserted value:
  12206. (when fn (setq value (funcall fn value)))
  12207. (unless (equal (org-entry-get nil property) value)
  12208. (org-entry-put nil property value)))))
  12209. (defun org-find-property (property &optional value)
  12210. "Find first entry in buffer that sets PROPERTY.
  12211. When optional argument VALUE is non-nil, only consider an entry
  12212. if it contains PROPERTY set to this value. If PROPERTY should be
  12213. explicitly set to nil, use string \"nil\" for VALUE.
  12214. Return position where the entry begins, or nil if there is no
  12215. such entry. If narrowing is in effect, only search the visible
  12216. part of the buffer."
  12217. (save-excursion
  12218. (goto-char (point-min))
  12219. (let ((case-fold-search t)
  12220. (re (org-re-property property nil (not value) value)))
  12221. (catch 'exit
  12222. (while (re-search-forward re nil t)
  12223. (when (if value (org-at-property-p)
  12224. (org-entry-get (point) property nil t))
  12225. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12226. (point)))))))))
  12227. (defun org-delete-property (property)
  12228. "In the current entry, delete PROPERTY."
  12229. (interactive
  12230. (let* ((completion-ignore-case t)
  12231. (cat (org-entry-get (point) "CATEGORY"))
  12232. (props0 (org-entry-properties nil 'standard))
  12233. (props (if cat props0
  12234. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12235. (prop (if (< 1 (length props))
  12236. (completing-read "Property: " props nil t)
  12237. (caar props))))
  12238. (list prop)))
  12239. (if (not property)
  12240. (message "No property to delete in this entry")
  12241. (org-entry-delete nil property)
  12242. (message "Property \"%s\" deleted" property)))
  12243. (defun org-delete-property-globally (property)
  12244. "Remove PROPERTY globally, from all entries.
  12245. This function ignores narrowing, if any."
  12246. (interactive
  12247. (let* ((completion-ignore-case t)
  12248. (prop (completing-read
  12249. "Globally remove property: "
  12250. (mapcar #'list (org-buffer-property-keys)))))
  12251. (list prop)))
  12252. (org-with-wide-buffer
  12253. (goto-char (point-min))
  12254. (let ((count 0)
  12255. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12256. (while (re-search-forward re nil t)
  12257. (when (org-entry-delete (point) property) (cl-incf count)))
  12258. (message "Property \"%s\" removed from %d entries" property count))))
  12259. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12260. (defun org-compute-property-at-point ()
  12261. "Compute the property at point.
  12262. This looks for an enclosing column format, extracts the operator and
  12263. then applies it to the property in the column format's scope."
  12264. (interactive)
  12265. (unless (org-at-property-p)
  12266. (user-error "Not at a property"))
  12267. (let ((prop (match-string-no-properties 2)))
  12268. (org-columns-get-format-and-top-level)
  12269. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12270. (user-error "No operator defined for property %s" prop))
  12271. (org-columns-compute prop)))
  12272. (defvar org-property-allowed-value-functions nil
  12273. "Hook for functions supplying allowed values for a specific property.
  12274. The functions must take a single argument, the name of the property, and
  12275. return a flat list of allowed values. If \":ETC\" is one of
  12276. the values, this means that these values are intended as defaults for
  12277. completion, but that other values should be allowed too.
  12278. The functions must return nil if they are not responsible for this
  12279. property.")
  12280. (defun org-property-get-allowed-values (pom property &optional table)
  12281. "Get allowed values for the property PROPERTY.
  12282. When TABLE is non-nil, return an alist that can directly be used for
  12283. completion."
  12284. (let (vals)
  12285. (cond
  12286. ((equal property "TODO")
  12287. (setq vals (org-with-point-at pom
  12288. (append org-todo-keywords-1 '("")))))
  12289. ((equal property "PRIORITY")
  12290. (let ((n org-priority-lowest))
  12291. (while (>= n org-priority-highest)
  12292. (push (char-to-string n) vals)
  12293. (setq n (1- n)))))
  12294. ((equal property "CATEGORY"))
  12295. ((member property org-special-properties))
  12296. ((setq vals (run-hook-with-args-until-success
  12297. 'org-property-allowed-value-functions property)))
  12298. (t
  12299. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12300. (when (and vals (string-match "\\S-" vals))
  12301. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12302. (setq vals (mapcar (lambda (x)
  12303. (cond ((stringp x) x)
  12304. ((numberp x) (number-to-string x))
  12305. ((symbolp x) (symbol-name x))
  12306. (t "???")))
  12307. vals)))))
  12308. (when (member ":ETC" vals)
  12309. (setq vals (remove ":ETC" vals))
  12310. (org-add-props (car vals) '(org-unrestricted t)))
  12311. (if table (mapcar 'list vals) vals)))
  12312. (defun org-property-previous-allowed-value (&optional _previous)
  12313. "Switch to the next allowed value for this property."
  12314. (interactive)
  12315. (org-property-next-allowed-value t))
  12316. (defun org-property-next-allowed-value (&optional previous)
  12317. "Switch to the next allowed value for this property."
  12318. (interactive)
  12319. (unless (org-at-property-p)
  12320. (user-error "Not at a property"))
  12321. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12322. (key (match-string 2))
  12323. (value (match-string 3))
  12324. (allowed (or (org-property-get-allowed-values (point) key)
  12325. (and (member value '("[ ]" "[-]" "[X]"))
  12326. '("[ ]" "[X]"))))
  12327. (heading (save-match-data (nth 4 (org-heading-components))))
  12328. nval)
  12329. (unless allowed
  12330. (user-error "Allowed values for this property have not been defined"))
  12331. (when previous (setq allowed (reverse allowed)))
  12332. (when (member value allowed)
  12333. (setq nval (car (cdr (member value allowed)))))
  12334. (setq nval (or nval (car allowed)))
  12335. (when (equal nval value)
  12336. (user-error "Only one allowed value for this property"))
  12337. (org-at-property-p)
  12338. (replace-match (concat " :" key ": " nval) t t)
  12339. (org-indent-line)
  12340. (beginning-of-line 1)
  12341. (skip-chars-forward " \t")
  12342. (when (equal prop org-effort-property)
  12343. (org-refresh-property
  12344. '((effort . identity)
  12345. (effort-minutes . org-duration-to-minutes))
  12346. nval)
  12347. (when (string= org-clock-current-task heading)
  12348. (setq org-clock-effort nval)
  12349. (org-clock-update-mode-line)))
  12350. (run-hook-with-args 'org-property-changed-functions key nval)))
  12351. (defun org-find-olp (path &optional this-buffer)
  12352. "Return a marker pointing to the entry at outline path OLP.
  12353. If anything goes wrong, throw an error, and if you need to do
  12354. something based on this error, you can catch it with
  12355. `condition-case'.
  12356. If THIS-BUFFER is set, the outline path does not contain a file,
  12357. only headings."
  12358. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12359. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12360. (level 1)
  12361. (lmin 1)
  12362. (lmax 1)
  12363. end found flevel)
  12364. (unless buffer (error "File not found :%s" file))
  12365. (with-current-buffer buffer
  12366. (unless (derived-mode-p 'org-mode)
  12367. (error "Buffer %s needs to be in Org mode" buffer))
  12368. (org-with-wide-buffer
  12369. (goto-char (point-min))
  12370. (dolist (heading path)
  12371. (let ((re (format org-complex-heading-regexp-format
  12372. (regexp-quote heading)))
  12373. (cnt 0))
  12374. (while (re-search-forward re end t)
  12375. (setq level (- (match-end 1) (match-beginning 1)))
  12376. (when (and (>= level lmin) (<= level lmax))
  12377. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12378. (when (= cnt 0)
  12379. (error "Heading not found on level %d: %s" lmax heading))
  12380. (when (> cnt 1)
  12381. (error "Heading not unique on level %d: %s" lmax heading))
  12382. (goto-char found)
  12383. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12384. (setq end (save-excursion (org-end-of-subtree t t)))))
  12385. (when (org-at-heading-p)
  12386. (point-marker))))))
  12387. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12388. "Find node HEADING in BUFFER.
  12389. Return a marker to the heading if it was found, or nil if not.
  12390. If POS-ONLY is set, return just the position instead of a marker.
  12391. The heading text must match exact, but it may have a TODO keyword,
  12392. a priority cookie and tags in the standard locations."
  12393. (with-current-buffer (or buffer (current-buffer))
  12394. (org-with-wide-buffer
  12395. (goto-char (point-min))
  12396. (let (case-fold-search)
  12397. (when (re-search-forward
  12398. (format org-complex-heading-regexp-format
  12399. (regexp-quote heading)) nil t)
  12400. (if pos-only
  12401. (match-beginning 0)
  12402. (move-marker (make-marker) (match-beginning 0))))))))
  12403. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12404. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12405. When the target headline is found, return a marker to this location."
  12406. (let ((files (directory-files (or dir default-directory)
  12407. t "\\`[^.#].*\\.org\\'"))
  12408. visiting m buffer)
  12409. (catch 'found
  12410. (dolist (file files)
  12411. (message "trying %s" file)
  12412. (setq visiting (org-find-base-buffer-visiting file))
  12413. (setq buffer (or visiting (find-file-noselect file)))
  12414. (setq m (org-find-exact-headline-in-buffer
  12415. heading buffer))
  12416. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12417. (and m (throw 'found m))))))
  12418. (defun org-find-entry-with-id (ident)
  12419. "Locate the entry that contains the ID property with exact value IDENT.
  12420. IDENT can be a string, a symbol or a number, this function will search for
  12421. the string representation of it.
  12422. Return the position where this entry starts, or nil if there is no such entry."
  12423. (interactive "sID: ")
  12424. (let ((id (cond
  12425. ((stringp ident) ident)
  12426. ((symbolp ident) (symbol-name ident))
  12427. ((numberp ident) (number-to-string ident))
  12428. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12429. (org-with-wide-buffer (org-find-property "ID" id))))
  12430. ;;;; Timestamps
  12431. (defvar org-last-changed-timestamp nil)
  12432. (defvar org-last-inserted-timestamp nil
  12433. "The last time stamp inserted with `org-insert-time-stamp'.")
  12434. (defun org-time-stamp (arg &optional inactive)
  12435. "Prompt for a date/time and insert a time stamp.
  12436. If the user specifies a time like HH:MM or if this command is
  12437. called with at least one prefix argument, the time stamp contains
  12438. the date and the time. Otherwise, only the date is included.
  12439. All parts of a date not specified by the user are filled in from
  12440. the timestamp at point, if any, or the current date/time
  12441. otherwise.
  12442. If there is already a timestamp at the cursor, it is replaced.
  12443. With two universal prefix arguments, insert an active timestamp
  12444. with the current time without prompting the user.
  12445. When called from lisp, the timestamp is inactive if INACTIVE is
  12446. non-nil."
  12447. (interactive "P")
  12448. (let* ((ts (cond
  12449. ((org-at-date-range-p t)
  12450. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12451. ((org-at-timestamp-p 'lax) (match-string 0))))
  12452. ;; Default time is either the timestamp at point or today.
  12453. ;; When entering a range, only the range start is considered.
  12454. (default-time (and ts (org-time-string-to-time ts)))
  12455. (default-input (and ts (org-get-compact-tod ts)))
  12456. (repeater (and ts
  12457. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12458. (match-string 0 ts)))
  12459. org-time-was-given
  12460. org-end-time-was-given
  12461. (time
  12462. (if (equal arg '(16)) (current-time)
  12463. ;; Preserve `this-command' and `last-command'.
  12464. (let ((this-command this-command)
  12465. (last-command last-command))
  12466. (org-read-date
  12467. arg 'totime nil nil default-time default-input
  12468. inactive)))))
  12469. (cond
  12470. ((and ts
  12471. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12472. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12473. (insert "--")
  12474. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12475. (ts
  12476. ;; Make sure we're on a timestamp. When in the middle of a date
  12477. ;; range, move arbitrarily to range end.
  12478. (unless (org-at-timestamp-p 'lax)
  12479. (skip-chars-forward "-")
  12480. (org-at-timestamp-p 'lax))
  12481. (replace-match "")
  12482. (setq org-last-changed-timestamp
  12483. (org-insert-time-stamp
  12484. time (or org-time-was-given arg)
  12485. inactive nil nil (list org-end-time-was-given)))
  12486. (when repeater
  12487. (backward-char)
  12488. (insert " " repeater)
  12489. (setq org-last-changed-timestamp
  12490. (concat (substring org-last-inserted-timestamp 0 -1)
  12491. " " repeater ">")))
  12492. (message "Timestamp updated"))
  12493. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12494. (t (org-insert-time-stamp
  12495. time (or org-time-was-given arg) inactive nil nil
  12496. (list org-end-time-was-given))))))
  12497. ;; FIXME: can we use this for something else, like computing time differences?
  12498. (defun org-get-compact-tod (s)
  12499. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12500. (let* ((t1 (match-string 1 s))
  12501. (h1 (string-to-number (match-string 2 s)))
  12502. (m1 (string-to-number (match-string 3 s)))
  12503. (t2 (and (match-end 4) (match-string 5 s)))
  12504. (h2 (and t2 (string-to-number (match-string 6 s))))
  12505. (m2 (and t2 (string-to-number (match-string 7 s))))
  12506. dh dm)
  12507. (if (not t2)
  12508. t1
  12509. (setq dh (- h2 h1) dm (- m2 m1))
  12510. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12511. (concat t1 "+" (number-to-string dh)
  12512. (and (/= 0 dm) (format ":%02d" dm)))))))
  12513. (defun org-time-stamp-inactive (&optional arg)
  12514. "Insert an inactive time stamp.
  12515. An inactive time stamp is enclosed in square brackets instead of
  12516. angle brackets. It is inactive in the sense that it does not
  12517. trigger agenda entries. So these are more for recording a
  12518. certain time/date.
  12519. If the user specifies a time like HH:MM or if this command is called with
  12520. at least one prefix argument, the time stamp contains the date and the time.
  12521. Otherwise, only the date is included.
  12522. When called with two universal prefix arguments, insert an inactive time stamp
  12523. with the current time without prompting the user."
  12524. (interactive "P")
  12525. (org-time-stamp arg 'inactive))
  12526. (defvar org-date-ovl (make-overlay 1 1))
  12527. (overlay-put org-date-ovl 'face 'org-date-selected)
  12528. (delete-overlay org-date-ovl)
  12529. (defvar org-ans1) ; dynamically scoped parameter
  12530. (defvar org-ans2) ; dynamically scoped parameter
  12531. (defvar org-plain-time-of-day-regexp) ; defined below
  12532. (defvar org-overriding-default-time nil) ; dynamically scoped
  12533. (defvar org-read-date-overlay nil)
  12534. (defvar org-read-date-history nil)
  12535. (defvar org-read-date-final-answer nil)
  12536. (defvar org-read-date-analyze-futurep nil)
  12537. (defvar org-read-date-analyze-forced-year nil)
  12538. (defvar org-read-date-inactive)
  12539. (defvar org-def)
  12540. (defvar org-defdecode)
  12541. (defvar org-with-time)
  12542. (defvar calendar-setup) ; Dynamically scoped.
  12543. (defun org-read-date (&optional with-time to-time from-string prompt
  12544. default-time default-input inactive)
  12545. "Read a date, possibly a time, and make things smooth for the user.
  12546. The prompt will suggest to enter an ISO date, but you can also enter anything
  12547. which will at least partially be understood by `parse-time-string'.
  12548. Unrecognized parts of the date will default to the current day, month, year,
  12549. hour and minute. If this command is called to replace a timestamp at point,
  12550. or to enter the second timestamp of a range, the default time is taken
  12551. from the existing stamp. Furthermore, the command prefers the future,
  12552. so if you are giving a date where the year is not given, and the day-month
  12553. combination is already past in the current year, it will assume you
  12554. mean next year. For details, see the manual. A few examples:
  12555. 3-2-5 --> 2003-02-05
  12556. feb 15 --> currentyear-02-15
  12557. 2/15 --> currentyear-02-15
  12558. sep 12 9 --> 2009-09-12
  12559. 12:45 --> today 12:45
  12560. 22 sept 0:34 --> currentyear-09-22 0:34
  12561. 12 --> currentyear-currentmonth-12
  12562. Fri --> nearest Friday after today
  12563. -Tue --> last Tuesday
  12564. etc.
  12565. Furthermore you can specify a relative date by giving, as the *first* thing
  12566. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12567. change in days weeks, months, years.
  12568. With a single plus or minus, the date is relative to today. With a double
  12569. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12570. +4d --> four days from today
  12571. +4 --> same as above
  12572. +2w --> two weeks from today
  12573. ++5 --> five days from default date
  12574. The function understands only English month and weekday abbreviations.
  12575. While prompting, a calendar is popped up - you can also select the
  12576. date with the mouse (button 1). The calendar shows a period of three
  12577. months. To scroll it to other months, use the keys `>' and `<'.
  12578. If you don't like the calendar, turn it off with
  12579. (setq org-read-date-popup-calendar nil)
  12580. With optional argument TO-TIME, the date will immediately be converted
  12581. to an internal time.
  12582. With an optional argument WITH-TIME, the prompt will suggest to
  12583. also insert a time. Note that when WITH-TIME is not set, you can
  12584. still enter a time, and this function will inform the calling routine
  12585. about this change. The calling routine may then choose to change the
  12586. format used to insert the time stamp into the buffer to include the time.
  12587. With optional argument FROM-STRING, read from this string instead from
  12588. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12589. the time/date that is used for everything that is not specified by the
  12590. user."
  12591. (require 'parse-time)
  12592. (let* ((org-with-time with-time)
  12593. (org-time-stamp-rounding-minutes
  12594. (if (equal org-with-time '(16))
  12595. '(0 0)
  12596. org-time-stamp-rounding-minutes))
  12597. (ct (org-current-time))
  12598. (org-def (or org-overriding-default-time default-time ct))
  12599. (org-defdecode (decode-time org-def))
  12600. (cur-frame (selected-frame))
  12601. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12602. (calendar-setup
  12603. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12604. (calendar-move-hook nil)
  12605. (calendar-view-diary-initially-flag nil)
  12606. (calendar-view-holidays-initially-flag nil)
  12607. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12608. ;; Rationalize `org-def' and `org-defdecode', if required.
  12609. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12610. (setf (nth 2 org-defdecode) -1)
  12611. (setf (nth 1 org-defdecode) 59)
  12612. (setq org-def (apply #'encode-time org-defdecode))
  12613. (setq org-defdecode (decode-time org-def)))
  12614. (let* ((timestr (format-time-string
  12615. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12616. org-def))
  12617. (prompt (concat (if prompt (concat prompt " ") "")
  12618. (format "Date+time [%s]: " timestr))))
  12619. (cond
  12620. (from-string (setq ans from-string))
  12621. (org-read-date-popup-calendar
  12622. (save-excursion
  12623. (save-window-excursion
  12624. (calendar)
  12625. (when (eq calendar-setup 'calendar-only)
  12626. (setq cal-frame
  12627. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12628. (select-frame cal-frame))
  12629. (org-eval-in-calendar '(setq cursor-type nil) t)
  12630. (unwind-protect
  12631. (progn
  12632. (calendar-forward-day (- (time-to-days org-def)
  12633. (calendar-absolute-from-gregorian
  12634. (calendar-current-date))))
  12635. (org-eval-in-calendar nil t)
  12636. (let* ((old-map (current-local-map))
  12637. (map (copy-keymap calendar-mode-map))
  12638. (minibuffer-local-map
  12639. (copy-keymap org-read-date-minibuffer-local-map)))
  12640. (org-defkey map (kbd "RET") 'org-calendar-select)
  12641. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12642. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12643. (unwind-protect
  12644. (progn
  12645. (use-local-map map)
  12646. (setq org-read-date-inactive inactive)
  12647. (add-hook 'post-command-hook 'org-read-date-display)
  12648. (setq org-ans0
  12649. (read-string prompt
  12650. default-input
  12651. 'org-read-date-history
  12652. nil))
  12653. ;; org-ans0: from prompt
  12654. ;; org-ans1: from mouse click
  12655. ;; org-ans2: from calendar motion
  12656. (setq ans
  12657. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12658. (remove-hook 'post-command-hook 'org-read-date-display)
  12659. (use-local-map old-map)
  12660. (when org-read-date-overlay
  12661. (delete-overlay org-read-date-overlay)
  12662. (setq org-read-date-overlay nil)))))
  12663. (bury-buffer "*Calendar*")
  12664. (when cal-frame
  12665. (delete-frame cal-frame)
  12666. (select-frame-set-input-focus cur-frame))))))
  12667. (t ; Naked prompt only
  12668. (unwind-protect
  12669. (setq ans (read-string prompt default-input
  12670. 'org-read-date-history timestr))
  12671. (when org-read-date-overlay
  12672. (delete-overlay org-read-date-overlay)
  12673. (setq org-read-date-overlay nil))))))
  12674. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12675. (when org-read-date-analyze-forced-year
  12676. (message "Year was forced into %s"
  12677. (if org-read-date-force-compatible-dates
  12678. "compatible range (1970-2037)"
  12679. "range representable on this machine"))
  12680. (ding))
  12681. (setq final (apply #'encode-time final))
  12682. (setq org-read-date-final-answer ans)
  12683. (if to-time
  12684. final
  12685. ;; This round-trip gets rid of 34th of August and stuff like that....
  12686. (setq final (decode-time final))
  12687. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12688. (format "%04d-%02d-%02d %02d:%02d"
  12689. (nth 5 final) (nth 4 final) (nth 3 final)
  12690. (nth 2 final) (nth 1 final))
  12691. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12692. (defun org-read-date-display ()
  12693. "Display the current date prompt interpretation in the minibuffer."
  12694. (when org-read-date-display-live
  12695. (when org-read-date-overlay
  12696. (delete-overlay org-read-date-overlay))
  12697. (when (minibufferp (current-buffer))
  12698. (save-excursion
  12699. (end-of-line 1)
  12700. (while (not (equal (buffer-substring
  12701. (max (point-min) (- (point) 4)) (point))
  12702. " "))
  12703. (insert " ")))
  12704. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12705. " " (or org-ans1 org-ans2)))
  12706. (org-end-time-was-given nil)
  12707. (f (org-read-date-analyze ans org-def org-defdecode))
  12708. (fmts (if org-display-custom-times
  12709. org-time-stamp-custom-formats
  12710. org-time-stamp-formats))
  12711. (fmt (if (or org-with-time
  12712. (and (boundp 'org-time-was-given) org-time-was-given))
  12713. (cdr fmts)
  12714. (car fmts)))
  12715. (txt (format-time-string fmt (apply #'encode-time f)))
  12716. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12717. (txt (concat "=> " txt)))
  12718. (when (and org-end-time-was-given
  12719. (string-match org-plain-time-of-day-regexp txt))
  12720. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12721. org-end-time-was-given
  12722. (substring txt (match-end 0)))))
  12723. (when org-read-date-analyze-futurep
  12724. (setq txt (concat txt " (=>F)")))
  12725. (setq org-read-date-overlay
  12726. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12727. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12728. (defun org-read-date-analyze (ans def defdecode)
  12729. "Analyze the combined answer of the date prompt."
  12730. ;; FIXME: cleanup and comment
  12731. (let ((org-def def)
  12732. (org-defdecode defdecode)
  12733. (nowdecode (decode-time))
  12734. delta deltan deltaw deltadef year month day
  12735. hour minute second wday pm h2 m2 tl wday1
  12736. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12737. (setq org-read-date-analyze-futurep nil
  12738. org-read-date-analyze-forced-year nil)
  12739. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12740. (setq ans "+0"))
  12741. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12742. (setq ans (replace-match "" t t ans)
  12743. deltan (car delta)
  12744. deltaw (nth 1 delta)
  12745. deltadef (nth 2 delta)))
  12746. ;; Check if there is an iso week date in there. If yes, store the
  12747. ;; info and postpone interpreting it until the rest of the parsing
  12748. ;; is done.
  12749. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12750. (setq iso-year (when (match-end 1)
  12751. (org-small-year-to-year
  12752. (string-to-number (match-string 1 ans))))
  12753. iso-weekday (when (match-end 3)
  12754. (string-to-number (match-string 3 ans)))
  12755. iso-week (string-to-number (match-string 2 ans)))
  12756. (setq ans (replace-match "" t t ans)))
  12757. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12758. (when (string-match
  12759. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12760. (setq year (if (match-end 2)
  12761. (string-to-number (match-string 2 ans))
  12762. (progn (setq kill-year t)
  12763. (string-to-number (format-time-string "%Y"))))
  12764. month (string-to-number (match-string 3 ans))
  12765. day (string-to-number (match-string 4 ans)))
  12766. (setq year (org-small-year-to-year year))
  12767. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12768. t nil ans)))
  12769. ;; Help matching dotted european dates
  12770. (when (string-match
  12771. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12772. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12773. (setq kill-year t)
  12774. (string-to-number (format-time-string "%Y")))
  12775. day (string-to-number (match-string 1 ans))
  12776. month (string-to-number (match-string 2 ans))
  12777. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12778. t nil ans)))
  12779. ;; Help matching american dates, like 5/30 or 5/30/7
  12780. (when (string-match
  12781. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12782. (setq year (if (match-end 4)
  12783. (string-to-number (match-string 4 ans))
  12784. (progn (setq kill-year t)
  12785. (string-to-number (format-time-string "%Y"))))
  12786. month (string-to-number (match-string 1 ans))
  12787. day (string-to-number (match-string 2 ans)))
  12788. (setq year (org-small-year-to-year year))
  12789. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12790. t nil ans)))
  12791. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12792. ;; If there is a time with am/pm, and *no* time without it, we convert
  12793. ;; so that matching will be successful.
  12794. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12795. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12796. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12797. (setq hour (string-to-number (match-string 1 ans))
  12798. minute (if (match-end 3)
  12799. (string-to-number (match-string 3 ans))
  12800. 0)
  12801. pm (equal ?p
  12802. (string-to-char (downcase (match-string 4 ans)))))
  12803. (if (and (= hour 12) (not pm))
  12804. (setq hour 0)
  12805. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12806. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12807. t t ans))))
  12808. ;; Check if a time range is given as a duration
  12809. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12810. (setq hour (string-to-number (match-string 1 ans))
  12811. h2 (+ hour (string-to-number (match-string 3 ans)))
  12812. minute (string-to-number (match-string 2 ans))
  12813. m2 (+ minute (if (match-end 5) (string-to-number
  12814. (match-string 5 ans))0)))
  12815. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12816. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12817. t t ans)))
  12818. ;; Check if there is a time range
  12819. (when (boundp 'org-end-time-was-given)
  12820. (setq org-time-was-given nil)
  12821. (when (and (string-match org-plain-time-of-day-regexp ans)
  12822. (match-end 8))
  12823. (setq org-end-time-was-given (match-string 8 ans))
  12824. (setq ans (concat (substring ans 0 (match-beginning 7))
  12825. (substring ans (match-end 7))))))
  12826. (setq tl (parse-time-string ans)
  12827. day (or (nth 3 tl) (nth 3 org-defdecode))
  12828. month
  12829. (cond ((nth 4 tl))
  12830. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12831. ;; Day was specified. Make sure DAY+MONTH
  12832. ;; combination happens in the future.
  12833. ((nth 3 tl)
  12834. (setq futurep t)
  12835. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12836. (nth 4 nowdecode)))
  12837. (t (nth 4 org-defdecode)))
  12838. year
  12839. (cond ((and (not kill-year) (nth 5 tl)))
  12840. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12841. ;; Month was guessed in the future and is at least
  12842. ;; equal to NOWDECODE's. Fix year accordingly.
  12843. (futurep
  12844. (if (or (> month (nth 4 nowdecode))
  12845. (>= day (nth 3 nowdecode)))
  12846. (nth 5 nowdecode)
  12847. (1+ (nth 5 nowdecode))))
  12848. ;; Month was specified. Make sure MONTH+YEAR
  12849. ;; combination happens in the future.
  12850. ((nth 4 tl)
  12851. (setq futurep t)
  12852. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12853. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12854. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12855. (t (nth 5 nowdecode))))
  12856. (t (nth 5 org-defdecode)))
  12857. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12858. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12859. second (or (nth 0 tl) 0)
  12860. wday (nth 6 tl))
  12861. (when (and (eq org-read-date-prefer-future 'time)
  12862. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12863. (equal day (nth 3 nowdecode))
  12864. (equal month (nth 4 nowdecode))
  12865. (equal year (nth 5 nowdecode))
  12866. (nth 2 tl)
  12867. (or (< (nth 2 tl) (nth 2 nowdecode))
  12868. (and (= (nth 2 tl) (nth 2 nowdecode))
  12869. (nth 1 tl)
  12870. (< (nth 1 tl) (nth 1 nowdecode)))))
  12871. (setq day (1+ day)
  12872. futurep t))
  12873. ;; Special date definitions below
  12874. (cond
  12875. (iso-week
  12876. ;; There was an iso week
  12877. (require 'cal-iso)
  12878. (setq futurep nil)
  12879. (setq year (or iso-year year)
  12880. day (or iso-weekday wday 1)
  12881. wday nil ; to make sure that the trigger below does not match
  12882. iso-date (calendar-gregorian-from-absolute
  12883. (calendar-iso-to-absolute
  12884. (list iso-week day year))))
  12885. ; FIXME: Should we also push ISO weeks into the future?
  12886. ; (when (and org-read-date-prefer-future
  12887. ; (not iso-year)
  12888. ; (< (calendar-absolute-from-gregorian iso-date)
  12889. ; (time-to-days nil)))
  12890. ; (setq year (1+ year)
  12891. ; iso-date (calendar-gregorian-from-absolute
  12892. ; (calendar-iso-to-absolute
  12893. ; (list iso-week day year)))))
  12894. (setq month (car iso-date)
  12895. year (nth 2 iso-date)
  12896. day (nth 1 iso-date)))
  12897. (deltan
  12898. (setq futurep nil)
  12899. (unless deltadef
  12900. (let ((now (decode-time)))
  12901. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12902. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12903. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12904. ((equal deltaw "m") (setq month (+ month deltan)))
  12905. ((equal deltaw "y") (setq year (+ year deltan)))))
  12906. ((and wday (not (nth 3 tl)))
  12907. ;; Weekday was given, but no day, so pick that day in the week
  12908. ;; on or after the derived date.
  12909. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12910. (unless (equal wday wday1)
  12911. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12912. (when (and (boundp 'org-time-was-given)
  12913. (nth 2 tl))
  12914. (setq org-time-was-given t))
  12915. (when (< year 100) (setq year (+ 2000 year)))
  12916. ;; Check of the date is representable
  12917. (if org-read-date-force-compatible-dates
  12918. (progn
  12919. (when (< year 1970)
  12920. (setq year 1970 org-read-date-analyze-forced-year t))
  12921. (when (> year 2037)
  12922. (setq year 2037 org-read-date-analyze-forced-year t)))
  12923. (condition-case nil
  12924. (ignore (encode-time second minute hour day month year))
  12925. (error
  12926. (setq year (nth 5 org-defdecode))
  12927. (setq org-read-date-analyze-forced-year t))))
  12928. (setq org-read-date-analyze-futurep futurep)
  12929. (list second minute hour day month year)))
  12930. (defvar parse-time-weekdays)
  12931. (defun org-read-date-get-relative (s today default)
  12932. "Check string S for special relative date string.
  12933. TODAY and DEFAULT are internal times, for today and for a default.
  12934. Return shift list (N what def-flag)
  12935. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12936. N is the number of WHATs to shift.
  12937. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12938. the DEFAULT date rather than TODAY."
  12939. (require 'parse-time)
  12940. (when (and
  12941. (string-match
  12942. (concat
  12943. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12944. "\\([0-9]+\\)?"
  12945. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12946. "\\([ \t]\\|$\\)") s)
  12947. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12948. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12949. (string-to-char (substring (match-string 1 s) -1))
  12950. ?+))
  12951. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12952. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12953. (what (if (match-end 3) (match-string 3 s) "d"))
  12954. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12955. (date (if rel default today))
  12956. (wday (nth 6 (decode-time date)))
  12957. delta)
  12958. (if wday1
  12959. (progn
  12960. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12961. (when (= delta 0) (setq delta 7))
  12962. (when (= dir ?-)
  12963. (setq delta (- delta 7))
  12964. (when (= delta 0) (setq delta -7)))
  12965. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12966. (list delta "d" rel))
  12967. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12968. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12969. "Turn a user-specified date into the internal representation.
  12970. The internal representation needed by the calendar is (month day year).
  12971. This is a wrapper to handle the brain-dead convention in calendar that
  12972. user function argument order change dependent on argument order."
  12973. (pcase calendar-date-style
  12974. (`american (list arg1 arg2 arg3))
  12975. (`european (list arg2 arg1 arg3))
  12976. (`iso (list arg2 arg3 arg1))))
  12977. (defun org-eval-in-calendar (form &optional keepdate)
  12978. "Eval FORM in the calendar window and return to current window.
  12979. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12980. (let ((sf (selected-frame))
  12981. (sw (selected-window)))
  12982. (select-window (get-buffer-window "*Calendar*" t))
  12983. (eval form)
  12984. (when (and (not keepdate) (calendar-cursor-to-date))
  12985. (let* ((date (calendar-cursor-to-date))
  12986. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12987. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12988. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12989. (select-window sw)
  12990. (select-frame-set-input-focus sf)))
  12991. (defun org-calendar-select ()
  12992. "Return to `org-read-date' with the date currently selected.
  12993. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12994. (interactive)
  12995. (when (calendar-cursor-to-date)
  12996. (let* ((date (calendar-cursor-to-date))
  12997. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12998. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12999. (when (active-minibuffer-window) (exit-minibuffer))))
  13000. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13001. "Insert a date stamp for the date given by the internal TIME.
  13002. See `format-time-string' for the format of TIME.
  13003. WITH-HM means use the stamp format that includes the time of the day.
  13004. INACTIVE means use square brackets instead of angular ones, so that the
  13005. stamp will not contribute to the agenda.
  13006. PRE and POST are optional strings to be inserted before and after the
  13007. stamp.
  13008. The command returns the inserted time stamp."
  13009. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13010. stamp)
  13011. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13012. (insert-before-markers (or pre ""))
  13013. (when (listp extra)
  13014. (setq extra (car extra))
  13015. (if (and (stringp extra)
  13016. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13017. (setq extra (format "-%02d:%02d"
  13018. (string-to-number (match-string 1 extra))
  13019. (string-to-number (match-string 2 extra))))
  13020. (setq extra nil)))
  13021. (when extra
  13022. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13023. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13024. (insert-before-markers (or post ""))
  13025. (setq org-last-inserted-timestamp stamp)))
  13026. (defun org-toggle-time-stamp-overlays ()
  13027. "Toggle the use of custom time stamp formats."
  13028. (interactive)
  13029. (setq org-display-custom-times (not org-display-custom-times))
  13030. (unless org-display-custom-times
  13031. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13032. (while (setq p (next-single-property-change p 'display))
  13033. (when (and (get-text-property p 'display)
  13034. (eq (get-text-property p 'face) 'org-date))
  13035. (remove-text-properties
  13036. p (setq p (next-single-property-change p 'display))
  13037. '(display t))))
  13038. (set-buffer-modified-p bmp)))
  13039. (org-restart-font-lock)
  13040. (setq org-table-may-need-update t)
  13041. (if org-display-custom-times
  13042. (message "Time stamps are overlaid with custom format")
  13043. (message "Time stamp overlays removed")))
  13044. (defun org-display-custom-time (beg end)
  13045. "Overlay modified time stamp format over timestamp between BEG and END."
  13046. (let* ((ts (buffer-substring beg end))
  13047. t1 with-hm tf time str (off 0))
  13048. (save-match-data
  13049. (setq t1 (org-parse-time-string ts t))
  13050. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13051. (setq off (- (match-end 0) (match-beginning 0)))))
  13052. (setq end (- end off))
  13053. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13054. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13055. time (org-fix-decoded-time t1)
  13056. str (org-add-props
  13057. (format-time-string
  13058. (substring tf 1 -1) (apply 'encode-time time))
  13059. nil 'mouse-face 'highlight))
  13060. (put-text-property beg end 'display str)))
  13061. (defun org-fix-decoded-time (time)
  13062. "Set 0 instead of nil for the first 6 elements of time.
  13063. Don't touch the rest."
  13064. (let ((n 0))
  13065. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13066. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13067. "Difference between TIMESTAMP-STRING and now in days.
  13068. If SECONDS is non-nil, return the difference in seconds."
  13069. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13070. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13071. (funcall fdiff nil))))
  13072. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13073. "Is the time in TIMESTAMP-STRING close to the current date?"
  13074. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13075. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13076. (not (org-entry-is-done-p))))
  13077. (defun org-get-wdays (ts &optional delay zero-delay)
  13078. "Get the deadline lead time appropriate for timestring TS.
  13079. When DELAY is non-nil, get the delay time for scheduled items
  13080. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13081. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13082. don't try to find the delay cookie in the scheduled timestamp."
  13083. (let ((tv (if delay org-scheduled-delay-days
  13084. org-deadline-warning-days)))
  13085. (cond
  13086. ((or (and delay (< tv 0))
  13087. (and delay zero-delay (<= tv 0))
  13088. (and (not delay) (<= tv 0)))
  13089. ;; Enforce this value no matter what
  13090. (- tv))
  13091. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13092. ;; lead time is specified.
  13093. (floor (* (string-to-number (match-string 1 ts))
  13094. (cdr (assoc (match-string 2 ts)
  13095. '(("d" . 1) ("w" . 7)
  13096. ("m" . 30.4) ("y" . 365.25)
  13097. ("h" . 0.041667)))))))
  13098. ;; go for the default.
  13099. (t tv))))
  13100. (defun org-calendar-select-mouse (ev)
  13101. "Return to `org-read-date' with the date currently selected.
  13102. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13103. (interactive "e")
  13104. (mouse-set-point ev)
  13105. (when (calendar-cursor-to-date)
  13106. (let* ((date (calendar-cursor-to-date))
  13107. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13108. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13109. (when (active-minibuffer-window) (exit-minibuffer))))
  13110. (defun org-check-deadlines (ndays)
  13111. "Check if there are any deadlines due or past due.
  13112. A deadline is considered due if it happens within `org-deadline-warning-days'
  13113. days from today's date. If the deadline appears in an entry marked DONE,
  13114. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13115. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13116. are shown."
  13117. (interactive "P")
  13118. (let* ((org-warn-days
  13119. (cond
  13120. ((equal ndays '(4)) 100000)
  13121. (ndays (prefix-numeric-value ndays))
  13122. (t (abs org-deadline-warning-days))))
  13123. (case-fold-search nil)
  13124. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13125. (callback
  13126. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13127. (message "%d deadlines past-due or due within %d days"
  13128. (org-occur regexp nil callback)
  13129. org-warn-days)))
  13130. (defsubst org-re-timestamp (type)
  13131. "Return a regexp for timestamp TYPE.
  13132. Allowed values for TYPE are:
  13133. all: all timestamps
  13134. active: only active timestamps (<...>)
  13135. inactive: only inactive timestamps ([...])
  13136. scheduled: only scheduled timestamps
  13137. deadline: only deadline timestamps
  13138. closed: only closed time-stamps
  13139. When TYPE is nil, fall back on returning a regexp that matches
  13140. both scheduled and deadline timestamps."
  13141. (cl-case type
  13142. (all org-ts-regexp-both)
  13143. (active org-ts-regexp)
  13144. (inactive org-ts-regexp-inactive)
  13145. (scheduled org-scheduled-time-regexp)
  13146. (deadline org-deadline-time-regexp)
  13147. (closed org-closed-time-regexp)
  13148. (otherwise
  13149. (concat "\\<"
  13150. (regexp-opt (list org-deadline-string org-scheduled-string))
  13151. " *<\\([^>]+\\)>"))))
  13152. (defun org-check-before-date (d)
  13153. "Check if there are deadlines or scheduled entries before date D."
  13154. (interactive (list (org-read-date)))
  13155. (let* ((case-fold-search nil)
  13156. (regexp (org-re-timestamp org-ts-type))
  13157. (ts-type org-ts-type)
  13158. (callback
  13159. (lambda ()
  13160. (let ((match (match-string 1)))
  13161. (and (if (memq ts-type '(active inactive all))
  13162. (eq (org-element-type (save-excursion
  13163. (backward-char)
  13164. (org-element-context)))
  13165. 'timestamp)
  13166. (org-at-planning-p))
  13167. (time-less-p
  13168. (org-time-string-to-time match)
  13169. (org-time-string-to-time d)))))))
  13170. (message "%d entries before %s"
  13171. (org-occur regexp nil callback)
  13172. d)))
  13173. (defun org-check-after-date (d)
  13174. "Check if there are deadlines or scheduled entries after date D."
  13175. (interactive (list (org-read-date)))
  13176. (let* ((case-fold-search nil)
  13177. (regexp (org-re-timestamp org-ts-type))
  13178. (ts-type org-ts-type)
  13179. (callback
  13180. (lambda ()
  13181. (let ((match (match-string 1)))
  13182. (and (if (memq ts-type '(active inactive all))
  13183. (eq (org-element-type (save-excursion
  13184. (backward-char)
  13185. (org-element-context)))
  13186. 'timestamp)
  13187. (org-at-planning-p))
  13188. (not (time-less-p
  13189. (org-time-string-to-time match)
  13190. (org-time-string-to-time d))))))))
  13191. (message "%d entries after %s"
  13192. (org-occur regexp nil callback)
  13193. d)))
  13194. (defun org-check-dates-range (start-date end-date)
  13195. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13196. (interactive (list (org-read-date nil nil nil "Range starts")
  13197. (org-read-date nil nil nil "Range end")))
  13198. (let ((case-fold-search nil)
  13199. (regexp (org-re-timestamp org-ts-type))
  13200. (callback
  13201. (let ((type org-ts-type))
  13202. (lambda ()
  13203. (let ((match (match-string 1)))
  13204. (and
  13205. (if (memq type '(active inactive all))
  13206. (eq (org-element-type (save-excursion
  13207. (backward-char)
  13208. (org-element-context)))
  13209. 'timestamp)
  13210. (org-at-planning-p))
  13211. (not (time-less-p
  13212. (org-time-string-to-time match)
  13213. (org-time-string-to-time start-date)))
  13214. (time-less-p
  13215. (org-time-string-to-time match)
  13216. (org-time-string-to-time end-date))))))))
  13217. (message "%d entries between %s and %s"
  13218. (org-occur regexp nil callback) start-date end-date)))
  13219. (defun org-evaluate-time-range (&optional to-buffer)
  13220. "Evaluate a time range by computing the difference between start and end.
  13221. Normally the result is just printed in the echo area, but with prefix arg
  13222. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13223. If the time range is actually in a table, the result is inserted into the
  13224. next column.
  13225. For time difference computation, a year is assumed to be exactly 365
  13226. days in order to avoid rounding problems."
  13227. (interactive "P")
  13228. (or
  13229. (org-clock-update-time-maybe)
  13230. (save-excursion
  13231. (unless (org-at-date-range-p t)
  13232. (goto-char (point-at-bol))
  13233. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13234. (unless (org-at-date-range-p t)
  13235. (user-error "Not at a time-stamp range, and none found in current line")))
  13236. (let* ((ts1 (match-string 1))
  13237. (ts2 (match-string 2))
  13238. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13239. (match-end (match-end 0))
  13240. (time1 (org-time-string-to-time ts1))
  13241. (time2 (org-time-string-to-time ts2))
  13242. (diff (abs (float-time (time-subtract time2 time1))))
  13243. (negative (time-less-p time2 time1))
  13244. ;; (ys (floor (* 365 24 60 60)))
  13245. (ds (* 24 60 60))
  13246. (hs (* 60 60))
  13247. (fy "%dy %dd %02d:%02d")
  13248. (fy1 "%dy %dd")
  13249. (fd "%dd %02d:%02d")
  13250. (fd1 "%dd")
  13251. (fh "%02d:%02d")
  13252. y d h m align)
  13253. (if havetime
  13254. (setq ; y (floor diff ys) diff (mod diff ys)
  13255. y 0
  13256. d (floor diff ds) diff (mod diff ds)
  13257. h (floor diff hs) diff (mod diff hs)
  13258. m (floor diff 60))
  13259. (setq ; y (floor diff ys) diff (mod diff ys)
  13260. y 0
  13261. d (round diff ds)
  13262. h 0 m 0))
  13263. (if (not to-buffer)
  13264. (message "%s" (org-make-tdiff-string y d h m))
  13265. (if (org-at-table-p)
  13266. (progn
  13267. (goto-char match-end)
  13268. (setq align t)
  13269. (and (looking-at " *|") (goto-char (match-end 0))))
  13270. (goto-char match-end))
  13271. (when (looking-at
  13272. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13273. (replace-match ""))
  13274. (when negative (insert " -"))
  13275. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13276. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13277. (insert " " (format fh h m))))
  13278. (when align (org-table-align))
  13279. (message "Time difference inserted")))))
  13280. (defun org-make-tdiff-string (y d h m)
  13281. (let ((fmt "")
  13282. (l nil))
  13283. (when (> y 0)
  13284. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13285. (push y l))
  13286. (when (> d 0)
  13287. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13288. (push d l))
  13289. (when (> h 0)
  13290. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13291. (push h l))
  13292. (when (> m 0)
  13293. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13294. (push m l))
  13295. (apply 'format fmt (nreverse l))))
  13296. (defun org-time-string-to-time (s)
  13297. "Convert timestamp string S into internal time."
  13298. (apply #'encode-time (org-parse-time-string s)))
  13299. (defun org-time-string-to-seconds (s)
  13300. "Convert a timestamp string S into a number of seconds."
  13301. (float-time (org-time-string-to-time s)))
  13302. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13303. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13304. "Convert time stamp S to an absolute day number.
  13305. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13306. stamp, get the closest date to DAYNR. If PREFER is
  13307. `past' (respectively `future') return a date past (respectively
  13308. after) or equal to DAYNR.
  13309. POS is the location of time stamp S, as a buffer position in
  13310. BUFFER.
  13311. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13312. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13313. signaled."
  13314. (cond
  13315. ((string-match "\\`%%\\((.*)\\)" s)
  13316. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13317. ;; only able to match individual dates. If it fails, raise an
  13318. ;; error.
  13319. (if (and daynr
  13320. (org-diary-sexp-entry
  13321. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13322. daynr
  13323. (signal 'org-diary-sexp-no-match (list s))))
  13324. (daynr (org-closest-date s daynr prefer))
  13325. (t (time-to-days
  13326. (condition-case errdata
  13327. (org-time-string-to-time s)
  13328. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13329. s
  13330. (if (not (and buffer pos)) ""
  13331. (format-message " at %d in buffer `%s'" pos buffer))
  13332. (cdr errdata))))))))
  13333. (defun org-days-to-iso-week (days)
  13334. "Return the ISO week number."
  13335. (require 'cal-iso)
  13336. (car (calendar-iso-from-absolute days)))
  13337. (defun org-small-year-to-year (year)
  13338. "Convert 2-digit years into 4-digit years.
  13339. YEAR is expanded into one of the 30 next years, if possible, or
  13340. into a past one. Any year larger than 99 is returned unchanged."
  13341. (if (>= year 100) year
  13342. (let* ((current (string-to-number (format-time-string "%Y")))
  13343. (century (/ current 100))
  13344. (offset (- year (% current 100))))
  13345. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13346. ((> offset -70) (+ (* century 100) year))
  13347. (t (+ (* (1+ century) 100) year))))))
  13348. (defun org-time-from-absolute (d)
  13349. "Return the time corresponding to date D.
  13350. D may be an absolute day number, or a calendar-type list (month day year)."
  13351. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13352. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13353. (defvar org-agenda-current-date)
  13354. (defun org-calendar-holiday ()
  13355. "List of holidays, for Diary display in Org mode."
  13356. (require 'holidays)
  13357. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13358. (and hl (mapconcat #'identity hl "; "))))
  13359. (defun org-diary-sexp-entry (sexp entry d)
  13360. "Process a SEXP diary ENTRY for date D."
  13361. (require 'diary-lib)
  13362. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13363. ;; dynamically.
  13364. (let* ((sexp `(let ((entry ,entry)
  13365. (date ',d))
  13366. ,(car (read-from-string sexp))))
  13367. (result (if calendar-debug-sexp (eval sexp)
  13368. (condition-case nil
  13369. (eval sexp)
  13370. (error
  13371. (beep)
  13372. (message "Bad sexp at line %d in %s: %s"
  13373. (org-current-line)
  13374. (buffer-file-name) sexp)
  13375. (sleep-for 2))))))
  13376. (cond ((stringp result) (split-string result "; "))
  13377. ((and (consp result)
  13378. (not (consp (cdr result)))
  13379. (stringp (cdr result))) (cdr result))
  13380. ((and (consp result)
  13381. (stringp (car result))) result)
  13382. (result entry))))
  13383. (defun org-diary-to-ical-string (frombuf)
  13384. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13385. This uses the icalendar.el library."
  13386. (let* ((tmpdir temporary-file-directory)
  13387. (tmpfile (make-temp-name
  13388. (expand-file-name "orgics" tmpdir)))
  13389. buf rtn b e)
  13390. (with-current-buffer frombuf
  13391. (icalendar-export-region (point-min) (point-max) tmpfile)
  13392. (setq buf (find-buffer-visiting tmpfile))
  13393. (set-buffer buf)
  13394. (goto-char (point-min))
  13395. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13396. (setq b (match-beginning 0)))
  13397. (goto-char (point-max))
  13398. (when (re-search-backward "^END:VEVENT" nil t)
  13399. (setq e (match-end 0)))
  13400. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13401. (kill-buffer buf)
  13402. (delete-file tmpfile)
  13403. rtn))
  13404. (defun org-closest-date (start current prefer)
  13405. "Return closest date to CURRENT starting from START.
  13406. CURRENT and START are both time stamps.
  13407. When PREFER is `past', return a date that is either CURRENT or
  13408. past. When PREFER is `future', return a date that is either
  13409. CURRENT or future.
  13410. Only time stamps with a repeater are modified. Any other time
  13411. stamp stay unchanged. In any case, return value is an absolute
  13412. day number."
  13413. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13414. ;; No repeater. Do not shift time stamp.
  13415. (time-to-days (org-time-string-to-time start))
  13416. (let ((value (string-to-number (match-string 1 start)))
  13417. (type (match-string 2 start)))
  13418. (if (= 0 value)
  13419. ;; Repeater with a 0-value is considered as void.
  13420. (time-to-days (org-time-string-to-time start))
  13421. (let* ((base (org-date-to-gregorian start))
  13422. (target (org-date-to-gregorian current))
  13423. (sday (calendar-absolute-from-gregorian base))
  13424. (cday (calendar-absolute-from-gregorian target))
  13425. n1 n2)
  13426. ;; If START is already past CURRENT, just return START.
  13427. (if (<= cday sday) sday
  13428. ;; Compute closest date before (N1) and closest date past
  13429. ;; (N2) CURRENT.
  13430. (pcase type
  13431. ("h"
  13432. (let ((missing-hours
  13433. (mod (+ (- (* 24 (- cday sday))
  13434. (nth 2 (org-parse-time-string start)))
  13435. org-extend-today-until)
  13436. value)))
  13437. (setf n1 (if (= missing-hours 0) cday
  13438. (- cday (1+ (/ missing-hours 24)))))
  13439. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13440. ((or "d" "w")
  13441. (let ((value (if (equal type "w") (* 7 value) value)))
  13442. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13443. (setf n2 (+ n1 value))))
  13444. ("m"
  13445. (let* ((add-months
  13446. (lambda (d n)
  13447. ;; Add N months to gregorian date D, i.e.,
  13448. ;; a list (MONTH DAY YEAR). Return a valid
  13449. ;; gregorian date.
  13450. (let ((m (+ (nth 0 d) n)))
  13451. (list (mod m 12)
  13452. (nth 1 d)
  13453. (+ (/ m 12) (nth 2 d))))))
  13454. (months ; Complete months to TARGET.
  13455. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13456. (- (nth 0 target) (nth 0 base))
  13457. ;; If START's day is greater than
  13458. ;; TARGET's, remove incomplete month.
  13459. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13460. value)
  13461. value))
  13462. (before (funcall add-months base months)))
  13463. (setf n1 (calendar-absolute-from-gregorian before))
  13464. (setf n2
  13465. (calendar-absolute-from-gregorian
  13466. (funcall add-months before value)))))
  13467. (_
  13468. (let* ((d (nth 1 base))
  13469. (m (nth 0 base))
  13470. (y (nth 2 base))
  13471. (years ; Complete years to TARGET.
  13472. (* (/ (- (nth 2 target)
  13473. y
  13474. ;; If START's month and day are
  13475. ;; greater than TARGET's, remove
  13476. ;; incomplete year.
  13477. (if (or (> (nth 0 target) m)
  13478. (and (= (nth 0 target) m)
  13479. (> (nth 1 target) d)))
  13480. 0
  13481. 1))
  13482. value)
  13483. value))
  13484. (before (list m d (+ y years))))
  13485. (setf n1 (calendar-absolute-from-gregorian before))
  13486. (setf n2 (calendar-absolute-from-gregorian
  13487. (list m d (+ (nth 2 before) value)))))))
  13488. ;; Handle PREFER parameter, if any.
  13489. (cond
  13490. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13491. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13492. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13493. (defun org-date-to-gregorian (d)
  13494. "Turn any specification of date D into a Gregorian date for the calendar."
  13495. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13496. ((and (listp d) (= (length d) 3)) d)
  13497. ((stringp d)
  13498. (let ((d (org-parse-time-string d)))
  13499. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13500. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13501. (defun org-timestamp-up (&optional arg)
  13502. "Increase the date item at the cursor by one.
  13503. If the cursor is on the year, change the year. If it is on the month,
  13504. the day or the time, change that. If the cursor is on the enclosing
  13505. bracket, change the timestamp type.
  13506. With prefix ARG, change by that many units."
  13507. (interactive "p")
  13508. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13509. (defun org-timestamp-down (&optional arg)
  13510. "Decrease the date item at the cursor by one.
  13511. If the cursor is on the year, change the year. If it is on the month,
  13512. the day or the time, change that. If the cursor is on the enclosing
  13513. bracket, change the timestamp type.
  13514. With prefix ARG, change by that many units."
  13515. (interactive "p")
  13516. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13517. (defun org-timestamp-up-day (&optional arg)
  13518. "Increase the date in the time stamp by one day.
  13519. With prefix ARG, change that many days."
  13520. (interactive "p")
  13521. (if (and (not (org-at-timestamp-p 'lax))
  13522. (org-at-heading-p))
  13523. (org-todo 'up)
  13524. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13525. (defun org-timestamp-down-day (&optional arg)
  13526. "Decrease the date in the time stamp by one day.
  13527. With prefix ARG, change that many days."
  13528. (interactive "p")
  13529. (if (and (not (org-at-timestamp-p 'lax))
  13530. (org-at-heading-p))
  13531. (org-todo 'down)
  13532. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13533. (defun org-at-timestamp-p (&optional extended)
  13534. "Non-nil if point is inside a timestamp.
  13535. By default, the function only consider syntactically valid active
  13536. timestamps. However, the caller may have a broader definition
  13537. for timestamps. As a consequence, optional argument EXTENDED can
  13538. be set to the following values
  13539. `inactive'
  13540. Include also syntactically valid inactive timestamps.
  13541. `agenda'
  13542. Include timestamps allowed in Agenda, i.e., those in
  13543. properties drawers, planning lines and clock lines.
  13544. `lax'
  13545. Ignore context. The function matches any part of the
  13546. document looking like a timestamp. This includes comments,
  13547. example blocks...
  13548. For backward-compatibility with Org 9.0, every other non-nil
  13549. value is equivalent to `inactive'.
  13550. When at a timestamp, return the position of the point as a symbol
  13551. among `bracket', `after', `year', `month', `hour', `minute',
  13552. `day' or a number of character from the last know part of the
  13553. time stamp.
  13554. When matching, the match groups are the following:
  13555. group 1: year
  13556. group 2: month
  13557. group 3: day number
  13558. group 4: day name
  13559. group 5: hours, if any
  13560. group 6: minutes, if any"
  13561. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13562. (pos (point))
  13563. (match?
  13564. (let ((boundaries (org-in-regexp regexp)))
  13565. (save-match-data
  13566. (cond ((null boundaries) nil)
  13567. ((eq extended 'lax) t)
  13568. (t
  13569. (or (and (eq extended 'agenda)
  13570. (or (org-at-planning-p)
  13571. (org-at-property-p)
  13572. (and (bound-and-true-p
  13573. org-agenda-include-inactive-timestamps)
  13574. (org-at-clock-log-p))))
  13575. (eq 'timestamp
  13576. (save-excursion
  13577. (when (= pos (cdr boundaries)) (forward-char -1))
  13578. (org-element-type (org-element-context)))))))))))
  13579. (cond
  13580. ((not match?) nil)
  13581. ((= pos (match-beginning 0)) 'bracket)
  13582. ;; Distinguish location right before the closing bracket from
  13583. ;; right after it.
  13584. ((= pos (1- (match-end 0))) 'bracket)
  13585. ((= pos (match-end 0)) 'after)
  13586. ((org-pos-in-match-range pos 2) 'year)
  13587. ((org-pos-in-match-range pos 3) 'month)
  13588. ((org-pos-in-match-range pos 7) 'hour)
  13589. ((org-pos-in-match-range pos 8) 'minute)
  13590. ((or (org-pos-in-match-range pos 4)
  13591. (org-pos-in-match-range pos 5)) 'day)
  13592. ((and (> pos (or (match-end 8) (match-end 5)))
  13593. (< pos (match-end 0)))
  13594. (- pos (or (match-end 8) (match-end 5))))
  13595. (t 'day))))
  13596. (defun org-toggle-timestamp-type ()
  13597. "Toggle the type (<active> or [inactive]) of a time stamp."
  13598. (interactive)
  13599. (when (org-at-timestamp-p 'lax)
  13600. (let ((beg (match-beginning 0)) (end (match-end 0))
  13601. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13602. (save-excursion
  13603. (goto-char beg)
  13604. (while (re-search-forward "[][<>]" end t)
  13605. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13606. t t)))
  13607. (message "Timestamp is now %sactive"
  13608. (if (equal (char-after beg) ?<) "" "in")))))
  13609. (defun org-at-clock-log-p ()
  13610. "Non-nil if point is on a clock log line."
  13611. (and (org-match-line org-clock-line-re)
  13612. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13613. (defvar org-clock-history) ; defined in org-clock.el
  13614. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13615. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13616. "Change the date in the time stamp at point.
  13617. The date is changed by N times WHAT. WHAT can be `day', `month',
  13618. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13619. position in the timestamp determines what is changed.
  13620. When optional argument UPDOWN is non-nil, minutes are rounded
  13621. according to `org-time-stamp-rounding-minutes'.
  13622. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13623. \"--2d\"."
  13624. (let ((origin (point))
  13625. (timestamp? (org-at-timestamp-p 'lax))
  13626. origin-cat
  13627. with-hm inactive
  13628. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13629. extra rem
  13630. ts time time0 fixnext clrgx)
  13631. (unless timestamp? (user-error "Not at a timestamp"))
  13632. (if (and (not what) (eq timestamp? 'bracket))
  13633. (org-toggle-timestamp-type)
  13634. ;; Point isn't on brackets. Remember the part of the time-stamp
  13635. ;; the point was in. Indeed, size of time-stamps may change,
  13636. ;; but point must be kept in the same category nonetheless.
  13637. (setq origin-cat timestamp?)
  13638. (when (and (not what) (not (eq timestamp? 'day))
  13639. org-display-custom-times
  13640. (get-text-property (point) 'display)
  13641. (not (get-text-property (1- (point)) 'display)))
  13642. (setq timestamp? 'day))
  13643. (setq timestamp? (or what timestamp?)
  13644. inactive (= (char-after (match-beginning 0)) ?\[)
  13645. ts (match-string 0))
  13646. (replace-match "")
  13647. (when (string-match
  13648. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13649. ts)
  13650. (setq extra (match-string 1 ts))
  13651. (when suppress-tmp-delay
  13652. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13653. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13654. (setq with-hm t))
  13655. (setq time0 (org-parse-time-string ts))
  13656. (when (and updown
  13657. (eq timestamp? 'minute)
  13658. (not current-prefix-arg))
  13659. ;; This looks like s-up and s-down. Change by one rounding step.
  13660. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13661. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13662. (setcar (cdr time0) (+ (nth 1 time0)
  13663. (if (> n 0) (- rem) (- dm rem))))))
  13664. (setq time
  13665. (apply #'encode-time
  13666. (or (car time0) 0)
  13667. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13668. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13669. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13670. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13671. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13672. (nthcdr 6 time0)))
  13673. (when (and (memq timestamp? '(hour minute))
  13674. extra
  13675. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13676. (setq extra (org-modify-ts-extra
  13677. extra
  13678. (if (eq timestamp? 'hour) 2 5)
  13679. n dm)))
  13680. (when (integerp timestamp?)
  13681. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13682. (when (eq what 'calendar)
  13683. (let ((cal-date (org-get-date-from-calendar)))
  13684. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13685. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13686. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13687. (setcar time0 (or (car time0) 0))
  13688. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13689. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13690. (setq time (apply 'encode-time time0))))
  13691. ;; Insert the new time-stamp, and ensure point stays in the same
  13692. ;; category as before (i.e. not after the last position in that
  13693. ;; category).
  13694. (let ((pos (point)))
  13695. ;; Stay before inserted string. `save-excursion' is of no use.
  13696. (setq org-last-changed-timestamp
  13697. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13698. (goto-char pos))
  13699. (save-match-data
  13700. (looking-at org-ts-regexp3)
  13701. (goto-char
  13702. (pcase origin-cat
  13703. ;; `day' category ends before `hour' if any, or at the end
  13704. ;; of the day name.
  13705. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13706. (`hour (min (match-end 7) origin))
  13707. (`minute (min (1- (match-end 8)) origin))
  13708. ((pred integerp) (min (1- (match-end 0)) origin))
  13709. ;; Point was right after the time-stamp. However, the
  13710. ;; time-stamp length might have changed, so refer to
  13711. ;; (match-end 0) instead.
  13712. (`after (match-end 0))
  13713. ;; `year' and `month' have both fixed size: point couldn't
  13714. ;; have moved into another part.
  13715. (_ origin))))
  13716. ;; Update clock if on a CLOCK line.
  13717. (org-clock-update-time-maybe)
  13718. ;; Maybe adjust the closest clock in `org-clock-history'
  13719. (when org-clock-adjust-closest
  13720. (if (not (and (org-at-clock-log-p)
  13721. (< 1 (length (delq nil (mapcar 'marker-position
  13722. org-clock-history))))))
  13723. (message "No clock to adjust")
  13724. (cond ((save-excursion ; fix previous clock?
  13725. (re-search-backward org-ts-regexp0 nil t)
  13726. (looking-back (concat org-clock-string " \\[")
  13727. (line-beginning-position)))
  13728. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13729. ((save-excursion ; fix next clock?
  13730. (re-search-backward org-ts-regexp0 nil t)
  13731. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13732. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13733. (save-window-excursion
  13734. ;; Find closest clock to point, adjust the previous/next one in history
  13735. (let* ((p (save-excursion (org-back-to-heading t)))
  13736. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13737. (clfixnth
  13738. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13739. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13740. (if (not clfixpos)
  13741. (message "No clock to adjust")
  13742. (save-excursion
  13743. (org-goto-marker-or-bmk clfixpos)
  13744. (org-show-subtree)
  13745. (when (re-search-forward clrgx nil t)
  13746. (goto-char (match-beginning 1))
  13747. (let (org-clock-adjust-closest)
  13748. (org-timestamp-change n timestamp? updown))
  13749. (message "Clock adjusted in %s for heading: %s"
  13750. (file-name-nondirectory (buffer-file-name))
  13751. (org-get-heading t t)))))))))
  13752. ;; Try to recenter the calendar window, if any.
  13753. (when (and org-calendar-follow-timestamp-change
  13754. (get-buffer-window "*Calendar*" t)
  13755. (memq timestamp? '(day month year)))
  13756. (org-recenter-calendar (time-to-days time))))))
  13757. (defun org-modify-ts-extra (s pos n dm)
  13758. "Change the different parts of the lead-time and repeat fields in timestamp."
  13759. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13760. ng h m new rem)
  13761. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13762. (cond
  13763. ((or (org-pos-in-match-range pos 2)
  13764. (org-pos-in-match-range pos 3))
  13765. (setq m (string-to-number (match-string 3 s))
  13766. h (string-to-number (match-string 2 s)))
  13767. (if (org-pos-in-match-range pos 2)
  13768. (setq h (+ h n))
  13769. (setq n (* dm (with-no-warnings (cl-signum n))))
  13770. (unless (= 0 (setq rem (% m dm)))
  13771. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13772. (setq m (+ m n)))
  13773. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13774. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13775. (setq h (mod h 24))
  13776. (setq ng 1 new (format "-%02d:%02d" h m)))
  13777. ((org-pos-in-match-range pos 6)
  13778. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13779. ((org-pos-in-match-range pos 5)
  13780. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13781. ((org-pos-in-match-range pos 9)
  13782. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13783. ((org-pos-in-match-range pos 8)
  13784. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13785. (when ng
  13786. (setq s (concat
  13787. (substring s 0 (match-beginning ng))
  13788. new
  13789. (substring s (match-end ng))))))
  13790. s))
  13791. (defun org-recenter-calendar (d)
  13792. "If the calendar is visible, recenter it to date D."
  13793. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13794. (when cwin
  13795. (let ((calendar-move-hook nil))
  13796. (with-selected-window cwin
  13797. (calendar-goto-date
  13798. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13799. (defun org-goto-calendar (&optional arg)
  13800. "Go to the Emacs calendar at the current date.
  13801. If there is a time stamp in the current line, go to that date.
  13802. A prefix ARG can be used to force the current date."
  13803. (interactive "P")
  13804. (let ((calendar-move-hook nil)
  13805. (calendar-view-holidays-initially-flag nil)
  13806. (calendar-view-diary-initially-flag nil)
  13807. diff)
  13808. (when (or (org-at-timestamp-p 'lax)
  13809. (org-match-line (concat ".*" org-ts-regexp)))
  13810. (let ((d1 (time-to-days nil))
  13811. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13812. (setq diff (- d2 d1))))
  13813. (calendar)
  13814. (calendar-goto-today)
  13815. (when (and diff (not arg)) (calendar-forward-day diff))))
  13816. (defun org-get-date-from-calendar ()
  13817. "Return a list (month day year) of date at point in calendar."
  13818. (with-current-buffer "*Calendar*"
  13819. (save-match-data
  13820. (calendar-cursor-to-date))))
  13821. (defun org-date-from-calendar ()
  13822. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13823. If there is already a time stamp at the cursor position, update it."
  13824. (interactive)
  13825. (if (org-at-timestamp-p 'lax)
  13826. (org-timestamp-change 0 'calendar)
  13827. (let ((cal-date (org-get-date-from-calendar)))
  13828. (org-insert-time-stamp
  13829. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13830. (defcustom org-image-actual-width t
  13831. "When non-nil, use the actual width of images when inlining them.
  13832. When set to a number, use imagemagick (when available) to set the
  13833. image's width to this value.
  13834. When set to a number in a list, try to get the width from any
  13835. #+ATTR.* keyword if it matches a width specification like
  13836. #+ATTR_HTML: :width 300px
  13837. and fall back on that number if none is found.
  13838. When set to nil, try to get the width from an #+ATTR.* keyword
  13839. and fall back on the original width if none is found.
  13840. When set to any other non-nil value, always use the image width.
  13841. This requires Emacs >= 24.1, built with imagemagick support."
  13842. :group 'org-appearance
  13843. :version "24.4"
  13844. :package-version '(Org . "8.0")
  13845. :type '(choice
  13846. (const :tag "Use the image width" t)
  13847. (integer :tag "Use a number of pixels")
  13848. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13849. (const :tag "Use #+ATTR* or don't resize" nil)))
  13850. (defcustom org-agenda-inhibit-startup nil
  13851. "Inhibit startup when preparing agenda buffers.
  13852. When this variable is t, the initialization of the Org agenda
  13853. buffers is inhibited: e.g. the visibility state is not set, the
  13854. tables are not re-aligned, etc."
  13855. :type 'boolean
  13856. :version "24.3"
  13857. :group 'org-agenda)
  13858. (defcustom org-agenda-ignore-properties nil
  13859. "Avoid updating text properties when building the agenda.
  13860. Properties are used to prepare buffers for effort estimates,
  13861. appointments, statistics and subtree-local categories.
  13862. If you don't use these in the agenda, you can add them to this
  13863. list and agenda building will be a bit faster.
  13864. The value is a list, with zero or more of the symbols `effort', `appt',
  13865. `stats' or `category'."
  13866. :type '(set :greedy t
  13867. (const effort)
  13868. (const appt)
  13869. (const stats)
  13870. (const category))
  13871. :version "26.1"
  13872. :package-version '(Org . "8.3")
  13873. :group 'org-agenda)
  13874. ;;;; Files
  13875. (defun org-save-all-org-buffers ()
  13876. "Save all Org buffers without user confirmation."
  13877. (interactive)
  13878. (message "Saving all Org buffers...")
  13879. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13880. (when (featurep 'org-id) (org-id-locations-save))
  13881. (message "Saving all Org buffers... done"))
  13882. (defun org-revert-all-org-buffers ()
  13883. "Revert all Org buffers.
  13884. Prompt for confirmation when there are unsaved changes.
  13885. Be sure you know what you are doing before letting this function
  13886. overwrite your changes.
  13887. This function is useful in a setup where one tracks Org files
  13888. with a version control system, to revert on one machine after pulling
  13889. changes from another. I believe the procedure must be like this:
  13890. 1. M-x org-save-all-org-buffers
  13891. 2. Pull changes from the other machine, resolve conflicts
  13892. 3. M-x org-revert-all-org-buffers"
  13893. (interactive)
  13894. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13895. (user-error "Abort"))
  13896. (save-excursion
  13897. (save-window-excursion
  13898. (dolist (b (buffer-list))
  13899. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13900. (with-current-buffer b buffer-file-name))
  13901. (pop-to-buffer-same-window b)
  13902. (revert-buffer t 'no-confirm)))
  13903. (when (and (featurep 'org-id) org-id-track-globally)
  13904. (org-id-locations-load)))))
  13905. ;;;; Agenda files
  13906. ;;;###autoload
  13907. (defun org-switchb (&optional arg)
  13908. "Switch between Org buffers.
  13909. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13910. With `\\[universal-argument] \\[universal-argument]' \
  13911. prefix, restrict available buffers to agenda files."
  13912. (interactive "P")
  13913. (let ((blist (org-buffer-list
  13914. (cond ((equal arg '(4)) 'files)
  13915. ((equal arg '(16)) 'agenda)))))
  13916. (pop-to-buffer-same-window
  13917. (completing-read "Org buffer: "
  13918. (mapcar #'list (mapcar #'buffer-name blist))
  13919. nil t))))
  13920. (defun org-buffer-list (&optional predicate exclude-tmp)
  13921. "Return a list of Org buffers.
  13922. PREDICATE can be `export', `files' or `agenda'.
  13923. export restrict the list to Export buffers.
  13924. files restrict the list to buffers visiting Org files.
  13925. agenda restrict the list to buffers visiting agenda files.
  13926. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13927. (let* ((bfn nil)
  13928. (agenda-files (and (eq predicate 'agenda)
  13929. (mapcar 'file-truename (org-agenda-files t))))
  13930. (filter
  13931. (cond
  13932. ((eq predicate 'files)
  13933. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13934. ((eq predicate 'export)
  13935. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13936. ((eq predicate 'agenda)
  13937. (lambda (b)
  13938. (with-current-buffer b
  13939. (and (derived-mode-p 'org-mode)
  13940. (setq bfn (buffer-file-name b))
  13941. (member (file-truename bfn) agenda-files)))))
  13942. (t (lambda (b) (with-current-buffer b
  13943. (or (derived-mode-p 'org-mode)
  13944. (string-match "\\*Org .*Export"
  13945. (buffer-name b)))))))))
  13946. (delq nil
  13947. (mapcar
  13948. (lambda(b)
  13949. (if (and (funcall filter b)
  13950. (or (not exclude-tmp)
  13951. (not (string-match "tmp" (buffer-name b)))))
  13952. b
  13953. nil))
  13954. (buffer-list)))))
  13955. (defun org-agenda-files (&optional unrestricted archives)
  13956. "Get the list of agenda files.
  13957. Optional UNRESTRICTED means return the full list even if a restriction
  13958. is currently in place.
  13959. When ARCHIVES is t, include all archive files that are really being
  13960. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13961. `org-agenda-archives-mode' is t."
  13962. (let ((files
  13963. (cond
  13964. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13965. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13966. ((listp org-agenda-files) org-agenda-files)
  13967. (t (error "Invalid value of `org-agenda-files'")))))
  13968. (setq files (apply 'append
  13969. (mapcar (lambda (f)
  13970. (if (file-directory-p f)
  13971. (directory-files
  13972. f t org-agenda-file-regexp)
  13973. (list f)))
  13974. files)))
  13975. (when org-agenda-skip-unavailable-files
  13976. (setq files (delq nil
  13977. (mapcar (lambda (file)
  13978. (and (file-readable-p file) file))
  13979. files))))
  13980. (when (or (eq archives t)
  13981. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13982. (setq files (org-add-archive-files files)))
  13983. files))
  13984. (defun org-agenda-file-p (&optional file)
  13985. "Return non-nil, if FILE is an agenda file.
  13986. If FILE is omitted, use the file associated with the current
  13987. buffer."
  13988. (let ((fname (or file (buffer-file-name))))
  13989. (and fname
  13990. (member (file-truename fname)
  13991. (mapcar #'file-truename (org-agenda-files t))))))
  13992. (defun org-edit-agenda-file-list ()
  13993. "Edit the list of agenda files.
  13994. Depending on setup, this either uses customize to edit the variable
  13995. `org-agenda-files', or it visits the file that is holding the list. In the
  13996. latter case, the buffer is set up in a way that saving it automatically kills
  13997. the buffer and restores the previous window configuration."
  13998. (interactive)
  13999. (if (stringp org-agenda-files)
  14000. (let ((cw (current-window-configuration)))
  14001. (find-file org-agenda-files)
  14002. (setq-local org-window-configuration cw)
  14003. (add-hook 'after-save-hook
  14004. (lambda ()
  14005. (set-window-configuration
  14006. (prog1 org-window-configuration
  14007. (kill-buffer (current-buffer))))
  14008. (org-install-agenda-files-menu)
  14009. (message "New agenda file list installed"))
  14010. nil 'local)
  14011. (message "%s" (substitute-command-keys
  14012. "Edit list and finish with \\[save-buffer]")))
  14013. (customize-variable 'org-agenda-files)))
  14014. (defun org-store-new-agenda-file-list (list)
  14015. "Set new value for the agenda file list and save it correctly."
  14016. (if (stringp org-agenda-files)
  14017. (let ((fe (org-read-agenda-file-list t)) b u)
  14018. (while (setq b (find-buffer-visiting org-agenda-files))
  14019. (kill-buffer b))
  14020. (with-temp-file org-agenda-files
  14021. (insert
  14022. (mapconcat
  14023. (lambda (f) ;; Keep un-expanded entries.
  14024. (if (setq u (assoc f fe))
  14025. (cdr u)
  14026. f))
  14027. list "\n")
  14028. "\n")))
  14029. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14030. (org-insert-mode-line-in-empty-file nil))
  14031. (setq org-agenda-files list)
  14032. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14033. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14034. "Read the list of agenda files from a file.
  14035. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14036. filenames, used by `org-store-new-agenda-file-list' to write back
  14037. un-expanded file names."
  14038. (when (file-directory-p org-agenda-files)
  14039. (error "`org-agenda-files' cannot be a single directory"))
  14040. (when (stringp org-agenda-files)
  14041. (with-temp-buffer
  14042. (insert-file-contents org-agenda-files)
  14043. (mapcar
  14044. (lambda (f)
  14045. (let ((e (expand-file-name (substitute-in-file-name f)
  14046. org-directory)))
  14047. (if pair-with-expansion
  14048. (cons e f)
  14049. e)))
  14050. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14051. ;;;###autoload
  14052. (defun org-cycle-agenda-files ()
  14053. "Cycle through the files in `org-agenda-files'.
  14054. If the current buffer visits an agenda file, find the next one in the list.
  14055. If the current buffer does not, find the first agenda file."
  14056. (interactive)
  14057. (let* ((fs (or (org-agenda-files t)
  14058. (user-error "No agenda files")))
  14059. (files (copy-sequence fs))
  14060. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14061. file)
  14062. (when tcf
  14063. (while (and (setq file (pop files))
  14064. (not (equal (file-truename file) tcf)))))
  14065. (find-file (car (or files fs)))
  14066. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14067. (defun org-agenda-file-to-front (&optional to-end)
  14068. "Move/add the current file to the top of the agenda file list.
  14069. If the file is not present in the list, it is added to the front. If it is
  14070. present, it is moved there. With optional argument TO-END, add/move to the
  14071. end of the list."
  14072. (interactive "P")
  14073. (let ((org-agenda-skip-unavailable-files nil)
  14074. (file-alist (mapcar (lambda (x)
  14075. (cons (file-truename x) x))
  14076. (org-agenda-files t)))
  14077. (ctf (file-truename
  14078. (or buffer-file-name
  14079. (user-error "Please save the current buffer to a file"))))
  14080. x had)
  14081. (setq x (assoc ctf file-alist) had x)
  14082. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14083. (if to-end
  14084. (setq file-alist (append (delq x file-alist) (list x)))
  14085. (setq file-alist (cons x (delq x file-alist))))
  14086. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14087. (org-install-agenda-files-menu)
  14088. (message "File %s to %s of agenda file list"
  14089. (if had "moved" "added") (if to-end "end" "front"))))
  14090. (defun org-remove-file (&optional file)
  14091. "Remove current file from the list of files in variable `org-agenda-files'.
  14092. These are the files which are being checked for agenda entries.
  14093. Optional argument FILE means use this file instead of the current."
  14094. (interactive)
  14095. (let* ((org-agenda-skip-unavailable-files nil)
  14096. (file (or file buffer-file-name
  14097. (user-error "Current buffer does not visit a file")))
  14098. (true-file (file-truename file))
  14099. (afile (abbreviate-file-name file))
  14100. (files (delq nil (mapcar
  14101. (lambda (x)
  14102. (unless (equal true-file
  14103. (file-truename x))
  14104. x))
  14105. (org-agenda-files t)))))
  14106. (if (not (= (length files) (length (org-agenda-files t))))
  14107. (progn
  14108. (org-store-new-agenda-file-list files)
  14109. (org-install-agenda-files-menu)
  14110. (message "Removed from Org Agenda list: %s" afile))
  14111. (message "File was not in list: %s (not removed)" afile))))
  14112. (defun org-file-menu-entry (file)
  14113. (vector file (list 'find-file file) t))
  14114. (defun org-check-agenda-file (file)
  14115. "Make sure FILE exists. If not, ask user what to do."
  14116. (unless (file-exists-p file)
  14117. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14118. (abbreviate-file-name file))
  14119. (let ((r (downcase (read-char-exclusive))))
  14120. (cond
  14121. ((equal r ?r)
  14122. (org-remove-file file)
  14123. (throw 'nextfile t))
  14124. (t (user-error "Abort"))))))
  14125. (defun org-get-agenda-file-buffer (file)
  14126. "Get an agenda buffer visiting FILE.
  14127. If the buffer needs to be created, add it to the list of buffers
  14128. which might be released later."
  14129. (let ((buf (org-find-base-buffer-visiting file)))
  14130. (if buf
  14131. buf ; just return it
  14132. ;; Make a new buffer and remember it
  14133. (setq buf (find-file-noselect file))
  14134. (when buf (push buf org-agenda-new-buffers))
  14135. buf)))
  14136. (defun org-release-buffers (blist)
  14137. "Release all buffers in list, asking the user for confirmation when needed.
  14138. When a buffer is unmodified, it is just killed. When modified, it is saved
  14139. \(if the user agrees) and then killed."
  14140. (let (file)
  14141. (dolist (buf blist)
  14142. (setq file (buffer-file-name buf))
  14143. (when (and (buffer-modified-p buf)
  14144. file
  14145. (y-or-n-p (format "Save file %s? " file)))
  14146. (with-current-buffer buf (save-buffer)))
  14147. (kill-buffer buf))))
  14148. (defun org-agenda-prepare-buffers (files)
  14149. "Create buffers for all agenda files, protect archived trees and comments."
  14150. (interactive)
  14151. (let ((pa '(:org-archived t))
  14152. (pc '(:org-comment t))
  14153. (pall '(:org-archived t :org-comment t))
  14154. (inhibit-read-only t)
  14155. (org-inhibit-startup org-agenda-inhibit-startup)
  14156. (rea (org-make-tag-string (list org-archive-tag)))
  14157. re pos)
  14158. (setq org-tag-alist-for-agenda nil
  14159. org-tag-groups-alist-for-agenda nil)
  14160. (save-excursion
  14161. (save-restriction
  14162. (dolist (file files)
  14163. (catch 'nextfile
  14164. (if (bufferp file)
  14165. (set-buffer file)
  14166. (org-check-agenda-file file)
  14167. (set-buffer (org-get-agenda-file-buffer file)))
  14168. (widen)
  14169. (org-set-regexps-and-options 'tags-only)
  14170. (setq pos (point))
  14171. (or (memq 'category org-agenda-ignore-properties)
  14172. (org-refresh-category-properties))
  14173. (or (memq 'stats org-agenda-ignore-properties)
  14174. (org-refresh-stats-properties))
  14175. (or (memq 'effort org-agenda-ignore-properties)
  14176. (org-refresh-effort-properties))
  14177. (or (memq 'appt org-agenda-ignore-properties)
  14178. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14179. (setq org-todo-keywords-for-agenda
  14180. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14181. (setq org-done-keywords-for-agenda
  14182. (append org-done-keywords-for-agenda org-done-keywords))
  14183. (setq org-todo-keyword-alist-for-agenda
  14184. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14185. (setq org-tag-alist-for-agenda
  14186. (org--tag-add-to-alist
  14187. org-tag-alist-for-agenda
  14188. org-current-tag-alist))
  14189. ;; Merge current file's tag groups into global
  14190. ;; `org-tag-groups-alist-for-agenda'.
  14191. (when org-group-tags
  14192. (dolist (alist org-tag-groups-alist)
  14193. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14194. (if old
  14195. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14196. (push alist org-tag-groups-alist-for-agenda)))))
  14197. (with-silent-modifications
  14198. (save-excursion
  14199. (remove-text-properties (point-min) (point-max) pall)
  14200. (when org-agenda-skip-archived-trees
  14201. (goto-char (point-min))
  14202. (while (re-search-forward rea nil t)
  14203. (when (org-at-heading-p t)
  14204. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14205. (goto-char (point-min))
  14206. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14207. (while (re-search-forward re nil t)
  14208. (when (save-match-data (org-in-commented-heading-p t))
  14209. (add-text-properties
  14210. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14211. (goto-char pos)))))
  14212. (setq org-todo-keywords-for-agenda
  14213. (org-uniquify org-todo-keywords-for-agenda))
  14214. (setq org-todo-keyword-alist-for-agenda
  14215. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14216. ;;;; CDLaTeX minor mode
  14217. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14218. "Keymap for the minor `org-cdlatex-mode'.")
  14219. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14220. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14221. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14222. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14223. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14224. (defvar org-cdlatex-texmathp-advice-is-done nil
  14225. "Flag remembering if we have applied the advice to texmathp already.")
  14226. (define-minor-mode org-cdlatex-mode
  14227. "Toggle the minor `org-cdlatex-mode'.
  14228. This mode supports entering LaTeX environment and math in LaTeX fragments
  14229. in Org mode.
  14230. \\{org-cdlatex-mode-map}"
  14231. nil " OCDL" nil
  14232. (when org-cdlatex-mode
  14233. (require 'cdlatex)
  14234. (run-hooks 'cdlatex-mode-hook)
  14235. (cdlatex-compute-tables))
  14236. (unless org-cdlatex-texmathp-advice-is-done
  14237. (setq org-cdlatex-texmathp-advice-is-done t)
  14238. (defadvice texmathp (around org-math-always-on activate)
  14239. "Always return t in Org buffers.
  14240. This is because we want to insert math symbols without dollars even outside
  14241. the LaTeX math segments. If Org mode thinks that point is actually inside
  14242. an embedded LaTeX fragment, let `texmathp' do its job.
  14243. `\\[org-cdlatex-mode-map]'"
  14244. (interactive)
  14245. (let (p)
  14246. (cond
  14247. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14248. ((eq this-command 'cdlatex-math-symbol)
  14249. (setq ad-return-value t
  14250. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14251. (t
  14252. (let ((p (org-inside-LaTeX-fragment-p)))
  14253. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14254. (setq ad-return-value t
  14255. texmathp-why '("Org mode embedded math" . 0))
  14256. (when p ad-do-it)))))))))
  14257. (defun turn-on-org-cdlatex ()
  14258. "Unconditionally turn on `org-cdlatex-mode'."
  14259. (org-cdlatex-mode 1))
  14260. (defun org-try-cdlatex-tab ()
  14261. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14262. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14263. - inside a LaTeX fragment, or
  14264. - after the first word in a line, where an abbreviation expansion could
  14265. insert a LaTeX environment."
  14266. (when org-cdlatex-mode
  14267. (cond
  14268. ;; Before any word on the line: No expansion possible.
  14269. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14270. ;; Just after first word on the line: Expand it. Make sure it
  14271. ;; cannot happen on headlines, though.
  14272. ((save-excursion
  14273. (skip-chars-backward "a-zA-Z0-9*")
  14274. (skip-chars-backward " \t")
  14275. (and (bolp) (not (org-at-heading-p))))
  14276. (cdlatex-tab) t)
  14277. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14278. (defun org-cdlatex-underscore-caret (&optional _arg)
  14279. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14280. Revert to the normal definition outside of these fragments."
  14281. (interactive "P")
  14282. (if (org-inside-LaTeX-fragment-p)
  14283. (call-interactively 'cdlatex-sub-superscript)
  14284. (let (org-cdlatex-mode)
  14285. (call-interactively (key-binding (vector last-input-event))))))
  14286. (defun org-cdlatex-math-modify (&optional _arg)
  14287. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14288. Revert to the normal definition outside of these fragments."
  14289. (interactive "P")
  14290. (if (org-inside-LaTeX-fragment-p)
  14291. (call-interactively 'cdlatex-math-modify)
  14292. (let (org-cdlatex-mode)
  14293. (call-interactively (key-binding (vector last-input-event))))))
  14294. (defun org-cdlatex-environment-indent (&optional environment item)
  14295. "Execute `cdlatex-environment' and indent the inserted environment.
  14296. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14297. The inserted environment is indented to current indentation
  14298. unless point is at the beginning of the line, in which the
  14299. environment remains unintended."
  14300. (interactive)
  14301. ;; cdlatex-environment always return nil. Therefore, capture output
  14302. ;; first and determine if an environment was selected.
  14303. (let* ((beg (point-marker))
  14304. (end (copy-marker (point) t))
  14305. (inserted (progn
  14306. (ignore-errors (cdlatex-environment environment item))
  14307. (< beg end)))
  14308. ;; Figure out how many lines to move forward after the
  14309. ;; environment has been inserted.
  14310. (lines (when inserted
  14311. (save-excursion
  14312. (- (cl-loop while (< beg (point))
  14313. with x = 0
  14314. do (forward-line -1)
  14315. (cl-incf x)
  14316. finally return x)
  14317. (if (progn (goto-char beg)
  14318. (and (progn (skip-chars-forward " \t") (eolp))
  14319. (progn (skip-chars-backward " \t") (bolp))))
  14320. 1 0)))))
  14321. (env (org-trim (delete-and-extract-region beg end))))
  14322. (when inserted
  14323. ;; Get indentation of next line unless at column 0.
  14324. (let ((ind (if (bolp) 0
  14325. (save-excursion
  14326. (org-return t)
  14327. (prog1 (current-indentation)
  14328. (when (progn (skip-chars-forward " \t") (eolp))
  14329. (delete-region beg (point)))))))
  14330. (bol (progn (skip-chars-backward " \t") (bolp))))
  14331. ;; Insert a newline before environment unless at column zero
  14332. ;; to "escape" the current line. Insert a newline if
  14333. ;; something is one the same line as \end{ENVIRONMENT}.
  14334. (insert
  14335. (concat (unless bol "\n") env
  14336. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14337. (unless (zerop ind)
  14338. (save-excursion
  14339. (goto-char beg)
  14340. (while (< (point) end)
  14341. (unless (eolp) (indent-line-to ind))
  14342. (forward-line))))
  14343. (goto-char beg)
  14344. (forward-line lines)
  14345. (indent-line-to ind)))
  14346. (set-marker beg nil)
  14347. (set-marker end nil)))
  14348. ;;;; LaTeX fragments
  14349. (defun org-inside-LaTeX-fragment-p ()
  14350. "Test if point is inside a LaTeX fragment.
  14351. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14352. sequence appearing also before point.
  14353. Even though the matchers for math are configurable, this function assumes
  14354. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14355. delimiters are skipped when they have been removed by customization.
  14356. The return value is nil, or a cons cell with the delimiter and the
  14357. position of this delimiter.
  14358. This function does a reasonably good job, but can locally be fooled by
  14359. for example currency specifications. For example it will assume being in
  14360. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14361. fragments that are properly closed, but during editing, we have to live
  14362. with the uncertainty caused by missing closing delimiters. This function
  14363. looks only before point, not after."
  14364. (catch 'exit
  14365. (let ((pos (point))
  14366. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14367. (lim (progn
  14368. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14369. 'move)
  14370. (point)))
  14371. dd-on str (start 0) m re)
  14372. (goto-char pos)
  14373. (when dodollar
  14374. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14375. re (nth 1 (assoc "$" org-latex-regexps)))
  14376. (while (string-match re str start)
  14377. (cond
  14378. ((= (match-end 0) (length str))
  14379. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14380. ((= (match-end 0) (- (length str) 5))
  14381. (throw 'exit nil))
  14382. (t (setq start (match-end 0))))))
  14383. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14384. (goto-char pos)
  14385. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14386. (and (match-beginning 2) (throw 'exit nil))
  14387. ;; count $$
  14388. (while (re-search-backward "\\$\\$" lim t)
  14389. (setq dd-on (not dd-on)))
  14390. (goto-char pos)
  14391. (when dd-on (cons "$$" m))))))
  14392. (defun org-inside-latex-macro-p ()
  14393. "Is point inside a LaTeX macro or its arguments?"
  14394. (save-match-data
  14395. (org-in-regexp
  14396. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14397. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14398. "Build an overlay between BEG and END using IMAGE file.
  14399. Argument IMAGETYPE is the extension of the displayed image,
  14400. as a string. It defaults to \"png\"."
  14401. (let ((ov (make-overlay beg end))
  14402. (imagetype (or (intern imagetype) 'png)))
  14403. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14404. (overlay-put ov 'evaporate t)
  14405. (overlay-put ov
  14406. 'modification-hooks
  14407. (list (lambda (o _flag _beg _end &optional _l)
  14408. (delete-overlay o))))
  14409. (overlay-put ov
  14410. 'display
  14411. (list 'image :type imagetype :file image :ascent 'center))))
  14412. (defun org-clear-latex-preview (&optional beg end)
  14413. "Remove all overlays with LaTeX fragment images in current buffer.
  14414. When optional arguments BEG and END are non-nil, remove all
  14415. overlays between them instead. Return a non-nil value when some
  14416. overlays were removed, nil otherwise."
  14417. (let ((overlays
  14418. (cl-remove-if-not
  14419. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14420. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14421. (mapc #'delete-overlay overlays)
  14422. overlays))
  14423. (defun org--latex-preview-region (beg end)
  14424. "Preview LaTeX fragments between BEG and END.
  14425. BEG and END are buffer positions."
  14426. (let ((file (buffer-file-name (buffer-base-buffer))))
  14427. (save-excursion
  14428. (org-format-latex
  14429. (concat org-preview-latex-image-directory "org-ltximg")
  14430. beg end
  14431. ;; Emacs cannot overlay images from remote hosts. Create it in
  14432. ;; `temporary-file-directory' instead.
  14433. (if (or (not file) (file-remote-p file))
  14434. temporary-file-directory
  14435. default-directory)
  14436. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14437. (defun org-latex-preview (&optional arg)
  14438. "Toggle preview of the LaTeX fragment at point.
  14439. If the cursor is on a LaTeX fragment, create the image and
  14440. overlay it over the source code, if there is none. Remove it
  14441. otherwise. If there is no fragment at point, display images for
  14442. all fragments in the current section.
  14443. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14444. for all fragments
  14445. in the current section.
  14446. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14447. argument ARG, display image for all
  14448. fragments in the buffer.
  14449. With a `\\[universal-argument] \\[universal-argument] \
  14450. \\[universal-argument]' prefix argument ARG, clear image for all
  14451. fragments in the buffer."
  14452. (interactive "P")
  14453. (cond
  14454. ((not (display-graphic-p)) nil)
  14455. ;; Clear whole buffer.
  14456. ((equal arg '(64))
  14457. (org-clear-latex-preview (point-min) (point-max))
  14458. (message "LaTeX previews removed from buffer"))
  14459. ;; Preview whole buffer.
  14460. ((equal arg '(16))
  14461. (message "Creating LaTeX previews in buffer...")
  14462. (org--latex-preview-region (point-min) (point-max))
  14463. (message "Creating LaTeX previews in buffer... done."))
  14464. ;; Clear current section.
  14465. ((equal arg '(4))
  14466. (org-clear-latex-preview
  14467. (if (org-before-first-heading-p) (point-min)
  14468. (save-excursion
  14469. (org-with-limited-levels (org-back-to-heading t) (point))))
  14470. (org-with-limited-levels (org-entry-end-position))))
  14471. ;; Toggle preview on LaTeX code at point.
  14472. ((let ((datum (org-element-context)))
  14473. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14474. (let ((beg (org-element-property :begin datum))
  14475. (end (org-element-property :end datum)))
  14476. (if (org-clear-latex-preview beg end)
  14477. (message "LaTeX preview removed")
  14478. (message "Creating LaTeX preview...")
  14479. (org--latex-preview-region beg end)
  14480. (message "Creating LaTeX preview... done."))
  14481. t))))
  14482. ;; Preview current section.
  14483. (t
  14484. (let ((beg (if (org-before-first-heading-p) (point-min)
  14485. (save-excursion
  14486. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14487. (end (org-with-limited-levels (org-entry-end-position))))
  14488. (message "Creating LaTeX previews in section...")
  14489. (org--latex-preview-region beg end)
  14490. (message "Creating LaTeX previews in section... done.")))))
  14491. (defun org-format-latex
  14492. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14493. "Replace LaTeX fragments with links to an image.
  14494. The function takes care of creating the replacement image.
  14495. Only consider fragments between BEG and END when those are
  14496. provided.
  14497. When optional argument OVERLAYS is non-nil, display the image on
  14498. top of the fragment instead of replacing it.
  14499. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14500. Some of the options can be changed using the variable
  14501. `org-format-latex-options', which see."
  14502. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14503. (unless (eq processing-type 'verbatim)
  14504. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14505. (cnt 0)
  14506. checkdir-flag)
  14507. (goto-char (or beg (point-min)))
  14508. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14509. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14510. (overlay-recenter (or end (point-max))))
  14511. (while (re-search-forward math-regexp end t)
  14512. (unless (and overlays
  14513. (eq (get-char-property (point) 'org-overlay-type)
  14514. 'org-latex-overlay))
  14515. (let* ((context (org-element-context))
  14516. (type (org-element-type context)))
  14517. (when (memq type '(latex-environment latex-fragment))
  14518. (let ((block-type (eq type 'latex-environment))
  14519. (value (org-element-property :value context))
  14520. (beg (org-element-property :begin context))
  14521. (end (save-excursion
  14522. (goto-char (org-element-property :end context))
  14523. (skip-chars-backward " \r\t\n")
  14524. (point))))
  14525. (cond
  14526. ((eq processing-type 'mathjax)
  14527. ;; Prepare for MathJax processing.
  14528. (if (not (string-match "\\`\\$\\$?" value))
  14529. (goto-char end)
  14530. (delete-region beg end)
  14531. (if (string= (match-string 0 value) "$$")
  14532. (insert "\\[" (substring value 2 -2) "\\]")
  14533. (insert "\\(" (substring value 1 -1) "\\)"))))
  14534. ((eq processing-type 'html)
  14535. (goto-char beg)
  14536. (delete-region beg end)
  14537. (insert (org-format-latex-as-html value)))
  14538. ((assq processing-type org-preview-latex-process-alist)
  14539. ;; Process to an image.
  14540. (cl-incf cnt)
  14541. (goto-char beg)
  14542. (let* ((processing-info
  14543. (cdr (assq processing-type org-preview-latex-process-alist)))
  14544. (face (face-at-point))
  14545. ;; Get the colors from the face at point.
  14546. (fg
  14547. (let ((color (plist-get org-format-latex-options
  14548. :foreground)))
  14549. (if (and forbuffer (eq color 'auto))
  14550. (face-attribute face :foreground nil 'default)
  14551. color)))
  14552. (bg
  14553. (let ((color (plist-get org-format-latex-options
  14554. :background)))
  14555. (if (and forbuffer (eq color 'auto))
  14556. (face-attribute face :background nil 'default)
  14557. color)))
  14558. (hash (sha1 (prin1-to-string
  14559. (list org-format-latex-header
  14560. org-latex-default-packages-alist
  14561. org-latex-packages-alist
  14562. org-format-latex-options
  14563. forbuffer value fg bg))))
  14564. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14565. (absprefix (expand-file-name prefix dir))
  14566. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14567. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14568. (sep (and block-type "\n\n"))
  14569. (link (concat sep "[[file:" linkfile "]]" sep))
  14570. (options
  14571. (org-combine-plists
  14572. org-format-latex-options
  14573. `(:foreground ,fg :background ,bg))))
  14574. (when msg (message msg cnt))
  14575. (unless checkdir-flag ; Ensure the directory exists.
  14576. (setq checkdir-flag t)
  14577. (let ((todir (file-name-directory absprefix)))
  14578. (unless (file-directory-p todir)
  14579. (make-directory todir t))))
  14580. (unless (file-exists-p movefile)
  14581. (org-create-formula-image
  14582. value movefile options forbuffer processing-type))
  14583. (if overlays
  14584. (progn
  14585. (dolist (o (overlays-in beg end))
  14586. (when (eq (overlay-get o 'org-overlay-type)
  14587. 'org-latex-overlay)
  14588. (delete-overlay o)))
  14589. (org--make-preview-overlay beg end movefile imagetype)
  14590. (goto-char end))
  14591. (delete-region beg end)
  14592. (insert
  14593. (org-add-props link
  14594. (list 'org-latex-src
  14595. (replace-regexp-in-string "\"" "" value)
  14596. 'org-latex-src-embed-type
  14597. (if block-type 'paragraph 'character)))))))
  14598. ((eq processing-type 'mathml)
  14599. ;; Process to MathML.
  14600. (unless (org-format-latex-mathml-available-p)
  14601. (user-error "LaTeX to MathML converter not configured"))
  14602. (cl-incf cnt)
  14603. (when msg (message msg cnt))
  14604. (goto-char beg)
  14605. (delete-region beg end)
  14606. (insert (org-format-latex-as-mathml
  14607. value block-type prefix dir)))
  14608. (t
  14609. (error "Unknown conversion process %s for LaTeX fragments"
  14610. processing-type)))))))))))
  14611. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14612. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14613. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14614. successful, return the portion between \"<math...> </math>\"
  14615. elements otherwise return nil. When MATHML-FILE is specified,
  14616. write the results in to that file. When invoked as an
  14617. interactive command, prompt for LATEX-FRAG, with initial value
  14618. set to the current active region and echo the results for user
  14619. inspection."
  14620. (interactive (list (let ((frag (when (org-region-active-p)
  14621. (buffer-substring-no-properties
  14622. (region-beginning) (region-end)))))
  14623. (read-string "LaTeX Fragment: " frag nil frag))))
  14624. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14625. (let* ((tmp-in-file
  14626. (let ((file (file-relative-name
  14627. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14628. (write-region latex-frag nil file)
  14629. file))
  14630. (tmp-out-file (file-relative-name
  14631. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14632. (cmd (format-spec
  14633. org-latex-to-mathml-convert-command
  14634. `((?j . ,(and org-latex-to-mathml-jar-file
  14635. (shell-quote-argument
  14636. (expand-file-name
  14637. org-latex-to-mathml-jar-file))))
  14638. (?I . ,(shell-quote-argument tmp-in-file))
  14639. (?i . ,latex-frag)
  14640. (?o . ,(shell-quote-argument tmp-out-file)))))
  14641. mathml shell-command-output)
  14642. (when (called-interactively-p 'any)
  14643. (unless (org-format-latex-mathml-available-p)
  14644. (user-error "LaTeX to MathML converter not configured")))
  14645. (message "Running %s" cmd)
  14646. (setq shell-command-output (shell-command-to-string cmd))
  14647. (setq mathml
  14648. (when (file-readable-p tmp-out-file)
  14649. (with-current-buffer (find-file-noselect tmp-out-file t)
  14650. (goto-char (point-min))
  14651. (when (re-search-forward
  14652. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14653. (regexp-quote
  14654. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14655. nil t)
  14656. (prog1 (match-string 0) (kill-buffer))))))
  14657. (cond
  14658. (mathml
  14659. (setq mathml
  14660. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14661. (when mathml-file
  14662. (write-region mathml nil mathml-file))
  14663. (when (called-interactively-p 'any)
  14664. (message mathml)))
  14665. ((warn "LaTeX to MathML conversion failed")
  14666. (message shell-command-output)))
  14667. (delete-file tmp-in-file)
  14668. (when (file-exists-p tmp-out-file)
  14669. (delete-file tmp-out-file))
  14670. mathml))
  14671. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14672. prefix &optional dir)
  14673. "Use `org-create-math-formula' but check local cache first."
  14674. (let* ((absprefix (expand-file-name prefix dir))
  14675. (print-length nil) (print-level nil)
  14676. (formula-id (concat
  14677. "formula-"
  14678. (sha1
  14679. (prin1-to-string
  14680. (list latex-frag
  14681. org-latex-to-mathml-convert-command)))))
  14682. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14683. (formula-cache-dir (file-name-directory formula-cache)))
  14684. (unless (file-directory-p formula-cache-dir)
  14685. (make-directory formula-cache-dir t))
  14686. (unless (file-exists-p formula-cache)
  14687. (org-create-math-formula latex-frag formula-cache))
  14688. (if (file-exists-p formula-cache)
  14689. ;; Successful conversion. Return the link to MathML file.
  14690. (org-add-props
  14691. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14692. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14693. 'org-latex-src-embed-type (if latex-frag-type
  14694. 'paragraph 'character)))
  14695. ;; Failed conversion. Return the LaTeX fragment verbatim
  14696. latex-frag)))
  14697. (defun org-format-latex-as-html (latex-fragment)
  14698. "Convert LATEX-FRAGMENT to HTML.
  14699. This uses `org-latex-to-html-convert-command', which see."
  14700. (let ((cmd (format-spec org-latex-to-html-convert-command
  14701. `((?i . ,latex-fragment)))))
  14702. (message "Running %s" cmd)
  14703. (shell-command-to-string cmd)))
  14704. (defun org--get-display-dpi ()
  14705. "Get the DPI of the display.
  14706. The function assumes that the display has the same pixel width in
  14707. the horizontal and vertical directions."
  14708. (if (display-graphic-p)
  14709. (round (/ (display-pixel-height)
  14710. (/ (display-mm-height) 25.4)))
  14711. (error "Attempt to calculate the dpi of a non-graphic display")))
  14712. (defun org-create-formula-image
  14713. (string tofile options buffer &optional processing-type)
  14714. "Create an image from LaTeX source using external processes.
  14715. The LaTeX STRING is saved to a temporary LaTeX file, then
  14716. converted to an image file by process PROCESSING-TYPE defined in
  14717. `org-preview-latex-process-alist'. A nil value defaults to
  14718. `org-preview-latex-default-process'.
  14719. The generated image file is eventually moved to TOFILE.
  14720. The OPTIONS argument controls the size, foreground color and
  14721. background color of the generated image.
  14722. When BUFFER non-nil, this function is used for LaTeX previewing.
  14723. Otherwise, it is used to deal with LaTeX snippets showed in
  14724. a HTML file."
  14725. (let* ((processing-type (or processing-type
  14726. org-preview-latex-default-process))
  14727. (processing-info
  14728. (cdr (assq processing-type org-preview-latex-process-alist)))
  14729. (programs (plist-get processing-info :programs))
  14730. (error-message (or (plist-get processing-info :message) ""))
  14731. (image-input-type (plist-get processing-info :image-input-type))
  14732. (image-output-type (plist-get processing-info :image-output-type))
  14733. (post-clean (or (plist-get processing-info :post-clean)
  14734. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14735. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14736. (latex-header
  14737. (or (plist-get processing-info :latex-header)
  14738. (org-latex-make-preamble
  14739. (org-export-get-environment (org-export-get-backend 'latex))
  14740. org-format-latex-header
  14741. 'snippet)))
  14742. (latex-compiler (plist-get processing-info :latex-compiler))
  14743. (image-converter (plist-get processing-info :image-converter))
  14744. (tmpdir temporary-file-directory)
  14745. (texfilebase (make-temp-name
  14746. (expand-file-name "orgtex" tmpdir)))
  14747. (texfile (concat texfilebase ".tex"))
  14748. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14749. '(1.0 . 1.0)))
  14750. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14751. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14752. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14753. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14754. "Black"))
  14755. (bg (or (plist-get options (if buffer :background :html-background))
  14756. "Transparent"))
  14757. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14758. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14759. (dolist (program programs)
  14760. (org-check-external-command program error-message))
  14761. (if (eq fg 'default)
  14762. (setq fg (org-latex-color :foreground))
  14763. (setq fg (org-latex-color-format fg)))
  14764. (setq bg (cond
  14765. ((eq bg 'default) (org-latex-color :background))
  14766. ((string= bg "Transparent") nil)
  14767. (t (org-latex-color-format bg))))
  14768. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14769. (if (string-suffix-p string "\n")
  14770. (aset string (1- (length string)) ?%)
  14771. (setq string (concat string "%")))
  14772. (with-temp-file texfile
  14773. (insert latex-header)
  14774. (insert "\n\\begin{document}\n"
  14775. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14776. (if bg
  14777. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14778. "\n\\pagecolor{bg}%\n")
  14779. "")
  14780. "\n{\\color{fg}\n"
  14781. string
  14782. "\n}\n"
  14783. "\n\\end{document}\n"))
  14784. (let* ((err-msg (format "Please adjust `%s' part of \
  14785. `org-preview-latex-process-alist'."
  14786. processing-type))
  14787. (image-input-file
  14788. (org-compile-file
  14789. texfile latex-compiler image-input-type err-msg log-buf))
  14790. (image-output-file
  14791. (org-compile-file
  14792. image-input-file image-converter image-output-type err-msg log-buf
  14793. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14794. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14795. (copy-file image-output-file tofile 'replace)
  14796. (dolist (e post-clean)
  14797. (when (file-exists-p (concat texfilebase e))
  14798. (delete-file (concat texfilebase e))))
  14799. image-output-file)))
  14800. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14801. "Fill a LaTeX header template TPL.
  14802. In the template, the following place holders will be recognized:
  14803. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14804. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14805. [PACKAGES] \\usepackage statements for PKG
  14806. [NO-PACKAGES] do not include PKG
  14807. [EXTRA] the string EXTRA
  14808. [NO-EXTRA] do not include EXTRA
  14809. For backward compatibility, if both the positive and the negative place
  14810. holder is missing, the positive one (without the \"NO-\") will be
  14811. assumed to be present at the end of the template.
  14812. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14813. EXTRA is a string.
  14814. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14815. (let (rpl (end ""))
  14816. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14817. (setq rpl (if (or (match-end 1) (not def-pkg))
  14818. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14819. tpl (replace-match rpl t t tpl))
  14820. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14821. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14822. (setq rpl (if (or (match-end 1) (not pkg))
  14823. "" (org-latex-packages-to-string pkg snippets-p t))
  14824. tpl (replace-match rpl t t tpl))
  14825. (when pkg (setq end
  14826. (concat end "\n"
  14827. (org-latex-packages-to-string pkg snippets-p)))))
  14828. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14829. (setq rpl (if (or (match-end 1) (not extra))
  14830. "" (concat extra "\n"))
  14831. tpl (replace-match rpl t t tpl))
  14832. (when (and extra (string-match "\\S-" extra))
  14833. (setq end (concat end "\n" extra))))
  14834. (if (string-match "\\S-" end)
  14835. (concat tpl "\n" end)
  14836. tpl)))
  14837. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14838. "Turn an alist of packages into a string with the \\usepackage macros."
  14839. (setq pkg (mapconcat (lambda(p)
  14840. (cond
  14841. ((stringp p) p)
  14842. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14843. (format "%% Package %s omitted" (cadr p)))
  14844. ((equal "" (car p))
  14845. (format "\\usepackage{%s}" (cadr p)))
  14846. (t
  14847. (format "\\usepackage[%s]{%s}"
  14848. (car p) (cadr p)))))
  14849. pkg
  14850. "\n"))
  14851. (if newline (concat pkg "\n") pkg))
  14852. (defun org-dvipng-color (attr)
  14853. "Return a RGB color specification for dvipng."
  14854. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14855. (defun org-dvipng-color-format (color-name)
  14856. "Convert COLOR-NAME to a RGB color value for dvipng."
  14857. (apply #'format "rgb %s %s %s"
  14858. (mapcar 'org-normalize-color
  14859. (color-values color-name))))
  14860. (defun org-latex-color (attr)
  14861. "Return a RGB color for the LaTeX color package."
  14862. (org-latex-color-format (face-attribute 'default attr nil)))
  14863. (defun org-latex-color-format (color-name)
  14864. "Convert COLOR-NAME to a RGB color value."
  14865. (apply #'format "%s,%s,%s"
  14866. (mapcar 'org-normalize-color
  14867. (color-values color-name))))
  14868. (defun org-normalize-color (value)
  14869. "Return string to be used as color value for an RGB component."
  14870. (format "%g" (/ value 65535.0)))
  14871. ;; Image display
  14872. (defvar-local org-inline-image-overlays nil)
  14873. (defun org-toggle-inline-images (&optional include-linked)
  14874. "Toggle the display of inline images.
  14875. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14876. (interactive "P")
  14877. (if org-inline-image-overlays
  14878. (progn
  14879. (org-remove-inline-images)
  14880. (when (called-interactively-p 'interactive)
  14881. (message "Inline image display turned off")))
  14882. (org-display-inline-images include-linked)
  14883. (when (called-interactively-p 'interactive)
  14884. (message (if org-inline-image-overlays
  14885. (format "%d images displayed inline"
  14886. (length org-inline-image-overlays))
  14887. "No images to display inline")))))
  14888. (defun org-redisplay-inline-images ()
  14889. "Assure display of inline images and refresh them."
  14890. (interactive)
  14891. (org-toggle-inline-images)
  14892. (unless org-inline-image-overlays
  14893. (org-toggle-inline-images)))
  14894. ;; For without-x builds.
  14895. (declare-function image-refresh "image" (spec &optional frame))
  14896. (defcustom org-display-remote-inline-images 'skip
  14897. "How to display remote inline images.
  14898. Possible values of this option are:
  14899. skip Don't display remote images.
  14900. download Always download and display remote images.
  14901. cache Display remote images, and open them in separate buffers
  14902. for caching. Silently update the image buffer when a file
  14903. change is detected."
  14904. :group 'org-appearance
  14905. :package-version '(Org . "9.4")
  14906. :type '(choice
  14907. (const :tag "Ignore remote images" skip)
  14908. (const :tag "Always display remote images" download)
  14909. (const :tag "Display and silently update remote images" cache))
  14910. :safe #'symbolp)
  14911. (defun org--create-inline-image (file width)
  14912. "Create image located at FILE, or return nil.
  14913. WIDTH is the width of the image. The image may not be created
  14914. according to the value of `org-display-remote-inline-images'."
  14915. (let* ((remote? (file-remote-p file))
  14916. (file-or-data
  14917. (pcase org-display-remote-inline-images
  14918. ((guard (not remote?)) file)
  14919. (`download (with-temp-buffer
  14920. (set-buffer-multibyte nil)
  14921. (insert-file-contents-literally file)
  14922. (buffer-string)))
  14923. (`cache (let ((revert-without-query '(".")))
  14924. (with-current-buffer (find-file-noselect file)
  14925. (buffer-string))))
  14926. (`skip nil)
  14927. (other
  14928. (message "Invalid value of `org-display-remote-inline-images': %S"
  14929. other)
  14930. nil))))
  14931. (when file-or-data
  14932. (create-image file-or-data
  14933. (and (image-type-available-p 'imagemagick)
  14934. width
  14935. 'imagemagick)
  14936. remote?
  14937. :width width))))
  14938. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14939. "Display inline images.
  14940. An inline image is a link which follows either of these
  14941. conventions:
  14942. 1. Its path is a file with an extension matching return value
  14943. from `image-file-name-regexp' and it has no contents.
  14944. 2. Its description consists in a single link of the previous
  14945. type. In this case, that link must be a well-formed plain
  14946. or angle link, i.e., it must have an explicit \"file\" type.
  14947. Equip each image with the key-map `image-map'.
  14948. When optional argument INCLUDE-LINKED is non-nil, also links with
  14949. a text description part will be inlined. This can be nice for
  14950. a quick look at those images, but it does not reflect what
  14951. exported files will look like.
  14952. When optional argument REFRESH is non-nil, refresh existing
  14953. images between BEG and END. This will create new image displays
  14954. only if necessary.
  14955. BEG and END define the considered part. They default to the
  14956. buffer boundaries with possible narrowing."
  14957. (interactive "P")
  14958. (when (display-graphic-p)
  14959. (unless refresh
  14960. (org-remove-inline-images)
  14961. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14962. (let ((end (or end (point-max))))
  14963. (org-with-point-at (or beg (point-min))
  14964. (let* ((case-fold-search t)
  14965. (file-extension-re (image-file-name-regexp))
  14966. (link-abbrevs (mapcar #'car
  14967. (append org-link-abbrev-alist-local
  14968. org-link-abbrev-alist)))
  14969. ;; Check absolute, relative file names and explicit
  14970. ;; "file:" links. Also check link abbreviations since
  14971. ;; some might expand to "file" links.
  14972. (file-types-re
  14973. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14974. (if (not link-abbrevs) ""
  14975. (concat "\\|" (regexp-opt link-abbrevs))))))
  14976. (while (re-search-forward file-types-re end t)
  14977. (let* ((link (org-element-lineage
  14978. (save-match-data (org-element-context))
  14979. '(link) t))
  14980. (linktype (org-element-property :type link))
  14981. (inner-start (match-beginning 1))
  14982. (path
  14983. (cond
  14984. ;; No link at point; no inline image.
  14985. ((not link) nil)
  14986. ;; File link without a description. Also handle
  14987. ;; INCLUDE-LINKED here since it should have
  14988. ;; precedence over the next case. I.e., if link
  14989. ;; contains filenames in both the path and the
  14990. ;; description, prioritize the path only when
  14991. ;; INCLUDE-LINKED is non-nil.
  14992. ((or (not (org-element-property :contents-begin link))
  14993. include-linked)
  14994. (and (or (equal "file" linktype)
  14995. (equal "attachment" linktype))
  14996. (org-element-property :path link)))
  14997. ;; Link with a description. Check if description
  14998. ;; is a filename. Even if Org doesn't have syntax
  14999. ;; for those -- clickable image -- constructs, fake
  15000. ;; them, as in `org-export-insert-image-links'.
  15001. ((not inner-start) nil)
  15002. (t
  15003. (org-with-point-at inner-start
  15004. (and (looking-at
  15005. (if (char-equal ?< (char-after inner-start))
  15006. org-link-angle-re
  15007. org-link-plain-re))
  15008. ;; File name must fill the whole
  15009. ;; description.
  15010. (= (org-element-property :contents-end link)
  15011. (match-end 0))
  15012. (match-string 2)))))))
  15013. (when (and path (string-match-p file-extension-re path))
  15014. (let ((file (if (equal "attachment" linktype)
  15015. (progn
  15016. (require 'org-attach)
  15017. (ignore-errors (org-attach-expand path)))
  15018. (expand-file-name path))))
  15019. (when (and file (file-exists-p file))
  15020. (let ((width
  15021. ;; Apply `org-image-actual-width' specifications.
  15022. (cond
  15023. ((eq org-image-actual-width t) nil)
  15024. ((listp org-image-actual-width)
  15025. (or
  15026. ;; First try to find a width among
  15027. ;; attributes associated to the paragraph
  15028. ;; containing link.
  15029. (pcase (org-element-lineage link '(paragraph))
  15030. (`nil nil)
  15031. (p
  15032. (let* ((case-fold-search t)
  15033. (end (org-element-property :post-affiliated p))
  15034. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15035. (when (org-with-point-at
  15036. (org-element-property :begin p)
  15037. (re-search-forward re end t))
  15038. (string-to-number (match-string 1))))))
  15039. ;; Otherwise, fall-back to provided number.
  15040. (car org-image-actual-width)))
  15041. ((numberp org-image-actual-width)
  15042. org-image-actual-width)
  15043. (t nil)))
  15044. (old (get-char-property-and-overlay
  15045. (org-element-property :begin link)
  15046. 'org-image-overlay)))
  15047. (if (and (car-safe old) refresh)
  15048. (image-refresh (overlay-get (cdr old) 'display))
  15049. (let ((image (org--create-inline-image file width)))
  15050. (when image
  15051. (let ((ov (make-overlay
  15052. (org-element-property :begin link)
  15053. (progn
  15054. (goto-char
  15055. (org-element-property :end link))
  15056. (skip-chars-backward " \t")
  15057. (point)))))
  15058. (overlay-put ov 'display image)
  15059. (overlay-put ov 'face 'default)
  15060. (overlay-put ov 'org-image-overlay t)
  15061. (overlay-put
  15062. ov 'modification-hooks
  15063. (list 'org-display-inline-remove-overlay))
  15064. (when (<= 26 emacs-major-version)
  15065. (cl-assert (boundp 'image-map))
  15066. (overlay-put ov 'keymap image-map))
  15067. (push ov org-inline-image-overlays))))))))))))))))
  15068. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15069. "Remove inline-display overlay if a corresponding region is modified."
  15070. (let ((inhibit-modification-hooks t))
  15071. (when (and ov after)
  15072. (delete ov org-inline-image-overlays)
  15073. (delete-overlay ov))))
  15074. (defun org-remove-inline-images ()
  15075. "Remove inline display of images."
  15076. (interactive)
  15077. (mapc #'delete-overlay org-inline-image-overlays)
  15078. (setq org-inline-image-overlays nil))
  15079. (defvar org-self-insert-command-undo-counter 0)
  15080. (defvar org-speed-command nil)
  15081. (defun org-self-insert-command (N)
  15082. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15083. If the cursor is in a table looking at whitespace, the whitespace is
  15084. overwritten, and the table is not marked as requiring realignment."
  15085. (interactive "p")
  15086. (org-check-before-invisible-edit 'insert)
  15087. (cond
  15088. ((and org-use-speed-commands
  15089. (let ((kv (this-command-keys-vector)))
  15090. (setq org-speed-command
  15091. (run-hook-with-args-until-success
  15092. 'org-speed-command-hook
  15093. (make-string 1 (aref kv (1- (length kv))))))))
  15094. (cond
  15095. ((commandp org-speed-command)
  15096. (setq this-command org-speed-command)
  15097. (call-interactively org-speed-command))
  15098. ((functionp org-speed-command)
  15099. (funcall org-speed-command))
  15100. ((and org-speed-command (listp org-speed-command))
  15101. (eval org-speed-command))
  15102. (t (let (org-use-speed-commands)
  15103. (call-interactively 'org-self-insert-command)))))
  15104. ((and
  15105. (= N 1)
  15106. (not (org-region-active-p))
  15107. (org-at-table-p)
  15108. (progn
  15109. ;; Check if we blank the field, and if that triggers align.
  15110. (and (featurep 'org-table)
  15111. org-table-auto-blank-field
  15112. (memq last-command
  15113. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15114. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15115. ;; Got extra space, this field does not determine
  15116. ;; column width.
  15117. (let (org-table-may-need-update) (org-table-blank-field))
  15118. ;; No extra space, this field may determine column
  15119. ;; width.
  15120. (org-table-blank-field)))
  15121. t)
  15122. (looking-at "[^|\n]* |"))
  15123. ;; There is room for insertion without re-aligning the table.
  15124. (self-insert-command N)
  15125. (org-table-with-shrunk-field
  15126. (save-excursion
  15127. (skip-chars-forward "^|")
  15128. ;; Do not delete last space, which is
  15129. ;; `org-table-separator-space', but the regular space before
  15130. ;; it.
  15131. (delete-region (- (point) 2) (1- (point))))))
  15132. (t
  15133. (setq org-table-may-need-update t)
  15134. (self-insert-command N)
  15135. (org-fix-tags-on-the-fly)
  15136. (when org-self-insert-cluster-for-undo
  15137. (if (not (eq last-command 'org-self-insert-command))
  15138. (setq org-self-insert-command-undo-counter 1)
  15139. (if (>= org-self-insert-command-undo-counter 20)
  15140. (setq org-self-insert-command-undo-counter 1)
  15141. (and (> org-self-insert-command-undo-counter 0)
  15142. buffer-undo-list (listp buffer-undo-list)
  15143. (not (cadr buffer-undo-list)) ; remove nil entry
  15144. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15145. (setq org-self-insert-command-undo-counter
  15146. (1+ org-self-insert-command-undo-counter))))))))
  15147. (defun org-check-before-invisible-edit (kind)
  15148. "Check if editing kind KIND would be dangerous with invisible text around.
  15149. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15150. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15151. (when (and org-catch-invisible-edits
  15152. (or (not (boundp 'visible-mode)) (not visible-mode))
  15153. (or (get-char-property (point) 'invisible)
  15154. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15155. ;; OK, we need to take a closer look. Do not consider
  15156. ;; invisibility obtained through text properties (e.g., link
  15157. ;; fontification), as it cannot be toggled.
  15158. (let* ((invisible-at-point
  15159. (pcase (get-char-property-and-overlay (point) 'invisible)
  15160. (`(,_ . ,(and (pred overlayp) o)) o)))
  15161. ;; Assume that point cannot land in the middle of an
  15162. ;; overlay, or between two overlays.
  15163. (invisible-before-point
  15164. (and (not invisible-at-point)
  15165. (not (bobp))
  15166. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15167. (`(,_ . ,(and (pred overlayp) o)) o))))
  15168. (border-and-ok-direction
  15169. (or
  15170. ;; Check if we are acting predictably before invisible
  15171. ;; text.
  15172. (and invisible-at-point
  15173. (memq kind '(insert delete-backward)))
  15174. ;; Check if we are acting predictably after invisible text
  15175. ;; This works not well, and I have turned it off. It seems
  15176. ;; better to always show and stop after invisible text.
  15177. ;; (and (not invisible-at-point) invisible-before-point
  15178. ;; (memq kind '(insert delete)))
  15179. )))
  15180. (when (or invisible-at-point invisible-before-point)
  15181. (when (eq org-catch-invisible-edits 'error)
  15182. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15183. (if (and org-custom-properties-overlays
  15184. (y-or-n-p "Display invisible properties in this buffer? "))
  15185. (org-toggle-custom-properties-visibility)
  15186. ;; Make the area visible
  15187. (save-excursion
  15188. (when invisible-before-point
  15189. (goto-char
  15190. (previous-single-char-property-change (point) 'invisible)))
  15191. ;; Remove whatever overlay is currently making yet-to-be
  15192. ;; edited text invisible. Also remove nested invisibility
  15193. ;; related overlays.
  15194. (delete-overlay (or invisible-at-point invisible-before-point))
  15195. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15196. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15197. (`(,_ . ,(and (pred overlayp) o))
  15198. (delete-overlay o)
  15199. t)))))
  15200. (cond
  15201. ((eq org-catch-invisible-edits 'show)
  15202. ;; That's it, we do the edit after showing
  15203. (message
  15204. "Unfolding invisible region around point before editing")
  15205. (sit-for 1))
  15206. ((and (eq org-catch-invisible-edits 'smart)
  15207. border-and-ok-direction)
  15208. (message "Unfolding invisible region around point before editing"))
  15209. (t
  15210. ;; Don't do the edit, make the user repeat it in full visibility
  15211. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15212. (defun org-fix-tags-on-the-fly ()
  15213. "Align tags in headline at point.
  15214. Unlike `org-align-tags', this function does nothing if point is
  15215. either not currently on a tagged headline or on a tag."
  15216. (when (and (org-match-line org-tag-line-re)
  15217. (< (point) (match-beginning 1)))
  15218. (org-align-tags)))
  15219. (defun org-delete-backward-char (N)
  15220. "Like `delete-backward-char', insert whitespace at field end in tables.
  15221. When deleting backwards, in tables this function will insert whitespace in
  15222. front of the next \"|\" separator, to keep the table aligned. The table will
  15223. still be marked for re-alignment if the field did fill the entire column,
  15224. because, in this case the deletion might narrow the column."
  15225. (interactive "p")
  15226. (save-match-data
  15227. (org-check-before-invisible-edit 'delete-backward)
  15228. (if (and (= N 1)
  15229. (not overwrite-mode)
  15230. (not (org-region-active-p))
  15231. (not (eq (char-before) ?|))
  15232. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15233. (looking-at-p ".*?|")
  15234. (org-at-table-p))
  15235. (progn (forward-char -1) (org-delete-char 1))
  15236. (backward-delete-char N)
  15237. (org-fix-tags-on-the-fly))))
  15238. (defun org-delete-char (N)
  15239. "Like `delete-char', but insert whitespace at field end in tables.
  15240. When deleting characters, in tables this function will insert whitespace in
  15241. front of the next \"|\" separator, to keep the table aligned. The table will
  15242. still be marked for re-alignment if the field did fill the entire column,
  15243. because, in this case the deletion might narrow the column."
  15244. (interactive "p")
  15245. (save-match-data
  15246. (org-check-before-invisible-edit 'delete)
  15247. (cond
  15248. ((or (/= N 1)
  15249. (eq (char-after) ?|)
  15250. (save-excursion (skip-chars-backward " \t") (bolp))
  15251. (not (org-at-table-p)))
  15252. (delete-char N)
  15253. (org-fix-tags-on-the-fly))
  15254. ((looking-at ".\\(.*?\\)|")
  15255. (let* ((update? org-table-may-need-update)
  15256. (noalign (looking-at-p ".*? |")))
  15257. (delete-char 1)
  15258. (org-table-with-shrunk-field
  15259. (save-excursion
  15260. ;; Last space is `org-table-separator-space', so insert
  15261. ;; a regular one before it instead.
  15262. (goto-char (- (match-end 0) 2))
  15263. (insert " ")))
  15264. ;; If there were two spaces at the end, this field does not
  15265. ;; determine the width of the column.
  15266. (when noalign (setq org-table-may-need-update update?))))
  15267. (t
  15268. (delete-char N)))))
  15269. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15270. (put 'org-self-insert-command 'delete-selection
  15271. (lambda ()
  15272. (not (run-hook-with-args-until-success
  15273. 'self-insert-uses-region-functions))))
  15274. (put 'orgtbl-self-insert-command 'delete-selection
  15275. (lambda ()
  15276. (not (run-hook-with-args-until-success
  15277. 'self-insert-uses-region-functions))))
  15278. (put 'org-delete-char 'delete-selection 'supersede)
  15279. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15280. (put 'org-yank 'delete-selection 'yank)
  15281. ;; Make `flyspell-mode' delay after some commands
  15282. (put 'org-self-insert-command 'flyspell-delayed t)
  15283. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15284. (put 'org-delete-char 'flyspell-delayed t)
  15285. (put 'org-delete-backward-char 'flyspell-delayed t)
  15286. ;; Make pabbrev-mode expand after Org mode commands
  15287. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15288. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15289. (defun org-transpose-words ()
  15290. "Transpose words for Org.
  15291. This uses the `org-mode-transpose-word-syntax-table' syntax
  15292. table, which interprets characters in `org-emphasis-alist' as
  15293. word constituents."
  15294. (interactive)
  15295. (with-syntax-table org-mode-transpose-word-syntax-table
  15296. (call-interactively 'transpose-words)))
  15297. (defvar org-ctrl-c-ctrl-c-hook nil
  15298. "Hook for functions attaching themselves to `C-c C-c'.
  15299. This can be used to add additional functionality to the `C-c C-c'
  15300. key which executes context-dependent commands. This hook is run
  15301. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15302. run after the last test.
  15303. Each function will be called with no arguments. The function
  15304. must check if the context is appropriate for it to act. If yes,
  15305. it should do its thing and then return a non-nil value. If the
  15306. context is wrong, just do nothing and return nil.")
  15307. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15308. "Hook for functions attaching themselves to `C-c C-c'.
  15309. This can be used to add additional functionality to the `C-c C-c'
  15310. key which executes context-dependent commands. This hook is run
  15311. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15312. before the first test.
  15313. Each function will be called with no arguments. The function
  15314. must check if the context is appropriate for it to act. If yes,
  15315. it should do its thing and then return a non-nil value. If the
  15316. context is wrong, just do nothing and return nil.")
  15317. (defvar org-tab-first-hook nil
  15318. "Hook for functions to attach themselves to TAB.
  15319. See `org-ctrl-c-ctrl-c-hook' for more information.
  15320. This hook runs as the first action when TAB is pressed, even before
  15321. `org-cycle' messes around with the `outline-regexp' to cater for
  15322. inline tasks and plain list item folding.
  15323. If any function in this hook returns t, any other actions that
  15324. would have been caused by TAB (such as table field motion or visibility
  15325. cycling) will not occur.")
  15326. (defvar org-tab-after-check-for-table-hook nil
  15327. "Hook for functions to attach themselves to TAB.
  15328. See `org-ctrl-c-ctrl-c-hook' for more information.
  15329. This hook runs after it has been established that the cursor is not in a
  15330. table, but before checking if the cursor is in a headline or if global cycling
  15331. should be done.
  15332. If any function in this hook returns t, not other actions like visibility
  15333. cycling will be done.")
  15334. (defvar org-tab-after-check-for-cycling-hook nil
  15335. "Hook for functions to attach themselves to TAB.
  15336. See `org-ctrl-c-ctrl-c-hook' for more information.
  15337. This hook runs after it has been established that not table field motion and
  15338. not visibility should be done because of current context. This is probably
  15339. the place where a package like yasnippets can hook in.")
  15340. (defvar org-tab-before-tab-emulation-hook nil
  15341. "Hook for functions to attach themselves to TAB.
  15342. See `org-ctrl-c-ctrl-c-hook' for more information.
  15343. This hook runs after every other options for TAB have been exhausted, but
  15344. before indentation and \t insertion takes place.")
  15345. (defvar org-metaleft-hook nil
  15346. "Hook for functions attaching themselves to `M-left'.
  15347. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15348. (defvar org-metaright-hook nil
  15349. "Hook for functions attaching themselves to `M-right'.
  15350. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15351. (defvar org-metaup-hook nil
  15352. "Hook for functions attaching themselves to `M-up'.
  15353. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15354. (defvar org-metadown-hook nil
  15355. "Hook for functions attaching themselves to `M-down'.
  15356. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15357. (defvar org-shiftmetaleft-hook nil
  15358. "Hook for functions attaching themselves to `M-S-left'.
  15359. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15360. (defvar org-shiftmetaright-hook nil
  15361. "Hook for functions attaching themselves to `M-S-right'.
  15362. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15363. (defvar org-shiftmetaup-hook nil
  15364. "Hook for functions attaching themselves to `M-S-up'.
  15365. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15366. (defvar org-shiftmetadown-hook nil
  15367. "Hook for functions attaching themselves to `M-S-down'.
  15368. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15369. (defvar org-metareturn-hook nil
  15370. "Hook for functions attaching themselves to `M-RET'.
  15371. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15372. (defvar org-shiftup-hook nil
  15373. "Hook for functions attaching themselves to `S-up'.
  15374. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15375. (defvar org-shiftup-final-hook nil
  15376. "Hook for functions attaching themselves to `S-up'.
  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-shiftdown-hook nil
  15380. "Hook for functions attaching themselves to `S-down'.
  15381. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15382. (defvar org-shiftdown-final-hook nil
  15383. "Hook for functions attaching themselves to `S-down'.
  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-shiftleft-hook nil
  15387. "Hook for functions attaching themselves to `S-left'.
  15388. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15389. (defvar org-shiftleft-final-hook nil
  15390. "Hook for functions attaching themselves to `S-left'.
  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. (defvar org-shiftright-hook nil
  15394. "Hook for functions attaching themselves to `S-right'.
  15395. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15396. (defvar org-shiftright-final-hook nil
  15397. "Hook for functions attaching themselves to `S-right'.
  15398. This one runs after all other options except shift-select have been excluded.
  15399. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15400. (defun org-modifier-cursor-error ()
  15401. "Throw an error, a modified cursor command was applied in wrong context."
  15402. (user-error "This command is active in special context like tables, headlines or items"))
  15403. (defun org-shiftselect-error ()
  15404. "Throw an error because Shift-Cursor command was applied in wrong context."
  15405. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15406. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15407. (user-error "This command works only in special context like headlines or timestamps")))
  15408. (defun org-call-for-shift-select (cmd)
  15409. (let ((this-command-keys-shift-translated t))
  15410. (call-interactively cmd)))
  15411. (defun org-shifttab (&optional arg)
  15412. "Global visibility cycling or move to previous table field.
  15413. Call `org-table-previous-field' within a table.
  15414. When ARG is nil, cycle globally through visibility states.
  15415. When ARG is a numeric prefix, show contents of this level."
  15416. (interactive "P")
  15417. (cond
  15418. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15419. ((integerp arg)
  15420. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15421. (message "Content view to level: %d" arg)
  15422. (org-content (prefix-numeric-value arg2))
  15423. (org-cycle-show-empty-lines t)
  15424. (setq org-cycle-global-status 'overview)
  15425. (run-hook-with-args 'org-cycle-hook 'overview)))
  15426. (t (call-interactively 'org-global-cycle))))
  15427. (defun org-shiftmetaleft ()
  15428. "Promote subtree or delete table column.
  15429. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15430. `org-table-delete-column', depending on context. See the
  15431. individual commands for more information."
  15432. (interactive)
  15433. (cond
  15434. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15435. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15436. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15437. ((if (not (org-region-active-p)) (org-at-item-p)
  15438. (save-excursion (goto-char (region-beginning))
  15439. (org-at-item-p)))
  15440. (call-interactively 'org-outdent-item-tree))
  15441. (t (org-modifier-cursor-error))))
  15442. (defun org-shiftmetaright ()
  15443. "Demote subtree or insert table column.
  15444. Calls `org-demote-subtree', `org-indent-item-tree', or
  15445. `org-table-insert-column', depending on context. See the
  15446. individual commands for more information."
  15447. (interactive)
  15448. (cond
  15449. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15450. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15451. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15452. ((if (not (org-region-active-p)) (org-at-item-p)
  15453. (save-excursion (goto-char (region-beginning))
  15454. (org-at-item-p)))
  15455. (call-interactively 'org-indent-item-tree))
  15456. (t (org-modifier-cursor-error))))
  15457. (defun org-shiftmetaup (&optional _arg)
  15458. "Drag the line at point up.
  15459. In a table, kill the current row.
  15460. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15461. but also adjust the previous clocked item in the clock history.
  15462. Everywhere else, drag the line at point up."
  15463. (interactive "P")
  15464. (cond
  15465. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15466. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15467. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15468. (call-interactively 'org-timestamp-up)))
  15469. (t (call-interactively 'org-drag-line-backward))))
  15470. (defun org-shiftmetadown (&optional _arg)
  15471. "Drag the line at point down.
  15472. In a table, insert an empty row at the current line.
  15473. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15474. but also adjust the previous clocked item in the clock history.
  15475. Everywhere else, drag the line at point down."
  15476. (interactive "P")
  15477. (cond
  15478. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15479. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15480. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15481. (call-interactively 'org-timestamp-down)))
  15482. (t (call-interactively 'org-drag-line-forward))))
  15483. (defsubst org-hidden-tree-error ()
  15484. (user-error
  15485. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15486. (defun org-metaleft (&optional _arg)
  15487. "Promote heading, list item at point or move table column left.
  15488. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15489. depending on context. With no specific context, calls the Emacs
  15490. default `backward-word'. See the individual commands for more
  15491. information.
  15492. This function runs the hook `org-metaleft-hook' as a first step,
  15493. and returns at first non-nil value."
  15494. (interactive "P")
  15495. (cond
  15496. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15497. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15498. ((org-with-limited-levels
  15499. (or (org-at-heading-p)
  15500. (and (org-region-active-p)
  15501. (save-excursion
  15502. (goto-char (region-beginning))
  15503. (org-at-heading-p)))))
  15504. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15505. (call-interactively 'org-do-promote))
  15506. ;; At an inline task.
  15507. ((org-at-heading-p)
  15508. (call-interactively 'org-inlinetask-promote))
  15509. ((or (org-at-item-p)
  15510. (and (org-region-active-p)
  15511. (save-excursion
  15512. (goto-char (region-beginning))
  15513. (org-at-item-p))))
  15514. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15515. (call-interactively 'org-outdent-item))
  15516. (t (call-interactively 'backward-word))))
  15517. (defun org-metaright (&optional _arg)
  15518. "Demote heading, list item at point or move table column right.
  15519. In front of a drawer or a block keyword, indent it correctly.
  15520. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15521. `org-indent-drawer' or `org-indent-block' depending on context.
  15522. With no specific context, calls the Emacs default `forward-word'.
  15523. See the individual commands for more information.
  15524. This function runs the hook `org-metaright-hook' as a first step,
  15525. and returns at first non-nil value."
  15526. (interactive "P")
  15527. (cond
  15528. ((run-hook-with-args-until-success 'org-metaright-hook))
  15529. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15530. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15531. ((org-at-block-p) (call-interactively 'org-indent-block))
  15532. ((org-with-limited-levels
  15533. (or (org-at-heading-p)
  15534. (and (org-region-active-p)
  15535. (save-excursion
  15536. (goto-char (region-beginning))
  15537. (org-at-heading-p)))))
  15538. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15539. (call-interactively 'org-do-demote))
  15540. ;; At an inline task.
  15541. ((org-at-heading-p)
  15542. (call-interactively 'org-inlinetask-demote))
  15543. ((or (org-at-item-p)
  15544. (and (org-region-active-p)
  15545. (save-excursion
  15546. (goto-char (region-beginning))
  15547. (org-at-item-p))))
  15548. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15549. (call-interactively 'org-indent-item))
  15550. (t (call-interactively 'forward-word))))
  15551. (defun org-check-for-hidden (what)
  15552. "Check if there are hidden headlines/items in the current visual line.
  15553. WHAT can be either `headlines' or `items'. If the current line is
  15554. an outline or item heading and it has a folded subtree below it,
  15555. this function returns t, nil otherwise."
  15556. (let ((re (cond
  15557. ((eq what 'headlines) org-outline-regexp-bol)
  15558. ((eq what 'items) (org-item-beginning-re))
  15559. (t (error "This should not happen"))))
  15560. beg end)
  15561. (save-excursion
  15562. (catch 'exit
  15563. (unless (org-region-active-p)
  15564. (setq beg (point-at-bol))
  15565. (beginning-of-line 2)
  15566. (while (and (not (eobp)) ;; this is like `next-line'
  15567. (get-char-property (1- (point)) 'invisible))
  15568. (beginning-of-line 2))
  15569. (setq end (point))
  15570. (goto-char beg)
  15571. (goto-char (point-at-eol))
  15572. (setq end (max end (point)))
  15573. (while (re-search-forward re end t)
  15574. (when (get-char-property (match-beginning 0) 'invisible)
  15575. (throw 'exit t))))
  15576. nil))))
  15577. (defun org-metaup (&optional _arg)
  15578. "Move subtree up or move table row up.
  15579. Calls `org-move-subtree-up' or `org-table-move-row' or
  15580. `org-move-item-up', depending on context. See the individual commands
  15581. for more information."
  15582. (interactive "P")
  15583. (cond
  15584. ((run-hook-with-args-until-success 'org-metaup-hook))
  15585. ((org-region-active-p)
  15586. (let* ((a (save-excursion
  15587. (goto-char (min (region-beginning) (region-end)))
  15588. (line-beginning-position)))
  15589. (b (save-excursion
  15590. (goto-char (max (region-beginning) (region-end)))
  15591. (if (bolp) (1- (point)) (line-end-position))))
  15592. (c (save-excursion
  15593. (goto-char a)
  15594. (move-beginning-of-line 0)
  15595. (point)))
  15596. (d (save-excursion
  15597. (goto-char a)
  15598. (move-end-of-line 0)
  15599. (point))))
  15600. (transpose-regions a b c d)
  15601. (goto-char c)))
  15602. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15603. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15604. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15605. (t (org-drag-element-backward))))
  15606. (defun org-metadown (&optional _arg)
  15607. "Move subtree down or move table row down.
  15608. Calls `org-move-subtree-down' or `org-table-move-row' or
  15609. `org-move-item-down', depending on context. See the individual
  15610. commands for more information."
  15611. (interactive "P")
  15612. (cond
  15613. ((run-hook-with-args-until-success 'org-metadown-hook))
  15614. ((org-region-active-p)
  15615. (let* ((a (save-excursion
  15616. (goto-char (min (region-beginning) (region-end)))
  15617. (line-beginning-position)))
  15618. (b (save-excursion
  15619. (goto-char (max (region-beginning) (region-end)))
  15620. (if (bolp) (1- (point)) (line-end-position))))
  15621. (c (save-excursion
  15622. (goto-char b)
  15623. (move-beginning-of-line (if (bolp) 1 2))
  15624. (point)))
  15625. (d (save-excursion
  15626. (goto-char b)
  15627. (move-end-of-line (if (bolp) 1 2))
  15628. (point))))
  15629. (transpose-regions a b c d)
  15630. (goto-char d)))
  15631. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15632. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15633. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15634. (t (org-drag-element-forward))))
  15635. (defun org-shiftup (&optional arg)
  15636. "Act on current element according to context.
  15637. Call `org-timestamp-up' or `org-priority-up', or
  15638. `org-previous-item', or `org-table-move-cell-up'. See the
  15639. individual commands for more information."
  15640. (interactive "P")
  15641. (cond
  15642. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15643. ((and org-support-shift-select (org-region-active-p))
  15644. (org-call-for-shift-select 'previous-line))
  15645. ((org-at-timestamp-p 'lax)
  15646. (call-interactively (if org-edit-timestamp-down-means-later
  15647. 'org-timestamp-down 'org-timestamp-up)))
  15648. ((and (not (eq org-support-shift-select 'always))
  15649. org-priority-enable-commands
  15650. (org-at-heading-p))
  15651. (call-interactively 'org-priority-up))
  15652. ((and (not org-support-shift-select) (org-at-item-p))
  15653. (call-interactively 'org-previous-item))
  15654. ((org-clocktable-try-shift 'up arg))
  15655. ((and (not (eq org-support-shift-select 'always))
  15656. (org-at-table-p))
  15657. (org-table-move-cell-up))
  15658. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15659. (org-support-shift-select
  15660. (org-call-for-shift-select 'previous-line))
  15661. (t (org-shiftselect-error))))
  15662. (defun org-shiftdown (&optional arg)
  15663. "Act on current element according to context.
  15664. Call `org-timestamp-down' or `org-priority-down', or
  15665. `org-next-item', or `org-table-move-cell-down'. See the
  15666. individual commands for more information."
  15667. (interactive "P")
  15668. (cond
  15669. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15670. ((and org-support-shift-select (org-region-active-p))
  15671. (org-call-for-shift-select 'next-line))
  15672. ((org-at-timestamp-p 'lax)
  15673. (call-interactively (if org-edit-timestamp-down-means-later
  15674. 'org-timestamp-up 'org-timestamp-down)))
  15675. ((and (not (eq org-support-shift-select 'always))
  15676. org-priority-enable-commands
  15677. (org-at-heading-p))
  15678. (call-interactively 'org-priority-down))
  15679. ((and (not org-support-shift-select) (org-at-item-p))
  15680. (call-interactively 'org-next-item))
  15681. ((org-clocktable-try-shift 'down arg))
  15682. ((and (not (eq org-support-shift-select 'always))
  15683. (org-at-table-p))
  15684. (org-table-move-cell-down))
  15685. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15686. (org-support-shift-select
  15687. (org-call-for-shift-select 'next-line))
  15688. (t (org-shiftselect-error))))
  15689. (defun org-shiftright (&optional arg)
  15690. "Act on the current element according to context.
  15691. This does one of the following:
  15692. - switch a timestamp at point one day into the future
  15693. - on a headline, switch to the next TODO keyword
  15694. - on an item, switch entire list to the next bullet type
  15695. - on a property line, switch to the next allowed value
  15696. - on a clocktable definition line, move time block into the future
  15697. - in a table, move a single cell right"
  15698. (interactive "P")
  15699. (cond
  15700. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15701. ((and org-support-shift-select (org-region-active-p))
  15702. (org-call-for-shift-select 'forward-char))
  15703. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15704. ((and (not (eq org-support-shift-select 'always))
  15705. (org-at-heading-p))
  15706. (let ((org-inhibit-logging
  15707. (not org-treat-S-cursor-todo-selection-as-state-change))
  15708. (org-inhibit-blocking
  15709. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15710. (org-call-with-arg 'org-todo 'right)))
  15711. ((or (and org-support-shift-select
  15712. (not (eq org-support-shift-select 'always))
  15713. (org-at-item-bullet-p))
  15714. (and (not org-support-shift-select) (org-at-item-p)))
  15715. (org-call-with-arg 'org-cycle-list-bullet nil))
  15716. ((and (not (eq org-support-shift-select 'always))
  15717. (org-at-property-p))
  15718. (call-interactively 'org-property-next-allowed-value))
  15719. ((org-clocktable-try-shift 'right arg))
  15720. ((and (not (eq org-support-shift-select 'always))
  15721. (org-at-table-p))
  15722. (org-table-move-cell-right))
  15723. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15724. (org-support-shift-select
  15725. (org-call-for-shift-select 'forward-char))
  15726. (t (org-shiftselect-error))))
  15727. (defun org-shiftleft (&optional arg)
  15728. "Act on current element according to context.
  15729. This does one of the following:
  15730. - switch a timestamp at point one day into the past
  15731. - on a headline, switch to the previous TODO keyword.
  15732. - on an item, switch entire list to the previous bullet type
  15733. - on a property line, switch to the previous allowed value
  15734. - on a clocktable definition line, move time block into the past
  15735. - in a table, move a single cell left"
  15736. (interactive "P")
  15737. (cond
  15738. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15739. ((and org-support-shift-select (org-region-active-p))
  15740. (org-call-for-shift-select 'backward-char))
  15741. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15742. ((and (not (eq org-support-shift-select 'always))
  15743. (org-at-heading-p))
  15744. (let ((org-inhibit-logging
  15745. (not org-treat-S-cursor-todo-selection-as-state-change))
  15746. (org-inhibit-blocking
  15747. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15748. (org-call-with-arg 'org-todo 'left)))
  15749. ((or (and org-support-shift-select
  15750. (not (eq org-support-shift-select 'always))
  15751. (org-at-item-bullet-p))
  15752. (and (not org-support-shift-select) (org-at-item-p)))
  15753. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15754. ((and (not (eq org-support-shift-select 'always))
  15755. (org-at-property-p))
  15756. (call-interactively 'org-property-previous-allowed-value))
  15757. ((org-clocktable-try-shift 'left arg))
  15758. ((and (not (eq org-support-shift-select 'always))
  15759. (org-at-table-p))
  15760. (org-table-move-cell-left))
  15761. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15762. (org-support-shift-select
  15763. (org-call-for-shift-select 'backward-char))
  15764. (t (org-shiftselect-error))))
  15765. (defun org-shiftcontrolright ()
  15766. "Switch to next TODO set."
  15767. (interactive)
  15768. (cond
  15769. ((and org-support-shift-select (org-region-active-p))
  15770. (org-call-for-shift-select 'forward-word))
  15771. ((and (not (eq org-support-shift-select 'always))
  15772. (org-at-heading-p))
  15773. (org-call-with-arg 'org-todo 'nextset))
  15774. (org-support-shift-select
  15775. (org-call-for-shift-select 'forward-word))
  15776. (t (org-shiftselect-error))))
  15777. (defun org-shiftcontrolleft ()
  15778. "Switch to previous TODO set."
  15779. (interactive)
  15780. (cond
  15781. ((and org-support-shift-select (org-region-active-p))
  15782. (org-call-for-shift-select 'backward-word))
  15783. ((and (not (eq org-support-shift-select 'always))
  15784. (org-at-heading-p))
  15785. (org-call-with-arg 'org-todo 'previousset))
  15786. (org-support-shift-select
  15787. (org-call-for-shift-select 'backward-word))
  15788. (t (org-shiftselect-error))))
  15789. (defun org-shiftcontrolup (&optional n)
  15790. "Change timestamps synchronously up in CLOCK log lines.
  15791. Optional argument N tells to change by that many units."
  15792. (interactive "P")
  15793. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15794. (let (org-support-shift-select)
  15795. (org-clock-timestamps-up n))
  15796. (user-error "Not at a clock log")))
  15797. (defun org-shiftcontroldown (&optional n)
  15798. "Change timestamps synchronously down in CLOCK log lines.
  15799. Optional argument N tells to change by that many units."
  15800. (interactive "P")
  15801. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15802. (let (org-support-shift-select)
  15803. (org-clock-timestamps-down n))
  15804. (user-error "Not at a clock log")))
  15805. (defun org-increase-number-at-point (&optional inc)
  15806. "Increment the number at point.
  15807. With an optional prefix numeric argument INC, increment using
  15808. this numeric value."
  15809. (interactive "p")
  15810. (if (not (number-at-point))
  15811. (user-error "Not on a number")
  15812. (unless inc (setq inc 1))
  15813. (let ((pos (point))
  15814. (beg (skip-chars-backward "-+^/*0-9eE."))
  15815. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15816. (setq nap (buffer-substring-no-properties
  15817. (+ pos beg) (+ pos beg end)))
  15818. (delete-region (+ pos beg) (+ pos beg end))
  15819. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15820. (when (org-at-table-p)
  15821. (org-table-align)
  15822. (org-table-end-of-field 1))))
  15823. (defun org-decrease-number-at-point (&optional inc)
  15824. "Decrement the number at point.
  15825. With an optional prefix numeric argument INC, decrement using
  15826. this numeric value."
  15827. (interactive "p")
  15828. (org-increase-number-at-point (- (or inc 1))))
  15829. (defun org-ctrl-c-ret ()
  15830. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15831. (interactive)
  15832. (cond
  15833. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15834. (t (call-interactively 'org-insert-heading))))
  15835. (defun org-copy-visible (beg end)
  15836. "Copy the visible parts of the region."
  15837. (interactive "r")
  15838. (let ((result ""))
  15839. (while (/= beg end)
  15840. (when (get-char-property beg 'invisible)
  15841. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15842. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15843. (setq result (concat result (buffer-substring beg next)))
  15844. (setq beg next)))
  15845. (setq deactivate-mark t)
  15846. (kill-new result)
  15847. (message "Visible strings have been copied to the kill ring.")))
  15848. (defun org-copy-special ()
  15849. "Copy region in table or copy current subtree.
  15850. Calls `org-table-copy-region' or `org-copy-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-copy-region #'org-copy-subtree)))
  15855. (defun org-cut-special ()
  15856. "Cut region in table or cut current subtree.
  15857. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15858. context. See the individual commands for more information."
  15859. (interactive)
  15860. (call-interactively
  15861. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15862. (defun org-paste-special (arg)
  15863. "Paste rectangular region into table, or past subtree relative to level.
  15864. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15865. See the individual commands for more information."
  15866. (interactive "P")
  15867. (if (org-at-table-p)
  15868. (org-table-paste-rectangle)
  15869. (org-paste-subtree arg)))
  15870. (defun org-edit-special (&optional arg)
  15871. "Call a special editor for the element at point.
  15872. When at a table, call the formula editor with `org-table-edit-formulas'.
  15873. When in a source code block, call `org-edit-src-code'.
  15874. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15875. When in an export block, call `org-edit-export-block'.
  15876. When in a LaTeX environment, call `org-edit-latex-environment'.
  15877. When at an #+INCLUDE keyword, visit the included file.
  15878. When at a footnote reference, call `org-edit-footnote-reference'.
  15879. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15880. When at an active timestamp, call `org-time-stamp'.
  15881. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15882. On a link, call `ffap' to visit the link at point.
  15883. Otherwise, return a user error."
  15884. (interactive "P")
  15885. (let ((element (org-element-at-point)))
  15886. (barf-if-buffer-read-only)
  15887. (pcase (org-element-type element)
  15888. (`src-block
  15889. (if (not arg) (org-edit-src-code)
  15890. (let* ((info (org-babel-get-src-block-info))
  15891. (lang (nth 0 info))
  15892. (params (nth 2 info))
  15893. (session (cdr (assq :session params))))
  15894. (if (not session) (org-edit-src-code)
  15895. ;; At a source block with a session and function called
  15896. ;; with an ARG: switch to the buffer related to the
  15897. ;; inferior process.
  15898. (switch-to-buffer
  15899. (funcall (intern (concat "org-babel-prep-session:" lang))
  15900. session params))))))
  15901. (`keyword
  15902. (unless (member (org-element-property :key element)
  15903. '("INCLUDE" "SETUPFILE"))
  15904. (user-error "No special environment to edit here"))
  15905. (let ((value (org-element-property :value element)))
  15906. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15907. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15908. (or (match-string 1 value)
  15909. (match-string 0 value)))))
  15910. (when (org-file-url-p file)
  15911. (user-error "Files located with a URL cannot be edited"))
  15912. (org-link-open-from-string
  15913. (format "[[%s]]" (expand-file-name file))))))
  15914. (`table
  15915. (if (eq (org-element-property :type element) 'table.el)
  15916. (org-edit-table.el)
  15917. (call-interactively 'org-table-edit-formulas)))
  15918. ;; Only Org tables contain `table-row' type elements.
  15919. (`table-row (call-interactively 'org-table-edit-formulas))
  15920. (`example-block (org-edit-src-code))
  15921. (`export-block (org-edit-export-block))
  15922. (`fixed-width (org-edit-fixed-width-region))
  15923. (`latex-environment (org-edit-latex-environment))
  15924. (`planning
  15925. (let ((proplist (cadr element)))
  15926. (mapc #'call-interactively
  15927. (remq nil
  15928. (list
  15929. (when (plist-get proplist :deadline) #'org-deadline)
  15930. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15931. (_
  15932. ;; No notable element at point. Though, we may be at a link or
  15933. ;; a footnote reference, which are objects. Thus, scan deeper.
  15934. (let ((context (org-element-context element)))
  15935. (pcase (org-element-type context)
  15936. (`footnote-reference (org-edit-footnote-reference))
  15937. (`inline-src-block (org-edit-inline-src-code))
  15938. (`latex-fragment (org-edit-latex-fragment))
  15939. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15940. (call-interactively #'org-time-stamp-inactive)
  15941. (call-interactively #'org-time-stamp)))
  15942. (`link (call-interactively #'ffap))
  15943. (_ (user-error "No special environment to edit here"))))))))
  15944. (defun org-ctrl-c-ctrl-c (&optional arg)
  15945. "Set tags in headline, or update according to changed information at point.
  15946. This command does many different things, depending on context:
  15947. - If column view is active, in agenda or org buffers, quit it.
  15948. - If there are highlights, remove them.
  15949. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15950. this is what we do.
  15951. - If the cursor is on a statistics cookie, update it.
  15952. - If the cursor is in a headline, in an agenda or an org buffer,
  15953. prompt for tags and insert them into the current line, aligned
  15954. to `org-tags-column'. When called with prefix arg, realign all
  15955. tags in the current buffer.
  15956. - If the cursor is in one of the special #+KEYWORD lines, this
  15957. triggers scanning the buffer for these lines and updating the
  15958. information.
  15959. - If the cursor is inside a table, realign the table. This command
  15960. works even if the automatic table editor has been turned off.
  15961. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15962. the entire table.
  15963. - If the cursor is at a footnote reference or definition, jump to
  15964. the corresponding definition or references, respectively.
  15965. - If the cursor is a the beginning of a dynamic block, update it.
  15966. - If the current buffer is a capture buffer, close note and file it.
  15967. - If the cursor is on a <<<target>>>, update radio targets and
  15968. corresponding links in this buffer.
  15969. - If the cursor is on a numbered item in a plain list, renumber the
  15970. ordered list.
  15971. - If the cursor is on a checkbox, toggle it.
  15972. - If the cursor is on a code block, evaluate it. The variable
  15973. `org-confirm-babel-evaluate' can be used to control prompting
  15974. before code block evaluation, by default every code block
  15975. evaluation requires confirmation. Code block evaluation can be
  15976. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15977. (interactive "P")
  15978. (cond
  15979. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15980. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15981. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15982. (org-remove-occur-highlights)
  15983. (message "Temporary highlights/overlays removed from current buffer"))
  15984. ((and (local-variable-p 'org-finish-function)
  15985. (fboundp org-finish-function))
  15986. (funcall org-finish-function))
  15987. ((org-babel-hash-at-point))
  15988. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15989. (t
  15990. (let* ((context
  15991. (org-element-lineage
  15992. (org-element-context)
  15993. ;; Limit to supported contexts.
  15994. '(babel-call clock dynamic-block footnote-definition
  15995. footnote-reference inline-babel-call inline-src-block
  15996. inlinetask item keyword node-property paragraph
  15997. plain-list planning property-drawer radio-target
  15998. src-block statistics-cookie table table-cell table-row
  15999. timestamp)
  16000. t))
  16001. (radio-list-p (org-at-radio-list-p))
  16002. (type (org-element-type context)))
  16003. ;; For convenience: at the first line of a paragraph on the same
  16004. ;; line as an item, apply function on that item instead.
  16005. (when (eq type 'paragraph)
  16006. (let ((parent (org-element-property :parent context)))
  16007. (when (and (eq (org-element-type parent) 'item)
  16008. (= (line-beginning-position)
  16009. (org-element-property :begin parent)))
  16010. (setq context parent)
  16011. (setq type 'item))))
  16012. ;; Act according to type of element or object at point.
  16013. ;;
  16014. ;; Do nothing on a blank line, except if it is contained in
  16015. ;; a source block. Hence, we first check if point is in such
  16016. ;; a block and then if it is at a blank line.
  16017. (pcase type
  16018. ((or `inline-src-block `src-block)
  16019. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16020. (org-babel-eval-wipe-error-buffer)
  16021. (org-babel-execute-src-block
  16022. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16023. ((guard (org-match-line "[ \t]*$"))
  16024. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16025. (user-error
  16026. (substitute-command-keys
  16027. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16028. ((or `babel-call `inline-babel-call)
  16029. (let ((info (org-babel-lob-get-info context)))
  16030. (when info (org-babel-execute-src-block nil info))))
  16031. (`clock (org-clock-update-time-maybe))
  16032. (`dynamic-block
  16033. (save-excursion
  16034. (goto-char (org-element-property :post-affiliated context))
  16035. (org-update-dblock)))
  16036. (`footnote-definition
  16037. (goto-char (org-element-property :post-affiliated context))
  16038. (call-interactively 'org-footnote-action))
  16039. (`footnote-reference (call-interactively #'org-footnote-action))
  16040. ((or `headline `inlinetask)
  16041. (save-excursion (goto-char (org-element-property :begin context))
  16042. (call-interactively #'org-set-tags-command)))
  16043. (`item
  16044. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16045. ;; unconditionally, whereas `C-u' will toggle its presence.
  16046. ;; Without a universal argument, if the item has a checkbox,
  16047. ;; toggle it. Otherwise repair the list.
  16048. (if (or radio-list-p
  16049. (and (boundp org-list-checkbox-radio-mode)
  16050. org-list-checkbox-radio-mode))
  16051. (org-toggle-radio-button arg)
  16052. (let* ((box (org-element-property :checkbox context))
  16053. (struct (org-element-property :structure context))
  16054. (old-struct (copy-tree struct))
  16055. (parents (org-list-parents-alist struct))
  16056. (prevs (org-list-prevs-alist struct))
  16057. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16058. (org-list-set-checkbox
  16059. (org-element-property :begin context) struct
  16060. (cond ((equal arg '(16)) "[-]")
  16061. ((and (not box) (equal arg '(4))) "[ ]")
  16062. ((or (not box) (equal arg '(4))) nil)
  16063. ((eq box 'on) "[ ]")
  16064. (t "[X]")))
  16065. ;; Mimic `org-list-write-struct' but with grabbing a return
  16066. ;; value from `org-list-struct-fix-box'.
  16067. (org-list-struct-fix-ind struct parents 2)
  16068. (org-list-struct-fix-item-end struct)
  16069. (org-list-struct-fix-bul struct prevs)
  16070. (org-list-struct-fix-ind struct parents)
  16071. (let ((block-item
  16072. (org-list-struct-fix-box struct parents prevs orderedp)))
  16073. (if (and box (equal struct old-struct))
  16074. (if (equal arg '(16))
  16075. (message "Checkboxes already reset")
  16076. (user-error "Cannot toggle this checkbox: %s"
  16077. (if (eq box 'on)
  16078. "all subitems checked"
  16079. "unchecked subitems")))
  16080. (org-list-struct-apply-struct struct old-struct)
  16081. (org-update-checkbox-count-maybe))
  16082. (when block-item
  16083. (message "Checkboxes were removed due to empty box at line %d"
  16084. (org-current-line block-item)))))))
  16085. (`plain-list
  16086. ;; At a plain list, with a double C-u argument, set
  16087. ;; checkboxes of each item to "[-]", whereas a single one
  16088. ;; will toggle their presence according to the state of the
  16089. ;; first item in the list. Without an argument, repair the
  16090. ;; list.
  16091. (if (or radio-list-p
  16092. (and (boundp org-list-checkbox-radio-mode)
  16093. org-list-checkbox-radio-mode))
  16094. (org-toggle-radio-button arg)
  16095. (let* ((begin (org-element-property :contents-begin context))
  16096. (struct (org-element-property :structure context))
  16097. (old-struct (copy-tree struct))
  16098. (first-box (save-excursion
  16099. (goto-char begin)
  16100. (looking-at org-list-full-item-re)
  16101. (match-string-no-properties 3)))
  16102. (new-box (cond ((equal arg '(16)) "[-]")
  16103. ((equal arg '(4)) (unless first-box "[ ]"))
  16104. ((equal first-box "[X]") "[ ]")
  16105. (t "[X]"))))
  16106. (cond
  16107. (arg
  16108. (dolist (pos
  16109. (org-list-get-all-items
  16110. begin struct (org-list-prevs-alist struct)))
  16111. (org-list-set-checkbox pos struct new-box)))
  16112. ((and first-box (eq (point) begin))
  16113. ;; For convenience, when point is at bol on the first
  16114. ;; item of the list and no argument is provided, simply
  16115. ;; toggle checkbox of that item, if any.
  16116. (org-list-set-checkbox begin struct new-box)))
  16117. (when (equal
  16118. (org-list-write-struct
  16119. struct (org-list-parents-alist struct) old-struct)
  16120. old-struct)
  16121. (message "Cannot update this checkbox"))
  16122. (org-update-checkbox-count-maybe))))
  16123. (`keyword
  16124. (let ((org-inhibit-startup-visibility-stuff t)
  16125. (org-startup-align-all-tables nil))
  16126. (when (boundp 'org-table-coordinate-overlays)
  16127. (mapc #'delete-overlay org-table-coordinate-overlays)
  16128. (setq org-table-coordinate-overlays nil))
  16129. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16130. (message "Local setup has been refreshed"))
  16131. ((or `property-drawer `node-property)
  16132. (call-interactively #'org-property-action))
  16133. (`radio-target
  16134. (call-interactively #'org-update-radio-target-regexp))
  16135. (`statistics-cookie
  16136. (call-interactively #'org-update-statistics-cookies))
  16137. ((or `table `table-cell `table-row)
  16138. ;; At a table, recalculate every field and align it. Also
  16139. ;; send the table if necessary. If the table has
  16140. ;; a `table.el' type, just give up. At a table row or cell,
  16141. ;; maybe recalculate line but always align table.
  16142. (if (eq (org-element-property :type context) 'table.el)
  16143. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16144. Use `\\[org-edit-special]' to edit table.el tables"))
  16145. (if (or (eq type 'table)
  16146. ;; Check if point is at a TBLFM line.
  16147. (and (eq type 'table-row)
  16148. (= (point) (org-element-property :end context))))
  16149. (save-excursion
  16150. (if (org-at-TBLFM-p)
  16151. (progn (require 'org-table)
  16152. (org-table-calc-current-TBLFM))
  16153. (goto-char (org-element-property :contents-begin context))
  16154. (org-call-with-arg 'org-table-recalculate (or arg t))
  16155. (orgtbl-send-table 'maybe)))
  16156. (org-table-maybe-eval-formula)
  16157. (cond (arg (call-interactively #'org-table-recalculate))
  16158. ((org-table-maybe-recalculate-line))
  16159. (t (org-table-align))))))
  16160. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16161. (org-timestamp-change 0 'day))
  16162. ((and `nil (guard (org-at-heading-p)))
  16163. ;; When point is on an unsupported object type, we can miss
  16164. ;; the fact that it also is at a heading. Handle it here.
  16165. (call-interactively #'org-set-tags-command))
  16166. ((guard
  16167. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16168. (_
  16169. (user-error
  16170. (substitute-command-keys
  16171. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16172. (defun org-mode-restart ()
  16173. "Restart `org-mode'."
  16174. (interactive)
  16175. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16176. (funcall major-mode)
  16177. (hack-local-variables)
  16178. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16179. (org-indent-mode -1))
  16180. (org-reset-file-cache))
  16181. (message "%s restarted" major-mode))
  16182. (defun org-flag-above-first-heading (&optional arg)
  16183. "Hide from bob up to the first heading.
  16184. Move point to the beginning of first heading or end of buffer."
  16185. (goto-char (point-min))
  16186. (unless (org-at-heading-p)
  16187. (outline-next-heading))
  16188. (unless (bobp)
  16189. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16190. (defun org-show-branches-buffer ()
  16191. "Show all branches in the buffer."
  16192. (org-flag-above-first-heading)
  16193. (outline-hide-sublevels 1)
  16194. (unless (eobp)
  16195. (outline-show-branches)
  16196. (while (outline-get-next-sibling)
  16197. (outline-show-branches)))
  16198. (goto-char (point-min)))
  16199. (defun org-kill-note-or-show-branches ()
  16200. "Abort storing current note, or show just branches."
  16201. (interactive)
  16202. (cond (org-finish-function
  16203. (let ((org-note-abort t)) (funcall org-finish-function)))
  16204. ((org-before-first-heading-p)
  16205. (org-show-branches-buffer)
  16206. (org-hide-archived-subtrees (point-min) (point-max)))
  16207. (t
  16208. (let ((beg (progn (org-back-to-heading) (point)))
  16209. (end (save-excursion (org-end-of-subtree t t) (point))))
  16210. (outline-hide-subtree)
  16211. (outline-show-branches)
  16212. (org-hide-archived-subtrees beg end)))))
  16213. (defun org-delete-indentation (&optional arg)
  16214. "Join current line to previous and fix whitespace at join.
  16215. If previous line is a headline add to headline title. Otherwise
  16216. the function calls `delete-indentation'.
  16217. I.e. with a non-nil optional argument, join the line with the
  16218. following one. If there is a region then join the lines in that
  16219. region."
  16220. (interactive "*P")
  16221. (if (save-excursion
  16222. (beginning-of-line (if arg 1 0))
  16223. (let ((case-fold-search nil))
  16224. (looking-at org-complex-heading-regexp)))
  16225. ;; At headline.
  16226. (let ((tags-column (when (match-beginning 5)
  16227. (save-excursion (goto-char (match-beginning 5))
  16228. (current-column))))
  16229. (string (concat " " (progn (when arg (forward-line 1))
  16230. (org-trim (delete-and-extract-region
  16231. (line-beginning-position)
  16232. (line-end-position)))))))
  16233. (unless (bobp) (delete-region (point) (1- (point))))
  16234. (goto-char (or (match-end 4)
  16235. (match-beginning 5)
  16236. (match-end 0)))
  16237. (skip-chars-backward " \t")
  16238. (save-excursion (insert string))
  16239. ;; Adjust alignment of tags.
  16240. (cond
  16241. ((not tags-column)) ;no tags
  16242. (org-auto-align-tags (org-align-tags))
  16243. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16244. (let ((current-prefix-arg arg))
  16245. (call-interactively #'delete-indentation))))
  16246. (defun org-open-line (n)
  16247. "Insert a new row in tables, call `open-line' elsewhere.
  16248. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16249. As a special case, when a document starts with a table, allow to
  16250. call `open-line' on the very first character."
  16251. (interactive "*p")
  16252. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16253. (org-table-insert-row)
  16254. (open-line n)))
  16255. (defun org--newline (indent arg interactive)
  16256. "Call `newline-and-indent' or just `newline'.
  16257. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16258. indent unconditionally; otherwise, call `newline' with ARG and
  16259. INTERACTIVE, which can trigger indentation if
  16260. `electric-indent-mode' is enabled."
  16261. (if indent
  16262. (org-newline-and-indent arg)
  16263. (newline arg interactive)))
  16264. (defun org-return (&optional indent arg interactive)
  16265. "Goto next table row or insert a newline.
  16266. Calls `org-table-next-row' or `newline', depending on context.
  16267. When optional INDENT argument is non-nil, call
  16268. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16269. and INTERACTIVE.
  16270. When `org-return-follows-link' is non-nil and point is on
  16271. a timestamp or a link, call `org-open-at-point'. However, it
  16272. will not happen if point is in a table or on a \"dead\"
  16273. object (e.g., within a comment). In these case, you need to use
  16274. `org-open-at-point' directly."
  16275. (interactive "i\nP\np")
  16276. (let ((context (if org-return-follows-link (org-element-context)
  16277. (org-element-at-point))))
  16278. (cond
  16279. ;; In a table, call `org-table-next-row'. However, before first
  16280. ;; column or after last one, split the table.
  16281. ((or (and (eq 'table (org-element-type context))
  16282. (not (eq 'table.el (org-element-property :type context)))
  16283. (>= (point) (org-element-property :contents-begin context))
  16284. (< (point) (org-element-property :contents-end context)))
  16285. (org-element-lineage context '(table-row table-cell) t))
  16286. (if (or (looking-at-p "[ \t]*$")
  16287. (save-excursion (skip-chars-backward " \t") (bolp)))
  16288. (insert "\n")
  16289. (org-table-justify-field-maybe)
  16290. (call-interactively #'org-table-next-row)))
  16291. ;; On a link or a timestamp, call `org-open-at-point' if
  16292. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16293. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16294. ((and org-return-follows-link
  16295. (or (and (eq 'link (org-element-type context))
  16296. ;; Ensure point is not on the white spaces after
  16297. ;; the link.
  16298. (let ((origin (point)))
  16299. (org-with-point-at (org-element-property :end context)
  16300. (skip-chars-backward " \t")
  16301. (> (point) origin))))
  16302. (org-in-regexp org-ts-regexp-both nil t)
  16303. (org-in-regexp org-tsr-regexp-both nil t)
  16304. (org-in-regexp org-link-any-re nil t)))
  16305. (call-interactively #'org-open-at-point))
  16306. ;; Insert newline in heading, but preserve tags.
  16307. ((and (not (bolp))
  16308. (let ((case-fold-search nil))
  16309. (org-match-line org-complex-heading-regexp)))
  16310. ;; At headline. Split line. However, if point is on keyword,
  16311. ;; priority cookie or tags, do not break any of them: add
  16312. ;; a newline after the headline instead.
  16313. (let ((tags-column (and (match-beginning 5)
  16314. (save-excursion (goto-char (match-beginning 5))
  16315. (current-column))))
  16316. (string
  16317. (when (and (match-end 4) (org-point-in-group (point) 4))
  16318. (delete-and-extract-region (point) (match-end 4)))))
  16319. ;; Adjust tag alignment.
  16320. (cond
  16321. ((not (and tags-column string)))
  16322. (org-auto-align-tags (org-align-tags))
  16323. (t (org--align-tags-here tags-column))) ;preserve tags column
  16324. (end-of-line)
  16325. (org-show-entry)
  16326. (org--newline indent arg interactive)
  16327. (when string (save-excursion (insert (org-trim string))))))
  16328. ;; In a list, make sure indenting keeps trailing text within.
  16329. ((and (not (eolp))
  16330. (org-element-lineage context '(item)))
  16331. (let ((trailing-data
  16332. (delete-and-extract-region (point) (line-end-position))))
  16333. (org--newline indent arg interactive)
  16334. (save-excursion (insert trailing-data))))
  16335. (t
  16336. ;; Do not auto-fill when point is in an Org property drawer.
  16337. (let ((auto-fill-function (and (not (org-at-property-p))
  16338. auto-fill-function)))
  16339. (org--newline indent arg interactive))))))
  16340. (defun org-return-and-maybe-indent ()
  16341. "Goto next table row, or insert a newline.
  16342. Call `org-table-next-row' or `org-return', depending on context.
  16343. See the individual commands for more information.
  16344. When inserting a newline, indent the new line if
  16345. `electric-indent-mode' is disabled."
  16346. (interactive)
  16347. (org-return (not electric-indent-mode)))
  16348. (defun org-ctrl-c-tab (&optional arg)
  16349. "Toggle columns width in a table, or show children.
  16350. Call `org-table-toggle-column-width' if point is in a table.
  16351. Otherwise provide a compact view of the children. ARG is the
  16352. level to hide."
  16353. (interactive "p")
  16354. (cond
  16355. ((org-at-table-p)
  16356. (call-interactively #'org-table-toggle-column-width))
  16357. ((org-before-first-heading-p)
  16358. (save-excursion
  16359. (org-flag-above-first-heading)
  16360. (outline-hide-sublevels (or arg 1))))
  16361. (t
  16362. (outline-hide-subtree)
  16363. (org-show-children arg))))
  16364. (defun org-ctrl-c-star ()
  16365. "Compute table, or change heading status of lines.
  16366. Calls `org-table-recalculate' or `org-toggle-heading',
  16367. depending on context."
  16368. (interactive)
  16369. (cond
  16370. ((org-at-table-p)
  16371. (call-interactively 'org-table-recalculate))
  16372. (t
  16373. ;; Convert all lines in region to list items
  16374. (call-interactively 'org-toggle-heading))))
  16375. (defun org-ctrl-c-minus ()
  16376. "Insert separator line in table or modify bullet status of line.
  16377. Also turns a plain line or a region of lines into list items.
  16378. Calls `org-table-insert-hline', `org-toggle-item', or
  16379. `org-cycle-list-bullet', depending on context."
  16380. (interactive)
  16381. (cond
  16382. ((org-at-table-p)
  16383. (call-interactively 'org-table-insert-hline))
  16384. ((org-region-active-p)
  16385. (call-interactively 'org-toggle-item))
  16386. ((org-in-item-p)
  16387. (call-interactively 'org-cycle-list-bullet))
  16388. (t
  16389. (call-interactively 'org-toggle-item))))
  16390. (defun org-toggle-heading (&optional nstars)
  16391. "Convert headings to normal text, or items or text to headings.
  16392. If there is no active region, only convert the current line.
  16393. With a `\\[universal-argument]' prefix, convert the whole list at
  16394. point into heading.
  16395. In a region:
  16396. - If the first non blank line is a headline, remove the stars
  16397. from all headlines in the region.
  16398. - If it is a normal line, turn each and every normal line (i.e.,
  16399. not an heading or an item) in the region into headings. If you
  16400. want to convert only the first line of this region, use one
  16401. universal prefix argument.
  16402. - If it is a plain list item, turn all plain list items into headings.
  16403. When converting a line into a heading, the number of stars is chosen
  16404. such that the lines become children of the current entry. However,
  16405. when a numeric prefix argument is given, its value determines the
  16406. number of stars to add."
  16407. (interactive "P")
  16408. (let ((skip-blanks
  16409. ;; Return beginning of first non-blank line, starting from
  16410. ;; line at POS.
  16411. (lambda (pos)
  16412. (save-excursion
  16413. (goto-char pos)
  16414. (while (org-at-comment-p) (forward-line))
  16415. (skip-chars-forward " \r\t\n")
  16416. (point-at-bol))))
  16417. beg end toggled)
  16418. ;; Determine boundaries of changes. If a universal prefix has
  16419. ;; been given, put the list in a region. If region ends at a bol,
  16420. ;; do not consider the last line to be in the region.
  16421. (when (and current-prefix-arg (org-at-item-p))
  16422. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16423. (org-mark-element))
  16424. (if (org-region-active-p)
  16425. (setq beg (funcall skip-blanks (region-beginning))
  16426. end (copy-marker (save-excursion
  16427. (goto-char (region-end))
  16428. (if (bolp) (point) (point-at-eol)))))
  16429. (setq beg (funcall skip-blanks (point-at-bol))
  16430. end (copy-marker (point-at-eol))))
  16431. ;; Ensure inline tasks don't count as headings.
  16432. (org-with-limited-levels
  16433. (save-excursion
  16434. (goto-char beg)
  16435. (cond
  16436. ;; Case 1. Started at an heading: de-star headings.
  16437. ((org-at-heading-p)
  16438. (while (< (point) end)
  16439. (when (org-at-heading-p t)
  16440. (looking-at org-outline-regexp) (replace-match "")
  16441. (setq toggled t))
  16442. (forward-line)))
  16443. ;; Case 2. Started at an item: change items into headlines.
  16444. ;; One star will be added by `org-list-to-subtree'.
  16445. ((org-at-item-p)
  16446. (while (< (point) end)
  16447. (when (org-at-item-p)
  16448. ;; Pay attention to cases when region ends before list.
  16449. (let* ((struct (org-list-struct))
  16450. (list-end
  16451. (min (org-list-get-bottom-point struct) (1+ end))))
  16452. (save-restriction
  16453. (narrow-to-region (point) list-end)
  16454. (insert (org-list-to-subtree
  16455. (org-list-to-lisp t)
  16456. (pcase (org-current-level)
  16457. (`nil 1)
  16458. (l (1+ (org-reduced-level l)))))
  16459. "\n")))
  16460. (setq toggled t))
  16461. (forward-line)))
  16462. ;; Case 3. Started at normal text: make every line an heading,
  16463. ;; skipping headlines and items.
  16464. (t (let* ((stars
  16465. (make-string
  16466. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16467. (add-stars
  16468. (cond (nstars "") ; stars from prefix only
  16469. ((equal stars "") "*") ; before first heading
  16470. (org-odd-levels-only "**") ; inside heading, odd
  16471. (t "*"))) ; inside heading, oddeven
  16472. (rpl (concat stars add-stars " "))
  16473. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16474. (while (< (point) (if (equal nstars '(4)) lend end))
  16475. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16476. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16477. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16478. (forward-line)))))))
  16479. (unless toggled (message "Cannot toggle heading from here"))))
  16480. (defun org-meta-return (&optional arg)
  16481. "Insert a new heading or wrap a region in a table.
  16482. Calls `org-insert-heading', `org-insert-item' or
  16483. `org-table-wrap-region', depending on context. When called with
  16484. an argument, unconditionally call `org-insert-heading'."
  16485. (interactive "P")
  16486. (org-check-before-invisible-edit 'insert)
  16487. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16488. (call-interactively (cond (arg #'org-insert-heading)
  16489. ((org-at-table-p) #'org-table-wrap-region)
  16490. ((org-in-item-p) #'org-insert-item)
  16491. (t #'org-insert-heading)))))
  16492. ;;; Menu entries
  16493. (defsubst org-in-subtree-not-table-p ()
  16494. "Are we in a subtree and not in a table?"
  16495. (and (not (org-before-first-heading-p))
  16496. (not (org-at-table-p))))
  16497. ;; Define the Org mode menus
  16498. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16499. `("Org"
  16500. ("Show/Hide"
  16501. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16502. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16503. ["Sparse Tree..." org-sparse-tree t]
  16504. ["Reveal Context" org-reveal t]
  16505. ["Show All" org-show-all t]
  16506. "--"
  16507. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16508. "--"
  16509. ["New Heading" org-insert-heading t]
  16510. ("Navigate Headings"
  16511. ["Up" outline-up-heading t]
  16512. ["Next" outline-next-visible-heading t]
  16513. ["Previous" outline-previous-visible-heading t]
  16514. ["Next Same Level" outline-forward-same-level t]
  16515. ["Previous Same Level" outline-backward-same-level t]
  16516. "--"
  16517. ["Jump" org-goto t])
  16518. ("Edit Structure"
  16519. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16520. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16521. "--"
  16522. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16523. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16524. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16525. "--"
  16526. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16527. "--"
  16528. ["Copy visible text" org-copy-visible t]
  16529. "--"
  16530. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16531. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16532. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16533. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16534. "--"
  16535. ["Sort Region/Children" org-sort t]
  16536. "--"
  16537. ["Convert to odd levels" org-convert-to-odd-levels t]
  16538. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16539. ("Editing"
  16540. ["Emphasis..." org-emphasize t]
  16541. ["Add block structure" org-insert-structure-template t]
  16542. ["Edit Source Example" org-edit-special t]
  16543. "--"
  16544. ["Footnote new/jump" org-footnote-action t]
  16545. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16546. ("Archive"
  16547. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16548. "--"
  16549. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16550. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16551. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16552. "--"
  16553. ("Hyperlinks"
  16554. ["Store Link (Global)" org-store-link t]
  16555. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16556. ["Insert Link" org-insert-link t]
  16557. ["Follow Link" org-open-at-point t]
  16558. "--"
  16559. ["Next link" org-next-link t]
  16560. ["Previous link" org-previous-link t]
  16561. "--"
  16562. ["Descriptive Links"
  16563. org-toggle-link-display
  16564. :style radio
  16565. :selected org-descriptive-links
  16566. ]
  16567. ["Literal Links"
  16568. org-toggle-link-display
  16569. :style radio
  16570. :selected (not org-descriptive-links)])
  16571. "--"
  16572. ("TODO Lists"
  16573. ["TODO/DONE/-" org-todo t]
  16574. ("Select keyword"
  16575. ["Next keyword" org-shiftright (org-at-heading-p)]
  16576. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16577. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16578. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16579. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16580. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16581. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16582. "--"
  16583. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16584. :selected org-enforce-todo-dependencies :style toggle :active t]
  16585. "Settings for tree at point"
  16586. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16587. :selected (org-entry-get nil "ORDERED")
  16588. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16589. ["Do Children parallel" org-toggle-ordered-property :style radio
  16590. :selected (not (org-entry-get nil "ORDERED"))
  16591. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16592. "--"
  16593. ["Set Priority" org-priority t]
  16594. ["Priority Up" org-shiftup t]
  16595. ["Priority Down" org-shiftdown t]
  16596. "--"
  16597. ["Get news from all feeds" org-feed-update-all t]
  16598. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16599. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16600. ("TAGS and Properties"
  16601. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16602. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16603. "--"
  16604. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16605. ["Column view of properties" org-columns t]
  16606. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16607. ("Dates and Scheduling"
  16608. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16609. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16610. ("Change Date"
  16611. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16612. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16613. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16614. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16615. ["Compute Time Range" org-evaluate-time-range t]
  16616. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16617. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16618. "--"
  16619. ["Custom time format" org-toggle-time-stamp-overlays
  16620. :style radio :selected org-display-custom-times]
  16621. "--"
  16622. ["Goto Calendar" org-goto-calendar t]
  16623. ["Date from Calendar" org-date-from-calendar t]
  16624. "--"
  16625. ["Start/Restart Timer" org-timer-start t]
  16626. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16627. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16628. ["Insert Timer String" org-timer t]
  16629. ["Insert Timer Item" org-timer-item t])
  16630. ("Logging work"
  16631. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16632. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16633. ["Clock out" org-clock-out t]
  16634. ["Clock cancel" org-clock-cancel t]
  16635. "--"
  16636. ["Mark as default task" org-clock-mark-default-task t]
  16637. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16638. ["Goto running clock" org-clock-goto t]
  16639. "--"
  16640. ["Display times" org-clock-display t]
  16641. ["Create clock table" org-clock-report t]
  16642. "--"
  16643. ["Record DONE time"
  16644. (progn (setq org-log-done (not org-log-done))
  16645. (message "Switching to %s will %s record a timestamp"
  16646. (car org-done-keywords)
  16647. (if org-log-done "automatically" "not")))
  16648. :style toggle :selected org-log-done])
  16649. "--"
  16650. ["Agenda Command..." org-agenda t]
  16651. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16652. ("File List for Agenda")
  16653. ("Special views current file"
  16654. ["TODO Tree" org-show-todo-tree t]
  16655. ["Check Deadlines" org-check-deadlines t]
  16656. ["Tags/Property tree" org-match-sparse-tree t])
  16657. "--"
  16658. ["Export/Publish..." org-export-dispatch t]
  16659. ("LaTeX"
  16660. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16661. :style toggle :selected org-cdlatex-mode]
  16662. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16663. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16664. ["Modify math symbol" org-cdlatex-math-modify
  16665. (org-inside-LaTeX-fragment-p)]
  16666. ["Insert citation" org-reftex-citation t])
  16667. "--"
  16668. ("Documentation"
  16669. ["Show Version" org-version t]
  16670. ["Info Documentation" org-info t]
  16671. ["Browse Org News" org-browse-news t])
  16672. ("Customize"
  16673. ["Browse Org Group" org-customize t]
  16674. "--"
  16675. ["Expand This Menu" org-create-customize-menu t])
  16676. ["Send bug report" org-submit-bug-report t]
  16677. "--"
  16678. ("Refresh/Reload"
  16679. ["Refresh setup current buffer" org-mode-restart t]
  16680. ["Reload Org (after update)" org-reload t]
  16681. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16682. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16683. '("Table"
  16684. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16685. ["Next Field" org-cycle (org-at-table-p)]
  16686. ["Previous Field" org-shifttab (org-at-table-p)]
  16687. ["Next Row" org-return (org-at-table-p)]
  16688. "--"
  16689. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16690. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16691. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16692. "--"
  16693. ("Column"
  16694. ["Move Column Left" org-metaleft (org-at-table-p)]
  16695. ["Move Column Right" org-metaright (org-at-table-p)]
  16696. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16697. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16698. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16699. ("Row"
  16700. ["Move Row Up" org-metaup (org-at-table-p)]
  16701. ["Move Row Down" org-metadown (org-at-table-p)]
  16702. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16703. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16704. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16705. "--"
  16706. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16707. ("Rectangle"
  16708. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16709. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16710. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16711. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16712. "--"
  16713. ("Calculate"
  16714. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16715. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16716. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16717. "--"
  16718. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16719. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16720. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16721. "--"
  16722. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16723. "--"
  16724. ["Sum Column/Rectangle" org-table-sum
  16725. (or (org-at-table-p) (org-region-active-p))]
  16726. ["Which Column?" org-table-current-column (org-at-table-p)])
  16727. ["Debug Formulas"
  16728. org-table-toggle-formula-debugger
  16729. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16730. ["Show Col/Row Numbers"
  16731. org-table-toggle-coordinate-overlays
  16732. :style toggle
  16733. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16734. "--"
  16735. ["Create" org-table-create (not (org-at-table-p))]
  16736. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16737. ["Import from File" org-table-import (not (org-at-table-p))]
  16738. ["Export to File" org-table-export (org-at-table-p)]
  16739. "--"
  16740. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16741. "--"
  16742. ("Plot"
  16743. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16744. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16745. (defun org-info (&optional node)
  16746. "Read documentation for Org in the info system.
  16747. With optional NODE, go directly to that node."
  16748. (interactive)
  16749. (info (format "(org)%s" (or node ""))))
  16750. (defun org-browse-news ()
  16751. "Browse the news for the latest major release."
  16752. (interactive)
  16753. (browse-url "https://orgmode.org/Changes.html"))
  16754. ;;;###autoload
  16755. (defun org-submit-bug-report ()
  16756. "Submit a bug report on Org via mail.
  16757. Don't hesitate to report any problems or inaccurate documentation.
  16758. If you don't have setup sending mail from (X)Emacs, please copy the
  16759. output buffer into your mail program, as it gives us important
  16760. information about your Org version and configuration."
  16761. (interactive)
  16762. (require 'reporter)
  16763. (defvar reporter-prompt-for-summary-p)
  16764. (org-load-modules-maybe)
  16765. (org-require-autoloaded-modules)
  16766. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16767. (reporter-submit-bug-report
  16768. "emacs-orgmode@gnu.org"
  16769. (org-version nil 'full)
  16770. (let (list)
  16771. (save-window-excursion
  16772. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16773. (delete-other-windows)
  16774. (erase-buffer)
  16775. (insert "You are about to submit a bug report to the Org mailing list.
  16776. If your report is about Org installation, please read this section:
  16777. https://orgmode.org/org.html#Installation
  16778. Please read https://orgmode.org/org.html#Feedback on how to make
  16779. a good report, it will help Org contributors fixing your problem.
  16780. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16781. if the issue you are about to raise has already been dealt with.
  16782. We also would like to add your full Org and Outline configuration
  16783. to the bug report. It will help us debugging the issue.
  16784. *HOWEVER*, some variables you have customized may contain private
  16785. information. The names of customers, colleagues, or friends, might
  16786. appear in the form of file names, tags, todo states or search strings.
  16787. If you answer \"yes\" to the prompt, you might want to check and remove
  16788. such private information before sending the email.")
  16789. (add-text-properties (point-min) (point-max) '(face org-warning))
  16790. (when (yes-or-no-p "Include your Org configuration ")
  16791. (mapatoms
  16792. (lambda (v)
  16793. (and (boundp v)
  16794. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16795. (or (and (symbol-value v)
  16796. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16797. (and
  16798. (get v 'custom-type) (get v 'standard-value)
  16799. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16800. (push v list)))))
  16801. (kill-buffer (get-buffer "*Warn about privacy*"))
  16802. list))
  16803. nil nil
  16804. "Remember to cover the basics, that is, what you expected to happen and
  16805. what in fact did happen. You don't know how to make a good report? See
  16806. https://orgmode.org/manual/Feedback.html#Feedback
  16807. Your bug report will be posted to the Org mailing list.
  16808. ------------------------------------------------------------------------")
  16809. (save-excursion
  16810. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16811. (replace-match "\\1Bug: \\3 [\\2]")))))
  16812. (defun org-install-agenda-files-menu ()
  16813. "Install agenda file menu."
  16814. (let ((bl (buffer-list)))
  16815. (save-excursion
  16816. (while bl
  16817. (set-buffer (pop bl))
  16818. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16819. (when (derived-mode-p 'org-mode)
  16820. (easy-menu-change
  16821. '("Org") "File List for Agenda"
  16822. (append
  16823. (list
  16824. ["Edit File List" (org-edit-agenda-file-list) t]
  16825. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16826. ["Remove Current File from List" org-remove-file t]
  16827. ["Cycle through agenda files" org-cycle-agenda-files t]
  16828. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16829. "--")
  16830. (mapcar 'org-file-menu-entry
  16831. ;; Prevent initialization from failing.
  16832. (ignore-errors (org-agenda-files t)))))))))
  16833. ;;;; Documentation
  16834. (defun org-require-autoloaded-modules ()
  16835. (interactive)
  16836. (mapc #'require
  16837. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16838. org-table org-timer)))
  16839. ;;;###autoload
  16840. (defun org-reload (&optional uncompiled)
  16841. "Reload all Org Lisp files.
  16842. With prefix arg UNCOMPILED, load the uncompiled versions."
  16843. (interactive "P")
  16844. (require 'loadhist)
  16845. (let* ((org-dir (org-find-library-dir "org"))
  16846. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16847. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16848. (remove-re (format "\\`%s\\'"
  16849. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16850. (feats (delete-dups
  16851. (mapcar 'file-name-sans-extension
  16852. (mapcar 'file-name-nondirectory
  16853. (delq nil
  16854. (mapcar 'feature-file
  16855. features))))))
  16856. (lfeat (append
  16857. (sort
  16858. (setq feats
  16859. (delq nil (mapcar
  16860. (lambda (f)
  16861. (if (and (string-match feature-re f)
  16862. (not (string-match remove-re f)))
  16863. f nil))
  16864. feats)))
  16865. 'string-lessp)
  16866. (list "org-version" "org")))
  16867. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16868. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16869. load-uncore load-misses)
  16870. (setq load-misses
  16871. (delq 't
  16872. (mapcar (lambda (f)
  16873. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16874. (and (string= org-dir contrib-dir)
  16875. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16876. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16877. (push f load-uncore)
  16878. 't)
  16879. f))
  16880. lfeat)))
  16881. (when load-uncore
  16882. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16883. (if (> (length load-uncore) 1) "s were" " was")
  16884. (reverse load-uncore)))
  16885. (if load-misses
  16886. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16887. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16888. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16889. ;;;###autoload
  16890. (defun org-customize ()
  16891. "Call the customize function with org as argument."
  16892. (interactive)
  16893. (org-load-modules-maybe)
  16894. (org-require-autoloaded-modules)
  16895. (customize-browse 'org))
  16896. (defun org-create-customize-menu ()
  16897. "Create a full customization menu for Org mode, insert it into the menu."
  16898. (interactive)
  16899. (org-load-modules-maybe)
  16900. (org-require-autoloaded-modules)
  16901. (easy-menu-change
  16902. '("Org") "Customize"
  16903. `(["Browse Org group" org-customize t]
  16904. "--"
  16905. ,(customize-menu-create 'org)
  16906. ["Set" Custom-set t]
  16907. ["Save" Custom-save t]
  16908. ["Reset to Current" Custom-reset-current t]
  16909. ["Reset to Saved" Custom-reset-saved t]
  16910. ["Reset to Standard Settings" Custom-reset-standard t]))
  16911. (message "\"Org\"-menu now contains full customization menu"))
  16912. ;;;; Miscellaneous stuff
  16913. ;;; Generally useful functions
  16914. (defun org-in-clocktable-p ()
  16915. "Check if the cursor is in a clocktable."
  16916. (let ((pos (point)) start)
  16917. (save-excursion
  16918. (end-of-line 1)
  16919. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16920. (setq start (match-beginning 0))
  16921. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16922. (>= (match-end 0) pos)
  16923. start))))
  16924. (defun org-in-verbatim-emphasis ()
  16925. (save-match-data
  16926. (and (org-in-regexp org-verbatim-re 2)
  16927. (>= (point) (match-beginning 3))
  16928. (<= (point) (match-end 4)))))
  16929. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16930. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16931. (if (and marker (marker-buffer marker)
  16932. (buffer-live-p (marker-buffer marker)))
  16933. (progn
  16934. (pop-to-buffer-same-window (marker-buffer marker))
  16935. (when (or (> marker (point-max)) (< marker (point-min)))
  16936. (widen))
  16937. (goto-char marker)
  16938. (org-show-context 'org-goto))
  16939. (if bookmark
  16940. (bookmark-jump bookmark)
  16941. (error "Cannot find location"))))
  16942. (defun org-quote-csv-field (s)
  16943. "Quote field for inclusion in CSV material."
  16944. (if (string-match "[\",]" s)
  16945. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16946. s))
  16947. (defun org-force-self-insert (N)
  16948. "Needed to enforce self-insert under remapping."
  16949. (interactive "p")
  16950. (self-insert-command N))
  16951. (defun org-quote-vert (s)
  16952. "Replace \"|\" with \"\\vert\"."
  16953. (while (string-match "|" s)
  16954. (setq s (replace-match "\\vert" t t s)))
  16955. s)
  16956. (defun org-uuidgen-p (s)
  16957. "Is S an ID created by UUIDGEN?"
  16958. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16959. (defun org-in-src-block-p (&optional inside)
  16960. "Whether point is in a code source block.
  16961. When INSIDE is non-nil, don't consider we are within a source
  16962. block when point is at #+BEGIN_SRC or #+END_SRC."
  16963. (let ((case-fold-search t))
  16964. (or (and (eq (get-char-property (point) 'src-block) t))
  16965. (and (not inside)
  16966. (save-match-data
  16967. (save-excursion
  16968. (beginning-of-line)
  16969. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16970. (defun org-context ()
  16971. "Return a list of contexts of the current cursor position.
  16972. If several contexts apply, all are returned.
  16973. Each context entry is a list with a symbol naming the context, and
  16974. two positions indicating start and end of the context. Possible
  16975. contexts are:
  16976. :headline anywhere in a headline
  16977. :headline-stars on the leading stars in a headline
  16978. :todo-keyword on a TODO keyword (including DONE) in a headline
  16979. :tags on the TAGS in a headline
  16980. :priority on the priority cookie in a headline
  16981. :item on the first line of a plain list item
  16982. :item-bullet on the bullet/number of a plain list item
  16983. :checkbox on the checkbox in a plain list item
  16984. :table in an Org table
  16985. :table-special on a special filed in a table
  16986. :table-table in a table.el table
  16987. :clocktable in a clocktable
  16988. :src-block in a source block
  16989. :link on a hyperlink
  16990. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16991. :latex-fragment on a LaTeX fragment
  16992. :latex-preview on a LaTeX fragment with overlaid preview image
  16993. This function expects the position to be visible because it uses font-lock
  16994. faces as a help to recognize the following contexts: :table-special, :link,
  16995. and :keyword."
  16996. (let* ((f (get-text-property (point) 'face))
  16997. (faces (if (listp f) f (list f)))
  16998. (case-fold-search t)
  16999. (p (point)) clist o)
  17000. ;; First the large context
  17001. (cond
  17002. ((org-at-heading-p t)
  17003. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17004. (when (progn
  17005. (beginning-of-line 1)
  17006. (looking-at org-todo-line-tags-regexp))
  17007. (push (org-point-in-group p 1 :headline-stars) clist)
  17008. (push (org-point-in-group p 2 :todo-keyword) clist)
  17009. (push (org-point-in-group p 4 :tags) clist))
  17010. (goto-char p)
  17011. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17012. (when (looking-at "\\[#[A-Z0-9]\\]")
  17013. (push (org-point-in-group p 0 :priority) clist)))
  17014. ((org-at-item-p)
  17015. (push (org-point-in-group p 2 :item-bullet) clist)
  17016. (push (list :item (point-at-bol)
  17017. (save-excursion (org-end-of-item) (point)))
  17018. clist)
  17019. (and (org-at-item-checkbox-p)
  17020. (push (org-point-in-group p 0 :checkbox) clist)))
  17021. ((org-at-table-p)
  17022. (push (list :table (org-table-begin) (org-table-end)) clist)
  17023. (when (memq 'org-formula faces)
  17024. (push (list :table-special
  17025. (previous-single-property-change p 'face)
  17026. (next-single-property-change p 'face))
  17027. clist)))
  17028. ((org-at-table-p 'any)
  17029. (push (list :table-table) clist)))
  17030. (goto-char p)
  17031. (let ((case-fold-search t))
  17032. ;; New the "medium" contexts: clocktables, source blocks
  17033. (cond ((org-in-clocktable-p)
  17034. (push (list :clocktable
  17035. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17036. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17037. (match-beginning 1))
  17038. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17039. (match-end 0)))
  17040. clist))
  17041. ((org-in-src-block-p)
  17042. (push (list :src-block
  17043. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17044. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17045. (match-beginning 1))
  17046. (and (search-forward "#+END_SRC" nil t)
  17047. (match-beginning 0)))
  17048. clist))))
  17049. (goto-char p)
  17050. ;; Now the small context
  17051. (cond
  17052. ((org-at-timestamp-p)
  17053. (push (org-point-in-group p 0 :timestamp) clist))
  17054. ((memq 'org-link faces)
  17055. (push (list :link
  17056. (previous-single-property-change p 'face)
  17057. (next-single-property-change p 'face))
  17058. clist))
  17059. ((memq 'org-special-keyword faces)
  17060. (push (list :keyword
  17061. (previous-single-property-change p 'face)
  17062. (next-single-property-change p 'face))
  17063. clist))
  17064. ((setq o (cl-some
  17065. (lambda (o)
  17066. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17067. o))
  17068. (overlays-at (point))))
  17069. (push (list :latex-fragment
  17070. (overlay-start o) (overlay-end o))
  17071. clist)
  17072. (push (list :latex-preview
  17073. (overlay-start o) (overlay-end o))
  17074. clist))
  17075. ((org-inside-LaTeX-fragment-p)
  17076. ;; FIXME: positions wrong.
  17077. (push (list :latex-fragment (point) (point)) clist)))
  17078. (setq clist (nreverse (delq nil clist)))
  17079. clist))
  17080. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17081. "Non-nil when point is between matches of START-RE and END-RE.
  17082. Also return a non-nil value when point is on one of the matches.
  17083. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17084. buffer positions. Default values are the positions of headlines
  17085. surrounding the point.
  17086. The functions returns a cons cell whose car (resp. cdr) is the
  17087. position before START-RE (resp. after END-RE)."
  17088. (save-match-data
  17089. (let ((pos (point))
  17090. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17091. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17092. beg end)
  17093. (save-excursion
  17094. ;; Point is on a block when on START-RE or if START-RE can be
  17095. ;; found before it...
  17096. (and (or (org-in-regexp start-re)
  17097. (re-search-backward start-re limit-up t))
  17098. (setq beg (match-beginning 0))
  17099. ;; ... and END-RE after it...
  17100. (goto-char (match-end 0))
  17101. (re-search-forward end-re limit-down t)
  17102. (> (setq end (match-end 0)) pos)
  17103. ;; ... without another START-RE in-between.
  17104. (goto-char (match-beginning 0))
  17105. (not (re-search-backward start-re (1+ beg) t))
  17106. ;; Return value.
  17107. (cons beg end))))))
  17108. (defun org-in-block-p (names)
  17109. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17110. NAMES is a list of strings containing names of blocks.
  17111. Return first block name matched, or nil. Beware that in case of
  17112. nested blocks, the returned name may not belong to the closest
  17113. block from point."
  17114. (save-match-data
  17115. (catch 'exit
  17116. (let ((case-fold-search t)
  17117. (lim-up (save-excursion (outline-previous-heading)))
  17118. (lim-down (save-excursion (outline-next-heading))))
  17119. (dolist (name names)
  17120. (let ((n (regexp-quote name)))
  17121. (when (org-between-regexps-p
  17122. (concat "^[ \t]*#\\+begin_" n)
  17123. (concat "^[ \t]*#\\+end_" n)
  17124. lim-up lim-down)
  17125. (throw 'exit n)))))
  17126. nil)))
  17127. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17128. "Call `multi-occur' with buffers for all agenda files."
  17129. (interactive "sOrg-files matching: ")
  17130. (let* ((files (org-agenda-files))
  17131. (tnames (mapcar #'file-truename files))
  17132. (extra org-agenda-text-search-extra-files))
  17133. (when (eq (car extra) 'agenda-archives)
  17134. (setq extra (cdr extra))
  17135. (setq files (org-add-archive-files files)))
  17136. (dolist (f extra)
  17137. (unless (member (file-truename f) tnames)
  17138. (unless (member f files) (setq files (append files (list f))))
  17139. (setq tnames (append tnames (list (file-truename f))))))
  17140. (multi-occur
  17141. (mapcar (lambda (x)
  17142. (with-current-buffer
  17143. ;; FIXME: Why not just (find-file-noselect x)?
  17144. ;; Is it to avoid the "revert buffer" prompt?
  17145. (or (get-file-buffer x) (find-file-noselect x))
  17146. (widen)
  17147. (current-buffer)))
  17148. files)
  17149. regexp)))
  17150. (add-hook 'occur-mode-find-occurrence-hook
  17151. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17152. (defun org-occur-link-in-agenda-files ()
  17153. "Create a link and search for it in the agendas.
  17154. The link is not stored in `org-stored-links', it is just created
  17155. for the search purpose."
  17156. (interactive)
  17157. (let ((link (condition-case nil
  17158. (org-store-link nil)
  17159. (error "Unable to create a link to here"))))
  17160. (org-occur-in-agenda-files (regexp-quote link))))
  17161. (defun org-back-over-empty-lines ()
  17162. "Move backwards over whitespace, to the beginning of the first empty line.
  17163. Returns the number of empty lines passed."
  17164. (let ((pos (point)))
  17165. (if (cdr (assq 'heading org-blank-before-new-entry))
  17166. (skip-chars-backward " \t\n\r")
  17167. (unless (eobp)
  17168. (forward-line -1)))
  17169. (beginning-of-line 2)
  17170. (goto-char (min (point) pos))
  17171. (count-lines (point) pos)))
  17172. ;;; TODO: Only called once, from ox-odt which should probably use
  17173. ;;; org-export-inline-image-p or something.
  17174. (defun org-file-image-p (file)
  17175. "Return non-nil if FILE is an image."
  17176. (save-match-data
  17177. (string-match (image-file-name-regexp) file)))
  17178. (defun org-get-cursor-date (&optional with-time)
  17179. "Return the date at cursor in as a time.
  17180. This works in the calendar and in the agenda, anywhere else it just
  17181. returns the current time.
  17182. If WITH-TIME is non-nil, returns the time of the event at point (in
  17183. the agenda) or the current time of the day; otherwise returns the
  17184. earliest time on the cursor date that Org treats as that date
  17185. (bearing in mind `org-extend-today-until')."
  17186. (let (date day defd tp hod mod)
  17187. (when with-time
  17188. (setq tp (get-text-property (point) 'time))
  17189. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17190. (setq hod (string-to-number (match-string 1 tp))
  17191. mod (string-to-number (match-string 2 tp))))
  17192. (or tp (let ((now (decode-time)))
  17193. (setq hod (nth 2 now)
  17194. mod (nth 1 now)))))
  17195. (cond
  17196. ((eq major-mode 'calendar-mode)
  17197. (setq date (calendar-cursor-to-date)
  17198. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17199. (nth 1 date) (nth 0 date) (nth 2 date))))
  17200. ((eq major-mode 'org-agenda-mode)
  17201. (setq day (get-text-property (point) 'day))
  17202. (when day
  17203. (setq date (calendar-gregorian-from-absolute day)
  17204. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17205. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17206. (or defd (current-time))))
  17207. (defun org-mark-subtree (&optional up)
  17208. "Mark the current subtree.
  17209. This puts point at the start of the current subtree, and mark at
  17210. the end. If a numeric prefix UP is given, move up into the
  17211. hierarchy of headlines by UP levels before marking the subtree."
  17212. (interactive "P")
  17213. (org-with-limited-levels
  17214. (cond ((org-at-heading-p) (beginning-of-line))
  17215. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17216. (t (outline-previous-visible-heading 1))))
  17217. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17218. (if (called-interactively-p 'any)
  17219. (call-interactively 'org-mark-element)
  17220. (org-mark-element)))
  17221. ;;; Indentation
  17222. (defvar org-element-greater-elements)
  17223. (defun org--get-expected-indentation (element contentsp)
  17224. "Expected indentation column for current line, according to ELEMENT.
  17225. ELEMENT is an element containing point. CONTENTSP is non-nil
  17226. when indentation is to be computed according to contents of
  17227. ELEMENT."
  17228. (let ((type (org-element-type element))
  17229. (start (org-element-property :begin element))
  17230. (post-affiliated (org-element-property :post-affiliated element)))
  17231. (org-with-wide-buffer
  17232. (cond
  17233. (contentsp
  17234. (cl-case type
  17235. ((diary-sexp footnote-definition) 0)
  17236. ((headline inlinetask nil)
  17237. (if (not org-adapt-indentation) 0
  17238. (let ((level (org-current-level)))
  17239. (if level (1+ level) 0))))
  17240. ((item plain-list) (org-list-item-body-column post-affiliated))
  17241. (t
  17242. (goto-char start)
  17243. (current-indentation))))
  17244. ((and
  17245. (eq org-adapt-indentation 'headline-data)
  17246. (memq type '(planning clock node-property property-drawer drawer)))
  17247. (org--get-expected-indentation
  17248. (org-element-property :parent element) t))
  17249. ((memq type '(headline inlinetask nil))
  17250. (if (org-match-line "[ \t]*$")
  17251. (org--get-expected-indentation element t)
  17252. 0))
  17253. ((memq type '(diary-sexp footnote-definition)) 0)
  17254. ;; First paragraph of a footnote definition or an item.
  17255. ;; Indent like parent.
  17256. ((< (line-beginning-position) start)
  17257. (org--get-expected-indentation
  17258. (org-element-property :parent element) t))
  17259. ;; At first line: indent according to previous sibling, if any,
  17260. ;; ignoring footnote definitions and inline tasks, or parent's
  17261. ;; contents.
  17262. ((and ( = (line-beginning-position) start)
  17263. (eq org-adapt-indentation t))
  17264. (catch 'exit
  17265. (while t
  17266. (if (= (point-min) start) (throw 'exit 0)
  17267. (goto-char (1- start))
  17268. (let* ((previous (org-element-at-point))
  17269. (parent previous))
  17270. (while (and parent (<= (org-element-property :end parent) start))
  17271. (setq previous parent
  17272. parent (org-element-property :parent parent)))
  17273. (cond
  17274. ((not previous) (throw 'exit 0))
  17275. ((> (org-element-property :end previous) start)
  17276. (throw 'exit (org--get-expected-indentation previous t)))
  17277. ((memq (org-element-type previous)
  17278. '(footnote-definition inlinetask))
  17279. (setq start (org-element-property :begin previous)))
  17280. (t (goto-char (org-element-property :begin previous))
  17281. (throw 'exit
  17282. (if (bolp) (current-indentation)
  17283. ;; At first paragraph in an item or
  17284. ;; a footnote definition.
  17285. (org--get-expected-indentation
  17286. (org-element-property :parent previous) t))))))))))
  17287. ;; Otherwise, move to the first non-blank line above.
  17288. ((not (eq org-adapt-indentation 'headline-data))
  17289. (beginning-of-line)
  17290. (let ((pos (point)))
  17291. (skip-chars-backward " \r\t\n")
  17292. (cond
  17293. ;; Two blank lines end a footnote definition or a plain
  17294. ;; list. When we indent an empty line after them, the
  17295. ;; containing list or footnote definition is over, so it
  17296. ;; qualifies as a previous sibling. Therefore, we indent
  17297. ;; like its first line.
  17298. ((and (memq type '(footnote-definition plain-list))
  17299. (> (count-lines (point) pos) 2))
  17300. (goto-char start)
  17301. (current-indentation))
  17302. ;; Line above is the first one of a paragraph at the
  17303. ;; beginning of an item or a footnote definition. Indent
  17304. ;; like parent.
  17305. ((< (line-beginning-position) start)
  17306. (org--get-expected-indentation
  17307. (org-element-property :parent element) t))
  17308. ;; Line above is the beginning of an element, i.e., point
  17309. ;; was originally on the blank lines between element's start
  17310. ;; and contents.
  17311. ((= (line-beginning-position) post-affiliated)
  17312. (org--get-expected-indentation element t))
  17313. ;; POS is after contents in a greater element. Indent like
  17314. ;; the beginning of the element.
  17315. ((and (memq type org-element-greater-elements)
  17316. (let ((cend (org-element-property :contents-end element)))
  17317. (and cend (<= cend pos))))
  17318. ;; As a special case, if point is at the end of a footnote
  17319. ;; definition or an item, indent like the very last element
  17320. ;; within. If that last element is an item, indent like
  17321. ;; its contents.
  17322. (if (memq type '(footnote-definition item plain-list))
  17323. (let ((last (org-element-at-point)))
  17324. (goto-char pos)
  17325. (org--get-expected-indentation
  17326. last (eq (org-element-type last) 'item)))
  17327. (goto-char start)
  17328. (current-indentation)))
  17329. ;; In any other case, indent like the current line.
  17330. (t (current-indentation)))))
  17331. ;; Finally, no indentation is needed, fall back to 0.
  17332. (t (current-indentation))))))
  17333. (defun org--align-node-property ()
  17334. "Align node property at point.
  17335. Alignment is done according to `org-property-format', which see."
  17336. (when (save-excursion
  17337. (beginning-of-line)
  17338. (looking-at org-property-re))
  17339. (replace-match
  17340. (concat (match-string 4)
  17341. (org-trim
  17342. (format org-property-format (match-string 1) (match-string 3))))
  17343. t t)))
  17344. (defun org-indent-line ()
  17345. "Indent line depending on context.
  17346. Indentation is done according to the following rules:
  17347. - Footnote definitions, diary sexps, headlines and inline tasks
  17348. have to start at column 0.
  17349. - On the very first line of an element, consider, in order, the
  17350. next rules until one matches:
  17351. 1. If there's a sibling element before, ignoring footnote
  17352. definitions and inline tasks, indent like its first line.
  17353. 2. If element has a parent, indent like its contents. More
  17354. precisely, if parent is an item, indent after the bullet.
  17355. Else, indent like parent's first line.
  17356. 3. Otherwise, indent relatively to current level, if
  17357. `org-adapt-indentation' is non-nil, or to left margin.
  17358. - On a blank line at the end of an element, indent according to
  17359. the type of the element. More precisely
  17360. 1. If element is a plain list, an item, or a footnote
  17361. definition, indent like the very last element within.
  17362. 2. If element is a paragraph, indent like its last non blank
  17363. line.
  17364. 3. Otherwise, indent like its very first line.
  17365. - In the code part of a source block, use language major mode
  17366. to indent current line if `org-src-tab-acts-natively' is
  17367. non-nil. If it is nil, do nothing.
  17368. - Otherwise, indent like the first non-blank line above.
  17369. The function doesn't indent an item as it could break the whole
  17370. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17371. `\\[org-shiftmetaright]'.
  17372. Also align node properties according to `org-property-format'."
  17373. (interactive)
  17374. (unless (org-at-heading-p)
  17375. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17376. (type (org-element-type element)))
  17377. (cond ((and (memq type '(plain-list item))
  17378. (= (line-beginning-position)
  17379. (org-element-property :post-affiliated element)))
  17380. nil)
  17381. ((and (eq type 'latex-environment)
  17382. (>= (point) (org-element-property :post-affiliated element))
  17383. (< (point)
  17384. (org-with-point-at (org-element-property :end element)
  17385. (skip-chars-backward " \t\n")
  17386. (line-beginning-position 2))))
  17387. nil)
  17388. ((and (eq type 'src-block)
  17389. org-src-tab-acts-natively
  17390. (> (line-beginning-position)
  17391. (org-element-property :post-affiliated element))
  17392. (< (line-beginning-position)
  17393. (org-with-point-at (org-element-property :end element)
  17394. (skip-chars-backward " \t\n")
  17395. (line-beginning-position))))
  17396. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17397. (t
  17398. (let ((column (org--get-expected-indentation element nil)))
  17399. ;; Preserve current column.
  17400. (if (<= (current-column) (current-indentation))
  17401. (indent-line-to column)
  17402. (save-excursion (indent-line-to column))))
  17403. ;; Align node property. Also preserve current column.
  17404. (when (eq type 'node-property)
  17405. (let ((column (current-column)))
  17406. (org--align-node-property)
  17407. (org-move-to-column column))))))))
  17408. (defun org-indent-region (start end)
  17409. "Indent each non-blank line in the region.
  17410. Called from a program, START and END specify the region to
  17411. indent. The function will not indent contents of example blocks,
  17412. verse blocks and export blocks as leading white spaces are
  17413. assumed to be significant there."
  17414. (interactive "r")
  17415. (save-excursion
  17416. (goto-char start)
  17417. (skip-chars-forward " \r\t\n")
  17418. (unless (eobp) (beginning-of-line))
  17419. (let ((indent-to
  17420. (lambda (ind pos)
  17421. ;; Set IND as indentation for all lines between point and
  17422. ;; POS. Blank lines are ignored. Leave point after POS
  17423. ;; once done.
  17424. (let ((limit (copy-marker pos)))
  17425. (while (< (point) limit)
  17426. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17427. (forward-line))
  17428. (set-marker limit nil))))
  17429. (end (copy-marker end)))
  17430. (while (< (point) end)
  17431. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17432. (let* ((element (org-element-at-point))
  17433. (type (org-element-type element))
  17434. (element-end (copy-marker (org-element-property :end element)))
  17435. (ind (org--get-expected-indentation element nil)))
  17436. (cond
  17437. ;; Element indented as a single block. Example blocks
  17438. ;; preserving indentation are a special case since the
  17439. ;; "contents" must not be indented whereas the block
  17440. ;; boundaries can.
  17441. ((or (memq type '(export-block latex-environment))
  17442. (and (eq type 'example-block)
  17443. (not
  17444. (or org-src-preserve-indentation
  17445. (org-element-property :preserve-indent element)))))
  17446. (let ((offset (- ind (current-indentation))))
  17447. (unless (zerop offset)
  17448. (indent-rigidly (org-element-property :begin element)
  17449. (org-element-property :end element)
  17450. offset)))
  17451. (goto-char element-end))
  17452. ;; Elements indented line wise. Be sure to exclude
  17453. ;; example blocks (preserving indentation) and source
  17454. ;; blocks from this category as they are treated
  17455. ;; specially later.
  17456. ((or (memq type '(paragraph table table-row))
  17457. (not (or (org-element-property :contents-begin element)
  17458. (memq type '(example-block src-block)))))
  17459. (when (eq type 'node-property)
  17460. (org--align-node-property)
  17461. (beginning-of-line))
  17462. (funcall indent-to ind (min element-end end)))
  17463. ;; Elements consisting of three parts: before the
  17464. ;; contents, the contents, and after the contents. The
  17465. ;; contents are treated specially, according to the
  17466. ;; element type, or not indented at all. Other parts are
  17467. ;; indented as a single block.
  17468. (t
  17469. (let* ((post (copy-marker
  17470. (org-element-property :post-affiliated element)))
  17471. (cbeg
  17472. (copy-marker
  17473. (cond
  17474. ((not (org-element-property :contents-begin element))
  17475. ;; Fake contents for source blocks.
  17476. (org-with-wide-buffer
  17477. (goto-char post)
  17478. (line-beginning-position 2)))
  17479. ((memq type '(footnote-definition item plain-list))
  17480. ;; Contents in these elements could start on
  17481. ;; the same line as the beginning of the
  17482. ;; element. Make sure we start indenting
  17483. ;; from the second line.
  17484. (org-with-wide-buffer
  17485. (goto-char post)
  17486. (end-of-line)
  17487. (skip-chars-forward " \r\t\n")
  17488. (if (eobp) (point) (line-beginning-position))))
  17489. (t (org-element-property :contents-begin element)))))
  17490. (cend (copy-marker
  17491. (or (org-element-property :contents-end element)
  17492. ;; Fake contents for source blocks.
  17493. (org-with-wide-buffer
  17494. (goto-char element-end)
  17495. (skip-chars-backward " \r\t\n")
  17496. (line-beginning-position)))
  17497. t)))
  17498. ;; Do not change items indentation individually as it
  17499. ;; might break the list as a whole. On the other
  17500. ;; hand, when at a plain list, indent it as a whole.
  17501. (cond ((eq type 'plain-list)
  17502. (let ((offset (- ind (current-indentation))))
  17503. (unless (zerop offset)
  17504. (indent-rigidly (org-element-property :begin element)
  17505. (org-element-property :end element)
  17506. offset))
  17507. (goto-char cbeg)))
  17508. ((eq type 'item) (goto-char cbeg))
  17509. (t (funcall indent-to ind (min cbeg end))))
  17510. (when (< (point) end)
  17511. (cl-case type
  17512. ((example-block verse-block))
  17513. (src-block
  17514. ;; In a source block, indent source code
  17515. ;; according to language major mode, but only if
  17516. ;; `org-src-tab-acts-natively' is non-nil.
  17517. (when (and (< (point) end) org-src-tab-acts-natively)
  17518. (ignore-errors
  17519. (org-babel-do-in-edit-buffer
  17520. (indent-region (point-min) (point-max))))))
  17521. (t (org-indent-region (point) (min cend end))))
  17522. (goto-char (min cend end))
  17523. (when (< (point) end)
  17524. (funcall indent-to ind (min element-end end))))
  17525. (set-marker post nil)
  17526. (set-marker cbeg nil)
  17527. (set-marker cend nil))))
  17528. (set-marker element-end nil))))
  17529. (set-marker end nil))))
  17530. (defun org-indent-drawer ()
  17531. "Indent the drawer at point."
  17532. (interactive)
  17533. (unless (save-excursion
  17534. (beginning-of-line)
  17535. (looking-at-p org-drawer-regexp))
  17536. (user-error "Not at a drawer"))
  17537. (let ((element (org-element-at-point)))
  17538. (unless (memq (org-element-type element) '(drawer property-drawer))
  17539. (user-error "Not at a drawer"))
  17540. (org-with-wide-buffer
  17541. (org-indent-region (org-element-property :begin element)
  17542. (org-element-property :end element))))
  17543. (message "Drawer at point indented"))
  17544. (defun org-indent-block ()
  17545. "Indent the block at point."
  17546. (interactive)
  17547. (unless (save-excursion
  17548. (beginning-of-line)
  17549. (let ((case-fold-search t))
  17550. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17551. (user-error "Not at a block"))
  17552. (let ((element (org-element-at-point)))
  17553. (unless (memq (org-element-type element)
  17554. '(comment-block center-block dynamic-block example-block
  17555. export-block quote-block special-block
  17556. src-block verse-block))
  17557. (user-error "Not at a block"))
  17558. (org-with-wide-buffer
  17559. (org-indent-region (org-element-property :begin element)
  17560. (org-element-property :end element))))
  17561. (message "Block at point indented"))
  17562. ;;; Filling
  17563. ;; We use our own fill-paragraph and auto-fill functions.
  17564. ;; `org-fill-paragraph' relies on adaptive filling and context
  17565. ;; checking. Appropriate `fill-prefix' is computed with
  17566. ;; `org-adaptive-fill-function'.
  17567. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17568. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17569. ;; `org-adaptive-fill-function' value. Internally,
  17570. ;; `org-comment-line-break-function' breaks the line.
  17571. ;; `org-setup-filling' installs filling and auto-filling related
  17572. ;; variables during `org-mode' initialization.
  17573. (defun org-setup-filling ()
  17574. (require 'org-element)
  17575. ;; Prevent auto-fill from inserting unwanted new items.
  17576. (when (boundp 'fill-nobreak-predicate)
  17577. (setq-local
  17578. fill-nobreak-predicate
  17579. (org-uniquify
  17580. (append fill-nobreak-predicate
  17581. '(org-fill-line-break-nobreak-p
  17582. org-fill-n-macro-as-item-nobreak-p
  17583. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17584. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17585. (setq-local paragraph-start paragraph-ending)
  17586. (setq-local paragraph-separate paragraph-ending))
  17587. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17588. (setq-local auto-fill-inhibit-regexp nil)
  17589. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17590. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17591. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17592. (defun org-fill-line-break-nobreak-p ()
  17593. "Non-nil when a new line at point would create an Org line break."
  17594. (save-excursion
  17595. (skip-chars-backward " \t")
  17596. (skip-chars-backward "\\\\")
  17597. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17598. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17599. "Non-nil when a new line at point would split a timestamp."
  17600. (and (org-at-timestamp-p 'lax)
  17601. (not (looking-at org-ts-regexp-both))))
  17602. (defun org-fill-n-macro-as-item-nobreak-p ()
  17603. "Non-nil when a new line at point would create a new list."
  17604. ;; During export, a "n" macro followed by a dot or a closing
  17605. ;; parenthesis can end up being parsed as a new list item.
  17606. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17607. (defun org-adaptive-fill-function ()
  17608. "Compute a fill prefix for the current line.
  17609. Return fill prefix, as a string, or nil if current line isn't
  17610. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17611. matches in paragraphs or comments, use it."
  17612. (org-with-wide-buffer
  17613. (unless (org-at-heading-p)
  17614. (let* ((p (line-beginning-position))
  17615. (element (save-excursion
  17616. (beginning-of-line)
  17617. (org-element-at-point)))
  17618. (type (org-element-type element))
  17619. (post-affiliated (org-element-property :post-affiliated element)))
  17620. (unless (< p post-affiliated)
  17621. (cl-case type
  17622. (comment
  17623. (save-excursion
  17624. (beginning-of-line)
  17625. (looking-at "[ \t]*")
  17626. (concat (match-string 0) "# ")))
  17627. (footnote-definition "")
  17628. ((item plain-list)
  17629. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17630. (paragraph
  17631. ;; Fill prefix is usually the same as the current line,
  17632. ;; unless the paragraph is at the beginning of an item.
  17633. (let ((parent (org-element-property :parent element)))
  17634. (save-excursion
  17635. (beginning-of-line)
  17636. (cond ((eq (org-element-type parent) 'item)
  17637. (make-string (org-list-item-body-column
  17638. (org-element-property :begin parent))
  17639. ?\s))
  17640. ((and adaptive-fill-regexp
  17641. ;; Locally disable
  17642. ;; `adaptive-fill-function' to let
  17643. ;; `fill-context-prefix' handle
  17644. ;; `adaptive-fill-regexp' variable.
  17645. (let (adaptive-fill-function)
  17646. (fill-context-prefix
  17647. post-affiliated
  17648. (org-element-property :end element)))))
  17649. ((looking-at "[ \t]+") (match-string 0))
  17650. (t "")))))
  17651. (comment-block
  17652. ;; Only fill contents if P is within block boundaries.
  17653. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17654. (forward-line)
  17655. (point)))
  17656. (cend (save-excursion
  17657. (goto-char (org-element-property :end element))
  17658. (skip-chars-backward " \r\t\n")
  17659. (line-beginning-position))))
  17660. (when (and (>= p cbeg) (< p cend))
  17661. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17662. (match-string 0)
  17663. ""))))))))))
  17664. (defun org-fill-element (&optional justify)
  17665. "Fill element at point, when applicable.
  17666. This function only applies to comment blocks, comments, example
  17667. blocks and paragraphs. Also, as a special case, re-align table
  17668. when point is at one.
  17669. If JUSTIFY is non-nil (interactively, with prefix argument),
  17670. justify as well. If `sentence-end-double-space' is non-nil, then
  17671. period followed by one space does not end a sentence, so don't
  17672. break a line there. The variable `fill-column' controls the
  17673. width for filling.
  17674. For convenience, when point is at a plain list, an item or
  17675. a footnote definition, try to fill the first paragraph within."
  17676. (with-syntax-table org-mode-transpose-word-syntax-table
  17677. ;; Move to end of line in order to get the first paragraph within
  17678. ;; a plain list or a footnote definition.
  17679. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17680. ;; First check if point is in a blank line at the beginning of
  17681. ;; the buffer. In that case, ignore filling.
  17682. (cl-case (org-element-type element)
  17683. ;; Use major mode filling function is source blocks.
  17684. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17685. ;; Align Org tables, leave table.el tables as-is.
  17686. (table-row (org-table-align) t)
  17687. (table
  17688. (when (eq (org-element-property :type element) 'org)
  17689. (save-excursion
  17690. (goto-char (org-element-property :post-affiliated element))
  17691. (org-table-align)))
  17692. t)
  17693. (paragraph
  17694. ;; Paragraphs may contain `line-break' type objects.
  17695. (let ((beg (max (point-min)
  17696. (org-element-property :contents-begin element)))
  17697. (end (min (point-max)
  17698. (org-element-property :contents-end element))))
  17699. ;; Do nothing if point is at an affiliated keyword.
  17700. (if (< (line-end-position) beg) t
  17701. ;; Fill paragraph, taking line breaks into account.
  17702. (save-excursion
  17703. (goto-char beg)
  17704. (let ((cuts (list beg)))
  17705. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17706. (when (eq 'line-break
  17707. (org-element-type
  17708. (save-excursion (backward-char)
  17709. (org-element-context))))
  17710. (push (point) cuts)))
  17711. (dolist (c (delq end cuts))
  17712. (fill-region-as-paragraph c end justify)
  17713. (setq end c))))
  17714. t)))
  17715. ;; Contents of `comment-block' type elements should be
  17716. ;; filled as plain text, but only if point is within block
  17717. ;; markers.
  17718. (comment-block
  17719. (let* ((case-fold-search t)
  17720. (beg (save-excursion
  17721. (goto-char (org-element-property :begin element))
  17722. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17723. (forward-line)
  17724. (point)))
  17725. (end (save-excursion
  17726. (goto-char (org-element-property :end element))
  17727. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17728. (line-beginning-position))))
  17729. (if (or (< (point) beg) (> (point) end)) t
  17730. (fill-region-as-paragraph
  17731. (save-excursion (end-of-line)
  17732. (re-search-backward "^[ \t]*$" beg 'move)
  17733. (line-beginning-position))
  17734. (save-excursion (beginning-of-line)
  17735. (re-search-forward "^[ \t]*$" end 'move)
  17736. (line-beginning-position))
  17737. justify))))
  17738. ;; Fill comments.
  17739. (comment
  17740. (let ((begin (org-element-property :post-affiliated element))
  17741. (end (org-element-property :end element)))
  17742. (when (and (>= (point) begin) (<= (point) end))
  17743. (let ((begin (save-excursion
  17744. (end-of-line)
  17745. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17746. (progn (forward-line) (point))
  17747. begin)))
  17748. (end (save-excursion
  17749. (end-of-line)
  17750. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17751. (1- (line-beginning-position))
  17752. (skip-chars-backward " \r\t\n")
  17753. (line-end-position)))))
  17754. ;; Do not fill comments when at a blank line.
  17755. (when (> end begin)
  17756. (let ((fill-prefix
  17757. (save-excursion
  17758. (beginning-of-line)
  17759. (looking-at "[ \t]*#")
  17760. (let ((comment-prefix (match-string 0)))
  17761. (goto-char (match-end 0))
  17762. (if (looking-at adaptive-fill-regexp)
  17763. (concat comment-prefix (match-string 0))
  17764. (concat comment-prefix " "))))))
  17765. (save-excursion
  17766. (fill-region-as-paragraph begin end justify))))))
  17767. t))
  17768. ;; Ignore every other element.
  17769. (otherwise t)))))
  17770. (defun org-fill-paragraph (&optional justify region)
  17771. "Fill element at point, when applicable.
  17772. This function only applies to comment blocks, comments, example
  17773. blocks and paragraphs. Also, as a special case, re-align table
  17774. when point is at one.
  17775. For convenience, when point is at a plain list, an item or
  17776. a footnote definition, try to fill the first paragraph within.
  17777. If JUSTIFY is non-nil (interactively, with prefix argument),
  17778. justify as well. If `sentence-end-double-space' is non-nil, then
  17779. period followed by one space does not end a sentence, so don't
  17780. break a line there. The variable `fill-column' controls the
  17781. width for filling.
  17782. The REGION argument is non-nil if called interactively; in that
  17783. case, if Transient Mark mode is enabled and the mark is active,
  17784. fill each of the elements in the active region, instead of just
  17785. filling the current element."
  17786. (interactive (progn
  17787. (barf-if-buffer-read-only)
  17788. (list (when current-prefix-arg 'full) t)))
  17789. (let ((hash (and (not (buffer-modified-p))
  17790. (org-buffer-hash))))
  17791. (cond
  17792. ((and region transient-mark-mode mark-active
  17793. (not (eq (region-beginning) (region-end))))
  17794. (let ((origin (point-marker))
  17795. (start (region-beginning)))
  17796. (unwind-protect
  17797. (progn
  17798. (goto-char (region-end))
  17799. (skip-chars-backward " \t\n")
  17800. (while (> (point) start)
  17801. (org-fill-element justify)
  17802. (org-backward-paragraph)))
  17803. (goto-char origin)
  17804. (set-marker origin nil))))
  17805. (t
  17806. (save-excursion
  17807. (when (org-match-line "[ \t]*$")
  17808. (skip-chars-forward " \t\n"))
  17809. (org-fill-element justify))))
  17810. ;; If we didn't change anything in the buffer (and the buffer was
  17811. ;; previously unmodified), then flip the modification status back
  17812. ;; to "unchanged".
  17813. (when (and hash (equal hash (org-buffer-hash)))
  17814. (set-buffer-modified-p nil))))
  17815. (defun org-auto-fill-function ()
  17816. "Auto-fill function."
  17817. ;; Check if auto-filling is meaningful.
  17818. (let ((fc (current-fill-column)))
  17819. (when (and fc (> (current-column) fc))
  17820. (let* ((fill-prefix (org-adaptive-fill-function))
  17821. ;; Enforce empty fill prefix, if required. Otherwise, it
  17822. ;; will be computed again.
  17823. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17824. (when fill-prefix (do-auto-fill))))))
  17825. (defun org-comment-line-break-function (&optional soft)
  17826. "Break line at point and indent, continuing comment if within one.
  17827. The inserted newline is marked hard if variable
  17828. `use-hard-newlines' is true, unless optional argument SOFT is
  17829. non-nil."
  17830. (if soft (insert-and-inherit ?\n) (newline 1))
  17831. (save-excursion (forward-char -1) (delete-horizontal-space))
  17832. (delete-horizontal-space)
  17833. (indent-to-left-margin)
  17834. (insert-before-markers-and-inherit fill-prefix))
  17835. ;;; Fixed Width Areas
  17836. (defun org-toggle-fixed-width ()
  17837. "Toggle fixed-width markup.
  17838. Add or remove fixed-width markup on current line, whenever it
  17839. makes sense. Return an error otherwise.
  17840. If a region is active and if it contains only fixed-width areas
  17841. or blank lines, remove all fixed-width markup in it. If the
  17842. region contains anything else, convert all non-fixed-width lines
  17843. to fixed-width ones.
  17844. Blank lines at the end of the region are ignored unless the
  17845. region only contains such lines."
  17846. (interactive)
  17847. (if (not (org-region-active-p))
  17848. ;; No region:
  17849. ;;
  17850. ;; Remove fixed width marker only in a fixed-with element.
  17851. ;;
  17852. ;; Add fixed width maker in paragraphs, in blank lines after
  17853. ;; elements or at the beginning of a headline or an inlinetask,
  17854. ;; and before any one-line elements (e.g., a clock).
  17855. (progn
  17856. (beginning-of-line)
  17857. (let* ((element (org-element-at-point))
  17858. (type (org-element-type element)))
  17859. (cond
  17860. ((and (eq type 'fixed-width)
  17861. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17862. (replace-match
  17863. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17864. ((and (memq type '(babel-call clock comment diary-sexp headline
  17865. horizontal-rule keyword paragraph
  17866. planning))
  17867. (<= (org-element-property :post-affiliated element) (point)))
  17868. (skip-chars-forward " \t")
  17869. (insert ": "))
  17870. ((and (looking-at-p "[ \t]*$")
  17871. (or (eq type 'inlinetask)
  17872. (save-excursion
  17873. (skip-chars-forward " \r\t\n")
  17874. (<= (org-element-property :end element) (point)))))
  17875. (delete-region (point) (line-end-position))
  17876. (org-indent-line)
  17877. (insert ": "))
  17878. (t (user-error "Cannot insert a fixed-width line here")))))
  17879. ;; Region active.
  17880. (let* ((begin (save-excursion
  17881. (goto-char (region-beginning))
  17882. (line-beginning-position)))
  17883. (end (copy-marker
  17884. (save-excursion
  17885. (goto-char (region-end))
  17886. (unless (eolp) (beginning-of-line))
  17887. (if (save-excursion (re-search-backward "\\S-" begin t))
  17888. (progn (skip-chars-backward " \r\t\n") (point))
  17889. (point)))))
  17890. (all-fixed-width-p
  17891. (catch 'not-all-p
  17892. (save-excursion
  17893. (goto-char begin)
  17894. (skip-chars-forward " \r\t\n")
  17895. (when (eobp) (throw 'not-all-p nil))
  17896. (while (< (point) end)
  17897. (let ((element (org-element-at-point)))
  17898. (if (eq (org-element-type element) 'fixed-width)
  17899. (goto-char (org-element-property :end element))
  17900. (throw 'not-all-p nil))))
  17901. t))))
  17902. (if all-fixed-width-p
  17903. (save-excursion
  17904. (goto-char begin)
  17905. (while (< (point) end)
  17906. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17907. (replace-match
  17908. "" nil nil nil
  17909. (if (= (line-end-position) (match-end 0)) 0 1)))
  17910. (forward-line)))
  17911. (let ((min-ind (point-max)))
  17912. ;; Find minimum indentation across all lines.
  17913. (save-excursion
  17914. (goto-char begin)
  17915. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17916. (setq min-ind 0)
  17917. (catch 'zerop
  17918. (while (< (point) end)
  17919. (unless (looking-at-p "[ \t]*$")
  17920. (let ((ind (current-indentation)))
  17921. (setq min-ind (min min-ind ind))
  17922. (when (zerop ind) (throw 'zerop t))))
  17923. (forward-line)))))
  17924. ;; Loop over all lines and add fixed-width markup everywhere
  17925. ;; but in fixed-width lines.
  17926. (save-excursion
  17927. (goto-char begin)
  17928. (while (< (point) end)
  17929. (cond
  17930. ((org-at-heading-p)
  17931. (insert ": ")
  17932. (forward-line)
  17933. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17934. (insert ":")
  17935. (forward-line)))
  17936. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17937. (let* ((element (org-element-at-point))
  17938. (element-end (org-element-property :end element)))
  17939. (if (eq (org-element-type element) 'fixed-width)
  17940. (progn (goto-char element-end)
  17941. (skip-chars-backward " \r\t\n")
  17942. (forward-line))
  17943. (let ((limit (min end element-end)))
  17944. (while (< (point) limit)
  17945. (org-move-to-column min-ind t)
  17946. (insert ": ")
  17947. (forward-line))))))
  17948. (t
  17949. (org-move-to-column min-ind t)
  17950. (insert ": ")
  17951. (forward-line)))))))
  17952. (set-marker end nil))))
  17953. ;;; Blocks
  17954. (defun org-block-map (function &optional start end)
  17955. "Call FUNCTION at the head of all source blocks in the current buffer.
  17956. Optional arguments START and END can be used to limit the range."
  17957. (let ((start (or start (point-min)))
  17958. (end (or end (point-max))))
  17959. (save-excursion
  17960. (goto-char start)
  17961. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17962. (save-excursion
  17963. (save-match-data
  17964. (goto-char (match-beginning 0))
  17965. (funcall function)))))))
  17966. (defun org-next-block (arg &optional backward block-regexp)
  17967. "Jump to the next block.
  17968. With a prefix argument ARG, jump forward ARG many blocks.
  17969. When BACKWARD is non-nil, jump to the previous block.
  17970. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17971. Match data is set according to this regexp when the function
  17972. returns.
  17973. Return point at beginning of the opening line of found block.
  17974. Throw an error if no block is found."
  17975. (interactive "p")
  17976. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17977. (case-fold-search t)
  17978. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17979. (count (or arg 1))
  17980. (origin (point))
  17981. last-element)
  17982. (if backward (beginning-of-line) (end-of-line))
  17983. (while (and (> count 0) (funcall search-fn re nil t))
  17984. (let ((element (save-excursion
  17985. (goto-char (match-beginning 0))
  17986. (save-match-data (org-element-at-point)))))
  17987. (when (and (memq (org-element-type element)
  17988. '(center-block comment-block dynamic-block
  17989. example-block export-block quote-block
  17990. special-block src-block verse-block))
  17991. (<= (match-beginning 0)
  17992. (org-element-property :post-affiliated element)))
  17993. (setq last-element element)
  17994. (cl-decf count))))
  17995. (if (= count 0)
  17996. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17997. (save-match-data (org-show-context)))
  17998. (goto-char origin)
  17999. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18000. (defun org-previous-block (arg &optional block-regexp)
  18001. "Jump to the previous block.
  18002. With a prefix argument ARG, jump backward ARG many source blocks.
  18003. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18004. (interactive "p")
  18005. (org-next-block arg t block-regexp))
  18006. ;;; Comments
  18007. ;; Org comments syntax is quite complex. It requires the entire line
  18008. ;; to be just a comment. Also, even with the right syntax at the
  18009. ;; beginning of line, some elements (e.g., verse-block or
  18010. ;; example-block) don't accept comments. Usual Emacs comment commands
  18011. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18012. ;; Org still relies on `comment-dwim', but cannot trust
  18013. ;; `comment-only-p'. So, `comment-region-function' and
  18014. ;; `uncomment-region-function' both point
  18015. ;; to`org-comment-or-uncomment-region'. Eventually,
  18016. ;; `org-insert-comment' takes care of insertion of comments at the
  18017. ;; beginning of line.
  18018. ;; `org-setup-comments-handling' install comments related variables
  18019. ;; during `org-mode' initialization.
  18020. (defun org-setup-comments-handling ()
  18021. (interactive)
  18022. (setq-local comment-use-syntax nil)
  18023. (setq-local comment-start "# ")
  18024. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18025. (setq-local comment-insert-comment-function 'org-insert-comment)
  18026. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18027. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18028. (defun org-insert-comment ()
  18029. "Insert an empty comment above current line.
  18030. If the line is empty, insert comment at its beginning. When
  18031. point is within a source block, comment according to the related
  18032. major mode."
  18033. (if (let ((element (org-element-at-point)))
  18034. (and (eq (org-element-type element) 'src-block)
  18035. (< (save-excursion
  18036. (goto-char (org-element-property :post-affiliated element))
  18037. (line-end-position))
  18038. (point))
  18039. (> (save-excursion
  18040. (goto-char (org-element-property :end element))
  18041. (skip-chars-backward " \r\t\n")
  18042. (line-beginning-position))
  18043. (point))))
  18044. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18045. (beginning-of-line)
  18046. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18047. (open-line 1))
  18048. (org-indent-line)
  18049. (insert "# ")))
  18050. (defvar comment-empty-lines) ; From newcomment.el.
  18051. (defun org-comment-or-uncomment-region (beg end &rest _)
  18052. "Comment or uncomment each non-blank line in the region.
  18053. Uncomment each non-blank line between BEG and END if it only
  18054. contains commented lines. Otherwise, comment them. If region is
  18055. strictly within a source block, use appropriate comment syntax."
  18056. (if (let ((element (org-element-at-point)))
  18057. (and (eq (org-element-type element) 'src-block)
  18058. (< (save-excursion
  18059. (goto-char (org-element-property :post-affiliated element))
  18060. (line-end-position))
  18061. beg)
  18062. (>= (save-excursion
  18063. (goto-char (org-element-property :end element))
  18064. (skip-chars-backward " \r\t\n")
  18065. (line-beginning-position))
  18066. end)))
  18067. ;; Translate region boundaries for the Org buffer to the source
  18068. ;; buffer.
  18069. (let ((offset (- end beg)))
  18070. (save-excursion
  18071. (goto-char beg)
  18072. (org-babel-do-in-edit-buffer
  18073. (comment-or-uncomment-region (point) (+ offset (point))))))
  18074. (save-restriction
  18075. ;; Restrict region
  18076. (narrow-to-region (save-excursion (goto-char beg)
  18077. (skip-chars-forward " \r\t\n" end)
  18078. (line-beginning-position))
  18079. (save-excursion (goto-char end)
  18080. (skip-chars-backward " \r\t\n" beg)
  18081. (line-end-position)))
  18082. (let ((uncommentp
  18083. ;; UNCOMMENTP is non-nil when every non blank line between
  18084. ;; BEG and END is a comment.
  18085. (save-excursion
  18086. (goto-char (point-min))
  18087. (while (and (not (eobp))
  18088. (let ((element (org-element-at-point)))
  18089. (and (eq (org-element-type element) 'comment)
  18090. (goto-char (min (point-max)
  18091. (org-element-property
  18092. :end element)))))))
  18093. (eobp))))
  18094. (if uncommentp
  18095. ;; Only blank lines and comments in region: uncomment it.
  18096. (save-excursion
  18097. (goto-char (point-min))
  18098. (while (not (eobp))
  18099. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18100. (replace-match "" nil nil nil 1))
  18101. (forward-line)))
  18102. ;; Comment each line in region.
  18103. (let ((min-indent (point-max)))
  18104. ;; First find the minimum indentation across all lines.
  18105. (save-excursion
  18106. (goto-char (point-min))
  18107. (while (and (not (eobp)) (not (zerop min-indent)))
  18108. (unless (looking-at "[ \t]*$")
  18109. (setq min-indent (min min-indent (current-indentation))))
  18110. (forward-line)))
  18111. ;; Then loop over all lines.
  18112. (save-excursion
  18113. (goto-char (point-min))
  18114. (while (not (eobp))
  18115. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18116. ;; Don't get fooled by invisible text (e.g. link path)
  18117. ;; when moving to column MIN-INDENT.
  18118. (let ((buffer-invisibility-spec nil))
  18119. (org-move-to-column min-indent t))
  18120. (insert comment-start))
  18121. (forward-line)))))))))
  18122. (defun org-comment-dwim (_arg)
  18123. "Call the comment command you mean.
  18124. Call `org-toggle-comment' if on a heading, otherwise call
  18125. `comment-dwim', within a source edit buffer if needed."
  18126. (interactive "*P")
  18127. (cond ((org-at-heading-p)
  18128. (call-interactively #'org-toggle-comment))
  18129. ((org-in-src-block-p)
  18130. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18131. (t (call-interactively #'comment-dwim))))
  18132. ;;; Timestamps API
  18133. ;; This section contains tools to operate on, or create, timestamp
  18134. ;; objects, as returned by, e.g. `org-element-context'.
  18135. (defun org-timestamp-from-string (s)
  18136. "Convert Org timestamp S, as a string, into a timestamp object.
  18137. Return nil if S is not a valid timestamp string."
  18138. (when (org-string-nw-p s)
  18139. (with-temp-buffer
  18140. (save-excursion (insert s))
  18141. (org-element-timestamp-parser))))
  18142. (defun org-timestamp-from-time (time &optional with-time inactive)
  18143. "Convert a time value into a timestamp object.
  18144. TIME is an Emacs internal time representation, as returned, e.g.,
  18145. by `current-time'.
  18146. When optional argument WITH-TIME is non-nil, return a timestamp
  18147. object with a time part, i.e., with hours and minutes.
  18148. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18149. return an active timestamp."
  18150. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18151. (org-element-create 'timestamp
  18152. (list :type (if inactive 'inactive 'active)
  18153. :year-start year
  18154. :month-start month
  18155. :day-start day
  18156. :hour-start (and with-time hour)
  18157. :minute-start (and with-time minute)))))
  18158. (defun org-timestamp-to-time (timestamp &optional end)
  18159. "Convert TIMESTAMP object into an Emacs internal time value.
  18160. Use end of date range or time range when END is non-nil.
  18161. Otherwise, use its start."
  18162. (apply #'encode-time 0
  18163. (mapcar
  18164. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18165. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18166. '(:minute-start :hour-start :day-start :month-start
  18167. :year-start)))))
  18168. (defun org-timestamp-has-time-p (timestamp)
  18169. "Non-nil when TIMESTAMP has a time specified."
  18170. (org-element-property :hour-start timestamp))
  18171. (defun org-timestamp-format (timestamp format &optional end utc)
  18172. "Format a TIMESTAMP object into a string.
  18173. FORMAT is a format specifier to be passed to
  18174. `format-time-string'.
  18175. When optional argument END is non-nil, use end of date-range or
  18176. time-range, if possible.
  18177. When optional argument UTC is non-nil, time is be expressed as
  18178. Universal Time."
  18179. (format-time-string format (org-timestamp-to-time timestamp end)
  18180. (and utc t)))
  18181. (defun org-timestamp-split-range (timestamp &optional end)
  18182. "Extract a TIMESTAMP object from a date or time range.
  18183. END, when non-nil, means extract the end of the range.
  18184. Otherwise, extract its start.
  18185. Return a new timestamp object."
  18186. (let ((type (org-element-property :type timestamp)))
  18187. (if (memq type '(active inactive diary)) timestamp
  18188. (let ((split-ts (org-element-copy timestamp)))
  18189. ;; Set new type.
  18190. (org-element-put-property
  18191. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18192. ;; Copy start properties over end properties if END is
  18193. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18194. (let ((p-alist '((:minute-start . :minute-end)
  18195. (:hour-start . :hour-end)
  18196. (:day-start . :day-end)
  18197. (:month-start . :month-end)
  18198. (:year-start . :year-end))))
  18199. (dolist (p-cell p-alist)
  18200. (org-element-put-property
  18201. split-ts
  18202. (funcall (if end #'car #'cdr) p-cell)
  18203. (org-element-property
  18204. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18205. ;; Eventually refresh `:raw-value'.
  18206. (org-element-put-property split-ts :raw-value nil)
  18207. (org-element-put-property
  18208. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18209. (defun org-timestamp-translate (timestamp &optional boundary)
  18210. "Translate TIMESTAMP object to custom format.
  18211. Format string is defined in `org-time-stamp-custom-formats',
  18212. which see.
  18213. When optional argument BOUNDARY is non-nil, it is either the
  18214. symbol `start' or `end'. In this case, only translate the
  18215. starting or ending part of TIMESTAMP if it is a date or time
  18216. range. Otherwise, translate both parts.
  18217. Return timestamp as-is if `org-display-custom-times' is nil or if
  18218. it has a `diary' type."
  18219. (let ((type (org-element-property :type timestamp)))
  18220. (if (or (not org-display-custom-times) (eq type 'diary))
  18221. (org-element-interpret-data timestamp)
  18222. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18223. org-time-stamp-custom-formats)))
  18224. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18225. (concat (org-timestamp-format timestamp fmt)
  18226. "--"
  18227. (org-timestamp-format timestamp fmt t))
  18228. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18229. ;;; Other stuff
  18230. (defvar reftex-docstruct-symbol)
  18231. (defvar org--rds)
  18232. (defun org-reftex-citation ()
  18233. "Use reftex-citation to insert a citation into the buffer.
  18234. This looks for a line like
  18235. #+BIBLIOGRAPHY: foo plain option:-d
  18236. and derives from it that foo.bib is the bibliography file relevant
  18237. for this document. It then installs the necessary environment for RefTeX
  18238. to work in this buffer and calls `reftex-citation' to insert a citation
  18239. into the buffer.
  18240. Export of such citations to both LaTeX and HTML is handled by the contributed
  18241. package ox-bibtex by Taru Karttunen."
  18242. (interactive)
  18243. (let ((reftex-docstruct-symbol 'org--rds)
  18244. org--rds bib)
  18245. (org-with-wide-buffer
  18246. (let ((case-fold-search t)
  18247. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18248. (if (not (save-excursion
  18249. (or (re-search-forward re nil t)
  18250. (re-search-backward re nil t))))
  18251. (user-error "No bibliography defined in file")
  18252. (setq bib (concat (match-string 1) ".bib")
  18253. org--rds (list (list 'bib bib))))))
  18254. (call-interactively 'reftex-citation)))
  18255. ;;;; Functions extending outline functionality
  18256. (defun org-beginning-of-line (&optional n)
  18257. "Go to the beginning of the current visible line.
  18258. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18259. symbol `reversed', on the first attempt move to where the
  18260. headline text starts, and only move to beginning of line when the
  18261. cursor is already before the start of the text of the headline.
  18262. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18263. start of the text on the second attempt.
  18264. With argument N not nil or 1, move forward N - 1 lines first."
  18265. (interactive "^p")
  18266. (let ((origin (point))
  18267. (special (pcase org-special-ctrl-a/e
  18268. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18269. deactivate-mark)
  18270. ;; First move to a visible line.
  18271. (if (bound-and-true-p visual-line-mode)
  18272. (beginning-of-visual-line n)
  18273. (move-beginning-of-line n)
  18274. ;; `move-beginning-of-line' may leave point after invisible
  18275. ;; characters if line starts with such of these (e.g., with
  18276. ;; a link at column 0). Really move to the beginning of the
  18277. ;; current visible line.
  18278. (beginning-of-line))
  18279. (cond
  18280. ;; No special behavior. Point is already at the beginning of
  18281. ;; a line, logical or visual.
  18282. ((not special))
  18283. ;; `beginning-of-visual-line' left point before logical beginning
  18284. ;; of line: point is at the beginning of a visual line. Bail
  18285. ;; out.
  18286. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18287. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18288. ;; At a headline, special position is before the title, but
  18289. ;; after any TODO keyword or priority cookie.
  18290. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18291. (line-end-position)))
  18292. (bol (point)))
  18293. (if (eq special 'reversed)
  18294. (when (and (= origin bol) (eq last-command this-command))
  18295. (goto-char refpos))
  18296. (when (or (> origin refpos) (= origin bol))
  18297. (goto-char refpos)))))
  18298. ((and (looking-at org-list-full-item-re)
  18299. (memq (org-element-type (save-match-data (org-element-at-point)))
  18300. '(item plain-list)))
  18301. ;; Set special position at first white space character after
  18302. ;; bullet, and check-box, if any.
  18303. (let ((after-bullet
  18304. (let ((box (match-end 3)))
  18305. (cond ((not box) (match-end 1))
  18306. ((eq (char-after box) ?\s) (1+ box))
  18307. (t box)))))
  18308. (if (eq special 'reversed)
  18309. (when (and (= (point) origin) (eq last-command this-command))
  18310. (goto-char after-bullet))
  18311. (when (or (> origin after-bullet) (= (point) origin))
  18312. (goto-char after-bullet)))))
  18313. ;; No special context. Point is already at beginning of line.
  18314. (t nil))))
  18315. (defun org-end-of-line (&optional n)
  18316. "Go to the end of the line, but before ellipsis, if any.
  18317. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18318. symbol `reversed', ignore tags on the first attempt, and only
  18319. move to after the tags when the cursor is already beyond the end
  18320. of the headline.
  18321. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18322. on the second attempt.
  18323. With argument N not nil or 1, move forward N - 1 lines first."
  18324. (interactive "^p")
  18325. (let ((origin (point))
  18326. (special (pcase org-special-ctrl-a/e
  18327. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18328. deactivate-mark)
  18329. ;; First move to a visible line.
  18330. (if (bound-and-true-p visual-line-mode)
  18331. (beginning-of-visual-line n)
  18332. (move-beginning-of-line n))
  18333. (cond
  18334. ;; At a headline, with tags.
  18335. ((and special
  18336. (save-excursion
  18337. (beginning-of-line)
  18338. (let ((case-fold-search nil))
  18339. (looking-at org-complex-heading-regexp)))
  18340. (match-end 5))
  18341. (let ((tags (save-excursion
  18342. (goto-char (match-beginning 5))
  18343. (skip-chars-backward " \t")
  18344. (point)))
  18345. (visual-end (and (bound-and-true-p visual-line-mode)
  18346. (save-excursion
  18347. (end-of-visual-line)
  18348. (point)))))
  18349. ;; If `end-of-visual-line' brings us before end of line or
  18350. ;; even tags, i.e., the headline spans over multiple visual
  18351. ;; lines, move there.
  18352. (cond ((and visual-end
  18353. (< visual-end tags)
  18354. (<= origin visual-end))
  18355. (goto-char visual-end))
  18356. ((eq special 'reversed)
  18357. (if (and (= origin (line-end-position))
  18358. (eq this-command last-command))
  18359. (goto-char tags)
  18360. (end-of-line)))
  18361. (t
  18362. (if (or (< origin tags) (= origin (line-end-position)))
  18363. (goto-char tags)
  18364. (end-of-line))))))
  18365. ((bound-and-true-p visual-line-mode)
  18366. (let ((bol (line-beginning-position)))
  18367. (end-of-visual-line)
  18368. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18369. ;; end of a line, backtrack and use `end-of-line' instead.
  18370. (when (/= bol (line-beginning-position))
  18371. (goto-char bol)
  18372. (end-of-line))))
  18373. (t (end-of-line)))))
  18374. (defun org-backward-sentence (&optional _arg)
  18375. "Go to beginning of sentence, or beginning of table field.
  18376. This will call `backward-sentence' or `org-table-beginning-of-field',
  18377. depending on context."
  18378. (interactive)
  18379. (let* ((element (org-element-at-point))
  18380. (contents-begin (org-element-property :contents-begin element))
  18381. (table (org-element-lineage element '(table) t)))
  18382. (if (and table
  18383. (> (point) contents-begin)
  18384. (<= (point) (org-element-property :contents-end table)))
  18385. (call-interactively #'org-table-beginning-of-field)
  18386. (save-restriction
  18387. (when (and contents-begin
  18388. (< (point-min) contents-begin)
  18389. (> (point) contents-begin))
  18390. (narrow-to-region contents-begin
  18391. (org-element-property :contents-end element)))
  18392. (call-interactively #'backward-sentence)))))
  18393. (defun org-forward-sentence (&optional _arg)
  18394. "Go to end of sentence, or end of table field.
  18395. This will call `forward-sentence' or `org-table-end-of-field',
  18396. depending on context."
  18397. (interactive)
  18398. (if (and (org-at-heading-p)
  18399. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18400. (save-restriction
  18401. (narrow-to-region (line-beginning-position) (line-end-position))
  18402. (call-interactively #'forward-sentence))
  18403. (let* ((element (org-element-at-point))
  18404. (contents-end (org-element-property :contents-end element))
  18405. (table (org-element-lineage element '(table) t)))
  18406. (if (and table
  18407. (>= (point) (org-element-property :contents-begin table))
  18408. (< (point) contents-end))
  18409. (call-interactively #'org-table-end-of-field)
  18410. (save-restriction
  18411. (when (and contents-end
  18412. (> (point-max) contents-end)
  18413. ;; Skip blank lines between elements.
  18414. (< (org-element-property :end element)
  18415. (save-excursion (goto-char contents-end)
  18416. (skip-chars-forward " \r\t\n"))))
  18417. (narrow-to-region (org-element-property :contents-begin element)
  18418. contents-end))
  18419. ;; End of heading is considered as the end of a sentence.
  18420. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18421. (call-interactively #'forward-sentence)))))))
  18422. (defun org-kill-line (&optional _arg)
  18423. "Kill line, to tags or end of line."
  18424. (interactive)
  18425. (cond
  18426. ((or (not org-special-ctrl-k)
  18427. (bolp)
  18428. (not (org-at-heading-p)))
  18429. (when (and (get-char-property (line-end-position) 'invisible)
  18430. org-ctrl-k-protect-subtree
  18431. (or (eq org-ctrl-k-protect-subtree 'error)
  18432. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18433. (user-error
  18434. (substitute-command-keys
  18435. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18436. (call-interactively
  18437. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18438. ((org-match-line org-tag-line-re)
  18439. (let ((end (save-excursion
  18440. (goto-char (match-beginning 1))
  18441. (skip-chars-backward " \t")
  18442. (point))))
  18443. (if (<= end (point)) ;on tags part
  18444. (kill-region (point) (line-end-position))
  18445. (kill-region (point) end)))
  18446. ;; Only align tags when we are still on a heading:
  18447. (if (org-at-heading-p) (org-align-tags)))
  18448. (t (kill-region (point) (line-end-position)))))
  18449. (defun org-yank (&optional arg)
  18450. "Yank. If the kill is a subtree, treat it specially.
  18451. This command will look at the current kill and check if is a single
  18452. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18453. cursor is at the beginning of a line or after the stars of a currently
  18454. empty headline, then the yank is handled specially. How exactly depends
  18455. on the value of the following variables.
  18456. `org-yank-folded-subtrees'
  18457. By default, this variable is non-nil, which results in
  18458. subtree(s) being folded after insertion, except if doing so
  18459. would swallow text after the yanked text.
  18460. `org-yank-adjusted-subtrees'
  18461. When non-nil (the default value is nil), the subtree will be
  18462. promoted or demoted in order to fit into the local outline tree
  18463. structure, which means that the level will be adjusted so that it
  18464. becomes the smaller one of the two *visible* surrounding headings.
  18465. Any prefix to this command will cause `yank' to be called directly with
  18466. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18467. will just
  18468. plainly yank the text as it is.
  18469. \[1] The test checks if the first non-white line is a heading
  18470. and if there are no other headings with fewer stars."
  18471. (interactive "P")
  18472. (org-yank-generic 'yank arg))
  18473. (defun org-yank-generic (command arg)
  18474. "Perform some yank-like command.
  18475. This function implements the behavior described in the `org-yank'
  18476. documentation. However, it has been generalized to work for any
  18477. interactive command with similar behavior."
  18478. ;; pretend to be command COMMAND
  18479. (setq this-command command)
  18480. (if arg
  18481. (call-interactively command)
  18482. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18483. (and (org-kill-is-subtree-p)
  18484. (or (bolp)
  18485. (and (looking-at "[ \t]*$")
  18486. (string-match
  18487. "\\`\\*+\\'"
  18488. (buffer-substring (point-at-bol) (point)))))))
  18489. swallowp)
  18490. (cond
  18491. ((and subtreep org-yank-folded-subtrees)
  18492. (let ((beg (point))
  18493. end)
  18494. (if (and subtreep org-yank-adjusted-subtrees)
  18495. (org-paste-subtree nil nil 'for-yank)
  18496. (call-interactively command))
  18497. (setq end (point))
  18498. (goto-char beg)
  18499. (when (and (bolp) subtreep
  18500. (not (setq swallowp
  18501. (org-yank-folding-would-swallow-text beg end))))
  18502. (org-with-limited-levels
  18503. (or (looking-at org-outline-regexp)
  18504. (re-search-forward org-outline-regexp-bol end t))
  18505. (while (and (< (point) end) (looking-at org-outline-regexp))
  18506. (org-flag-subtree t)
  18507. (org-cycle-show-empty-lines 'folded)
  18508. (condition-case nil
  18509. (outline-forward-same-level 1)
  18510. (error (goto-char end))))))
  18511. (when swallowp
  18512. (message
  18513. "Inserted text not folded because that would swallow text"))
  18514. (goto-char end)
  18515. (skip-chars-forward " \t\n\r")
  18516. (beginning-of-line 1)
  18517. (push-mark beg 'nomsg)))
  18518. ((and subtreep org-yank-adjusted-subtrees)
  18519. (let ((beg (point-at-bol)))
  18520. (org-paste-subtree nil nil 'for-yank)
  18521. (push-mark beg 'nomsg)))
  18522. (t
  18523. (call-interactively command))))))
  18524. (defun org-yank-folding-would-swallow-text (beg end)
  18525. "Would hide-subtree at BEG swallow any text after END?"
  18526. (let (level)
  18527. (org-with-limited-levels
  18528. (save-excursion
  18529. (goto-char beg)
  18530. (when (or (looking-at org-outline-regexp)
  18531. (re-search-forward org-outline-regexp-bol end t))
  18532. (setq level (org-outline-level)))
  18533. (goto-char end)
  18534. (skip-chars-forward " \t\r\n\v\f")
  18535. (not (or (eobp)
  18536. (and (bolp) (looking-at-p org-outline-regexp)
  18537. (<= (org-outline-level) level))))))))
  18538. (defun org-back-to-heading (&optional invisible-ok)
  18539. "Call `outline-back-to-heading', but provide a better error message."
  18540. (condition-case nil
  18541. (outline-back-to-heading invisible-ok)
  18542. (error
  18543. (user-error "Before first headline at position %d in buffer %s"
  18544. (point) (current-buffer)))))
  18545. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18546. "Go back to heading or first point in buffer.
  18547. If point is before first heading go to first point in buffer
  18548. instead of back to heading."
  18549. (condition-case nil
  18550. (outline-back-to-heading invisible-ok)
  18551. (error
  18552. (goto-char (point-min)))))
  18553. (defun org-before-first-heading-p ()
  18554. "Before first heading?"
  18555. (org-with-limited-levels
  18556. (save-excursion
  18557. (end-of-line)
  18558. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18559. (defun org-at-heading-p (&optional _)
  18560. "Non-nil when on a headline."
  18561. (outline-on-heading-p t))
  18562. (defun org-in-commented-heading-p (&optional no-inheritance)
  18563. "Non-nil if point is under a commented heading.
  18564. This function also checks ancestors of the current headline,
  18565. unless optional argument NO-INHERITANCE is non-nil."
  18566. (cond
  18567. ((org-before-first-heading-p) nil)
  18568. ((let ((headline (nth 4 (org-heading-components))))
  18569. (and headline
  18570. (let ((case-fold-search nil))
  18571. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18572. headline)))))
  18573. (no-inheritance nil)
  18574. (t
  18575. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18576. (defun org-in-archived-heading-p (&optional no-inheritance)
  18577. "Non-nil if point is under an archived heading.
  18578. This function also checks ancestors of the current headline,
  18579. unless optional argument NO-INHERITANCE is non-nil."
  18580. (cond
  18581. ((org-before-first-heading-p) nil)
  18582. ((let ((tags (org-get-tags nil 'local)))
  18583. (and tags
  18584. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18585. (no-inheritance nil)
  18586. (t
  18587. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18588. (defun org-at-comment-p nil
  18589. "Return t if cursor is in a commented line."
  18590. (save-excursion
  18591. (save-match-data
  18592. (beginning-of-line)
  18593. (looking-at org-comment-regexp))))
  18594. (defun org-at-keyword-p nil
  18595. "Return t if cursor is at a keyword-line."
  18596. (save-excursion
  18597. (move-beginning-of-line 1)
  18598. (looking-at org-keyword-regexp)))
  18599. (defun org-at-drawer-p nil
  18600. "Return t if cursor is at a drawer keyword."
  18601. (save-excursion
  18602. (move-beginning-of-line 1)
  18603. (looking-at org-drawer-regexp)))
  18604. (defun org-at-block-p nil
  18605. "Return t if cursor is at a block keyword."
  18606. (save-excursion
  18607. (move-beginning-of-line 1)
  18608. (looking-at org-block-regexp)))
  18609. (defun org-point-at-end-of-empty-headline ()
  18610. "If point is at the end of an empty headline, return t, else nil.
  18611. If the heading only contains a TODO keyword, it is still still considered
  18612. empty."
  18613. (let ((case-fold-search nil))
  18614. (and (looking-at "[ \t]*$")
  18615. org-todo-line-regexp
  18616. (save-excursion
  18617. (beginning-of-line)
  18618. (looking-at org-todo-line-regexp)
  18619. (string= (match-string 3) "")))))
  18620. (defun org-at-heading-or-item-p ()
  18621. (or (org-at-heading-p) (org-at-item-p)))
  18622. (defun org-up-heading-all (arg)
  18623. "Move to the heading line of which the present line is a subheading.
  18624. This function considers both visible and invisible heading lines.
  18625. With argument, move up ARG levels."
  18626. (outline-up-heading arg t))
  18627. (defun org-up-heading-safe ()
  18628. "Move to the heading line of which the present line is a subheading.
  18629. This version will not throw an error. It will return the level of the
  18630. headline found, or nil if no higher level is found.
  18631. Also, this function will be a lot faster than `outline-up-heading',
  18632. because it relies on stars being the outline starters. This can really
  18633. make a significant difference in outlines with very many siblings."
  18634. (when (ignore-errors (org-back-to-heading t))
  18635. (let ((level-up (1- (funcall outline-level))))
  18636. (and (> level-up 0)
  18637. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18638. (funcall outline-level)))))
  18639. (defun org-up-heading-or-point-min ()
  18640. "Move to the heading line of which the present is a subheading, or point-min.
  18641. This version is needed to make point-min behave like a virtual
  18642. heading of level 0 for property-inheritance. It will return the
  18643. level of the headline found (down to 0) or nil if already at a
  18644. point before the first headline or at point-min."
  18645. (when (ignore-errors (org-back-to-heading t))
  18646. (if (< 1 (funcall outline-level))
  18647. (org-up-heading-safe)
  18648. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18649. (defun org-first-sibling-p ()
  18650. "Is this heading the first child of its parents?"
  18651. (interactive)
  18652. (let ((re org-outline-regexp-bol)
  18653. level l)
  18654. (unless (org-at-heading-p t)
  18655. (user-error "Not at a heading"))
  18656. (setq level (funcall outline-level))
  18657. (save-excursion
  18658. (if (not (re-search-backward re nil t))
  18659. t
  18660. (setq l (funcall outline-level))
  18661. (< l level)))))
  18662. (defun org-goto-sibling (&optional previous)
  18663. "Goto the next sibling, even if it is invisible.
  18664. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18665. when a sibling was found. When none is found, return nil and don't
  18666. move point."
  18667. (let ((fun (if previous 're-search-backward 're-search-forward))
  18668. (pos (point))
  18669. (re org-outline-regexp-bol)
  18670. level l)
  18671. (when (ignore-errors (org-back-to-heading t))
  18672. (setq level (funcall outline-level))
  18673. (catch 'exit
  18674. (or previous (forward-char 1))
  18675. (while (funcall fun re nil t)
  18676. (setq l (funcall outline-level))
  18677. (when (< l level) (goto-char pos) (throw 'exit nil))
  18678. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18679. (goto-char pos)
  18680. nil))))
  18681. (defun org-show-siblings ()
  18682. "Show all siblings of the current headline."
  18683. (save-excursion
  18684. (while (org-goto-sibling) (org-flag-heading nil)))
  18685. (save-excursion
  18686. (while (org-goto-sibling 'previous)
  18687. (org-flag-heading nil))))
  18688. (defun org-goto-first-child ()
  18689. "Goto the first child, even if it is invisible.
  18690. Return t when a child was found. Otherwise don't move point and
  18691. return nil."
  18692. (let (level (pos (point)) (re org-outline-regexp-bol))
  18693. (when (org-back-to-heading-or-point-min t)
  18694. (setq level (org-outline-level))
  18695. (forward-char 1)
  18696. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18697. (progn (goto-char (match-beginning 0)) t)
  18698. (goto-char pos) nil))))
  18699. (defun org-show-hidden-entry ()
  18700. "Show an entry where even the heading is hidden."
  18701. (save-excursion
  18702. (org-show-entry)))
  18703. (defun org-flag-heading (flag &optional entry)
  18704. "Flag the current heading. FLAG non-nil means make invisible.
  18705. When ENTRY is non-nil, show the entire entry."
  18706. (save-excursion
  18707. (org-back-to-heading t)
  18708. ;; Check if we should show the entire entry
  18709. (if (not entry)
  18710. (org-flag-region
  18711. (line-end-position 0) (line-end-position) flag 'outline)
  18712. (org-show-entry)
  18713. (save-excursion
  18714. (and (outline-next-heading)
  18715. (org-flag-heading nil))))))
  18716. (defun org-get-next-sibling ()
  18717. "Move to next heading of the same level, and return point.
  18718. If there is no such heading, return nil.
  18719. This is like outline-next-sibling, but invisible headings are ok."
  18720. (let ((level (funcall outline-level)))
  18721. (outline-next-heading)
  18722. (while (and (not (eobp)) (> (funcall outline-level) level))
  18723. (outline-next-heading))
  18724. (unless (or (eobp) (< (funcall outline-level) level))
  18725. (point))))
  18726. (defun org-get-last-sibling ()
  18727. "Move to previous heading of the same level, and return point.
  18728. If there is no such heading, return nil."
  18729. (let ((opoint (point))
  18730. (level (funcall outline-level)))
  18731. (outline-previous-heading)
  18732. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18733. (while (and (> (funcall outline-level) level)
  18734. (not (bobp)))
  18735. (outline-previous-heading))
  18736. (unless (< (funcall outline-level) level)
  18737. (point)))))
  18738. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18739. "Goto to the end of a subtree."
  18740. ;; This contains an exact copy of the original function, but it uses
  18741. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18742. ;; trees and before first headline. And is uses an invisible-ok argument.
  18743. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18744. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18745. ;; with many children and grandchildren etc, this can be much faster
  18746. ;; than the outline version.
  18747. (org-back-to-heading-or-point-min invisible-ok)
  18748. (let ((first t)
  18749. (level (funcall outline-level)))
  18750. (cond ((= level 0)
  18751. (goto-char (point-max)))
  18752. ((and (derived-mode-p 'org-mode) (< level 1000))
  18753. ;; A true heading (not a plain list item), in Org
  18754. ;; This means we can easily find the end by looking
  18755. ;; only for the right number of stars. Using a regexp to do
  18756. ;; this is so much faster than using a Lisp loop.
  18757. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18758. (forward-char 1)
  18759. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18760. (t
  18761. ;; something else, do it the slow way
  18762. (while (and (not (eobp))
  18763. (or first (> (funcall outline-level) level)))
  18764. (setq first nil)
  18765. (outline-next-heading))))
  18766. (unless to-heading
  18767. (when (memq (preceding-char) '(?\n ?\^M))
  18768. ;; Go to end of line before heading
  18769. (forward-char -1)
  18770. (when (memq (preceding-char) '(?\n ?\^M))
  18771. ;; leave blank line before heading
  18772. (forward-char -1)))))
  18773. (point))
  18774. (defun org-end-of-meta-data (&optional full)
  18775. "Skip planning line and properties drawer in current entry.
  18776. When optional argument FULL is t, also skip planning information,
  18777. clocking lines and any kind of drawer.
  18778. When FULL is non-nil but not t, skip planning information,
  18779. clocking lines and only non-regular drawers, i.e. properties and
  18780. logbook drawers."
  18781. (org-back-to-heading t)
  18782. (forward-line)
  18783. ;; Skip planning information.
  18784. (when (looking-at-p org-planning-line-re) (forward-line))
  18785. ;; Skip property drawer.
  18786. (when (looking-at org-property-drawer-re)
  18787. (goto-char (match-end 0))
  18788. (forward-line))
  18789. ;; When FULL is not nil, skip more.
  18790. (when (and full (not (org-at-heading-p)))
  18791. (catch 'exit
  18792. (let ((end (save-excursion (outline-next-heading) (point)))
  18793. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18794. (while (not (eobp))
  18795. (cond ;; Skip clock lines.
  18796. ((looking-at-p re) (forward-line))
  18797. ;; Skip logbook drawer.
  18798. ((looking-at-p org-logbook-drawer-re)
  18799. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18800. (forward-line)
  18801. (throw 'exit t)))
  18802. ;; When FULL is t, skip regular drawer too.
  18803. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18804. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18805. (forward-line)
  18806. (throw 'exit t)))
  18807. (t (throw 'exit t))))))))
  18808. (defun org--line-fully-invisible-p ()
  18809. "Return non-nil if the current line is fully invisible."
  18810. (let ((line-beg (line-beginning-position))
  18811. (line-pos (1- (line-end-position)))
  18812. (is-invisible t))
  18813. (while (and (< line-beg line-pos) is-invisible)
  18814. (setq is-invisible (org-invisible-p line-pos))
  18815. (setq line-pos (1- line-pos)))
  18816. is-invisible))
  18817. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18818. "Move forward to the ARG'th subheading at same level as this one.
  18819. Stop at the first and last subheadings of a superior heading.
  18820. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18821. non-nil it will also look at invisible ones."
  18822. (interactive "p")
  18823. (let ((backward? (and arg (< arg 0))))
  18824. (if (org-before-first-heading-p)
  18825. (if backward? (goto-char (point-min)) (outline-next-heading))
  18826. (org-back-to-heading invisible-ok)
  18827. (unless backward? (end-of-line)) ;do not match current headline
  18828. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18829. (f (if backward? #'re-search-backward #'re-search-forward))
  18830. (count (if arg (abs arg) 1))
  18831. (result (point)))
  18832. (while (and (> count 0)
  18833. (funcall f org-outline-regexp-bol nil 'move))
  18834. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18835. (cond ((< l level) (setq count 0))
  18836. ((and (= l level)
  18837. (or invisible-ok
  18838. ;; FIXME: See commit a700fadd72 and the
  18839. ;; related discussion on why using
  18840. ;; `org--line-fully-invisible-p' is needed
  18841. ;; here, which is to serve the needs of an
  18842. ;; external package. If the change is
  18843. ;; wrong regarding Org itself, it should
  18844. ;; be removed.
  18845. (not (org--line-fully-invisible-p))))
  18846. (cl-decf count)
  18847. (when (= l level) (setq result (point)))))))
  18848. (goto-char result))
  18849. (beginning-of-line))))
  18850. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18851. "Move backward to the ARG'th subheading at same level as this one.
  18852. Stop at the first and last subheadings of a superior heading."
  18853. (interactive "p")
  18854. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18855. (defun org-next-visible-heading (arg)
  18856. "Move to the next visible heading line.
  18857. With ARG, repeats or can move backward if negative."
  18858. (interactive "p")
  18859. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18860. (if (< arg 0)
  18861. (beginning-of-line)
  18862. (end-of-line))
  18863. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18864. (unless (bobp)
  18865. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18866. (`(outline . ,o)
  18867. (goto-char (overlay-start o))
  18868. (re-search-backward regexp nil :move))
  18869. (_ nil))))
  18870. (cl-incf arg))
  18871. (while (and (> arg 0) (re-search-forward regexp nil t))
  18872. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18873. (`(outline . ,o)
  18874. (goto-char (overlay-end o))
  18875. (re-search-forward regexp nil :move))
  18876. (_
  18877. (end-of-line)
  18878. nil))) ;leave the loop
  18879. (cl-decf arg))
  18880. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18881. (defun org-previous-visible-heading (arg)
  18882. "Move to the previous visible heading.
  18883. With ARG, repeats or can move forward if negative."
  18884. (interactive "p")
  18885. (org-next-visible-heading (- arg)))
  18886. (defun org-forward-paragraph (&optional arg)
  18887. "Move forward by a paragraph, or equivalent, unit.
  18888. With argument ARG, do it ARG times;
  18889. a negative argument ARG = -N means move backward N paragraphs.
  18890. The function moves point between two structural
  18891. elements (paragraphs, tables, lists, etc.).
  18892. It also provides the following special moves for convenience:
  18893. - on a table or a property drawer, move to its beginning;
  18894. - on comment, example, export, source and verse blocks, stop
  18895. at blank lines;
  18896. - skip consecutive clocks, diary S-exps, and keywords."
  18897. (interactive "^p")
  18898. (unless arg (setq arg 1))
  18899. (if (< arg 0) (org-backward-paragraph (- arg))
  18900. (while (and (> arg 0) (not (eobp)))
  18901. (org--forward-paragraph-once)
  18902. (cl-decf arg))
  18903. ;; Return moves left.
  18904. arg))
  18905. (defun org-backward-paragraph (&optional arg)
  18906. "Move backward by a paragraph, or equivalent, unit.
  18907. With argument ARG, do it ARG times;
  18908. a negative argument ARG = -N means move forward N paragraphs.
  18909. The function moves point between two structural
  18910. elements (paragraphs, tables, lists, etc.).
  18911. It also provides the following special moves for convenience:
  18912. - on a table or a property drawer, move to its beginning;
  18913. - on comment, example, export, source and verse blocks, stop
  18914. at blank lines;
  18915. - skip consecutive clocks, diary S-exps, and keywords."
  18916. (interactive "^p")
  18917. (unless arg (setq arg 1))
  18918. (if (< arg 0) (org-forward-paragraph (- arg))
  18919. (while (and (> arg 0) (not (bobp)))
  18920. (org--backward-paragraph-once)
  18921. (cl-decf arg))
  18922. ;; Return moves left.
  18923. arg))
  18924. (defun org--paragraph-at-point ()
  18925. "Return paragraph, or equivalent, element at point.
  18926. Paragraph element at point is the element at point, with the
  18927. following special cases:
  18928. - treat table rows (resp. node properties) as the table
  18929. \(resp. property drawer) containing them.
  18930. - treat plain lists with an item every line as a whole.
  18931. - treat consecutive keywords, clocks, and diary-sexps as a single
  18932. block.
  18933. Function may return a real element, or a pseudo-element with type
  18934. `pseudo-paragraph'."
  18935. (let* ((e (org-element-at-point))
  18936. (type (org-element-type e))
  18937. ;; If we need to fake a new pseudo-element, triplet is
  18938. ;;
  18939. ;; (BEG END PARENT)
  18940. ;;
  18941. ;; where BEG and END are element boundaries, and PARENT the
  18942. ;; element containing it, or nil.
  18943. (triplet
  18944. (cond
  18945. ((memq type '(table property-drawer))
  18946. (list (org-element-property :begin e)
  18947. (org-element-property :end e)
  18948. (org-element-property :parent e)))
  18949. ((memq type '(node-property table-row))
  18950. (let ((e (org-element-property :parent e)))
  18951. (list (org-element-property :begin e)
  18952. (org-element-property :end e)
  18953. (org-element-property :parent e))))
  18954. ((memq type '(clock diary-sexp keyword))
  18955. (let* ((regexp (pcase type
  18956. (`clock org-clock-line-re)
  18957. (`diary-sexp "%%(")
  18958. (_ org-keyword-regexp)))
  18959. (end (if (< 0 (org-element-property :post-blank e))
  18960. (org-element-property :end e)
  18961. (org-with-wide-buffer
  18962. (forward-line)
  18963. (while (looking-at regexp) (forward-line))
  18964. (skip-chars-forward " \t\n")
  18965. (line-beginning-position))))
  18966. (begin (org-with-point-at (org-element-property :begin e)
  18967. (while (and (not (bobp)) (looking-at regexp))
  18968. (forward-line -1))
  18969. ;; We may have gotten one line too far.
  18970. (if (looking-at regexp)
  18971. (point)
  18972. (line-beginning-position 2)))))
  18973. (list begin end (org-element-property :parent e))))
  18974. ;; Find the full plain list containing point, the check it
  18975. ;; contains exactly one line per item.
  18976. ((let ((l (org-element-lineage e '(plain-list) t)))
  18977. (while (memq (org-element-type (org-element-property :parent l))
  18978. '(item plain-list))
  18979. (setq l (org-element-property :parent l)))
  18980. (and l
  18981. (org-with-point-at (org-element-property :post-affiliated l)
  18982. (forward-line (length (org-element-property :structure l)))
  18983. (= (point) (org-element-property :contents-end l)))
  18984. ;; Return value.
  18985. (list (org-element-property :begin l)
  18986. (org-element-property :end l)
  18987. (org-element-property :parent l)))))
  18988. (t nil)))) ;no triplet: return element
  18989. (pcase triplet
  18990. (`(,b ,e ,p)
  18991. (org-element-create
  18992. 'pseudo-paragraph
  18993. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18994. (_ e))))
  18995. (defun org--forward-paragraph-once ()
  18996. "Move forward to end of paragraph or equivalent, once.
  18997. See `org-forward-paragraph'."
  18998. (interactive)
  18999. (save-restriction
  19000. (widen)
  19001. (skip-chars-forward " \t\n")
  19002. (cond
  19003. ((eobp) nil)
  19004. ;; When inside a folded part, move out of it.
  19005. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19006. (`(,(or `outline `org-hide-block) . ,o)
  19007. (goto-char (overlay-end o))
  19008. (forward-line)
  19009. t)
  19010. (_ nil)))
  19011. (t
  19012. (let* ((element (org--paragraph-at-point))
  19013. (type (org-element-type element))
  19014. (contents-begin (org-element-property :contents-begin element))
  19015. (end (org-element-property :end element))
  19016. (post-affiliated (org-element-property :post-affiliated element)))
  19017. (cond
  19018. ((eq type 'plain-list)
  19019. (forward-char)
  19020. (org--forward-paragraph-once))
  19021. ;; If the element is folded, skip it altogether.
  19022. ((pcase (org-with-point-at post-affiliated
  19023. (get-char-property-and-overlay (line-end-position)
  19024. 'invisible))
  19025. (`(,(or `outline `org-hide-block) . ,o)
  19026. (goto-char (overlay-end o))
  19027. (forward-line)
  19028. t)
  19029. (_ nil)))
  19030. ;; At a greater element, move inside.
  19031. ((and contents-begin
  19032. (> contents-begin (point))
  19033. (not (eq type 'paragraph)))
  19034. (goto-char contents-begin)
  19035. ;; Items and footnote definitions contents may not start at
  19036. ;; the beginning of the line. In this case, skip until the
  19037. ;; next paragraph.
  19038. (cond
  19039. ((not (bolp)) (org--forward-paragraph-once))
  19040. ((org-previous-line-empty-p) (forward-line -1))
  19041. (t nil)))
  19042. ;; Move between empty lines in some blocks.
  19043. ((memq type '(comment-block example-block export-block src-block
  19044. verse-block))
  19045. (let ((contents-start
  19046. (org-with-point-at post-affiliated
  19047. (line-beginning-position 2))))
  19048. (if (< (point) contents-start)
  19049. (goto-char contents-start)
  19050. (let ((contents-end
  19051. (org-with-point-at end
  19052. (skip-chars-backward " \t\n")
  19053. (line-beginning-position))))
  19054. (cond
  19055. ((>= (point) contents-end)
  19056. (goto-char end)
  19057. (skip-chars-backward " \t\n")
  19058. (forward-line))
  19059. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19060. (forward-line -1))
  19061. (t nil))))))
  19062. (t
  19063. ;; Move to element's end.
  19064. (goto-char end)
  19065. (skip-chars-backward " \t\n")
  19066. (forward-line))))))))
  19067. (defun org--backward-paragraph-once ()
  19068. "Move backward to start of paragraph or equivalent, once.
  19069. See `org-backward-paragraph'."
  19070. (interactive)
  19071. (save-restriction
  19072. (widen)
  19073. (cond
  19074. ((bobp) nil)
  19075. ;; Blank lines at the beginning of the buffer.
  19076. ((and (org-match-line "^[ \t]*$")
  19077. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19078. (goto-char (point-min)))
  19079. ;; When inside a folded part, move out of it.
  19080. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19081. (`(,(or `outline `org-hide-block) . ,o)
  19082. (goto-char (1- (overlay-start o)))
  19083. (org--backward-paragraph-once)
  19084. t)
  19085. (_ nil)))
  19086. (t
  19087. (let* ((element (org--paragraph-at-point))
  19088. (type (org-element-type element))
  19089. (begin (org-element-property :begin element))
  19090. (post-affiliated (org-element-property :post-affiliated element))
  19091. (contents-end (org-element-property :contents-end element))
  19092. (end (org-element-property :end element))
  19093. (parent (org-element-property :parent element))
  19094. (reach
  19095. ;; Move to the visible empty line above position P, or
  19096. ;; to position P. Return t.
  19097. (lambda (p)
  19098. (goto-char p)
  19099. (when (and (org-previous-line-empty-p)
  19100. (let ((end (line-end-position 0)))
  19101. (or (= end (point-min))
  19102. (not (org-invisible-p (1- end))))))
  19103. (forward-line -1))
  19104. t)))
  19105. (cond
  19106. ;; Already at the beginning of an element.
  19107. ((= begin (point))
  19108. (cond
  19109. ;; There is a blank line above. Move there.
  19110. ((and (org-previous-line-empty-p)
  19111. (not (org-invisible-p (1- (line-end-position 0)))))
  19112. (forward-line -1))
  19113. ;; At the beginning of the first element within a greater
  19114. ;; element. Move to the beginning of the greater element.
  19115. ((and parent (= begin (org-element-property :contents-begin parent)))
  19116. (funcall reach (org-element-property :begin parent)))
  19117. ;; Since we have to move anyway, find the beginning
  19118. ;; position of the element above.
  19119. (t
  19120. (forward-char -1)
  19121. (org--backward-paragraph-once))))
  19122. ;; Skip paragraphs at the very beginning of footnote
  19123. ;; definitions or items.
  19124. ((and (eq type 'paragraph)
  19125. (org-with-point-at begin (not (bolp))))
  19126. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19127. ;; If the element is folded, skip it altogether.
  19128. ((org-with-point-at post-affiliated
  19129. (org-invisible-p (line-end-position) t))
  19130. (funcall reach begin))
  19131. ;; At the end of a greater element, move inside.
  19132. ((and contents-end
  19133. (<= contents-end (point))
  19134. (not (eq type 'paragraph)))
  19135. (cond
  19136. ((memq type '(footnote-definition plain-list))
  19137. (skip-chars-backward " \t\n")
  19138. (org--backward-paragraph-once))
  19139. ((= contents-end (point))
  19140. (forward-char -1)
  19141. (org--backward-paragraph-once))
  19142. (t
  19143. (goto-char contents-end))))
  19144. ;; Move between empty lines in some blocks.
  19145. ((and (memq type '(comment-block example-block export-block src-block
  19146. verse-block))
  19147. (let ((contents-start
  19148. (org-with-point-at post-affiliated
  19149. (line-beginning-position 2))))
  19150. (when (> (point) contents-start)
  19151. (let ((contents-end
  19152. (org-with-point-at end
  19153. (skip-chars-backward " \t\n")
  19154. (line-beginning-position))))
  19155. (if (> (point) contents-end)
  19156. (progn (goto-char contents-end) t)
  19157. (skip-chars-backward " \t\n" begin)
  19158. (re-search-backward "^[ \t]*\n" contents-start :move)
  19159. t))))))
  19160. ;; Move to element's start.
  19161. (t
  19162. (funcall reach begin))))))))
  19163. (defun org-forward-element ()
  19164. "Move forward by one element.
  19165. Move to the next element at the same level, when possible."
  19166. (interactive)
  19167. (cond ((eobp) (user-error "Cannot move further down"))
  19168. ((org-with-limited-levels (org-at-heading-p))
  19169. (let ((origin (point)))
  19170. (goto-char (org-end-of-subtree nil t))
  19171. (unless (org-with-limited-levels (org-at-heading-p))
  19172. (goto-char origin)
  19173. (user-error "Cannot move further down"))))
  19174. (t
  19175. (let* ((elem (org-element-at-point))
  19176. (end (org-element-property :end elem))
  19177. (parent (org-element-property :parent elem)))
  19178. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19179. (goto-char (org-element-property :end parent)))
  19180. ((integer-or-marker-p end) (goto-char end))
  19181. (t (message "No element at point")))))))
  19182. (defun org-backward-element ()
  19183. "Move backward by one element.
  19184. Move to the previous element at the same level, when possible."
  19185. (interactive)
  19186. (cond ((bobp) (user-error "Cannot move further up"))
  19187. ((org-with-limited-levels (org-at-heading-p))
  19188. ;; At a headline, move to the previous one, if any, or stay
  19189. ;; here.
  19190. (let ((origin (point)))
  19191. (org-with-limited-levels (org-backward-heading-same-level 1))
  19192. ;; When current headline has no sibling above, move to its
  19193. ;; parent.
  19194. (when (= (point) origin)
  19195. (or (org-with-limited-levels (org-up-heading-safe))
  19196. (progn (goto-char origin)
  19197. (user-error "Cannot move further up"))))))
  19198. (t
  19199. (let* ((elem (org-element-at-point))
  19200. (beg (org-element-property :begin elem)))
  19201. (cond
  19202. ;; Move to beginning of current element if point isn't
  19203. ;; there already.
  19204. ((null beg) (message "No element at point"))
  19205. ((/= (point) beg) (goto-char beg))
  19206. (t (goto-char beg)
  19207. (skip-chars-backward " \r\t\n")
  19208. (unless (bobp)
  19209. (let ((prev (org-element-at-point)))
  19210. (goto-char (org-element-property :begin prev))
  19211. (while (and (setq prev (org-element-property :parent prev))
  19212. (<= (org-element-property :end prev) beg))
  19213. (goto-char (org-element-property :begin prev)))))))))))
  19214. (defun org-up-element ()
  19215. "Move to upper element."
  19216. (interactive)
  19217. (if (org-with-limited-levels (org-at-heading-p))
  19218. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19219. (let* ((elem (org-element-at-point))
  19220. (parent (org-element-property :parent elem)))
  19221. (if parent (goto-char (org-element-property :begin parent))
  19222. (if (org-with-limited-levels (org-before-first-heading-p))
  19223. (user-error "No surrounding element")
  19224. (org-with-limited-levels (org-back-to-heading)))))))
  19225. (defun org-down-element ()
  19226. "Move to inner element."
  19227. (interactive)
  19228. (let ((element (org-element-at-point)))
  19229. (cond
  19230. ((memq (org-element-type element) '(plain-list table))
  19231. (goto-char (org-element-property :contents-begin element))
  19232. (forward-char))
  19233. ((memq (org-element-type element) org-element-greater-elements)
  19234. ;; If contents are hidden, first disclose them.
  19235. (when (org-invisible-p (line-end-position)) (org-cycle))
  19236. (goto-char (or (org-element-property :contents-begin element)
  19237. (user-error "No content for this element"))))
  19238. (t (user-error "No inner element")))))
  19239. (defun org-drag-element-backward ()
  19240. "Move backward element at point."
  19241. (interactive)
  19242. (let ((elem (or (org-element-at-point)
  19243. (user-error "No element at point"))))
  19244. (if (eq (org-element-type elem) 'headline)
  19245. ;; Preserve point when moving a whole tree, even if point was
  19246. ;; on blank lines below the headline.
  19247. (let ((offset (skip-chars-backward " \t\n")))
  19248. (unwind-protect (org-move-subtree-up)
  19249. (forward-char (- offset))))
  19250. (let ((prev-elem
  19251. (save-excursion
  19252. (goto-char (org-element-property :begin elem))
  19253. (skip-chars-backward " \r\t\n")
  19254. (unless (bobp)
  19255. (let* ((beg (org-element-property :begin elem))
  19256. (prev (org-element-at-point))
  19257. (up prev))
  19258. (while (and (setq up (org-element-property :parent up))
  19259. (<= (org-element-property :end up) beg))
  19260. (setq prev up))
  19261. prev)))))
  19262. ;; Error out if no previous element or previous element is
  19263. ;; a parent of the current one.
  19264. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19265. (user-error "Cannot drag element backward")
  19266. (let ((pos (point)))
  19267. (org-element-swap-A-B prev-elem elem)
  19268. (goto-char (+ (org-element-property :begin prev-elem)
  19269. (- pos (org-element-property :begin elem))))))))))
  19270. (defun org-drag-element-forward ()
  19271. "Move forward element at point."
  19272. (interactive)
  19273. (let* ((pos (point))
  19274. (elem (or (org-element-at-point)
  19275. (user-error "No element at point"))))
  19276. (when (= (point-max) (org-element-property :end elem))
  19277. (user-error "Cannot drag element forward"))
  19278. (goto-char (org-element-property :end elem))
  19279. (let ((next-elem (org-element-at-point)))
  19280. (when (or (org-element-nested-p elem next-elem)
  19281. (and (eq (org-element-type next-elem) 'headline)
  19282. (not (eq (org-element-type elem) 'headline))))
  19283. (goto-char pos)
  19284. (user-error "Cannot drag element forward"))
  19285. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19286. ;; body's length (without final blanks) and by the length of
  19287. ;; blanks between ELEM and NEXT-ELEM.
  19288. (let ((size-next (- (save-excursion
  19289. (goto-char (org-element-property :end next-elem))
  19290. (skip-chars-backward " \r\t\n")
  19291. (forward-line)
  19292. ;; Small correction if buffer doesn't end
  19293. ;; with a newline character.
  19294. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19295. (org-element-property :begin next-elem)))
  19296. (size-blank (- (org-element-property :end elem)
  19297. (save-excursion
  19298. (goto-char (org-element-property :end elem))
  19299. (skip-chars-backward " \r\t\n")
  19300. (forward-line)
  19301. (point)))))
  19302. (org-element-swap-A-B elem next-elem)
  19303. (goto-char (+ pos size-next size-blank))))))
  19304. (defun org-drag-line-forward (arg)
  19305. "Drag the line at point ARG lines forward."
  19306. (interactive "p")
  19307. (dotimes (_ (abs arg))
  19308. (let ((c (current-column)))
  19309. (if (< 0 arg)
  19310. (progn
  19311. (beginning-of-line 2)
  19312. (transpose-lines 1)
  19313. (beginning-of-line 0))
  19314. (transpose-lines 1)
  19315. (beginning-of-line -1))
  19316. (org-move-to-column c))))
  19317. (defun org-drag-line-backward (arg)
  19318. "Drag the line at point ARG lines backward."
  19319. (interactive "p")
  19320. (org-drag-line-forward (- arg)))
  19321. (defun org-mark-element ()
  19322. "Put point at beginning of this element, mark at end.
  19323. Interactively, if this command is repeated or (in Transient Mark
  19324. mode) if the mark is active, it marks the next element after the
  19325. ones already marked."
  19326. (interactive)
  19327. (let (deactivate-mark)
  19328. (if (and (called-interactively-p 'any)
  19329. (or (and (eq last-command this-command) (mark t))
  19330. (and transient-mark-mode mark-active)))
  19331. (set-mark
  19332. (save-excursion
  19333. (goto-char (mark))
  19334. (goto-char (org-element-property :end (org-element-at-point)))
  19335. (point)))
  19336. (let ((element (org-element-at-point)))
  19337. (end-of-line)
  19338. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19339. (goto-char (org-element-property :begin element))))))
  19340. (defun org-narrow-to-element ()
  19341. "Narrow buffer to current element."
  19342. (interactive)
  19343. (let ((elem (org-element-at-point)))
  19344. (cond
  19345. ((eq (car elem) 'headline)
  19346. (narrow-to-region
  19347. (org-element-property :begin elem)
  19348. (org-element-property :end elem)))
  19349. ((memq (car elem) org-element-greater-elements)
  19350. (narrow-to-region
  19351. (org-element-property :contents-begin elem)
  19352. (org-element-property :contents-end elem)))
  19353. (t
  19354. (narrow-to-region
  19355. (org-element-property :begin elem)
  19356. (org-element-property :end elem))))))
  19357. (defun org-transpose-element ()
  19358. "Transpose current and previous elements, keeping blank lines between.
  19359. Point is moved after both elements."
  19360. (interactive)
  19361. (org-skip-whitespace)
  19362. (let ((end (org-element-property :end (org-element-at-point))))
  19363. (org-drag-element-backward)
  19364. (goto-char end)))
  19365. (defun org-unindent-buffer ()
  19366. "Un-indent the visible part of the buffer.
  19367. Relative indentation (between items, inside blocks, etc.) isn't
  19368. modified."
  19369. (interactive)
  19370. (unless (eq major-mode 'org-mode)
  19371. (user-error "Cannot un-indent a buffer not in Org mode"))
  19372. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19373. (unindent-tree
  19374. (lambda (contents)
  19375. (dolist (element (reverse contents))
  19376. (if (memq (org-element-type element) '(headline section))
  19377. (funcall unindent-tree (org-element-contents element))
  19378. (save-excursion
  19379. (save-restriction
  19380. (narrow-to-region
  19381. (org-element-property :begin element)
  19382. (org-element-property :end element))
  19383. (org-do-remove-indentation))))))))
  19384. (funcall unindent-tree (org-element-contents parse-tree))))
  19385. (defun org-make-options-regexp (kwds &optional extra)
  19386. "Make a regular expression for keyword lines.
  19387. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19388. when non-nil, is a regexp matching keywords names."
  19389. (concat "^[ \t]*#\\+\\("
  19390. (regexp-opt kwds)
  19391. (and extra (concat (and kwds "\\|") extra))
  19392. "\\):[ \t]*\\(.*\\)"))
  19393. ;;; Conveniently switch to Info nodes
  19394. (defun org-info-find-node (&optional nodename)
  19395. "Find Info documentation NODENAME or Org documentation according context.
  19396. Started from `gnus-info-find-node'."
  19397. (interactive)
  19398. (Info-goto-node
  19399. (or nodename
  19400. (let ((default-org-info-node "(org) Top"))
  19401. (cond
  19402. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19403. ((eq 'org-mode major-mode)
  19404. (let* ((context (org-element-at-point))
  19405. (element-info-nodes ; compare to `org-element-all-elements'.
  19406. `((babel-call . "(org) Evaluating Code Blocks")
  19407. (center-block . "(org) Paragraphs")
  19408. (clock . ,default-org-info-node)
  19409. (comment . "(org) Comment Lines")
  19410. (comment-block . "(org) Comment Lines")
  19411. (diary-sexp . ,default-org-info-node)
  19412. (drawer . "(org) Drawers")
  19413. (dynamic-block . "(org) Dynamic Blocks")
  19414. (example-block . "(org) Literal Examples")
  19415. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19416. (fixed-width . ,default-org-info-node)
  19417. (footnote-definition . "(org) Creating Footnotes")
  19418. (headline . "(org) Document Structure")
  19419. (horizontal-rule . "(org) Built-in Table Editor")
  19420. (inlinetask . ,default-org-info-node)
  19421. (item . "(org) Plain Lists")
  19422. (keyword . "(org) Per-file keywords")
  19423. (latex-environment . "(org) LaTeX Export")
  19424. (node-property . "(org) Properties and Columns")
  19425. (paragraph . "(org) Paragraphs")
  19426. (plain-list . "(org) Plain Lists")
  19427. (planning . "(org) Deadlines and Scheduling")
  19428. (property-drawer . "(org) Properties and Columns")
  19429. (quote-block . "(org) Paragraphs")
  19430. (section . ,default-org-info-node)
  19431. (special-block . ,default-org-info-node)
  19432. (src-block . "(org) Working with Source Code")
  19433. (table . "(org) Tables")
  19434. (table-row . "(org) Tables")
  19435. (verse-block . "(org) Paragraphs"))))
  19436. (or (cdr (assoc (car context) element-info-nodes))
  19437. default-org-info-node)))
  19438. (t default-org-info-node))))))
  19439. ;;; Finish up
  19440. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19441. (lambda () (add-hook 'change-major-mode-hook
  19442. 'org-show-all 'append 'local)))
  19443. (provide 'org)
  19444. (run-hooks 'org-load-hook)
  19445. ;;; org.el ends here